neurastream 0.1.21 → 0.1.23

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.
package/README.md CHANGED
@@ -58,7 +58,7 @@ Check the merged result:
58
58
  neurastream config --json
59
59
  ```
60
60
 
61
- Every tool is one program, selected by the name it was called with: `agent-score`, `agent-ledger`, `brief-lint`, `oc-run`, `wip-check`, `wip-backup`, `wip-snapshot`, `pm-fail-facts`, `main-health`, `queue-check`, `queue-close`, `queue-cancel`, `main-start`, `machine-guard`, `glm-reset`, `priority-watch`, `resource-alerts`, `tmp-snapshot`, `heavy-run`.
61
+ Every tool is one program, selected by the name it was called with: `agent-score`, `agent-ledger`, `brief-lint`, `oc-run`, `wip-check`, `wip-backup`, `wip-snapshot`, `pm-fail-facts`, `main-health`, `queue-check`, `queue-close`, `queue-cancel`, `queue-trim`, `main-start`, `machine-guard`, `glm-reset`, `priority-watch`, `resource-alerts`, `tmp-snapshot`, `heavy-run`.
62
62
 
63
63
  ## Develop
64
64
 
@@ -147,7 +147,16 @@ bun add -g neurastream@latest
147
147
  neurastream adapter install omp
148
148
  ```
149
149
 
150
- Live copies are never hand-edited. `neurastream doctor` names each hand-edited or foreign installed file, and a stale install (the installed version is not `npm view neurastream version`). If the registry cannot be reached, that check is a warning, not a failure.
150
+ Live copies are never hand-edited. `neurastream doctor` names each hand-edited installed file and each missing one (`missing:`), and a stale install (the installed version is not `npm view neurastream version`). If the registry cannot be reached, that check is a warning, not a failure.
151
+
152
+ ## AGENTS.md block
153
+
154
+ `adapter install omp` writes the neurastream orchestrator rules into `~/.omp/agent/AGENTS.md`, between the markers `<!-- neurastream:begin (managed by neurastream; edit the package, not this block) -->` and `<!-- neurastream:end -->`. The rules come from `templates/AGENTS.md`; the agent dir comes from your config.
155
+
156
+ - Managed: the text between the markers. Install replaces it. A second install changes nothing.
157
+ - Yours: every line outside the markers. Install keeps it byte for byte. A file with no markers gets the block appended.
158
+ - Drift: `neurastream doctor` reports `stale:` when the text between the markers differs from the package's block, and `missing:` when the markers are absent. Edits outside the markers are never reported.
159
+ - Edit limit: the project-file changes Main gets per window come from `guards.main_edit_limit` and `guards.main_window_min`, not from the block text.
151
160
 
152
161
  ## License
153
162
 
package/bin/queue-trim ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env bun
2
+ import { basename } from "node:path";
3
+ import { run } from "../src/cli/dispatch.ts";
4
+
5
+ const invoked = basename(process.argv[1] ?? "");
6
+ process.exit(await run(invoked, process.argv.slice(2)));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.1.21",
3
+ "version": "0.1.23",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": ["ai-agents", "coding-agents", "orchestration", "guardrails", "omp", "bun", "cli"],
6
6
  "homepage": "https://github.com/umiddey/neurastream#readme",
@@ -37,6 +37,7 @@
37
37
  "pm-fail-facts": "bin/pm-fail-facts",
38
38
  "main-health": "bin/main-health",
39
39
  "queue-check": "bin/queue-check",
40
+ "queue-trim": "bin/queue-trim",
40
41
  "queue-close": "bin/queue-close",
41
42
  "queue-cancel": "bin/queue-cancel",
42
43
  "main-start": "bin/main-start",
@@ -1,5 +1,5 @@
1
- // Reports hand-edited or foreign live files the omp adapter installs, and a stale
2
- // registry version. Offline `npm view` is a warning, not a failure.
1
+ // Reports hand-edited or missing live files the omp adapter installs, the managed block in
2
+ // the owner's AGENTS.md, and a stale registry version. Offline `npm view` is a warning, not a failure.
3
3
  // Notes, INDEX, queue state and config are user state: not checked.
4
4
 
5
5
  import { spawnSync } from "node:child_process";
@@ -7,6 +7,8 @@ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from "
7
7
  import { homedir } from "node:os";
8
8
  import { dirname, join, relative, resolve } from "node:path";
9
9
  import { fileURLToPath } from "node:url";
10
+ import { blockState, renderBlock } from "../../core/agents-md.ts";
11
+ import { loadConfig } from "../../core/config.ts";
10
12
 
11
13
  const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
12
14
 
