neurastream 0.1.14 → 0.1.16

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
@@ -124,6 +124,19 @@ Caveat: M4 is a whole-run measure. A main run counts entirely by its last write
124
124
 
125
125
  Weekly loop: run `neurastream metrics report`, then propose ONE rule change to the owner. When the owner decides, record it with `neurastream metrics rule "<text>" --approved|--rejected`; approved rules get a before/after check once a full window has passed. Record CI with `neurastream metrics ci <repo-dir> <mr-id>` and guard false alarms with `neurastream metrics false-alarm <log-ts> --why "<text>"`. main-start shows the report as due when it is missing or older than `metrics.report_days`.
126
126
 
127
+ ## Self-improvement
128
+
129
+ Bugs in neurastream itself are found by code, written to a persistent list, and pushed on Main until each one has a plan or a recorded dismissal — not remembered. The list is `<paths.queue_state>/incidents.jsonl`; `neurastream incident list [--open] [--json]` reads it.
130
+
131
+ Four sources feed it:
132
+
133
+ - Real time (at Main's prompt and after each Main bash result): a finished subagent the agent-ledger still shows RUNNING/WAITING past `incidents.contradiction_grace_min` (D1); a neurastream tool that crashed in a Main bash result (D2); the same guard block firing `incidents.block_repeat` times within one hour (D3); an owner message matching `metrics.correction_patterns` (D4). D2 and D4 run on every event; D1 and D3 read the session files and the guard logs at most once per `incidents.scan_interval_sec` (state: `incident-scan.json` in the queue state dir).
134
+ - Daily: at the first main-start or Main prompt of a day, M1-M5 for the last 24 hours against the mean of the 7 days before; a metric worse by `incidents.daily_worse_pct` and above its `incidents.daily_floor` floor is an incident.
135
+ - Weekly: when the metrics report is due, the code writes `<paths.notes>/metrics.md` itself and its worst ranked metric becomes an incident.
136
+ - Main itself: `neurastream incident add "<summary>" --kind <k>`.
137
+
138
+ While an incident is open (no plan, dismissal or fixed record), every Main prompt carries one `INCIDENT <id> [<source>/<kind>]: <summary>` line per open incident, Main's `task` spawns and bypass launches are refused unless the brief names a plan citing `INCIDENT <id>`, and Main cannot stop with an incident that has neither. The loop closes three ways: `neurastream incident plan <id> <plan.md>` (the plan must exist, be listed in its repo INDEX, cite `INCIDENT <id>`, and carry a fail-before phase — its regression test has to fail on the old code), `neurastream incident dismiss <id> --why "<text>"`, and `fixed` — written by the queue itself when it closes a plan that cites the incident. `neurastream metrics report` shows M6: incidents opened / planned / dismissed / fixed and the median hours from open to fixed.
139
+
127
140
  ## Changing a script
128
141
 
129
142
  Edit the script in this repo. Green is `bun run typecheck` and `bun test`, both exit 0. Main tags the release. The publish workflow puts that tag on npm. Then:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.1.14",
3
+ "version": "0.1.16",
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",
@@ -21,10 +21,14 @@ import { dirname, join, resolve } from "node:path";
21
21
  import { fileURLToPath } from "node:url";
22
22
  import type { Decision } from "../../core/adapter.ts";
23
23
  import { loadConfig, type Config } from "../../core/config.ts";
24
+ import { nowSec } from "../../core/clock.ts";
25
+ import { runDetectorsGated } from "../../core/incident-detectors.ts";
24
26
  import { checkInject, checkPlanEdit, checkStop, checkTool, MAIN_PLAN_FILE, recordMainResult } from "../../core/guards.ts";
25
27
  import { applyQueueEnv } from "../../core/queue/env.ts";
26
- import { mainStartText } from "../../core/main-start.ts";
28
+ import { mainStartText, runDailyCheck } from "../../core/main-start.ts";
29
+ import { readBlocks } from "../../core/metrics.ts";
27
30
  import { buildHandoff, holdsBlock, notePath, noteRequest, relaunchPath, rolloverState, spawnRefusal, type RolloverState } from "../../core/rollover.ts";
31
+ import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
28
32
  import * as q from "../../core/queue/lib.ts";
29
33
  // Registers the plugin-command matcher into core's writeTargets (side effect).
30
34
  import "./package-ops.ts";
@@ -103,6 +107,27 @@ export function adapterLog(cfg: Config, line: string): void {
103
107
  } catch {}
104
108
  }
