neurastream 0.1.26 → 0.1.28

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
@@ -105,6 +105,9 @@ A relaunch keeps the flags of the first run (`--model`, `--session-dir`, …) an
105
105
 
106
106
  In both modes:
107
107
 
108
+ - If omp does not exit within `rollover.exit_grace_s` seconds (default 20, `docs/config.md`) after a relaunch was requested, the adapter stops waiting and rolls over in-process: the fresh session opens in the same process and carries the owner's typed messages in its handoff. A real shutdown (`session_shutdown`) cancels the fallback.
109
+ - The relaunch is requested only when Main's run has really ended: a tool result mid-run never restarts the session, and while a relaunch is pending every later terminal run end calls `shutdown()` again (omp re-checks its deferred exit only then).
110
+ - The launcher prints one stderr line while it collects the handoff state (`neurastream: starting a new session from the handoff (collecting state, about a minute)…`) and removes the request only after the handoff message is built; a fresh `neurastream main` with no message of its own continues an interrupted rollover whose request is at most one hour old.
108
111
  - A note counts only if it was written after the threshold was crossed and is at most one hour old.
109
112
  - The running plugin going stale counts as over the threshold too: at every check the adapter re-reads the `package.json` it was loaded from, and a different (or unreadable) version asks for the handoff note even below `rollover.max_session_mb`, naming both versions (`NEURASTREAM_PACKAGE_JSON` overrides the path it watches).
110
113
  - While a rollover is pending (no fresh note, own jobs still running, or the handoff is ready and waiting for idle), Main cannot start new subagents: a `task` call is refused until the running jobs finish and the session rolls over.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.1.26",
3
+ "version": "0.1.28",
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",
@@ -17,8 +17,7 @@
17
17
 
18
18
  import { execFileSync, spawn } from "node:child_process";