@@ -30,6 +32,11 @@ export function packageBins(root: string): { name: string; source: string }[] {
30
32
  return Object.entries(pkg.bin ?? {}).map(([name, rel]) => ({ name, source: join(root, rel) }));
31
33
  }
32
34
 
35
+ /** The omp agent's AGENTS.md, which carries the managed neurastream block. */
36
+ export function liveAgentsMd(home: string): string {
37
+ return join(home, ".omp/agent/AGENTS.md");
38
+ }
39
+
33
40
  /** Files adapter install places under this home. Bun's global bin dir is extra, checked only when a name is present. */
34
41
  export function adapterLiveFiles(home: string, root: string = PACKAGE_ROOT): LiveFile[] {
35
42
  const files: LiveFile[] = [];
@@ -154,7 +161,7 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env)
154
161
  if (seen.has(file.live)) continue;
155
162
  seen.add(file.live);
156
163
  if (!existsSync(file.live)) {
157
- problems.push(`foreign: ${file.live}`);
164
+ problems.push(`missing: ${file.live}`);
158
165
  continue;
159
166
  }
160
167
  if (isPackageFile(file.live, file.source)) {
@@ -163,6 +170,11 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env)
163
170
  }
164
171
  problems.push(`hand-edited: ${file.live}`);
165
172
  }
173
+ const agents = liveAgentsMd(home);
174
+ const text = existsSync(agents) ? readFileSync(agents, "utf8") : "";
175
+ const state = blockState(text, renderBlock(loadConfig({ home, env })));
176
+ if (state === "ok") ok.push(`${agents} neurastream block`);
177
+ else problems.push(`${state}: ${agents} neurastream block`);
166
178
  const warnings: string[] = [];
167
179
  const viewed = npmViewVersion(name, env);
168
180
  let registry: string | null = null;
@@ -23,11 +23,11 @@ import type { Decision } from "../../core/adapter.ts";
23
23
  import { loadConfig, type Config } from "../../core/config.ts";
24
24
  import { nowSec } from "../../core/clock.ts";
25
25
  import { runDetectorsGated } from "../../core/incident-detectors.ts";
26
- import { checkInject, checkPlanEdit, checkStop, checkTool, MAIN_PLAN_FILE, recordMainResult } from "../../core/guards.ts";
26
+ import { checkInject, checkPlanEdit, checkStop, checkTool, MAIN_PLAN_FILE, recordMainResult, rekeySpawnFile } from "../../core/guards.ts";
27
27
  import { applyQueueEnv } from "../../core/queue/env.ts";
28
28
  import { mainStartText, runDailyCheck } from "../../core/main-start.ts";
29
29
  import { readBlocks } from "../../core/metrics.ts";
30
- import { buildHandoff, holdsBlock, notePath, noteRequest, relaunchPath, rolloverState, spawnRefusal, type RolloverState } from "../../core/rollover.ts";
30
+ import { buildHandoff, holdsBlock, notePath, noteRequest, ownerText, relaunchPath, rolloverState, spawnRefusal, type RolloverState } from "../../core/rollover.ts";
31
31
  import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
32
32
  import * as q from "../../core/queue/lib.ts";
33
33
  // Registers the plugin-command matcher into core's writeTargets (side effect).
@@ -306,7 +306,8 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
306
306
  // A turn the harness starts from the guard's own stop continuation is not an owner
307
307
  // message: D4 (owner-correction) only sees real prompts; D1/D3 run either way.
308
308
  const prompt = asString(asRecord(event).prompt);
309
- mainDetectors(cfg, { prompt: prompt.trimStart().startsWith("main-guard:") ? undefined : prompt });
309
+ // Machine prompts (guard continuation, rollover note request, handoff note) are not owner messages.
310
+ mainDetectors(cfg, { prompt: ownerText(prompt) });
310
311
  return {
311
312
  message: {
312
313
  customType: "main-guard.queue",
@@ -368,12 +369,21 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
368
369
  return Object.keys(out).length > 0 ? out : undefined;
369
370
  });
370
371
 