105
109
 
110
+ /**
111
+ * Real-time incident detectors (plan 20261022_2330 P3) at Main's prompt and after each Main bash
112
+ * result, plus the once-per-day metrics check (P4, retried until it marks the day). The cheap
113
+ * detectors (D2 bash, D4 prompt) run on every call; D1/D3 and their inputs — Main's session
114
+ * file, the ledger runs, both guard logs — are gathered behind the scan interval
115
+ * (incidents.scan_interval_sec, see runDetectorsGated). Best effort: a failed check is logged,
116
+ * never thrown.
117
+ */
118
+ function mainDetectors(cfg: Config, extra: { prompt?: string; bash?: { command: string; output: string } }): void {
119
+ try {
120
+ runDetectorsGated(cfg, extra, () => ({
121
+ results: defaultCompletedResults(cfg),
122
+ runs: defaultRunSource(cfg).listRuns(nowSec() - 2 * 86400),
123
+ blocks: readBlocks(cfg),
124
+ }));
125
+ runDailyCheck(cfg, defaultRunSource(cfg), nowSec());
126
+ } catch (err) {
127
+ adapterLog(cfg, `incident detectors failed: ${err instanceof Error ? err.message : String(err)}`);
128
+ }
129
+ }
130
+
106
131
  // Background queue-close for every plan Main marked complete (owner 2026-10-15). Ported from the
107
132
  // original autoClose: same filter, same "--- auto-close attempt" log line, detached child with
108
133
  // stdio on the per-plan close log. QUEUE_CLOSE_BIN overrides the binary (tests); without it the
@@ -278,6 +303,10 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
278
303
  callsSinceStop = d.state?.callsSinceStop ?? callsSinceStop;
279
304
  idleStops = d.state?.idleStops ?? idleStops;
280
305
  const notice = rolloverNotice(ctx);
306
+ // A turn the harness starts from the guard's own stop continuation is not an owner
307
+ // message: D4 (owner-correction) only sees real prompts; D1/D3 run either way.
308
+ const prompt = asString(asRecord(event).prompt);
309
+ mainDetectors(cfg, { prompt: prompt.trimStart().startsWith("main-guard:") ? undefined : prompt });
281
310
  return {
282
311
  message: {
283
312
  customType: "main-guard.queue",
@@ -370,6 +399,13 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
370
399
  const text = content.map(p => asString(asRecord(p).text)).join("\n");
371
400
  recordMainResult(asString(e.toolName), asRecord(e.input), c.cwd ?? process.cwd(), text);
372
401
  }
402
+ // Real-time detectors after each Main bash result, crashes included (D2 wants the stack).
403
+ if ((!c.hasAgent || c.kind === "main") && asString(e.toolName) === "bash") {
404
+ const content = Array.isArray(e.content) ? e.content : [];
405
+ mainDetectors(cfg, {
406
+ bash: { command: asString(asRecord(e.input).command), output: content.map(p => asString(asRecord(p).text)).join("\n") },
407
+ });
408
+ }
373
409
  return undefined;
374
410
  });
375
411
 
@@ -522,7 +558,10 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
522
558
  return;
523
559
  }
524
560
  c.notify("main-rollover: collecting main-start state for the handoff (this can take a minute)…");