19
19
  import { appendFileSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
20
- import { dirname, join, resolve } from "node:path";
21
- import { fileURLToPath } from "node:url";
20
+ import { dirname, join } from "node:path";
22
21
  import type { Decision } from "../../core/adapter.ts";
23
22
  import { loadConfig, type Config } from "../../core/config.ts";
24
23
  import { nowSec } from "../../core/clock.ts";
@@ -27,8 +26,9 @@ import { checkInject, checkPlanEdit, checkStop, checkTool, MAIN_PLAN_FILE, recor
27
26
  import { applyQueueEnv } from "../../core/queue/env.ts";
28
27
  import { mainStartText, runDailyCheck } from "../../core/main-start.ts";
29
28
  import { readBlocks } from "../../core/metrics.ts";
30
- import { buildHandoff, holdsBlock, notePath, noteRequest, ownerText, relaunchPath, rolloverState, spawnRefusal, type RolloverState } from "../../core/rollover.ts";
29
+ import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, type RolloverState } from "../../core/rollover.ts";
31
30
  import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
31
+ import { packageJsonPath, packageVersion } from "./package-root.ts";
32
32
  import * as q from "../../core/queue/lib.ts";
33
33
  // Registers the plugin-command matcher into core's writeTargets (side effect).
34
34
  import "./package-ops.ts";
@@ -85,21 +85,7 @@ export function toExtensionResult(d: Decision): Record<string, unknown> {
85
85
  // A push or merge by Main may have landed a completed plan: try closing right away.
86
86
  const PUSH_MERGE = /\bgit\b[^\n;|&]*\bpush\b|\b(glab\s+mr|gh\s+pr)\s+merge\b/;
87
87
 
88
- // The installed copy this plugin comes from (computed as in doctor.ts) and the package.json whose
89
- // version decides staleness. omp never reloads a plugin, so the version is read once at adapter
90
- // start (the code actually running) and re-read at every rollover check; a different or unreadable
91
- // version means the running plugin is stale. NEURASTREAM_PACKAGE_JSON overrides the path (tests
92
- // and the sandbox smoke point it at a copy whose version changes mid-run), like QUEUE_CLOSE_BIN.
93
- const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
94
-
95
- function packageVersion(packageJson: string): string | null {
96
- try {
97
- const version = asRecord(JSON.parse(readFileSync(packageJson, "utf8"))).version;
98
- return typeof version === "string" ? version : null;
99
- } catch {
100
- return null;
101
- }
102
- }
88
+ // The installed package and its version: see ./package-root.ts.
103
89
 
104
90
  export function adapterLog(cfg: Config, line: string): void {
105
91
  try {
@@ -378,7 +364,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
378
364
  };
379
365
 
380
366
  pi.on("tool_result", (event, ctx) => {
381
- onSizeCheck(event, ctx);
367
+ onSizeCheck("tool_result", event, ctx);
382
368
  const e = asRecord(event);
383
369
  const c = asCtx(ctx);
384
370
  const id = asString(e.toolCallId);
@@ -458,7 +444,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
458
444
  // once. The size and the installed version are re-read at every turn end and tool result; the
459
445
  // note request goes out once per session file and note state.
460
446
  // The version this process loaded at start: the plugin code that is actually running.
461
- const loadedVersion = packageVersion(process.env.NEURASTREAM_PACKAGE_JSON ?? join(PACKAGE_ROOT, "package.json"));
447
+ const loadedVersion = packageVersion(packageJsonPath());
462
448
  let crossed: { file: string; atMs: number } | null = null;
463
449
  // The note request already sent, keyed by session file + note mtime at send time ("none" when
464
450
  // no note exists): a note that expires while jobs run falls back to need-note with a key no
@@ -471,7 +457,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
471
457
  const bytes = sizeOf(c.sessionFile);
472
458
  const maxMb = cfg.rollover.max_session_mb;
473
459
  const noteMtimeMs = mtimeOf(notePath(c.sessionId));
474
- const liveVersion = packageVersion(process.env.NEURASTREAM_PACKAGE_JSON ?? join(PACKAGE_ROOT, "package.json"));
460
+ const liveVersion = packageVersion(packageJsonPath());
475
461
  const stale = liveVersion === null || loadedVersion === null || liveVersion !== loadedVersion;
476
462
  if (stale) {
477
463
  // Note freshness is measured against the crossing: a stale session counts as crossed
@@ -502,6 +488,67 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
502
488
  };
503
489
 
504
490
  let relaunched = false;
491
+ // omp 18.11.1 defers an extension shutdown: it re-checks only when shutdown() is called again or
492
+ // an owner submission finishes, so a refused exit once left a dead UI that swallowed every owner
493
+ // message (I-20261024-4). One unref'd timer per request: if omp still has not exited
494
+ // rollover.exit_grace_s after the request, the adapter rolls over in-process. The timer keeps its
495
+ // own clearer: session_shutdown cancels the fallback when omp really exits.
496
+ let clearGrace: (() => void) | null = null;
497
+ const armGraceTimer = (c: RolloverCtx): void => {
498
+ clearGrace?.();
499
+ const t = setTimeout(() => {
500
+ clearGrace = null;
501
+ exitGraceElapsed(c);
502
+ }, cfg.rollover.exit_grace_s * 1000);
503
+ if (t && typeof t === "object" && "unref" in t && typeof t.unref === "function") t.unref();
504
+ clearGrace = () => {
505
+ clearTimeout(t);
506
+ clearGrace = null;
507
+ };
508
+ };
509
+
510
+ // One /main-rollover at a time: while one waits for idle, a second call adds its text to the owner message.
511
+ let flight: string[] | null = null;
512
+
513
+ // The one in-process rollover, shared by /main-rollover and the exit-grace fallback: gather the
514
+ // generated state, wait for idle, then start a fresh session whose first message is the handoff.
515
+ // A state change during the wait sends the owner's text to this session as an ordinary message.
516
+ const rolloverInProcess = async (c: RolloverCtx, owner: string[], notice: string): Promise<void> => {
517
+ const previous = c.sessionFile;
518
+ const path = notePath(c.sessionId);
519
+ flight = owner;
520
+ try {
521
+ c.notify(notice);
522
+ const generated = [
523
+ await mainStartText([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg) }),
524
+ holdsBlock(q.ownerHolds()),
525
+ ].join("\n");
526
+ const note = readFileSync(path, "utf8");
527
+ adapterLog(cfg, `rollover: new session from ${previous}; note ${path}`);
528
+ await c.waitForIdle();
529
+ const again = rolloverSnapshot(c).state;
530
+ if (relaunched || again !== "ready") {
531
+ c.notify(`main-rollover: the state changed while waiting for idle (${relaunched ? "relaunch requested" : again}); no new session.`);
532
+ // The owner's text is not lost: it goes to this session as an ordinary message.
533
+ const pending = owner.filter(s => s !== "").join("\n");
534
+ if (pending !== "") pi.sendUserMessage(pending);
535
+ return;
536
+ }
537
+ const r = asRecord(await c.newSession({ parentSession: previous }));
538
+ if (r.cancelled === true) return;
539
+ // Read after the await: owner messages that arrived during newSession are part of the handoff.
540
+ const handoff = buildHandoff({
541
+ generated,
542
+ note,
543
+ previousSessionFile: previous,
544
+ ownerMessage: owner.filter(s => s !== "").join("\n"),
545
+ });
546
+ pi.sendUserMessage(handoff);
547
+ } finally {
548
+ flight = null;
549
+ }
550
+ };
551
+
505
552
  // The launcher restarts omp: the request file carries the note and the editor draft, and omp
506
553
  // shuts down only after the file is written. A failed write keeps the session running.
507
554
  // Returns whether the request was written.
@@ -516,6 +563,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
516
563
  relaunched = true;
517
564
  adapterLog(cfg, `rollover: relaunch requested from ${c.sessionFile}`);
518
565
  c.shutdown();
566
+ armGraceTimer(c);
519
567
  return true;
520
568
  };
521
569
 
@@ -535,22 +583,49 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
535
583
  }
536
584
  };
537
585
 
538
- const onSizeCheck = (_e: unknown, ctx: unknown): void => {
586
+ // The grace elapsed without a session_shutdown: omp refused the exit. Read the request's draft,
587
+ // drop the request and roll over here, so the owner's messages reach a live session instead of a
588
+ // dead UI. The owner-away text stands in when nothing was typed.
589
+ const exitGraceElapsed = (c: RolloverCtx): void => {
590
+ adapterLog(cfg, `rollover: omp did not exit within ${cfg.rollover.exit_grace_s}s; rolling over in-process`);
591
+ let draft = "";
592
+ try {
593
+ draft = asString(asRecord(JSON.parse(readFileSync(relaunchPath(), "utf8"))).draft);
594
+ } catch {}
595
+ rmSync(relaunchPath(), { force: true });
596
+ relaunched = false;
597
+ rolloverInProcess(c, [draft.trim() === "" ? OWNER_AWAY : draft], "rollover: omp did not restart; continuing in a new session here").catch((err: unknown) => {
598
+ adapterLog(cfg, `rollover: in-process rollover failed: ${err instanceof Error ? err.message : String(err)}`);
599
+ });
600
+ };
601
+
602
+ const onSizeCheck = (kind: "tool_result" | "agent_end", e: unknown, ctx: unknown): void => {
539
603
  const c = asRolloverCtx(ctx);
540
604
  if (!cfg.rollover.enabled || !c || !isMain(ctx)) return;
541
605
  const snap = rolloverSnapshot(c);
542
606
  const key = `${c.sessionFile}:${snap.noteMtimeMs ?? "none"}`;
607
+ // A terminal run end: omp 18.11.1 sets willContinue on a non-terminal agent_end.
608
+ const terminal = kind === "agent_end" && asRecord(e).willContinue !== true;
543
609
  if (snap.state === "need-note" && asked !== key) {
544
610
  asked = key;
545
611
  pi.sendMessage(
546
612
  { customType: "main-guard.rollover", content: noteRequestFor(c, snap), display: false },
547
613
  { triggerTurn: true, deliverAs: "nextTurn" },
548
614
  );
549
- } else if (snap.state === "ready" && process.env.NEURASTREAM_MAIN_LAUNCHER === "1" && !relaunched) {
615
+ } else if (terminal && snap.state === "ready" && process.env.NEURASTREAM_MAIN_LAUNCHER === "1" && !relaunched && flight === null) {
616
+ // flight !== null: an in-process rollover (fallback or /main-rollover) owns this session's end.
550
617
  requestRelaunch(c, notePath(c.sessionId));
618
+ } else if (terminal && relaunched) {
619
+ // A tool result mid-run never restarts the session (I-20261024-4), and omp's interactive
620
+ // mode re-runs its deferred exit check only when shutdown() is called again: re-arm at
621
+ // every later terminal run end instead of waiting for an owner message.
622
+ c.shutdown();
551
623
  }
552
624
  };
553
- pi.on("agent_end", onSizeCheck);
625
+ pi.on("agent_end", (e, ctx) => onSizeCheck("agent_end", e, ctx));
626
+
627
+ // omp is really shutting down: the exit-grace fallback must not fire.
628
+ pi.on("session_shutdown", () => clearGrace?.());
554
629
 
555
630
  // Compaction keeps the owner's holds true: a summary may state a hold only as a plans' WAITING on owner line says it.
556
631
  pi.on("session.compacting", (_e, ctx) => {
@@ -595,6 +670,8 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
595
670
  }
596
671
  if (appendToRelaunch(text)) c.notify("rollover in progress: your message goes to the new session");
597
672
  else c.notify("rollover in progress: your message could not be saved and was not sent; send it again after the rollover");
673
+ // omp re-checks its deferred exit only when shutdown() is called again: re-arm per message.
674
+ c.shutdown();
598
675
  return { handled: true };
599
676
  }
600
677
  if (rolloverSnapshot(c).state !== "ready") return undefined;
@@ -602,7 +679,6 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
602
679
  });
