neurastream 0.2.36 → 0.2.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,155 @@
1
+ // Provider out-until state (plan 20261025_1700 P1): who is rate-limited comes from live data,
2
+ // recorded by code from the provider's own words, never typed from memory. The state is an
3
+ // append-only JSONL file under <paths.queue_state>/provider-out.jsonl, one
4
+ // {provider, until, at, source} object per line; the newest record per provider wins. Decisions
5
+ // read it (agent-ledger --cap, the guards, the score gate); recordings come from
6
+ // `quota-reset --provider`, from task results that quote a reset time, and from rate-limited
7
+ // turn ends (the adapter wires those; this file stays harness-free).
8
+
9
+ import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import type { Config } from "./config.ts";
12
+ import { nowSec, strftime } from "./clock.ts";
13
+ import { parseWhen, wallToEpoch } from "./reset-time.ts";
14
+
15
+ /** One recorded out-until: `until`/`at` are epoch seconds. */
16
+ export interface OutRecord {
17
+ provider: string;
18
+ until: number;
19
+ at: number;
20
+ source: string;
21
+ }
22
+
23
+ export function outFile(cfg: Config): string {
24
+ return join(cfg.paths.queue_state, "provider-out.jsonl");
25
+ }
26
+
27
+ /** Every parseable record, oldest first; unparseable lines are skipped, never thrown. */
28
+ export function readOut(cfg: Config): OutRecord[] {
29
+ let text: string;
30
+ try {
31
+ text = readFileSync(outFile(cfg), "utf8");
32
+ } catch {
33
+ return [];
34
+ }
35
+ const out: OutRecord[] = [];
36
+ for (const line of text.split("\n")) {
37
+ if (!line.trim()) continue;
38
+ try {
39
+ const r = JSON.parse(line) as Partial<OutRecord>;
40
+ if (typeof r.provider === "string" && typeof r.until === "number" && Number.isFinite(r.until)
41
+ && typeof r.at === "number" && Number.isFinite(r.at) && typeof r.source === "string") {
42
+ out.push({ provider: r.provider, until: r.until, at: r.at, source: r.source });
43
+ }
44
+ } catch {}
45
+ }
46
+ return out;
47
+ }
48
+
49
+ /** Append one record. A failed write is swallowed like the other guard state files. */
50
+ export function recordOut(cfg: Config, provider: string, untilEpoch: number, source: string, at: number = Math.floor(Date.now() / 1000)): void {
51
+ try {
52
+ mkdirSync(cfg.paths.queue_state, { recursive: true });
53
+ appendFileSync(outFile(cfg), `${JSON.stringify({ provider, until: untilEpoch, at, source })}\n`);
54
+ } catch {}
55
+ }
56
+
57
+ /**
58
+ * The provider's active out-until (epoch seconds), or null when it is free: the newest record's
59
+ * until while it is still in the future, else null — absence of a record is free too, because
60
+ * this file is the only source that may claim a limit.
61
+ */
62
+ export function outUntil(cfg: Config, provider: string, now: number = nowSec()): number | null {
63
+ let until: number | null = null;
64
+ for (const r of readOut(cfg)) {
65
+ if (r.provider !== provider) continue;
66
+ until = r.until;
67
+ }
68
+ return until !== null && until > now ? until : null;
69
+ }
70
+
71
+ export interface ProviderOut {
72
+ provider: string;
73
+ /** Epoch seconds while out, null when free. */
74
+ until: number | null;
75
+ }
76
+
77
+ /** Per recorded provider (configured order first, then the rest as first recorded): free or out. */
78
+ export function providerStatus(cfg: Config, now: number = nowSec()): ProviderOut[] {
79
+ const records = readOut(cfg);
80
+ const seen: string[] = [];
81
+ for (const p of cfg.ledger.providers) {
82
+ if (records.some(r => r.provider === p) && !seen.includes(p)) seen.push(p);
83
+ }
84
+ for (const r of records) {
85
+ if (!seen.includes(r.provider)) seen.push(r.provider);
86
+ }
87
+ return seen.map(provider => ({ provider, until: outUntil(cfg, provider, now) }));
88
+ }
89
+
90
+ /**
91
+ * The one `providers:` line for Main's decision points (agent-ledger --cap, main-start): each
92
+ * recorded provider `free` or `out until <local HH:MM>`, configured order first. Null when
93
+ * nothing is recorded — an empty line would invite guessing, the incident's exact mistake.
94
+ */
95
+ export function providersLine(cfg: Config, now: number = nowSec()): string | null {
96
+ const status = providerStatus(cfg, now);
97
+ if (status.length === 0) return null;
98
+ const parts = status.map(s => (s.until === null ? `${s.provider} free` : `${s.provider} out until ${strftime(s.until, "%H:%M")}`));
99
+ return `providers: ${parts.join(" · ")}`;
100
+ }
101
+
102
+ /** The provider half of a `provider/model` pin, or null when the model names no provider. */
103
+ export function providerOfModel(model: string | null): string | null {
104
+ if (!model || !model.includes("/")) return null;
105
+ const provider = model.split("/")[0] ?? "";
106
+ return provider === "" ? null : provider;
107
+ }
108
+
109
+ /**
110
+ * The `model:` line of an agent's pin frontmatter (the shipped pin template's format, the same
111
+ * one the session reader resolves a run's model from), or null when the pin is missing or silent.
112
+ */
113
+ export function pinModel(cfg: Config, agent: string): string | null {
114
+ if (!cfg.adapter?.pins || agent === "") return null;
115
+ let text: string;
116
+ try {
117
+ text = readFileSync(join(cfg.adapter.pins, `${agent}.md`), "utf8");
118
+ } catch {
119
+ return null;
120
+ }
121
+ const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
122
+ return /^model:\s*(\S+)/m.exec(fm?.[1] ?? "")?.[1] ?? null;
123
+ }
124
+
125
+ /**
126
+ * The first reset time a text names, as epoch seconds, or null when it names none we can trust.
127
+ * Reuses parseWhen/wallToEpoch: the wall time comes from capture group 1, the zone from group 2
128
+ * when the text names one (Z/UTC/GMT, ±HH:MM) and `rule.zone` otherwise. reset-time.ts cannot
129
+ * grow an export for this (the plan freezes that file), so the ±HH:MM arithmetic sits here.
130
+ */
131
+ export function resetEpochFromText(text: string, rule: { pattern: string; zone: string }): number | null {
132
+ let pattern: RegExp;
133
+ try {
134
+ pattern = new RegExp(rule.pattern);
135
+ } catch {
136
+ return null;
137
+ }
138
+ const m = pattern.exec(text);
139
+ if (!m) return null;
140
+ const wall = m[1] ? parseWhen(m[1]) : null;
141
+ if (!wall) return null;
142
+ const zone = (m[2] ?? "").trim();
143
+ try {
144
+ if (!zone || zone === rule.zone) return wallToEpoch(wall, rule.zone);
145
+ if (zone === "Z" || zone === "UTC" || zone === "GMT") return wallToEpoch(wall, "UTC");
146
+ const offset = /^([+-])(\d{2}):?(\d{2})$/.exec(zone);
147
+ if (offset) {
148
+ const minutes = (Number(offset[2]) * 60 + Number(offset[3])) * (offset[1] === "+" ? 1 : -1);
149
+ return Math.floor((Date.UTC(wall.y, wall.mo - 1, wall.d, wall.h, wall.mi, wall.s) - minutes * 60_000) / 1000);
150
+ }
151
+ return wallToEpoch(wall, zone);
152
+ } catch {
153
+ return null;
154
+ }
155
+ }
@@ -14,6 +14,10 @@ function agentDir(): string {
14
14
  export function indexPath(): string {
15
15
  return process.env.QUEUE_INDEX ?? `${agentDir()}/INDEX.md`;
16
16
  }
17
+ /** FINISHED.md sits beside the main index: one short entry per closed plan. */
18
+ export function finishedPath(): string {
19
+ return path.join(path.dirname(indexPath()), "FINISHED.md");
20
+ }
17
21
  export function blockersDirPath(): string {
18
22
  return process.env.QUEUE_BLOCKERS ?? `${agentDir()}/blockers`;
19
23
  }
@@ -121,6 +125,14 @@ export function outsideProgress(text: string): string {
121
125
  export function progressBody(text: string): string {
122
126
  return sections(text).get("progress") ?? "";
123
127
  }
128
+ /** Last real Progress bullet, collapsed to one line. Main-only lines and the archive pointer are not entries. */
129
+ export function lastProgressLine(text: string): string {
130
+ let last = "";
131
+ for (const line of progressBody(text).split("\n")) {
132
+ if (/^\s*-\s+/.test(line) && !line.startsWith(POINTER_PREFIX)) last = line.replace(/^\s*-\s+/, "");
133
+ }
134
+ return last.replace(/\s+/g, " ").trim();
135
+ }
124
136
 
125
137
  export type ProgressTrim = { body: string; moved: string; count: number };
126
138
 
@@ -791,6 +803,35 @@ export function cancelledLine(file: string, text: string, date: string): string
791
803
  const owner = (progressBody(text).match(/^Cancelled by owner:\s*(.+?)\s*$/m)?.[1] ?? "").replace(/\|/g, "/");
792
804
  return `- ${path.basename(file)} | ${date} | owner: ${owner} | words: ${planWords(text).join(" ")}`;
793
805
  }
806
+ const FINISHED_HEADER = "# Finished plans (newest first; written by queue-close and queue-finished)\n";
807
+
808
+ /** Heading plus at most 4 body lines: Summary, Result, Plan path. */
809
+ export function finishedEntry(plan: Plan, archived: string, date: string): string {
810
+ const summary = (plan.summary ?? plan.goal[0] ?? "").replace(/\s+/g, " ").trim();
811
+ const result = lastProgressLine(plan.text);
812
+ const body = [`Summary: ${summary}`, `Result: ${result}`, `Plan: ${path.resolve(archived)}`];
813
+ return [`## ${date} · ${path.basename(plan.repo)} · ${plan.title}`, ...body].join("\n");
814
+ }
815
+
816
+ /** Inserts the entry above older ones. Returns false when that Plan path is already listed. */
817
+ export function prependFinished(entry: string, file = finishedPath()): boolean {
818
+ const planLine = entry.split("\n").find(l => l.startsWith("Plan: "));
819
+ let current = "";
820
+ try {
821
+ current = readFileSync(file, "utf8");
822
+ } catch {}
823
+ if (planLine && current.split("\n").includes(planLine)) return false;
824
+ mkdirSync(path.dirname(file), { recursive: true });
825
+ const block = entry.endsWith("\n") ? entry : `${entry}\n`;
826
+ if (!current.trim()) {
827
+ writeFileSync(file, `${FINISHED_HEADER}\n${block}`);
828
+ return true;
829
+ }
830
+ const at = current.search(/^## /m);
831
+ const next = at < 0 ? `${current.replace(/\s*$/, "\n\n")}${block}` : `${current.slice(0, at)}${block}\n${current.slice(at)}`;
832
+ writeFileSync(file, next);
833
+ return true;
834
+ }
794
835
  const slug = (name: string) => name.replace(/\.md$/, "").replace(/^\d{8}_\d{4}_/, "");
795
836
  export function cancelledMatches(plan: Plan): CancelledEntry[] {
796
837
  if (plan.status !== "open") return [];
@@ -798,7 +839,7 @@ export function cancelledMatches(plan: Plan): CancelledEntry[] {
798
839
  const name = path.basename(plan.file);
799
840
  return [...readCancelled(plan.repo), ...readGlobalCancelled()].filter(c => {
800
841
  const cleared = plan.text.split("\n").some(l => {
801
- const m = l.match(/^\s*(?:[-*]\s+)?False positive:\s*`?(\S+?)`?\s*[—:–-]+\s*(.+)$/);
842
+ const m = l.match(/^\s*(?:[-*]\s+)?False positive:\s*`?([^\s`]+)`?\s+[—:–-]+\s*(.+)$/);
802
843
  return m && m[1] === c.name && (m[2] ?? "").trim().length >= 15;
803
844
  });
804
845
  if (cleared || c.name === name) return false;
@@ -4,7 +4,7 @@ import os from "node:os";
4
4
  import path from "node:path";
5
5
  import type { Config } from "./config.ts";
6
6
  import { applyQueueEnv } from "./queue/env.ts";
7
- import { activePlans, cancelledFile, cancelledLine, closeLog, INDEX, readIndex, sha, STATE_DIR } from "./queue/lib.ts";
7
+ import { activePlans, cancelledFile, cancelledLine, closeLog, finishedEntry, finishedPath, INDEX, prependFinished, readIndex, sha, STATE_DIR } from "./queue/lib.ts";
8
8
  import { fixedIncident } from "./incidents.ts";
9
9
 
10
10
  export function queueClose(args: string[], cfg: Config): number {
@@ -277,6 +277,11 @@ export function queueClose(args: string[], cfg: Config): number {
277
277
  renameSync(file, dest);
278
278
  console.log(`queue-close: plan moved to ${dest}`);
279
279
  }
280
+ if (!cancelling) {
281
+ const listed = finishedPath();
282
+ const added = prependFinished(finishedEntry(plan, dest, today));
283
+ console.log(added ? `queue-close: recorded in ${listed}` : `queue-close: already in ${listed}`);
284
+ }
280
285
 
281
286
  // One index: the closed plan's line leaves the main index; there is no repo INDEX.md.
282
287
  const lines = readFileSync(INDEX, "utf8").split("\n").filter(l => l.trim());
@@ -0,0 +1,126 @@
1
+ // queue-finished: fill and search FINISHED.md. Backfill reads archived plans; a word prints matches.
2
+
3
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
4
+ import path from "node:path";
5
+ import type { Config } from "./config.ts";
6
+ import { applyQueueEnv } from "./queue/env.ts";
7
+ import { finishedEntry, finishedPath, parsePlan, planRepo, prependFinished } from "./queue/lib.ts";
8
+
9
+ const USAGE = "usage: queue-finished --backfill | queue-finished <word>";
10
+
11
+ function walkMd(dir: string, out: string[]): void {
12
+ let names: string[];
13
+ try {
14
+ names = readdirSync(dir);
15
+ } catch {
16
+ return;
17
+ }
18
+ for (const name of names) {
19
+ const file = path.join(dir, name);
20
+ let st: ReturnType<typeof statSync> | null = null;
21
+ try {
22
+ st = statSync(file);
23
+ } catch {
24
+ continue;
25
+ }
26
+ if (st.isDirectory()) walkMd(file, out);
27
+ else if (name.endsWith(".md")) out.push(file);
28
+ }
29
+ }
30
+
31
+ /** Repos named by work_roots, plus one level of children so a root that holds many checkouts still counts. */
32
+ function repoRoots(roots: string[]): string[] {
33
+ const out: string[] = [];
34
+ for (const root of roots) {
35
+ if (!existsSync(root)) continue;
36
+ out.push(root);
37
+ let names: string[] = [];
38
+ try {
39
+ names = readdirSync(root);
40
+ } catch {
41
+ continue;
42
+ }
43
+ for (const name of names) {
44
+ if (name.startsWith(".")) continue;
45
+ const child = path.join(root, name);
46
+ try {
47
+ if (statSync(child).isDirectory()) out.push(child);
48
+ } catch {}
49
+ }
50
+ }
51
+ return out;
52
+ }
53
+
54
+ function stampDate(file: string): string {
55
+ const stamp = /^(\d{4})(\d{2})(\d{2})_/.exec(path.basename(file));
56
+ if (stamp) return `${stamp[1]}-${stamp[2]}-${stamp[3]}`;
57
+ try {
58
+ return new Date(statSync(file).mtimeMs).toISOString().slice(0, 10);
59
+ } catch {
60
+ return new Date().toISOString().slice(0, 10);
61
+ }
62
+ }
63
+
64
+ function archivedPlans(roots: string[]): string[] {
65
+ const files: string[] = [];
66
+ for (const repo of repoRoots(roots)) walkMd(path.join(repo, "docs/plans/archive"), files);
67
+ return files;
68
+ }
69
+
70
+ function backfill(cfg: Config): number {
71
+ const files = archivedPlans(cfg.paths.work_roots);
72
+ const plans = files
73
+ .map(file => {
74
+ let raw = "";
75
+ try {
76
+ raw = readFileSync(file, "utf8");
77
+ } catch {
78
+ return null;
79
+ }
80
+ const plan = parsePlan(planRepo(file), file, raw);
81
+ return plan.status === "complete" ? plan : null;
82
+ })
83
+ .filter(p => p !== null)
84
+ .sort((a, b) => (path.basename(a.file) < path.basename(b.file) ? -1 : 1));
85
+ let added = 0;
86
+ // Oldest first so each prepend leaves the newer entry on top.
87
+ for (const plan of plans) {
88
+ if (prependFinished(finishedEntry(plan, plan.file, stampDate(plan.file)))) added++;
89
+ }
90
+ console.log(`queue-finished: backfill added ${added} (${plans.length} complete archived)`);
91
+ return 0;
92
+ }
93
+
94
+ function entries(text: string): string[] {
95
+ return text.split(/^(?=## )/m).filter(p => p.startsWith("## ")).map(p => p.trimEnd());
96
+ }
97
+
98
+ function search(word: string): number {
99
+ let text = "";
100
+ try {
101
+ text = readFileSync(finishedPath(), "utf8");
102
+ } catch {}
103
+ const needle = word.toLowerCase();
104
+ const hits = entries(text).filter(e => e.toLowerCase().includes(needle));
105
+ if (!hits.length) {
106
+ console.error(`queue-finished: no entry matches ${word}`);
107
+ return 1;
108
+ }
109
+ console.log(hits.join("\n\n"));
110
+ return 0;
111
+ }
112
+
113
+ export function queueFinished(args: string[], cfg: Config): number {
114
+ applyQueueEnv(cfg);
115
+ if (args[0] === "--help" || args[0] === "-h") {
116
+ console.log(USAGE);
117
+ return 0;
118
+ }
119
+ if (args.includes("--backfill")) return backfill(cfg);
120
+ const word = args.filter(a => !a.startsWith("-")).join(" ").trim();
121
+ if (!word) {
122
+ console.error(USAGE);
123
+ return 2;
124
+ }
125
+ return search(word);
126
+ }
@@ -1,12 +1,14 @@
1
1
  import type { Config } from "./config.ts";
2
+ import { recordOut } from "./provider-state.ts";
2
3
  import { localStamp, parseWhen, wallToEpoch } from "./reset-time.ts";
3
4
 
4
5
  const USAGE =
5
- 'usage: quota-reset "YYYY-MM-DD HH:MM[:SS]" [--tz <zone>] (reset time from your provider\'s rate-limit message)\n';
6
+ 'usage: quota-reset "YYYY-MM-DD HH:MM[:SS]" [--tz <zone>] [--provider <name>] (reset time from your provider\'s rate-limit message; --provider records it)\n';
6
7
 
7
8
 
8
9
  export function quotaReset(args: string[], cfg: Config): number {
9
10
  let zone = cfg.quota.reset_tz;
11
+ let provider: string | null = null;
10
12
  const words: string[] = [];
11
13
  for (let i = 0; i < args.length; i++) {
12
14
  const arg = args[i] ?? "";
@@ -18,6 +20,14 @@ export function quotaReset(args: string[], cfg: Config): number {
18
20
  }
19
21
  zone = value;
20
22
  i++;
23
+ } else if (arg === "--provider") {
24
+ const value = args[i + 1];
25
+ if (value === undefined) {
26
+ process.stderr.write(USAGE);
27
+ return 2;
28
+ }
29
+ provider = value;
30
+ i++;
21
31
  } else {
22
32
  words.push(arg);
23
33
  }
@@ -48,5 +58,13 @@ export function quotaReset(args: string[], cfg: Config): number {
48
58
  const d = epoch - now;
49
59
  console.log(`${label} reset (local): ${local} — in ${Math.floor(d / 3600)}h ${Math.floor((d % 3600) / 60)}m`);
50
60
  }
61
+ if (provider !== null) {
62
+ if (!cfg.ledger.providers.includes(provider)) {
63
+ process.stderr.write(`quota-reset: unknown provider "${provider}" (ledger.providers: ${cfg.ledger.providers.join(", ")})\n`);
64
+ return 1;
65
+ }
66
+ recordOut(cfg, provider, epoch, "quota-reset");
67
+ console.log(`recorded: ${provider} out until ${local} (local) — agent-ledger --cap and the guards read it back`);
68
+ }
51
69
  return 0;
52
70
  }
@@ -0,0 +1,95 @@
1
+ // Project rules reach the agent: a repo's own AGENTS.md (test lanes, no-push, conventions) the way
2
+ // Main gets the queue summary. The finder and the hash cache are host-neutral; the hook wiring
3
+ // (when an agent's context gets the text) is in src/adapters/<harness>/.
4
+ //
5
+ // The owner's burden rule is a neurastream rule, not a repo rule: it is read from
6
+ // templates/AGENTS.md, never copied here, so the template stays the one place it is written.
7
+
8
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { AGENTS_TEMPLATE } from "./agents-md.ts";
11
+ import type { Config } from "./config.ts";
12
+ import { MAIN_PLAN_FILE } from "./guards.ts";
13
+ import { readPlans, repoRoot, sections, sha } from "./queue/lib.ts";
14
+
15
+ /** A repo's rules file and the text to inject (cut to `rules.max_bytes`). */
16
+ export interface RepoRules {
17
+ path: string;
18
+ text: string;
19
+ }
20
+
21
+ /** The file's text, or null when it is not there (a repo without AGENTS.md has no rules to inject). */
22
+ function readRules(file: string): { path: string; text: string } | null {
23
+ try {
24
+ return { path: file, text: readFileSync(file, "utf8") };
25
+ } catch {
26
+ return null;
27
+ }
28
+ }
29
+
30
+ /**
31
+ * The rules of the repo a plan is worked in: the plan's own checkout (git top of its main repo),
32
+ * or — when the plan is worked in a linked worktree whose AGENTS.md differs — that worktree's.
33
+ * Null when the repo has no AGENTS.md. Text past `rules.max_bytes` is cut and one line names the
34
+ * file to read for the rest, so a huge rules file cannot fill a context.
35
+ */
36
+ export function repoRules(cfg: Config, planPath: string): RepoRules | null {
37
+ const repo = repoRoot(planPath);
38
+ if (!repo) return null;
39
+ const main = readRules(join(repo, "AGENTS.md"));
40
+ // The Worktree line names where the plan's promises are made; it can carry its own rules.
41
+ const worktree = MAIN_PLAN_FILE.test(planPath) ? readPlans([planPath])[0]?.worktree : null;
42
+ const work = worktree && worktree !== repo ? readRules(join(worktree, "AGENTS.md")) : null;
43
+ const rules = work && work.text !== main?.text ? work : main;
44
+ if (!rules) return null;
45
+ const max = cfg.rules.max_bytes;
46
+ if (rules.text.length <= max) return rules;
47
+ return { path: rules.path, text: `${rules.text.slice(0, max).trimEnd()}\n…cut, read ${rules.path}` };
48
+ }
49
+
50
+ /**
51
+ * The owner's burden rule (the first bullet of the template's Plans section) as templates/AGENTS.md
52
+ * words it. The rule text lives in the template only: nothing here repeats a word of it, so Main's
53
+ * context and every implementer's read the same sentence. Empty when the template is unreadable.
54
+ */
55
+ export function burdenRule(): string {
56
+ let template: string;
57
+ try {
58
+ template = readFileSync(AGENTS_TEMPLATE, "utf8");
59
+ } catch {
60
+ return "";
61
+ }
62
+ const plans = sections(template).get("plans") ?? "";
63
+ return plans.split("\n").find(line => line.startsWith("- ")) ?? "";
64
+ }
65
+
66
+ /** How many (session, file) hashes the cache keeps; beyond it the oldest entries are dropped. */
67
+ const KEEP = 200;
68
+
69
+ /**
70
+ * True when this session has not been handed this file's current text yet; records the hash so the
71
+ * next turn does not inject it again. A changed file hashes differently and comes back once. One
72
+ * JSON file under `paths.queue_state`, bounded to the newest `KEEP` entries.
73
+ */
74
+ export function rulesChanged(cfg: Config, session: string, path: string, text: string): boolean {
75
+ const file = join(cfg.paths.queue_state, "repo-rules.json");
76
+ const seen: Record<string, string> = {};
77
+ try {
78
+ const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
79
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
80
+ for (const [key, hash] of Object.entries(parsed)) if (typeof hash === "string") seen[key] = hash;
81
+ } catch {}
82
+ const key = `${session}\u0000${path}`;
83
+ const hash = sha(text);
84
+ if (seen[key] === hash) return false;
85
+ // Re-insert so the entry moves to the end: the file drops from the front.
86
+ delete seen[key];
87
+ seen[key] = hash;
88
+ const keys = Object.keys(seen);
89
+ for (const old of keys.slice(0, Math.max(0, keys.length - KEEP))) delete seen[old];
90
+ try {
91
+ mkdirSync(cfg.paths.queue_state, { recursive: true });
92
+ writeFileSync(file, JSON.stringify(seen));
93
+ } catch {}
94
+ return true;
95
+ }
@@ -119,6 +119,7 @@ export function noteRequest(path: string, auto = false, reason = ""): string {
119
119
  : `${NOTE_REQUEST_PREFIX} this session has grown past rollover.max_session_mb.`,
120
120
  `Write a handoff note to ${path} (overwrite it). Cover the work in progress and its state, the decisions made and why, the next step, and the files involved.`,
121
121
  "Do not list holds or owner blockers in the note; they come from the plans' WAITING on owner lines.",
122
+ "Do not state which agents or providers are rate-limited or free; that comes from agent-ledger --cap.",
122
123
  auto
123
124
  ? "As soon as this note is written and no own jobs run, this session restarts into a fresh one that starts from this note verbatim plus the generated main-start state."
124
125
  : "When the owner's next message arrives, this session closes and a fresh one starts from that note verbatim plus the generated main-start state.",
@@ -34,7 +34,9 @@ export function wipSnapshot(args: string[], cfg: Config): number {
34
34
  const maxMb = cfg.wip.snapshot_max_mb;
35
35
  const secret = secretRx(cfg.wip.secret_file);
36
36
  const stamp = strftime(nowSec(), "%Y%m%d-%H%M");
37
- const homePrefix = cfg.paths.home.endsWith("/") ? cfg.paths.home : `${cfg.paths.home}/`;
37
+ // git prints worktree paths resolved (macOS: /var → /private/var), so the home prefix must be resolved too.
38
+ const home = existsSync(cfg.paths.home) ? realpathSync(cfg.paths.home) : cfg.paths.home;
39
+ const homePrefix = home.endsWith("/") ? home : `${home}/`;
38
40
  const seen = new Set<string>();
39
41
  const worktrees: string[] = [];
40
42
  for (const repo of repos(cfg.paths.work_roots)) {
@@ -12,6 +12,7 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
12
12
  - Main writes every plan in `<repo>/docs/plans/`, shaped like `{{AGENT_DIR}}/queue/TEMPLATE.md`. Do the research yourself; never base a plan on another agent's findings.
13
13
  - Phase 0 of every plan: blocker scripts that stop the implementer from going against the plan. They must exist before any spawn.
14
14
  - An open plan gets an implementer subagent. When it claims done, verify (another subagent or yourself). Not done → spawn another implementer for the rest. Done → set `Status: complete`; `queue-close` then archives it and cleans the indexes.
15
+ - Owner asks about a past plan → grep FINISHED.md first; open the archived plan only for details.
15
16
  - An implementer's new `## Progress` entry ends with a `Findings:` line — `Findings: none`, or one item per finding with `file:line` evidence; plan-guard restores an entry without it, and each item becomes an incident.
16
17
  - Main may push and publish once the repo's AGENTS.md test rules are met.
17
18
 
@@ -20,6 +21,7 @@ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implem
20
21
  |---|---|
21
22
  |`main-start`|session start, after an abort, before every status report; prints the MR sweep (open forge MRs vs open plans)|
22
23
  |`queue-check`|after changing a plan or an index, before every spawn; exit 1 = fix first; also fails when a reachable forge lists an open MR no open plan mentions (`MR !N: ignored <reason>` in a plan marks it tracked)|
24
+ |`queue-finished`|owner asks about a past plan (`<word>` prints matching FINISHED.md entries; `--backfill` fills it from archived plans)|
23
25
  |`agent-ledger --cap`|before every spawn|
24
26
  |`agent-score`|`gate <agent>` before every spawn; `accept`/`diagnose`/`penalty` after reviewing a result; `check` after every merge; `board` after a score change|
25
27
  |`brief-lint <plan.md>`|before every spawn on that plan|
@@ -24,6 +24,12 @@ paths:
24
24
  # Which adapter (docs/adapter.md) serves runs, traces, launch, install and doctor.
25
25
  harness: omp
26
26
 
27
+ # Live project rules (src/core/repo-rules.ts): the repo's own AGENTS.md, handed to the agent that
28
+ # works in it — a subagent on its plan's repo, Main the first time a session touches the repo.
29
+ # max_bytes caps the injected text; past it the text is cut and one line names the file to read.
30
+ rules:
31
+ max_bytes: 24000
32
+
27
33
  score:
28
34
  default_repo: ""
29
35
  default_branch: "" # no default: pass --branch (agent-score refuses to guess a branch)
@@ -45,6 +51,10 @@ ledger:
45
51
  idle_not_live_min: 60
46
52
  max_running_per_provider: 2
47
53
  max_slots: 2
54
+ # The owner's pick order (plan 20261025_1700 P3): agent names, first = preferred; empty = off.
55
+ # The spawn gates refuse a later agent while an earlier one is free and under its provider cap
56
+ # unless the brief carries "Pick note: <why>"; agent-score gate ranks inside this order.
57
+ prefer: []
48
58
  providers:
49
59
  - zai
50
60
  - openai-codex
@@ -145,6 +155,9 @@ pages:
145
155
  port: 7788
146
156
  dir: "~/.local/share/neurastream/pages"
147
157
  keep_days: 15 # delete a published page this many days later; publish --keep is permanent
158
+ knowledge: # repo-local HTML explainers (docs/knowledge/<topic>.html) on the phone page's Knowledge tab
159
+ roots: ["$HOME/projects", "$HOME/Work"] # scanned for git repos; $HOME expands to the config's home
160
+ max_age_s: 300 # rebuild the topic list when older, so a git pull shows up on the next reload
148
161
  rollover:
149
162
  enabled: true
150
163
  max_session_mb: 5