525
- const generated = [await mainStartText([], cfg, { inheritStdin: false }), holdsBlock(q.ownerHolds())].join("\n");
561
+ const generated = [
562
+ await mainStartText([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg) }),
563
+ holdsBlock(q.ownerHolds()),
564
+ ].join("\n");
526
565
  const handoff = buildHandoff({
527
566
  generated,
528
567
  note: readFileSync(path, "utf8"),
@@ -12,6 +12,7 @@ import { applyQueueEnv } from "../../core/queue/env.ts";
12
12
  import * as q from "../../core/queue/lib.ts";
13
13
  import { buildHandoff, holdsBlock, relaunchPath } from "../../core/rollover.ts";
14
14
  import { adapterLog } from "./index.ts";
15
+ import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
15
16
 
16
17
  /** The harness the launcher runs. Tests pass another path through LaunchOptions. */
17
18
  export const OMP_BIN = "omp";
@@ -144,7 +145,10 @@ async function nextMessage(req: RelaunchRequest, cfg: Config): Promise<string |
144
145
  adapterLog(cfg, `rollover: relaunch stopped, note unreadable ${req.notePath}: ${String(err)}`);
145
146
  return null;
146
147
  }
147
- const generated = [await mainStartText([], cfg, { inheritStdin: false }), holdsBlock(q.ownerHolds())].join("\n");
148
+ const generated = [
149
+ await mainStartText([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg) }),
150
+ holdsBlock(q.ownerHolds()),
151
+ ].join("\n");
148
152
  const draft = req.draft.trim() === "" ? "" : `\nOwner's unsent draft: ${req.draft}`;