603
680
 
604
681
  // One /main-rollover at a time: while one waits for idle, a second call adds its text to the owner message.
605
- let flight: string[] | null = null;
606
682
  pi.registerCommand("main-rollover", {
607
683
  description: "Start a fresh session from Main's handoff note; the rest of the message is the owner's first message",
608
684
  handler: async (args: unknown, ctx: unknown) => {
@@ -632,39 +708,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
632
708
  c.notify(`main-rollover: own jobs are still running (${c.runningJobs().join(", ")}); a rollover would cancel them.`);
633
709
  return;
634
710
  }
635
- const previous = c.sessionFile;
636
- const owner = [text];
637
- flight = owner;
638
- try {
639
- c.notify("main-rollover: collecting main-start state for the handoff (this can take a minute)…");
640
- const generated = [
641
- await mainStartText([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg) }),
642
- holdsBlock(q.ownerHolds()),
643
- ].join("\n");
644
- const note = readFileSync(path, "utf8");
645
- adapterLog(cfg, `rollover: new session from ${previous}; note ${path}`);
646
- await c.waitForIdle();
647
- const again = rolloverSnapshot(c).state;
648
- if (relaunched || again !== "ready") {
649
- c.notify(`main-rollover: the state changed while waiting for idle (${relaunched ? "relaunch requested" : again}); no new session.`);
650
- // The owner's text is not lost: it goes to this session as an ordinary message.
651
- const pending = owner.filter(s => s !== "").join("\n");
652
- if (pending !== "") pi.sendUserMessage(pending);
653
- return;
654
- }
655
- const r = asRecord(await c.newSession({ parentSession: previous }));
656
- if (r.cancelled === true) return;
657
- // Read after the await: owner messages that arrived during newSession are part of the handoff.
658
- const handoff = buildHandoff({
659
- generated,
660
- note,
661
- previousSessionFile: previous,
662
- ownerMessage: owner.filter(s => s !== "").join("\n"),
663
- });
664
- pi.sendUserMessage(handoff);
665
- } finally {
666
- flight = null;
667
- }
711
+ await rolloverInProcess(c, [text], "main-rollover: collecting main-start state for the handoff (this can take a minute)…");
668
712
  },
