neurastream 0.1.25 → 0.1.27

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.1.25",
3
+ "version": "0.1.27",
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";
@@ -29,6 +28,7 @@ import { mainStartText, runDailyCheck } from "../../core/main-start.ts";
29
28
  import { readBlocks } from "../../core/metrics.ts";
30
29
  import { buildHandoff, holdsBlock, notePath, noteRequest, 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 {
@@ -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
@@ -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 { 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. */
@@ -72,6 +73,8 @@ const OWNER_AWAY =
72
73
 
73
74
  export interface LaunchOptions {
74
75
  harness?: string;
76
+ /** The main-start text generator for the handoff (default: src/core/main-start.ts). Tests inject a failing one. */
77
+ mainStart?: typeof mainStartText;
75
78
  }
76
79
 
77
80
  interface RelaunchRequest {
@@ -80,40 +83,72 @@ interface RelaunchRequest {
80
83
  draft: string;
81
84
  }
82
85
 
83
- /** Runs the harness until a run ends without a fresh relaunch request; returns the last run's code. */
86
+ /**
87
+ * Runs the harness until a run ends without a fresh relaunch request; returns the last run's code.
88
+ * The launcher keeps the version it loaded. When the package on disk has another version (or either
89
+ * is unreadable) by the time a run leaves a request, that request goes to a fresh launcher started
90
+ * from the package on disk: the handoff is then built with the installed code, not the old code.
91
+ */
84
92
  export async function runMainLauncher(args: string[], cfg: Config, opts: LaunchOptions = {}): Promise<number> {
85
93
  applyQueueEnv(cfg);
86
94
  const harness = opts.harness ?? OMP_BIN;
95
+ const mainStart = opts.mainStart ?? mainStartText;
87
96
  const carried = carriedArgs(args);
97
+ const loaded = packageVersion(packageJsonPath());
98
+ // Set only in a fresh launcher the previous one started: its first step is the request that run left.
99
+ const handedOver = process.env.NEURASTREAM_RELAUNCH_SINCE;
100
+ delete process.env.NEURASTREAM_RELAUNCH_SINCE;
88
101
  let runArgs = args;
102
+ const since = handedOver === undefined ? Number.NaN : Number(handedOver);
103
+ if (Number.isFinite(since)) {
104
+ const req = readRequest(since, cfg);
105
+ if (req !== null) {
106
+ rmSync(relaunchPath(), { force: true });
107
+ const message = await nextMessage(req, cfg, mainStart);
108
+ if (message === null) return 1;
109
+ runArgs = [...carried, message];
110
+ }
111
+ }
89
112
  for (;;) {
90
113
  rmSync(relaunchPath(), { force: true });
91
114
  const started = Date.now();
92
- const code = await runChild(harness, runArgs);
93
- const req = takeRequest(started, cfg);
115
+ const code = await runChild(harness, runArgs, { ...process.env, NEURASTREAM_MAIN_LAUNCHER: "1" });
116
+ const req = readRequest(started, cfg);
94
117
  if (req === null) return code;
95
- const message = await nextMessage(req, cfg);
118
+ const installed = packageVersion(packageJsonPath());
119
+ const changed = loaded === null || installed === null || loaded !== installed;
120
+ if (changed && noteReadable(req.notePath)) {
121
+ adapterLog(cfg, `rollover: relaunch handed to a fresh launcher (${loaded ?? "unknown"} → ${installed ?? "unknown"})`);
122
+ return runChild(process.execPath, [join(PACKAGE_ROOT, "src", "cli", "main.ts"), "main", ...carried], {
123
+ ...process.env,
124
+ NEURASTREAM_RELAUNCH_SINCE: String(started),
125
+ });
126
+ }
127
+ rmSync(relaunchPath(), { force: true });
128
+ const message = await nextMessage(req, cfg, mainStart);
96
129
  if (message === null) return code;
97
130
  runArgs = [...carried, message];
98
131
  }
99
132
  }
100
133
 
101
- function runChild(harness: string, args: string[]): Promise<number> {
134
+ /** Runs a command with inherited stdio; resolves to its exit code (127 when it cannot start). */
135
+ function runChild(cmd: string, args: string[], env: NodeJS.ProcessEnv): Promise<number> {
102
136
  const { promise, resolve } = Promise.withResolvers<number>();
103
- const child = spawn(harness, args, {
104
- stdio: "inherit",
105
- env: { ...process.env, NEURASTREAM_MAIN_LAUNCHER: "1" },
106
- });
137
+ const child = spawn(cmd, args, { stdio: "inherit", env });
107
138
  child.on("error", err => {
108
- console.error(`neurastream main: cannot start ${harness}: ${err.message}`);
139
+ console.error(`neurastream main: cannot start ${cmd}: ${err.message}`);
109
140
  resolve(127);
110
141
  });
111
142
  child.on("close", code => resolve(code ?? 1));
112
143
  return promise;
113
144
  }
114
145
 
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 {
146
+ /**
147
+ * The request the last run left behind, only if it was written during that run (mtime at or after
148
+ * `since`). Not consumed: the caller removes it once it has decided to use it. A request without the
149
+ * required fields is removed and logged; an unreadable one is logged and left in place.
150
+ */
151
+ function readRequest(since: number, cfg: Config): RelaunchRequest | null {
117
152
  const path = relaunchPath();
118
153
  let mtimeMs: number;
119
154
  try {
@@ -122,22 +157,33 @@ function takeRequest(since: number, cfg: Config): RelaunchRequest | null {
122
157
  return null;
123
158
  }
124
159
  if (mtimeMs < since) return null;
160
+ let raw: Partial<RelaunchRequest>;
125
161
  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 ?? "" };
162
+ raw = JSON.parse(readFileSync(path, "utf8")) as Partial<RelaunchRequest>;
133
163
  } catch (err) {
134
164
  adapterLog(cfg, `rollover: relaunch request ignored, unreadable ${path}: ${String(err)}`);
135
165
  return null;
136
166
  }
167
+ if (typeof raw.previousSessionFile !== "string" || typeof raw.notePath !== "string") {
168
+ rmSync(path, { force: true });
169
+ adapterLog(cfg, `rollover: relaunch request ignored, missing fields in ${path}`);
170
+ return null;
171
+ }
172
+ return { previousSessionFile: raw.previousSessionFile, notePath: raw.notePath, draft: raw.draft ?? "" };
173
+ }
174
+
175
+ /** Whether the handoff note can be read now: a launcher cannot relaunch without it. */
176
+ function noteReadable(path: string): boolean {
177
+ try {
178
+ readFileSync(path, "utf8");
179
+ return true;
180
+ } catch {
181
+ return false;
182
+ }
137
183
  }
138
184
 
139
185
  /** 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> {
186
+ async function nextMessage(req: RelaunchRequest, cfg: Config, mainStart: typeof mainStartText): Promise<string | null> {
141
187
  let note: string;
142
188
  try {
143
189
  note = readFileSync(req.notePath, "utf8");
@@ -145,10 +191,18 @@ async function nextMessage(req: RelaunchRequest, cfg: Config): Promise<string |
145
191
  adapterLog(cfg, `rollover: relaunch stopped, note unreadable ${req.notePath}: ${String(err)}`);
146
192
  return null;
147
193
  }
148
- const generated = [
149
- await mainStartText([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg) }),
150
- holdsBlock(q.ownerHolds()),
151
- ].join("\n");
194
+ let generated: string;
195
+ try {
196
+ generated = [
197
+ await mainStart([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg) }),
198
+ holdsBlock(q.ownerHolds()),
199
+ ].join("\n");
200
+ } catch (err) {
201
+ // A failing main-start must not cost the owner the note: the handoff says it failed.
202
+ const first = (err instanceof Error ? err.message : String(err)).split("\n")[0] ?? "";
203
+ adapterLog(cfg, `rollover: main-start failed: ${first}`);
204
+ generated = `main-start failed during the rollover (${first}); run main-start yourself.`;
205
+ }
152
206
  const draft = req.draft.trim() === "" ? "" : `\nOwner's messages during the rollover (and any unsent draft): ${req.draft}`;
153
207
  const handoff = buildHandoff({
154
208
  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
+ }
@@ -168,6 +168,18 @@ export function addIncident(cfg: Config, input: IncidentInput, now = nowSec()):
168
168
  return { incident: { ...rec, resolution: null }, deduped: false };
169
169
  }
170
170
 
171
+ /**
172
+ * The repo a plan belongs to: the nearest directory from the plan's folder upward that holds the
173
+ * repo INDEX.md. Plans live at any depth under the repo (docs/plans/immediate/…), so a fixed
174
+ * number of dirname steps lands short of the root.
175
+ */
176
+ function repoForPlan(abs: string): string | null {
177
+ for (let dir = dirname(abs); ; dir = dirname(dir)) {
178
+ if (existsSync(join(dir, q.REPO_INDEX))) return dir;
179
+ if (dirname(dir) === dir) return null;
180
+ }
181
+ }
182
+
171
183
  /**
172
184
  * Records the plan that fixes an incident: refused unless the file exists, is listed in its repo
173
185
  * INDEX.md, and contains `INCIDENT <id>` (the spawn gates look for that text). Returns the
@@ -181,7 +193,8 @@ export function planIncident(cfg: Config, id: string, planPath: string): string
181
193
  if (res) return `incident ${id} already has a ${res.type} record`;
182
194
  const abs = resolve(q.expandHome(planPath));
183
195
  if (!existsSync(abs)) return `plan file not found: ${abs}`;
184
- const repo = dirname(dirname(dirname(abs)));
196
+ const repo = repoForPlan(abs);
197
+ if (!repo) return `${abs} is not under a directory holding ${q.REPO_INDEX}`;
185
198
  if (!q.readRepoIndex(repo).includes(abs)) return `${abs} is not listed in ${join(repo, q.REPO_INDEX)}`;
186
199
  let text: string;
187
200
  try {
@@ -210,15 +223,17 @@ export function dismissIncident(cfg: Config, id: string, why: string): string |
210
223
 
211
224
  /**
212
225
  * Records that an incident's fix shipped: the queue writes this when it closes a plan citing
213
- * `INCIDENT <id>` (plan P5), so the guards stop pushing a bug whose fix just landed. Refusals
214
- * 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.
215
229
  */
216
230
  export function fixedIncident(cfg: Config, id: string, plan: string, now = nowSec()): string | null {
217
231
  const file = incidentsFile(cfg);
218
232
  const store = readStore(file);
219
233
  if (!store.incidents.some(i => i.id === id)) return `unknown incident ${id}`;
220
234
  const res = store.resolutions.filter(r => r.id === id).at(-1);
221
- 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`;
222
237
  mkdirSync(dirname(file), { recursive: true });
223
238
  appendFileSync(file, `${JSON.stringify({ type: "fixed", id, plan, ts: now })}\n`);
224
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
  }
@@ -1,7 +1,10 @@
1
+ import { spawnSync } from "node:child_process";
1
2
  import type { Config } from "./config.ts";
2
3
 
3
4
  // Converts a provider's rate-limit reset time (wall clock in the provider's zone) into the caller's
4
- // local time. Intl does the zone math, so this needs no GNU date and behaves the same on macOS.
5
+ // local time. Intl does the zone math; date(1) supplies the local zone abbreviation, because Intl's
6
+ // short timeZoneName is a tzdata abbreviation only for US zones (Europe/Berlin prints "GMT+2" where
7
+ // date +%Z prints "CEST"). macOS's BSD date is used there, so no GNU date is needed.
5
8
 
6
9
  const USAGE =
7
10
  'usage: quota-reset "YYYY-MM-DD HH:MM[:SS]" [--tz <zone>] (reset time from your provider\'s rate-limit message)\n';
@@ -49,6 +52,19 @@ function parseWhen(text: string): { y: number; mo: number; d: number; h: number;
49
52
  return valid ? wall : null;
50
53
  }
51
54
 
55
+ // The tzdata abbreviation for this instant (CEST, CET, CST, +05) as date(1) prints it in the zone
56
+ // env this process runs in (the child inherits it, so the abbreviation always matches the wall
57
+ // clock next to it). Falls back to the Intl short name only when date fails.
58
+ function zoneAbbrev(epoch: number): string {
59
+ const probe =
60
+ process.platform === "darwin"
61
+ ? spawnSync("date", ["-r", String(epoch), "+%Z"], { encoding: "utf8" })
62
+ : spawnSync("date", ["-d", `@${epoch}`, "+%Z"], { encoding: "utf8" });
63
+ if (probe.status === 0 && probe.stdout?.trim()) return probe.stdout.trim();
64
+ const parts = new Intl.DateTimeFormat("en-US", { timeZoneName: "short" }).formatToParts(new Date(epoch * 1000));
65
+ return parts.find(p => p.type === "timeZoneName")?.value ?? "";
66
+ }
67
+
52
68
  // Local wall clock of the process, "YYYY-MM-DD HH:MM:SS ZONE".
53
69
  function localStamp(epoch: number): string {
54
70
  const parts = new Intl.DateTimeFormat("en-US", {
@@ -59,10 +75,9 @@ function localStamp(epoch: number): string {
59
75
  hour: "2-digit",
60
76
  minute: "2-digit",
61
77
  second: "2-digit",
62
- timeZoneName: "short",
63
78
  }).formatToParts(new Date(epoch * 1000));
64
- const get = (type: string): string => parts.find((p) => p.type === type)?.value ?? "";
65
- return `${get("year")}-${get("month")}-${get("day")} ${get("hour")}:${get("minute")}:${get("second")} ${get("timeZoneName")}`;
79
+ const get = (type: string): string => parts.find(p => p.type === type)?.value ?? "";
80
+ return `${get("year")}-${get("month")}-${get("day")} ${get("hour")}:${get("minute")}:${get("second")} ${zoneAbbrev(epoch)}`;
66
81
  }
67
82
 
68
83
  export function quotaReset(args: string[], cfg: Config): number {