372
+ // Main ticked a phase: keep the newest Progress entries in the plan and move older ones to its archive.
373
+ const trimProgress = (file: string): string | undefined => {
374
+ const t = q.trimPlanProgress(file, cfg.queue.progress_keep);
375
+ if (!t) return undefined;
376
+ rekeySpawnFile(file, t.before, t.after);
377
+ return `plan-guard: moved ${t.count} older Progress entries to ${t.archive}; re-read the plan before editing it again.`;
378
+ };
379
+
371
380
  pi.on("tool_result", (event, ctx) => {
372
381
  onSizeCheck(event, ctx);
373
382
  const e = asRecord(event);
374
383
  const c = asCtx(ctx);
375
384
  const id = asString(e.toolCallId);
376
385
  const snap = pending.get(id);
386
+ const notes: string[] = [];
377
387
  if (snap) {
378
388
  pending.delete(id);
379
389
  for (const [file, before] of snap) {
@@ -389,6 +399,10 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
389
399
  } catch {}
390
400
  return { isError: true, content: [{ type: "text", text: d.reason }] };
391
401
  }
402
+ if (d.allow && (!c.hasAgent || c.kind === "main") && q.doneCount(after) > q.doneCount(before) && q.planAt(file, q.activePlans())) {
403
+ const note = trimProgress(file);
404
+ if (note) notes.push(note);
405
+ }
392
406
  }
393
407
  }
394
408
  if ((!c.hasAgent || c.kind === "main") && asString(e.toolName) === "bash" && !e.isError) {
@@ -406,6 +420,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
406
420
  bash: { command: asString(asRecord(e.input).command), output: content.map(p => asString(asRecord(p).text)).join("\n") },
407
421
  });
408
422
  }
423
+ if (notes.length) return { content: [...(Array.isArray(e.content) ? e.content : []), ...notes.map(text => ({ type: "text", text }))] };
409
424
  return undefined;
410
425
  });
411
426
 