669
713
  });
670
714
  }
@@ -10,8 +10,9 @@ import type { Config } from "../../core/config.ts";
10
10
  import { mainStartText } from "../../core/main-start.ts";
11
11
  import { applyQueueEnv } from "../../core/queue/env.ts";
12
12
  import * as q from "../../core/queue/lib.ts";
13
- import { buildHandoff, holdsBlock, relaunchPath } from "../../core/rollover.ts";
13
+ import { buildHandoff, holdsBlock, MAX_NOTE_AGE_MS, OWNER_AWAY, relaunchPath } from "../../core/rollover.ts";
14
14
  import { adapterLog } from "./index.ts";
15
+ import { PACKAGE_ROOT, packageJsonPath, packageVersion } from "./package-root.ts";
15
16
  import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
16
17
 
17
18
  /** The harness the launcher runs. Tests pass another path through LaunchOptions. */
@@ -67,11 +68,26 @@ export function carriedArgs(args: string[]): string[] {
67
68
  /** Handoffs up to this many bytes go in the first message; larger ones go to a file. */
68
69
  const MAX_INLINE_HANDOFF = 100_000;
69
70
 
70
- const OWNER_AWAY =
71
- "Owner away (automatic rollover). Continue the work in the note and the queue; the owner reads results later.";
71
+ /** Printed before the launcher builds a handoff: main-start collects state, which takes about a minute. */
72
+ const HANDOFF_PENDING_LINE = "neurastream: starting a new session from the handoff (collecting state, about a minute)…";
73
+
74
+ /** Whether `args` carry a positional (the first message): flags with their values do not count. */
75
+ function hasPositional(args: string[]): boolean {
76
+ for (let i = 0; i < args.length; i++) {
77
+ const arg = args[i] ?? "";
78
+ if (arg === "--") return true;
79
+ if (!arg.startsWith("-")) return true;
80
+ const eq = arg.indexOf("=");
81
+ const flag = eq === -1 ? arg : arg.slice(0, eq);
82
+ if (eq === -1 && takesValue(flag, args[i + 1])) i++;
83
+ }
84
+ return false;
85
+ }
72
86
 
73
87
  export interface LaunchOptions {
74
88
  harness?: string;
89
+ /** The main-start text generator for the handoff (default: src/core/main-start.ts). Tests inject a failing one. */
90
+ mainStart?: typeof mainStartText;
75
91
  }
76
92
 
77
93
  interface RelaunchRequest {
@@ -80,40 +96,89 @@ interface RelaunchRequest {
80
96
  draft: string;
81
97
  }
82
98
 
83
- /** Runs the harness until a run ends without a fresh relaunch request; returns the last run's code. */
99
+ /**
100
+ * Runs the harness until a run ends without a fresh relaunch request; returns the last run's code.
101
+ * The launcher keeps the version it loaded. When the package on disk has another version (or either
102
+ * is unreadable) by the time a run leaves a request, that request goes to a fresh launcher started
103
+ * from the package on disk: the handoff is then built with the installed code, not the old code.
104
+ */
84
105
  export async function runMainLauncher(args: string[], cfg: Config, opts: LaunchOptions = {}): Promise<number> {
85
106
  applyQueueEnv(cfg);
86
107
  const harness = opts.harness ?? OMP_BIN;
108
+ const mainStart = opts.mainStart ?? mainStartText;
87
109
  const carried = carriedArgs(args);
110
+ const loaded = packageVersion(packageJsonPath());
111
+ // Set only in a fresh launcher the previous one started: its first step is the request that run left.
112
+ const handedOver = process.env.NEURASTREAM_RELAUNCH_SINCE;
113
+ delete process.env.NEURASTREAM_RELAUNCH_SINCE;
88
114
  let runArgs = args;
115
+ const since = handedOver === undefined ? Number.NaN : Number(handedOver);
116
+ if (Number.isFinite(since)) {
117
+ const req = readRequest(since, cfg);
118
+ if (req !== null) {
119
+ console.error(HANDOFF_PENDING_LINE);
120
+ const message = await nextMessage(req, cfg, mainStart);
121
+ if (message === null) return 1;
122
+ // The request is removed only once its message exists: a kill during main-start
123
+ // (I-20261024-4) must leave it for the next launcher to continue.
124
+ rmSync(relaunchPath(), { force: true });
125
+ runArgs = [...carried, message];
126
+ }
127
+ } else if (!hasPositional(args)) {
128
+ // A fresh start with no message of its own continues a rollover a killed launcher left
129
+ // behind: the request counts while it is at most MAX_NOTE_AGE_MS old, like a note. An
130
+ // older or unreadable one is left alone.
131
+ const req = readRequest(Date.now() - MAX_NOTE_AGE_MS, cfg);
132
+ if (req !== null) {
133
+ console.error(`neurastream: continuing the interrupted rollover from ${req.previousSessionFile}`);
134
+ console.error(HANDOFF_PENDING_LINE);
135
+ const message = await nextMessage(req, cfg, mainStart);
136
+ if (message !== null) {
137
+ rmSync(relaunchPath(), { force: true });
138
+ runArgs = [...carried, message];
139
+ }
140
+ }
141
+ }
89
142
  for (;;) {
90
- rmSync(relaunchPath(), { force: true });
91
143
  const started = Date.now();
92
- const code = await runChild(harness, runArgs);
93
- const req = takeRequest(started, cfg);
144
+ const code = await runChild(harness, runArgs, { ...process.env, NEURASTREAM_MAIN_LAUNCHER: "1" });
145
+ const req = readRequest(started, cfg);
94
146
  if (req === null) return code;
95
- const message = await nextMessage(req, cfg);
147
+ const installed = packageVersion(packageJsonPath());
148
+ const changed = loaded === null || installed === null || loaded !== installed;
149
+ if (changed && noteReadable(req.notePath)) {
150
+ adapterLog(cfg, `rollover: relaunch handed to a fresh launcher (${loaded ?? "unknown"} → ${installed ?? "unknown"})`);
151
+ return runChild(process.execPath, [join(PACKAGE_ROOT, "src", "cli", "main.ts"), "main", ...carried], {
152
+ ...process.env,
153
+ NEURASTREAM_RELAUNCH_SINCE: String(started),
154
+ });
155
+ }
156
+ console.error(HANDOFF_PENDING_LINE);
157
+ const message = await nextMessage(req, cfg, mainStart);
96
158
  if (message === null) return code;
159
+ rmSync(relaunchPath(), { force: true });
97
160
  runArgs = [...carried, message];
98
161
  }
99
162
  }
100
163
 
101
- function runChild(harness: string, args: string[]): Promise<number> {
164
+ /** Runs a command with inherited stdio; resolves to its exit code (127 when it cannot start). */
165
+ function runChild(cmd: string, args: string[], env: NodeJS.ProcessEnv): Promise<number> {
102
166
  const { promise, resolve } = Promise.withResolvers<number>();
103
- const child = spawn(harness, args, {
104
- stdio: "inherit",
105
- env: { ...process.env, NEURASTREAM_MAIN_LAUNCHER: "1" },
106
- });
167
+ const child = spawn(cmd, args, { stdio: "inherit", env });
107
168
  child.on("error", err => {
108
- console.error(`neurastream main: cannot start ${harness}: ${err.message}`);
169
+ console.error(`neurastream main: cannot start ${cmd}: ${err.message}`);
109
170
  resolve(127);
110
171
  });
111
172
  child.on("close", code => resolve(code ?? 1));
112
173
  return promise;
113
174
  }
114
175
 
115
- /** The request the last run left behind, only if it was written during that run; consumed on read. */
116
- function takeRequest(since: number, cfg: Config): RelaunchRequest | null {
176
+ /**
177
+ * The request the last run left behind, only if it was written during that run (mtime at or after
178
+ * `since`). Not consumed: the caller removes it once it has decided to use it. A request without the
179
+ * required fields is removed and logged; an unreadable one is logged and left in place.
180
+ */
181
+ function readRequest(since: number, cfg: Config): RelaunchRequest | null {
117
182
  const path = relaunchPath();
118
183
  let mtimeMs: number;
119
184
  try {
@@ -122,22 +187,33 @@ function takeRequest(since: number, cfg: Config): RelaunchRequest | null {
122
187
  return null;
123
188
  }
124
189
  if (mtimeMs < since) return null;
190
+ let raw: Partial<RelaunchRequest>;
125
191
  try {
126
- const raw = JSON.parse(readFileSync(path, "utf8")) as Partial<RelaunchRequest>;
127
- rmSync(path, { force: true });
128
- if (typeof raw.previousSessionFile !== "string" || typeof raw.notePath !== "string") {
129
- adapterLog(cfg, `rollover: relaunch request ignored, missing fields in ${path}`);
130
- return null;
131
- }
132
- return { previousSessionFile: raw.previousSessionFile, notePath: raw.notePath, draft: raw.draft ?? "" };
192
+ raw = JSON.parse(readFileSync(path, "utf8")) as Partial<RelaunchRequest>;
133
193
  } catch (err) {
134
194
  adapterLog(cfg, `rollover: relaunch request ignored, unreadable ${path}: ${String(err)}`);
135
195
  return null;
136
196
  }
197
+ if (typeof raw.previousSessionFile !== "string" || typeof raw.notePath !== "string") {
198
+ rmSync(path, { force: true });
199
+ adapterLog(cfg, `rollover: relaunch request ignored, missing fields in ${path}`);
200
+ return null;
201
+ }
202
+ return { previousSessionFile: raw.previousSessionFile, notePath: raw.notePath, draft: raw.draft ?? "" };
203
+ }
204
+
205
+ /** Whether the handoff note can be read now: a launcher cannot relaunch without it. */
206
+ function noteReadable(path: string): boolean {
207
+ try {
208
+ readFileSync(path, "utf8");
209
+ return true;
210
+ } catch {
211
+ return false;
212
+ }
137
213
  }
138
214
 
139
215
  /** The next run's message: the handoff inline, or the pointer to a file that holds it. */
140
- async function nextMessage(req: RelaunchRequest, cfg: Config): Promise<string | null> {
216
+ async function nextMessage(req: RelaunchRequest, cfg: Config, mainStart: typeof mainStartText): Promise<string | null> {
141
217
  let note: string;
142
218
  try {
143
219
  note = readFileSync(req.notePath, "utf8");
@@ -145,10 +221,18 @@ async function nextMessage(req: RelaunchRequest, cfg: Config): Promise<string |
145
221
  adapterLog(cfg, `rollover: relaunch stopped, note unreadable ${req.notePath}: ${String(err)}`);
146
222
  return null;
147
223
  }
148
- const generated = [
149
- await mainStartText([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg) }),
150
- holdsBlock(q.ownerHolds()),
151
- ].join("\n");
224
+ let generated: string;
225
+ try {
226
+ generated = [
227
+ await mainStart([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg) }),
228
+ holdsBlock(q.ownerHolds()),
229
+ ].join("\n");
230
+ } catch (err) {
231
+ // A failing main-start must not cost the owner the note: the handoff says it failed.
232
+ const first = (err instanceof Error ? err.message : String(err)).split("\n")[0] ?? "";
233
+ adapterLog(cfg, `rollover: main-start failed: ${first}`);
234
+ generated = `main-start failed during the rollover (${first}); run main-start yourself.`;
235
+ }
152
236
  const draft = req.draft.trim() === "" ? "" : `\nOwner's messages during the rollover (and any unsent draft): ${req.draft}`;
153
237
  const handoff = buildHandoff({
154
238
  generated,
@@ -0,0 +1,27 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ // The installed copy this plugin comes from, and the package.json whose version decides staleness.
6
+ // omp never reloads a plugin, so the version is read once at adapter start (the code actually
7
+ // running) and re-read at every rollover check; a different or unreadable version means the running
8
+ // plugin is stale. NEURASTREAM_PACKAGE_JSON overrides the path (tests and the sandbox smoke point it
9
+ // at a copy whose version changes mid-run), like QUEUE_CLOSE_BIN.
10
+
11
+ /** The package root: this file is src/adapters/omp/package-root.ts. */
12
+ export const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
13
+
14
+ /** The package.json whose version is compared: NEURASTREAM_PACKAGE_JSON, else the package on disk. */
15
+ export function packageJsonPath(): string {
16
+ return process.env.NEURASTREAM_PACKAGE_JSON ?? join(PACKAGE_ROOT, "package.json");
17
+ }
18
+
19
+ /** The version in a package.json, or null when it cannot be read or has no string version. */
20
+ export function packageVersion(packageJson: string): string | null {
21
+ try {
22
+ const version = (JSON.parse(readFileSync(packageJson, "utf8")) as { version?: unknown } | null)?.version;
23
+ return typeof version === "string" ? version : null;
24
+ } catch {
25
+ return null;
26
+ }
27
+ }
@@ -116,7 +116,7 @@ export interface Config {
116
116
  protected: string[];
117
117
  ledger_command: string;
118
118
  };
119
- rollover: { enabled: boolean; max_session_mb: number };
119
+ rollover: { enabled: boolean; max_session_mb: number; exit_grace_s: number };
120
120
  metrics: { report_days: number; correction_patterns: string[]; ci_pipelines_cmd: string };
121
121
  /** Incident detectors (src/core/incident-detectors.ts): when a sighting becomes an incident. */
122
122
  incidents: {
@@ -281,6 +281,7 @@ function check(cfg: Config): void {
281
281
  throw new ConfigError("guards.sub_warn_calls must be <= guards.sub_max_calls");
282
282
  }
283
283
  if (!(cfg.rollover.max_session_mb > 0)) throw new ConfigError("rollover.max_session_mb must be > 0");
284
+ if (!(cfg.rollover.exit_grace_s > 0)) throw new ConfigError("rollover.exit_grace_s must be > 0");
284
285
  if (!(cfg.metrics.report_days >= 1)) throw new ConfigError("metrics.report_days must be >= 1");
285
286
  for (const p of cfg.metrics.correction_patterns) {
286
287
  try {
@@ -223,15 +223,17 @@ export function dismissIncident(cfg: Config, id: string, why: string): string |
223
223
 
224
224
  /**
225
225
  * Records that an incident's fix shipped: the queue writes this when it closes a plan citing
226
- * `INCIDENT <id>` (plan P5), so the guards stop pushing a bug whose fix just landed. Refusals
227
- * mirror `incident plan`; the caller logs them and closes anyway.
226
+ * `INCIDENT <id>` (plan P5), so the guards stop pushing a bug whose fix just landed. A plan record
227
+ * (the normal path: planned, then fixed) may be closed out; a dismissed or fixed incident is final.
228
+ * The caller logs refusals and closes anyway.
228
229
  */
229
230
  export function fixedIncident(cfg: Config, id: string, plan: string, now = nowSec()): string | null {
230
231
  const file = incidentsFile(cfg);
231
232
  const store = readStore(file);
232
233
  if (!store.incidents.some(i => i.id === id)) return `unknown incident ${id}`;
233
234
  const res = store.resolutions.filter(r => r.id === id).at(-1);
234
- if (res) return `incident ${id} already has a ${res.type} record`;
235
+ // A plan record is the normal path (planned, then fixed); dismissed or fixed is final.
236
+ if (res && res.type !== "plan") return `incident ${id} already has a ${res.type} record`;
235
237
  mkdirSync(dirname(file), { recursive: true });
236
238
  appendFileSync(file, `${JSON.stringify({ type: "fixed", id, plan, ts: now })}\n`);
237
239
  return null;
@@ -310,10 +310,12 @@ export function queueClose(args: string[], cfg: Config): number {
310
310
  // resolved) is logged into the close log and never fails the close.
311
311
  if (!cancelling) {
312
312
  const recorded: string[] = [];
313
- for (const m of plan.text.matchAll(/\bINCIDENT\s+(I-\d{8}-\d+)\b/g)) {
314
- const why = fixedIncident(cfg, m[1]!, file);
315
- if (why) result(`queue-close: not recording fixed for ${m[1]}: ${why}`);
316
- else recorded.push(m[1]!);
313
+ // A plan may cite one incident several times; record it once so the second citation is not a refusal.
314
+ const ids = new Set([...plan.text.matchAll(/\bINCIDENT\s+(I-\d{8}-\d+)\b/g)].map(m => m[1]!));
315
+ for (const id of ids) {
316
+ const why = fixedIncident(cfg, id, file);
317
+ if (why) result(`queue-close: not recording fixed for ${id}: ${why}`);
318
+ else recorded.push(id);
317
319
  }
318
320
  if (recorded.length) console.log(`queue-close: recorded fixed for ${recorded.join(", ")}`);
319
321
  }
@@ -104,6 +104,13 @@ export function holdsBlock(holds: readonly string[]): string {
104
104
  return ["=== owner holds (plans' WAITING on owner lines)", ...(holds.length > 0 ? holds : ["none"]), ""].join("\n");
105
105
  }
106
106
 
107
+ /**
108
+ * The launcher's owner-away text: the handoff's owner message when the owner typed nothing during the
109
+ * rollover. The adapter's in-process fallback carries the same text, so it lives here, harness-free.
110
+ */
111
+ export const OWNER_AWAY =
112
+ "Owner away (automatic rollover). Continue the work in the note and the queue; the owner reads results later.";
113
+
107
114
  /** The one-time note instruction for Main's next turn. `reason` (a stale install) names both versions and replaces the size line. */
108
115
  export function noteRequest(path: string, auto = false, reason = ""): string {
109
116
  return [
@@ -119,6 +119,7 @@ guards:
119
119
  rollover:
120
120
  enabled: true
121
121
  max_session_mb: 5
122
+ exit_grace_s: 20
122
123
 
123
124
  metrics:
124
125
  report_days: 7