149
153
  const handoff = buildHandoff({
150
154
  generated,
@@ -159,7 +159,7 @@ function build(file: string, cfg: Config, mtime: number): Run | null {
159
159
 
160
160
  const done = yielded || final;
161
161
  let state: string;
162
- if (yielded && !id.startsWith("MAIN")) state = "done";
162
+ if (!id.startsWith("MAIN") && (yielded || final)) state = "done";
163
163
  else if (!exited && !err) {
164
164
  const idle = Math.floor((nowSec() - mtime) / 60);
165
165
  state = (waiting || "RUNNING") + (idle >= cfg.ledger.idle_show_min ? ` (idle ${idle}m)` : "");
@@ -283,3 +283,59 @@ export function defaultRunSource(cfg: Config): RunSource {
283
283
  const root = cfg.adapter?.sessions || join(cfg.paths.home, ".omp", "agent", "sessions");
284
284
  return ompRunSource(root, cfg);
285
285
  }
286
+
287
+ /**
288
+ * Completed subagent task-results announced in one Main session file. Two carriers:
289
+ * `custom_message` lines of `customType` "async-result" whose content carries
290
+ * `<task-result id="X" … status="completed">` (trimmed real case:
291
+ * tests/fixtures/incidents/async-result-line.json), and `wait` toolResults — Main's `wait`
292
+ * returns the finished jobs' `<task-result …>` blocks in its text (trimmed real case:
293
+ * tests/fixtures/incidents/wait-toolresult-line.json; P3 fix B: results Main receives through
294
+ * wait were invisible here, so D1 never saw them). A line without a readable timestamp is
295
+ * skipped — without one the contradiction grace cannot be aged.
296
+ */
297
+ export function completedResults(text: string): { agent: string; ts: number }[] {
298
+ const out: { agent: string; ts: number }[] = [];
299
+ for (const line of text.split("\n")) {
300
+ const isAsync = line.includes('"async-result"');
301
+ const isWait = line.includes('"toolName":"wait"');
302
+ if (!isAsync && !isWait) continue;
303
+ let d: Record<string, unknown> | null = null;
304
+ try {
305
+ d = asObj(JSON.parse(line) as unknown);
306
+ } catch {
307
+ d = null;
308
+ }
309
+ if (!d) continue;
310
+ const ts = typeof d.timestamp === "string" ? parseTs(d.timestamp) : null;
311
+ if (ts === null) continue;
312
+ if (isAsync) {
313
+ if (d.type !== "custom_message" || d.customType !== "async-result") continue;
314
+ const content = typeof d.content === "string" ? d.content : "";
315
+ const m = /<task-result\s+id="([^"]+)"[^>]*\bstatus="completed"/.exec(content);
316
+ if (m) out.push({ agent: m[1]!, ts });
317
+ continue;
318
+ }
319
+ const m = asObj(d.message);
320
+ if (!m || m.role !== "toolResult" || m.toolName !== "wait") continue;
321
+ const content = Array.isArray(m.content)
322
+ ? m.content.map((p) => asObj(p)?.text).filter((t): t is string => typeof t === "string").join("\n")
323
+ : typeof m.content === "string"
324
+ ? m.content
325
+ : "";
326
+ for (const hit of content.matchAll(/<task-result\s+id="([^"]+)"[^>]*\bstatus="completed"/g)) {
327
+ out.push({ agent: hit[1]!, ts });
328
+ }
329
+ }
330
+ return out;
331
+ }
332
+
333
+ /** `completedResults` of the newest Main session file (the one `mainSession()` picks). */
334
+ export function defaultCompletedResults(cfg: Config): { agent: string; ts: number }[] {
335
+ try {
336
+ const s = defaultRunSource(cfg).mainSession();
337
+ return s ? completedResults(readFileSync(s.file, "utf8")) : [];
338
+ } catch {
339
+ return [];
340
+ }
341
+ }
@@ -19,6 +19,7 @@ import { wipCheck } from "../core/wip-check.ts";
19
19
  import { wipSnapshot } from "../core/wip-snapshot.ts";
20
20
  import { runtime } from "./runtime.ts";
21
21
  import { runMainLauncher } from "../adapters/omp/launch.ts";
22
+ import { defaultCompletedResults, defaultRunSource } from "../adapters/omp/sessions.ts";
22
23
 
23
24
  export const PORTED = [
24
25
  "agent-score",
@@ -74,7 +75,7 @@ export async function runPorted(cmd: string, args: string[]): Promise<number> {
74
75
  case "queue-cancel":
75
76
  return queueCancel(args, rt.cfg);
76
77
  case "main-start":
77
- return mainStart(args, rt.cfg);
78
+ return mainStart(args, rt.cfg, { source: defaultRunSource(rt.cfg), results: defaultCompletedResults(rt.cfg) });
78
79
  case "machine-guard":
79
80
  return machineGuard(args, rt.cfg);
80
81
  case "glm-reset":
@@ -6,6 +6,7 @@ import { GUARD_USAGE, runGuard } from "./guard.ts";
6
6
  import { runInit } from "./init.ts";
7
7
  import { PORTED, runMain, runPorted } from "./commands.ts";
8
8
  import { runMetrics } from "./metrics.ts";
9
+ import { runIncident } from "./incident.ts";
9
10
 
10
11
  const BINS = [
11
12
  "agent-score",
@@ -46,6 +47,7 @@ export function helpText(): string {
46
47
  ` (${GUARD_USAGE.slice(GUARD_USAGE.indexOf("(") + 1, -1)})`,
47
48
  " neurastream main [args] run omp under the launcher (automatic session rollover)",
48
49
  " neurastream metrics <cmd> self-metrics: report, ci, false-alarm, rule (see README)",
50
+ " neurastream incident <cmd> incidents Main must act on: list, add, plan, dismiss (see README)",
49
51
  "",
50
52
  "Compatibility bins (same names as today; ports land in later phases):",
51
53
  ...BINS.map(b => ` ${b}`),
@@ -63,6 +65,7 @@ export async function run(cmd: string, args: string[]): Promise<number> {
63
65
  if (cmd === "main") return runMain(args);
64
66
  if (cmd === "init") return runInit(args);
65
67
  if (cmd === "metrics") return runMetrics(args);
68
+ if (cmd === "incident") return runIncident(args);
66
69
  if (cmd === "adapter") return runAdapterInstall(args);
67
70
  if (cmd === "config") {
68
71
  try {
@@ -0,0 +1,109 @@
1
+ // `neurastream incident …`: the incident list Main must act on (store: src/core/incidents.ts).
2
+ // `list` prints incidents (--open: only the ones with no plan/dismiss/fixed yet; --json: the full
3
+ // records); `add` records Main's own finding (source "main"); `plan` records the plan that fixes
4
+ // an incident; `dismiss` records why an incident is not a bug.
5
+
6
+ import { ConfigError, loadConfig, type Config } from "../core/config.ts";
7
+ import {
8
+ addIncident,
9
+ dismissIncident,
10
+ openIncidents,
11
+ planIncident,
12
+ readIncidents,
13
+ type IncidentView,
14
+ } from "../core/incidents.ts";
15
+
16
+ export const INCIDENT_USAGE = [
17
+ "usage: neurastream incident list [--open] [--json]",
18
+ ' neurastream incident add "<summary>" --kind <k> [--evidence <text>]',
19
+ " neurastream incident plan <id> <plan.md>",
20
+ ' neurastream incident dismiss <id> --why "<text>"',
21
+ ].join("\n");
22
+
23
+ function flagValue(args: string[], name: string): string | undefined {
24
+ const i = args.indexOf(name);
25
+ return i >= 0 ? args[i + 1] : undefined;
26
+ }
27
+
28
+ /** OPEN, or the last resolution as a past-tense label. */
29
+ const STATE_LABEL = { plan: "PLANNED", dismiss: "DISMISSED", fixed: "FIXED" } as const;
30
+
31
+ function stateOf(v: IncidentView): "OPEN" | "PLANNED" | "DISMISSED" | "FIXED" {
32
+ return v.resolution ? STATE_LABEL[v.resolution.type] : "OPEN";
33
+ }
34
+
35
+ export function listIncidents(cfg: Config, args: string[]): number {
36
+ const views = args.includes("--open") ? openIncidents(cfg) : readIncidents(cfg);
37
+ if (args.includes("--json")) {
38
+ console.log(JSON.stringify(views, null, 2));
39
+ return 0;
40
+ }
41
+ for (const v of views) console.log(`${v.id} ${stateOf(v)} [${v.source}/${v.kind}] x${v.count} ${v.summary}`);
42
+ return 0;
43
+ }
44
+
45
+ export function addIncidentCmd(cfg: Config, args: string[]): number {
46
+ const summary = args[0];
47
+ const kind = flagValue(args, "--kind");
48
+ if (!summary || summary.startsWith("-") || !kind) {
49
+ console.error(INCIDENT_USAGE);
50
+ return 2;
51
+ }
52
+ const { incident, deduped } = addIncident(cfg, {
53
+ source: "main",
54
+ kind,
55
+ summary,
56
+ evidence: flagValue(args, "--evidence"),
57
+ });
58
+ if (deduped)
59
+ console.log(
60
+ `${incident.id} already open (seen x${incident.count}, last ${new Date(incident.lastSeen * 1000).toISOString()}): count and last seen updated, no new incident`,
61
+ );
62
+ else console.log(`${incident.id} recorded (open) [main/${incident.kind}]: ${incident.summary}`);
63
+ return 0;
64
+ }
65
+
66
+ export function planIncidentCmd(cfg: Config, id: string, planPath: string): number {
67
+ if (!id || !planPath) {
68
+ console.error(INCIDENT_USAGE);
69
+ return 2;
70
+ }
71
+ const why = planIncident(cfg, id, planPath);
72
+ if (why) {
73
+ console.error(why);
74
+ return 1;
75
+ }
76
+ console.log(`incident ${id}: plan recorded (${planPath})`);
77
+ return 0;
78
+ }
79
+
80
+ export function dismissIncidentCmd(cfg: Config, id: string, why: string | undefined): number {
81
+ if (!id || why === undefined) {
82
+ console.error(INCIDENT_USAGE);
83
+ return 2;
84
+ }
85
+ const problem = dismissIncident(cfg, id, why);
86
+ if (problem) {
87
+ console.error(problem);
88
+ return 1;
89
+ }
90
+ console.log(`incident ${id}: dismissed`);
91
+ return 0;
92
+ }
93
+
94
+ export async function runIncident(args: string[]): Promise<number> {
95
+ let cfg: Config;
96
+ try {
97
+ cfg = loadConfig();
98
+ } catch (err) {
99
+ console.error(err instanceof ConfigError ? err.message : String(err));
100
+ return 1;
101
+ }
102
+ const [sub = "", ...rest] = args;
103
+ if (sub === "list") return listIncidents(cfg, rest);
104
+ if (sub === "add") return addIncidentCmd(cfg, rest);
105
+ if (sub === "plan") return planIncidentCmd(cfg, rest[0] ?? "", rest[1] ?? "");
106
+ if (sub === "dismiss") return dismissIncidentCmd(cfg, rest[0] ?? "", flagValue(rest, "--why"));
107
+ console.error(INCIDENT_USAGE);
108
+ return 2;
109
+ }
@@ -63,6 +63,10 @@ export function agentLedger(args: string[], cfg: Config, source: RunSource): num
63
63
  process.stdout.write(`TOTAL ${pyFixed(tt / 1e6, 1)} Mtok, $${pyFixed(tc, 2)} list: whole-run totals of sessions active in the last ${formatG(hours)}h\n`);
64
64
 
65
65
  if (!args.includes("--cap")) return 0;
66
+ // --incident <id>: the cap check runs while Main is spawning the fix for a recorded incident;
67
+ // then OVER-BUDGET lines must not fail the cap (a ledger bug cannot block its own fix).
68
+ // Provider slots and the priority check stay binding.
69
+ const incident = opt(args, "--incident");
66
70
  const live: Record<string, string[]> = {};
67
71
  const notLive: string[] = [];
68
72
  for (const r of rows) {
@@ -105,5 +109,5 @@ export function agentLedger(args: string[], cfg: Config, source: RunSource): num
105
109
  if (prioIdle) {
106
110
  process.stdout.write(`PRIORITY IDLE: no running agent for ${idleIds.join(", ")} (owner queue PRIORITY-ID). Start it first (name must contain the ID), or spawn it with --priority.\n`);
107
111
  }
108
- return full.length || prioIdle || over.length ? 1 : 0;
112
+ return full.length || prioIdle || (over.length > 0 && incident === undefined) ? 1 : 0;
109
113
  }
@@ -87,6 +87,12 @@ function lint(path: string, cfg: Config): { errs: string[]; warns: string[] } {
87
87
  "missing: call budget line ('stop and report within ~100 calls'); long agents reread huge contexts",
88
88
  );
89
89
 
90
+ // An incident fix plan (plan 20261022_2330 P5) must ship its regression test fail-before:
91
+ // some phase's text has to say the test failed on the old code.
92
+ if (/\bINCIDENT\s+I-\d{8}-\d+\b/.test(text)) {
93
+ need(/fail-before/i.test(low), "plan cites INCIDENT <id> but no phase says 'fail-before': its regression test must fail on the old code");
94
+ }
95
+
90
96
  const keys = new Set<string>();
91
97
  for (const prefix of cfg.brief.path_prefixes) {
92
98
  const re = new RegExp(`(${escapeReg(prefix)}[\\w./\\-]*keys[\\w.\\-]*\\.txt)`, "g");
@@ -113,6 +113,19 @@ export interface Config {
113
113
  };
114
114
  rollover: { enabled: boolean; max_session_mb: number };
115
115
  metrics: { report_days: number; correction_patterns: string[]; ci_pipelines_cmd: string };
116
+ /** Incident detectors (src/core/incident-detectors.ts): when a sighting becomes an incident. */
117
+ incidents: {
118
+ /** Minutes after a finished task-result before a RUNNING/WAITING ledger row contradicts it. */
119
+ contradiction_grace_min: number;
120
+ /** Same guard BLOCK reason within one hour that means a block loop. */
121
+ block_repeat: number;
122
+ /** Seconds between scans of the expensive detectors (D1 ledger, D3 block loop). */
123
+ scan_interval_sec: number;
124
+ /** A daily metric must be worse than the 7-day mean by at least this percent. */
125
+ daily_worse_pct: number;
126
+ /** Per-metric daily floors (keys: m1, m2, m3, m4_corrections, m4_questions, m5): a regression below the floor is noise. */
127
+ daily_floor: Record<string, number>;
128
+ };
116
129
  machine: {
117
130
  load_over_cores: number;
118
131
  load_max: number;
@@ -13,12 +13,16 @@
13
13
  // - main: 5 project-file changes per `main_window_min` window (owner message resets), spawn
14
14
  // gate (allow-list, task-only, open plan, new Progress since last run), bypass launches go
15
15
  // through the same plan gate, cancel-pending blocks spawns and stops, keep-working stop rule
16
+ // - incidents: while an incident is open (src/core/incidents.ts: no plan/dismiss/fixed record)
17
+ // every Main prompt lists it, a spawn must be fix work (its plan cites `INCIDENT <id>`), and
18
+ // the stop is refused; an incident with a plan no longer blocks (owner 2026-10-22)
16
19
 
17
20
  import { execFileSync } from "node:child_process";
18
21
  import { appendFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
19
22
  import path from "node:path";
20
23
  import type { Decision, InjectEvent, PlanEditEvent, SpawnEvent, StopEvent, ToolEvent } from "./adapter.ts";
21
24
  import type { Config } from "./config.ts";
25
+ import { openIncidents, type IncidentView } from "./incidents.ts";
22
26
  import * as q from "./queue/lib.ts";
23
27
  import type { Plan } from "./queue/lib.ts";
24
28
 
@@ -28,7 +32,8 @@ function deny(reason: string): Decision {
28
32
  return { allow: false, reason };
29
33
  }
30
34
 
31
- function log(file: string, line: string): void {
35
+ /** Guard-log line, `<ISO UTC> <line>`; a failed append is swallowed. */
36
+ export function log(file: string, line: string): void {
32
37
  try {
33
38
  appendFileSync(file, `${new Date().toISOString()} ${line}\n`);
34
39
  } catch {}
@@ -302,6 +307,50 @@ function editWindow(e: ToolEvent, input: Record<string, unknown>, cfg: Config):
302
307
  return ALLOW;
303
308
  }
304
309
 
310
+ // --- incidents (src/core/incidents.ts): open ones push Main until each has a plan or dismissal ---
311
+
312
+ function openIncidentList(cfg: Config): IncidentView[] {
313
+ try {
314
+ return openIncidents(cfg);
315
+ } catch (err) {
316
+ log(cfg.paths.guard_log, `cannot read incidents: ${err}`);
317
+ return [];
318
+ }
319
+ }
320
+
321
+ /** The injected prompt line for one open incident, with the two ways to clear it. */
322
+ export function incidentLine(i: IncidentView): string {
323
+ return (
324
+ `INCIDENT ${i.id} [${i.source}/${i.kind}]: ${i.summary} — plan the fix: \`neurastream incident plan ${i.id} <plan.md>\`` +
325
+ ` (the plan must contain "INCIDENT ${i.id}"), or dismiss: \`neurastream incident dismiss ${i.id} --why "<text>"\``
326
+ );
327
+ }
328
+
329
+ /**
330
+ * While an incident is open, a launch must be fix work: its brief (or a plan the brief names)
331
+ * cites `INCIDENT <id>` of an open incident. Anything else is refused until every open incident
332
+ * has a plan or a dismissal. Returns the refusal reason, or null; `label` names the log line.
333
+ */
334
+ function incidentSpawnProblem(label: string, brief: string, namedPlans: string[], cfg: Config): string | null {
335
+ const open = openIncidentList(cfg);
336
+ if (!open.length) return null;
337
+ const texts = [brief];
338
+ for (const f of namedPlans) {
339
+ try {
340
+ texts.push(readFileSync(f, "utf8"));
341
+ } catch {}
342
+ }
343
+ const remaining = open.filter(i => !texts.some(t => t.includes(`INCIDENT ${i.id}`)));
344
+ if (!remaining.length) return null;
345
+ const ids = remaining.map(i => i.id).join(", ");
346
+ log(cfg.paths.guard_log, `BLOCK ${label}: open incidents: ${ids}`);
347
+ return (
348
+ `open incident(s) ${ids} must be acted on before other work. Write a plan that contains "INCIDENT <id>" ` +
349
+ `(listed in its repo INDEX.md) and record it: \`neurastream incident plan <id> <plan.md>\`, or dismiss the ` +
350
+ 'incident: `neurastream incident dismiss <id> --why "<text>"`. Fix work goes through: name that plan in the brief.'
351
+ );
352
+ }
353
+
305
354
  function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): Decision {
306
355
  if (e.tool === "task") {
307
356
  const pending = q.cancelPending();
@@ -315,6 +364,8 @@ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): De
315
364
  log(cfg.paths.guard_log, `BLOCK spawn: ${why}`);
316
365
  return deny(`main-guard: ${why}`);
317
366
  }
367
+ const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
368
+ if (inc) return deny(`main-guard: ${inc}`);
318
369
  recordSpawns(files);
319
370
  return ALLOW;
320
371
  }
@@ -332,6 +383,8 @@ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): De
332
383
  log(cfg.paths.guard_log, `BLOCK bypass launch: ${why}`);
333
384
  return deny(`main-guard: ${why}`);
334
385
  }
386
+ const inc = incidentSpawnProblem("bypass launch", command, named, cfg);
387
+ if (inc) return deny(`main-guard: ${inc}`);
335
388
  if (named.length) recordSpawns(named);
336
389
  }
337
390
  }
@@ -455,6 +508,8 @@ export function checkSpawn(e: SpawnEvent, cfg: Config): Decision {
455
508
  log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${why}`);
456
509
  return deny(`main-guard: ${why}`);
457
510
  }
511
+ const inc = incidentSpawnProblem(`spawn ${e.agent}`, e.brief, named, cfg);
512
+ if (inc) return deny(`main-guard: ${inc}`);
458
513
  recordSpawns(named);
459
514
  return ALLOW;
460
515
  }
@@ -478,8 +533,9 @@ export function flagCancel(text: string, cfg: Config): string {
478
533
  }
479
534
 
480
535
  /**
481
- * prompt/owner message: inject the queue summary, flag cancel wording, reset Main's edit window
482
- * and the stop counters (the original resets them at every user message). A turn the harness
536
+ * prompt/owner message: inject the queue summary, flag cancel wording, list open incidents, reset
537
+ * Main's edit window and the stop counters (the original resets them at every user message). A
538
+ * turn the harness
483
539
  * starts from this guard's own stop continuation ("main-guard: …") is not an owner message: it
484
540
  * keeps the counters and the edit window, else every continuation reset the idle streak and a
485
541
  * model that only answers text was nudged again forever (2026-10-21 OOM: ~205 agent starts in one
@@ -496,10 +552,12 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
496
552
  summary = `Queue unreadable (${q.INDEX}): ${err}`;
497
553
  }
498
554
  const cancel = continuation ? "" : flagCancel(e.inject, cfg);
555
+ const incidents = openIncidentList(cfg);
556
+ const incidentText = incidents.length ? `\n${incidents.map(incidentLine).join("\n")}` : "";
499
557
  return {
500
558
  allow: true,
501
559
  reason: "",
502
- 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}`,
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}`,
503
561
  ...(continuation ? {} : { state: { callsSinceStop: 0, idleStops: 0 } }),
504
562
  };
505
563
  }
@@ -624,7 +682,8 @@ export function liveSubagents(ledgerOut: string): string[] {
624
682
 
625
683
  /**
626
684
  * stop: Main may not stop while an open plan is not parked "WAITING on owner" (or the queue has a
627
- * problem) and no subagent is alive to wake it. Three stop attempts in a row with zero tool calls
685
+ * problem) and no subagent is alive to wake it; an open incident (no plan, no dismissal) blocks
686
+ * the stop regardless of live subagents. Three stop attempts in a row with zero tool calls
628
687
  * in between are let through. Returns the next counters in `state`.
629
688
  */
630
689
  export function checkStop(e: StopEvent, cfg: Config): Decision {
@@ -644,6 +703,23 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
644
703
  log(cfg.paths.guard_log, `BLOCK stop: cancel pending (${pending.words})`);
645
704
  return { allow: false, reason: `main-guard: ${CANCEL_TODO} Flagged: "${pending.words}"`, state };
646
705
  }
706
+ // Same release valve as cancel-pending: an idle Main that cannot act is let out after two
707
+ // empty stop attempts instead of looping forever. Live subagents do not clear this block.
708
+ const incidents = openIncidentList(cfg);
709
+ if (incidents.length && state.idleStops < 2) {
710
+ if (state.callsSinceStop === 0) state.idleStops++;
711
+ state.callsSinceStop = 0;
712
+ const ids = incidents.map(i => i.id).join(", ");
713
+ log(cfg.paths.guard_log, `BLOCK stop: open incidents: ${ids}`);
714
+ return {
715
+ allow: false,
716
+ reason:
717
+ `main-guard: ${incidents.length} open incident(s) with no plan and no dismissal: ${ids}. Plan the fix: ` +
718
+ "`neurastream incident plan <id> <plan.md>` (the plan must contain \"INCIDENT <id>\"), or dismiss it: " +
719
+ '`neurastream incident dismiss <id> --why "<text>"`. The stop stays refused while an incident is open.',
720
+ state,
721
+ };
722
+ }
647
723
  if (open.length === 0) return { ...ALLOW, state };
648
724
  if (liveSubagents(e.ledgerText).length > 0) {
649
725
  log(cfg.paths.guard_log, "ALLOW stop: live subagents");