@@ -6,9 +6,10 @@ import { copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSy
6
6
  import { homedir } from "node:os";
7
7
  import { dirname, join, resolve } from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
- import { configFile } from "../../core/config.ts";
9
+ import { renderBlock, upsertBlock } from "../../core/agents-md.ts";
10
+ import { configFile, loadConfig } from "../../core/config.ts";
10
11
 
11
- import { adapterLiveFiles } from "./doctor.ts";
12
+ import { adapterLiveFiles, liveAgentsMd } from "./doctor.ts";
12
13
  // Registers the plugin-command matcher into core's writeTargets (side effect).
13
14
  import "./package-ops.ts";
14
15
  const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
@@ -31,6 +32,7 @@ export interface InstallResult {
31
32
  pinsCopied: string[];
32
33
  pinsKept: string[];
33
34
  overlay: "written" | "unchanged";
35
+ agentsMd: "written" | "unchanged";
34
36
  }
35
37
 
36
38
  function ensureLink(link: string, target: string): void {
@@ -101,6 +103,17 @@ function writeOverlay(file: string): "written" | "unchanged" {
101
103
  return "written";
102
104
  }
103
105
 
106
+ // Writes the managed block into the owner's AGENTS.md: the rest of the file is never touched.
107
+ function writeAgentsMd(home: string): "written" | "unchanged" {
108
+ const file = liveAgentsMd(home);
109
+ const current = existsSync(file) ? readFileSync(file, "utf8") : "";
110
+ const next = upsertBlock(current, renderBlock(loadConfig({ home })));
111
+ if (next === current) return "unchanged";
112
+ mkdirSync(dirname(file), { recursive: true });
113
+ writeFileSync(file, next);
114
+ return "written";
115
+ }
116
+
104
117
  function linkPlugin(home: string): string {
105
118
  const r = spawnSync("omp", ["plugin", "link", PACKAGE_ROOT], {
106
119
  env: { ...process.env, HOME: home },
@@ -141,7 +154,8 @@ export function installOmp(home: string): InstallResult {
141
154
  linkInstalled(home);
142
155
  const plugin = linkPlugin(home);
143
156
  const overlay = writeOverlay(file);
144
- return { plugin, removedStaleLink, pinsCopied: pins.copied, pinsKept: pins.kept, overlay };
157
+ const agentsMd = writeAgentsMd(home);
158
+ return { plugin, removedStaleLink, pinsCopied: pins.copied, pinsKept: pins.kept, overlay, agentsMd };
145
159
  }
146
160
 
147
161
  export function printInstall(result: InstallResult): void {
@@ -150,6 +164,7 @@ export function printInstall(result: InstallResult): void {
150
164
  console.log(
151
165
  `neurastream adapter install omp: pins copied ${result.pinsCopied.length}, kept ${result.pinsKept.length}; overlay ${result.overlay}`,
152
166
  );
167
+ console.log(`neurastream adapter install omp: AGENTS.md block ${result.agentsMd}`);
153
168
  }
154
169
 
155
170
  export function runAdapterInstall(args: string[]): number {
@@ -11,6 +11,7 @@ import { pmFailFacts } from "../core/pm-fail-facts.ts";
11
11
  import { priorityWatch } from "../core/priority-watch.ts";
12
12
  import { queueCancel } from "../core/queue-cancel.ts";
13
13
  import { queueCheck } from "../core/queue-check.ts";
14
+ import { queueTrim } from "../core/queue-trim.ts";
14
15
  import { queueClose } from "../core/queue-close.ts";
15
16
  import { resourceAlerts } from "../core/resource-alerts.ts";
16
17
  import { tmpSnapshot } from "../core/tmp-snapshot.ts";
@@ -32,6 +33,7 @@ export const PORTED = [
32
33
  "pm-fail-facts",
33
34
  "main-health",
34
35
  "queue-check",
36
+ "queue-trim",
35
37
  "queue-close",
36
38
  "queue-cancel",
37
39
  "main-start",
@@ -70,6 +72,8 @@ export async function runPorted(cmd: string, args: string[]): Promise<number> {
70
72
  return mainHealth(args, rt.cfg, rt.source);
71
73
  case "queue-check":
72
74
  return queueCheck(args, rt.cfg);
75
+ case "queue-trim":
76
+ return queueTrim(args, rt.cfg);
73
77
  case "queue-close":
74
78
  return queueClose(args, rt.cfg);
75
79
  case "queue-cancel":
@@ -19,6 +19,7 @@ const BINS = [
19
19
  "pm-fail-facts",
20
20
  "main-health",
21
21
  "queue-check",
22
+ "queue-trim",
22
23
  "queue-close",
23
24
  "queue-cancel",
24
25
  "main-start",
@@ -0,0 +1,58 @@
1
+ // The managed block in the owner's AGENTS.md. The rules come from templates/AGENTS.md with the
2
+ // config's agent dir filled in; they sit between two markers, and only what is between them is
3
+ // ever written or checked against the package's block. Everything outside the markers stays the owner's.
4
+
5
+ import { readFileSync } from "node:fs";
6
+ import { dirname, join } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import type { Config } from "./config.ts";
9
+
10
+ const HERE = dirname(fileURLToPath(import.meta.url));
11
+ export const AGENTS_TEMPLATE = join(HERE, "../../templates/AGENTS.md");
12
+ export const BEGIN_MARK = "<!-- neurastream:begin (managed by neurastream; edit the package, not this block) -->";
13
+ export const END_MARK = "<!-- neurastream:end -->";
14
+
15
+ export function renderBlock(cfg: Config, template: string = readFileSync(AGENTS_TEMPLATE, "utf8")): string {
16
+ const body = template.trimEnd().split("{{AGENT_DIR}}").join(cfg.paths.agent_dir);
17
+ return `${BEGIN_MARK}\n${body}\n${END_MARK}`;
18
+ }
19
+
20
+ function occurrences(text: string, mark: string): number[] {
21
+ const at: number[] = [];
22
+ for (let i = text.indexOf(mark); i !== -1; i = text.indexOf(mark, i + mark.length)) at.push(i);
23
+ return at;
24
+ }
25
+
26
+ // The block's span in a file, or null when there are no markers. Anything other than exactly one
27
+ // begin marker followed by exactly one end marker is malformed and throws.
28
+ function span(text: string): { start: number; end: number } | null {
29
+ const begins = occurrences(text, BEGIN_MARK);
30
+ const ends = occurrences(text, END_MARK);
31
+ const begin = begins[0];
32
+ const end = ends[0];
33
+ if (begin === undefined && end === undefined) return null;
34
+ if (begins.length !== 1 || ends.length !== 1 || begin === undefined || end === undefined || end < begin) {
35
+ throw new Error("neurastream block markers malformed: expected one begin marker, then one end marker");
36
+ }
37
+ return { start: begin, end: end + END_MARK.length };
38
+ }
39
+
40
+ // Replace the marked block, or append one when the file has none. Bytes outside the markers are kept.
41
+ export function upsertBlock(fileText: string, block: string): string {
42
+ const at = span(fileText);
43
+ if (at) return fileText.slice(0, at.start) + block + fileText.slice(at.end);
44
+ if (fileText === "") return `${block}\n`;
45
+ return `${fileText}\n${block}\n`;
46
+ }
47
+
48
+ // "missing": no block in the file. "stale": the block differs, or its markers are malformed.
49
+ export function blockState(fileText: string, block: string): "ok" | "stale" | "missing" {
50
+ let at: { start: number; end: number } | null;
51
+ try {
52
+ at = span(fileText);
53
+ } catch {
54
+ return "stale";
55
+ }
56
+ if (!at) return "missing";
57
+ return fileText.slice(at.start, at.end) === block ? "ok" : "stale";
58
+ }
@@ -86,6 +86,7 @@ export interface Config {
86
86
  queue: {
87
87
  archive_days: number;
88
88
  background_max_lines: number;
89
+ progress_keep: number;
89
90
  priority_id: string;
90
91
  cancel_min_words: number;
91
92
  auto_close_min: number;
@@ -106,6 +106,24 @@ export function recordSpawns(files: string[]): void {
106
106
  }
107
107
  }
108
108
 
109
+ /** Re-key a plan's spawn hash after its Progress body was trimmed. Only a hash that matched the old body moves. Pure. */
110
+ export function rekeySpawns(spawns: Record<string, string>, file: string, before: string, after: string): boolean {
111
+ if (spawns[file] !== q.sha(before)) return false;
112
+ spawns[file] = q.sha(after);
113
+ return true;
114
+ }
115
+
116
+ /** Apply rekeySpawns to the stored spawn hashes. */
117
+ export function rekeySpawnFile(file: string, before: string, after: string): void {
118
+ const s = readSpawns();
119
+ if (!rekeySpawns(s, file, before, after)) return;
120
+ try {
121
+ writeFileSync(spawnsFile(), JSON.stringify(s, null, 1));
122
+ } catch (err) {
123
+ log(`${q.STATE_DIR}/../main-guard.log`, `cannot write ${spawnsFile()}: ${err}`);
124
+ }
125
+ }
126
+
109
127
  // --- shared pieces ---
110
128
 
111
129
  function unlocked(cfg: Config): boolean {
@@ -554,10 +572,11 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
554
572
  const cancel = continuation ? "" : flagCancel(e.inject, cfg);
555
573
  const incidents = openIncidentList(cfg);
556
574
  const incidentText = incidents.length ? `\n${incidents.map(incidentLine).join("\n")}` : "";
575
+ const editLimit = continuation ? "" : `\nmain-guard: Main may change project files at most ${cfg.guards.main_edit_limit} times per ${cfg.guards.main_window_min}-minute window; then delegate.`;
557
576
  return {
558
577
  allow: true,
559
578
  reason: "",
560
- inject: `${summary}\n(main-guard: read ${q.INDEX} and the listed repo INDEX.md files are summarised above; work the open plans, close finished ones with queue-close.)${cancel}${incidentText}`,
579
+ inject: `${summary}\n(main-guard: read ${q.INDEX} and the listed repo INDEX.md files are summarised above; work the open plans, close finished ones with queue-close.)${editLimit}${cancel}${incidentText}`,
561
580
  ...(continuation ? {} : { state: { callsSinceStop: 0, idleStops: 0 } }),
562
581
  };
563
582
  }
@@ -592,7 +611,10 @@ export function checkPlanEdit(e: PlanEditEvent, cfg: Config): Decision {
592
611
  // An empty `before` means the plan file did not exist yet; a refusal then deletes it.
593
612
  function checkMainPlan(e: PlanEditEvent, cfg: Config): Decision {
594
613
  if (q.outsideProgress(e.after) === q.outsideProgress(e.before)) return ALLOW;
595
- const problems = planReadProblems(e.after, e.path, cfg);
614
+ // Refuse only what this edit adds: a problem the plan already had is not Main's doing now.
615
+ // The missing-section problem is always refused: a plan with no read list has no evidence behind its text.
616
+ const known = new Set(e.before ? planReadProblems(e.before, e.path, cfg) : []);
617
+ const problems = planReadProblems(e.after, e.path, cfg).filter(p => p === NO_SECTION || !known.has(p));
596
618
  if (!problems.length) return ALLOW;
597
619
  log(cfg.paths.plan_guard_log, `REFUSE-READ ${e.path}: ${problems.join("; ")}`);
598
620
  return {
@@ -606,11 +628,13 @@ const READ_SECTION = /^## Code read by Main[^\n]*\n([\s\S]*?)(?=^## |(?![\s\S]))
606
628
  const LISTED_PATH = /`([^`\s]+)`/g;
607
629
  const CITED_PATH = /((?:~\/|\/|\.{1,2}\/)?[\w@.-]+(?:\/[\w@.-]+)*\.[A-Za-z0-9]+):\d+/g;
608
630
 
631
+ const NO_SECTION = `no "## Code read by Main" section lists a file (list each file you read for this plan as a backticked path)`;
632
+
609
633
  /** Read evidence behind a plan edit: section present, each listed path read within the window, no unlisted cited path. */
610
634
  function planReadProblems(text: string, planPath: string, cfg: Config): string[] {
611
635
  const section = READ_SECTION.exec(text)?.[1] ?? "";
612
636
  const listed = [...section.matchAll(LISTED_PATH)].map(m => (m[1] ?? "").replace(/:[\d,+\- ]+$/, ""));
613
- if (!listed.length) return [`no "## Code read by Main" section lists a file (list each file you read for this plan as a backticked path)`];
637
+ if (!listed.length) return [NO_SECTION];
614
638
  const reads = readMainReads();
615
639
  const maxMs = cfg.guards.plan_read_max_hours * 3_600_000;
616
640
  const problems: string[] = [];
@@ -621,7 +645,7 @@ function planReadProblems(text: string, planPath: string, cfg: Config): string[]
621
645
  if (!isFile(abs)) problems.push(`${p} does not exist`);
622
646
  else if (!(Date.parse(reads[abs] ?? "") >= Date.now() - maxMs)) problems.push(`${p} was not read by Main within ${cfg.guards.plan_read_max_hours} h`);
623
647
  }
624
- for (const [, cited = ""] of text.matchAll(CITED_PATH)) {
648
+ for (const [, cited = ""] of q.outsideProgress(text).matchAll(CITED_PATH)) {
625
649
  const abs = planFile(cited, planPath, text);
626
650
  if (abs.includes("/docs/plans/") || named.has(abs) || !isFile(abs)) continue;
627
651
  problems.push(`${cited} is cited but not listed under "## Code read by Main"`);
@@ -8,6 +8,7 @@ import { join } from "node:path";
8
8
  import type { Config } from "./config.ts";
9
9
  import type { Run, RunSource } from "./adapter.ts";
10
10
  import { readEvents } from "./agent-score.ts";
11
+ import { ownerText } from "./rollover.ts";
11
12
 
12
13
  export type Ev = Record<string, unknown>;
13
14
 
@@ -199,7 +200,9 @@ export function m4(runs: Run[], w: Window, patterns: RegExp[]): M4 {
199
200
  const text = blocks(m.text)
200
201
  .map((b) => b.text)
201
202
  .join("\n");
202
- if (patterns.some((p) => p.test(text))) out.corrections++;
203
+ // Machine-written messages (rollover note request, handoff note text) are not owner corrections.
204
+ const own = ownerText(text);
205
+ if (own !== undefined && patterns.some((p) => p.test(own))) out.corrections++;
203
206
  } else if (m.role === "assistant") {
204
207
  const last = blocks(m.text)
205
208
  .filter((b) => b.type === "text")
@@ -1,7 +1,7 @@
1
1
  // Queue model: main index, repo INDEX.md, plan shape (templates/queue/TEMPLATE.md).
2
2
 
3
3
  import { createHash } from "node:crypto";
4
- import { accessSync, constants, existsSync, readFileSync, realpathSync, statSync } from "node:fs";
4
+ import { accessSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
7
 
@@ -108,6 +108,57 @@ export function progressBody(text: string): string {
108
108
  return sections(text).get("progress") ?? "";
109
109
  }
110
110
 
111
+ export type ProgressTrim = { body: string; moved: string; count: number };
112
+
113
+ // Entries start at a top-level "- " line. The pointer line that a trim leaves behind is not an entry,
114
+ // and Main-only lines (status, owner parking/cancel, cancelled-list clearance) never move to the archive.
115
+ const POINTER_PREFIX = "- Older Progress entries:";
116
+ const MAIN_ONLY_LINE = /^\s*(?:[-*]\s+)?(Status:|WAITING on owner:|Cancelled by owner:|False positive:)/;
117
+
118
+ /** Keep the first `keep` entries (the file lists them newest first) and move the rest. Pure. */
119
+ export function trimProgressBody(body: string, keep: number, pointer: string): ProgressTrim | undefined {
120
+ const lines = body.split("\n").filter(l => !l.startsWith(POINTER_PREFIX));
121
+ const starts = lines.flatMap((l, i) => (/^- /.test(l) && !MAIN_ONLY_LINE.test(l) ? [i] : []));
122
+ if (starts.length <= keep) return undefined;
123
+ const cut = starts[keep];
124
+ const tail = lines.slice(cut);
125
+ const pinned = tail.filter(l => MAIN_ONLY_LINE.test(l));
126
+ const moved = tail.filter(l => !MAIN_ONLY_LINE.test(l));
127
+ let end = moved.length;
128
+ while (end > 0 && moved[end - 1] === "") end--;
129
+ return {
130
+ body: [...lines.slice(0, cut), ...pinned, pointer, ...moved.slice(end)].join("\n"),
131
+ moved: moved.slice(0, end).join("\n"),
132
+ count: starts.length - keep,
133
+ };
134
+ }
135
+
136
+ /** Trim the `## Progress` body of a plan file in place and append the moved entries to its archive (newest batch on top). */
137
+ export function trimPlanProgress(planFile: string, keep: number): { count: number; archive: string; before: string; after: string } | undefined {
138
+ const text = readFileSync(planFile, "utf8");
139
+ const head = /^## Progress[^\n]*\n/m.exec(text);
140
+ if (!head) return undefined;
141
+ const start = head.index + head[0].length;
142
+ const next = text.slice(start).search(/^## /m);
143
+ const end = next === -1 ? text.length : start + next;
144
+ const before = text.slice(start, end);
145
+ const archiveName = `${path.basename(planFile, ".md")}-progress.md`;
146
+ const res = trimProgressBody(before, keep, `- Older Progress entries: archive/${archiveName}`);
147
+ if (!res) return undefined;
148
+ const dir = path.join(path.dirname(planFile), "archive");
149
+ const archive = path.join(dir, archiveName);
150
+ const older = (existsSync(archive) ? readFileSync(archive, "utf8") : "").replace(/^# Progress archive:[^\n]*\n?/, "").trim();
151
+ mkdirSync(dir, { recursive: true });
152
+ writeFileSync(archive, `# Progress archive: ${path.basename(planFile)}\n\n${res.moved.trim()}\n${older ? `\n${older}\n` : ""}`);
153
+ writeFileSync(planFile, text.slice(0, start) + res.body + text.slice(end));
154
+ return { count: res.count, archive, before, after: res.body };
155
+ }
156
+
157
+ /** Number of ticked phase lines ("- [x]") in a plan. */
158
+ export function doneCount(text: string): number {
159
+ return (text.match(/^\s*[-*] \[x\]/gm) ?? []).length;
160
+ }
161
+
111
162
  export function statusOf(text: string): Plan["status"] {
112
163
  const m = progressBody(text).match(/^Status:\s*(\S+)\s*$/m);
113
164
  const st = m?.[1];
@@ -0,0 +1,41 @@
1
+ // queue-trim <plan> [--keep N]: keep the newest Progress entries of an indexed plan and move the
2
+ // older ones to its archive. The adapter runs the same trim after Main ticks a phase.
3
+
4
+ import { existsSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { rekeySpawnFile } from "./guards.ts";
7
+ import type { Config } from "./config.ts";
8
+ import { applyQueueEnv } from "./queue/env.ts";
9
+ import * as q from "./queue/lib.ts";
10
+
11
+ const USAGE = "usage: queue-trim <plan file> [--keep N]";
12
+
13
+ export function queueTrim(args: string[], cfg: Config): number {
14
+ applyQueueEnv(cfg);
15
+ const hasKeep = args.includes("--keep");
16
+ const rest = args.filter((a, i) => a !== "--keep" && args[i - 1] !== "--keep");
17
+ const planArg = rest[0];
18
+ if (!planArg) {
19
+ console.error(USAGE);
20
+ return 2;
21
+ }
22
+ const keepArg = hasKeep ? args[args.indexOf("--keep") + 1] : undefined;
23
+ const keep = hasKeep ? Number(keepArg) : cfg.queue.progress_keep;
24
+ if (!Number.isInteger(keep) || keep < 0) {
25
+ console.error(`queue-trim: --keep takes a whole number, got ${keepArg ?? "nothing"}`);
26
+ return 2;
27
+ }
28
+ const file = path.resolve(planArg);
29
+ if (!existsSync(file) || !q.planAt(file, q.activePlans())) {
30
+ console.error(`queue-trim: ${file} is not an indexed plan`);
31
+ return 2;
32
+ }
33
+ const t = q.trimPlanProgress(file, keep);
34
+ if (!t) {
35
+ console.log(`queue-trim: ${file} has no more than ${keep} Progress entries; nothing moved`);
36
+ return 0;
37
+ }
38
+ rekeySpawnFile(file, t.before, t.after);
39
+ console.log(`queue-trim: moved ${t.count} older Progress entries of ${file} to ${t.archive}`);
40
+ return 0;
41
+ }
@@ -64,10 +64,15 @@ export interface HandoffInput {
64
64
  ownerMessage: string;
65
65
  }
66
66
 
67
+ /** Prefixes of the machine-written messages: the builders write them, ownerText reads them. */
68
+ const NOTE_REQUEST_PREFIX = "Session rollover:";
69
+ const HANDOFF_PREFIX = "Previous session file:";
70
+ const OWNER_MARK = "Owner's message:";
71
+
67
72
  /** The first user message of the new session: header, Main's note, generated state, owner message. */
68
73
  export function buildHandoff(p: HandoffInput): string {
69
74
  return [
70
- `Previous session file: ${p.previousSessionFile}. Its full history stays there; this session continues from the handoff below.`,
75
+ `${HANDOFF_PREFIX} ${p.previousSessionFile}. Its full history stays there; this session continues from the handoff below.`,
71
76
  "",
72
77
  "## Main's handoff note (verbatim)",
73
78
  p.note.trimEnd(),
@@ -75,11 +80,25 @@ export function buildHandoff(p: HandoffInput): string {
75
80
  "## Generated state (main-start)",
76
81
  p.generated.trimEnd(),
77
82
  "",
78
- "Owner's message:",
83
+ OWNER_MARK,
79
84
  p.ownerMessage,
80
85
  ].join("\n");
81
86
  }
82
87
 
88
+ /**
89
+ * The owner's own words in a user prompt, or undefined for a machine prompt: a guard continuation, the
90
+ * rollover note request, or a handoff without its owner marker. A handoff yields only its owner message.
91
+ */
92
+ export function ownerText(prompt: string): string | undefined {
93
+ const t = prompt.trimStart();
94
+ if (t.startsWith("main-guard:") || t.startsWith(NOTE_REQUEST_PREFIX)) return undefined;
95
+ if (t.startsWith(HANDOFF_PREFIX)) {
96
+ const at = prompt.lastIndexOf(OWNER_MARK);
97
+ return at < 0 ? undefined : prompt.slice(at + OWNER_MARK.length).trim();
98
+ }
99
+ return prompt;
100
+ }
101
+
83
102
  /** The owner-holds part of the generated state: each WAITING on owner line verbatim, or none. */
84
103
  export function holdsBlock(holds: readonly string[]): string {
85
104
  return ["=== owner holds (plans' WAITING on owner lines)", ...(holds.length > 0 ? holds : ["none"]), ""].join("\n");
@@ -89,8 +108,8 @@ export function holdsBlock(holds: readonly string[]): string {
89
108
  export function noteRequest(path: string, auto = false, reason = ""): string {
90
109
  return [
91
110
  reason
92
- ? `Session rollover: a new neurastream version is installed (${reason}).`
93
- : "Session rollover: this session has grown past rollover.max_session_mb.",
111
+ ? `${NOTE_REQUEST_PREFIX} a new neurastream version is installed (${reason}).`
112
+ : `${NOTE_REQUEST_PREFIX} this session has grown past rollover.max_session_mb.`,
94
113
  `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.`,
95
114
  "Do not list holds or owner blockers in the note; they come from the plans' WAITING on owner lines.",
96
115
  auto
@@ -0,0 +1,27 @@
1
+ # neurastream: orchestrator rules
2
+
3
+ You are Main, the orchestrator. Main plans, delegates, reviews and lands; implementers do the work.
4
+
5
+ ## Plans
6
+ - When the owner asks for work in a repo, add the repo to `{{AGENT_DIR}}/INDEX.md` and the plan to the repo's INDEX.md.
7
+ - Entering a repo: read its AGENTS.md first.
8
+ - 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.
9
+ - Phase 0 of every plan: blocker scripts that stop the implementer from going against the plan. They must exist before any spawn.
10
+ - 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.
11
+ - Main may push and publish once the repo's AGENTS.md test rules are met.
12
+
13
+ ## Scripts (run at the stated moment)
14
+ |Script|When|
15
+ |---|---|
16
+ |`main-start`|session start, after an abort, before every status report|
17
+ |`queue-check`|after changing a plan or an index, before every spawn; exit 1 = fix first|
18
+ |`agent-ledger --cap`|before every spawn|
19
+ |`agent-score`|`gate <agent>` before every spawn; `accept`/`diagnose`/`penalty` after reviewing a result; `check` after every merge; `board` after a score change|
20
+ |`brief-lint <plan.md>`|before every spawn on that plan|
21
+ |`wip-check`|session start, before new work|
22
+ |`neurastream metrics ci <repo> <mr>`|after every merge|
23
+ |`neurastream metrics report`|weekly when main-start says due; propose ONE rule change to the owner|
24
+ |`neurastream incident list --open`|session start, before status reports, when a spawn or stop is blocked|
25
+ |`machine-guard`, `heavy-run`|machine-guard at session start and before launches; every test run goes through heavy-run|
26
+
27
+ Guard files are locked for every agent; the owner unlocks with `touch {{AGENT_DIR}}/.guard-unlock` (30 min).
@@ -89,6 +89,7 @@ health:
89
89
  queue:
90
90
  archive_days: 30
91
91
  background_max_lines: 40
92
+ progress_keep: 6
92
93
  priority_id: '^[A-Z]{2}[0-9]{2}$'
93
94
  cancel_min_words: 3
94
95
  auto_close_min: 15