neurastream 0.2.64 → 0.2.65

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.2.64",
3
+ "version": "0.2.65",
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": [
6
6
  "ai-agents",
@@ -16,7 +16,7 @@
16
16
  // Harness payloads are untyped at the boundary: every field read goes through a runtime check.
17
17
 
18
18
  import { execFileSync, spawn } from "node:child_process";
19
- import { appendFileSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
19
+ import { appendFileSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
20
20
  import { basename, dirname, extname, join, resolve } from "node:path";
21
21
  import type { Decision, TraceEvent } from "../../core/adapter.ts";
22
22
  import { AGENTS_TEMPLATE, renderBlock } from "../../core/agents-md.ts";
@@ -27,13 +27,15 @@ import { configFile, loadConfig, reloadingConfig, type Config } from "../../core
27
27
  import { checkWrite, deferSteer, type WriteCheckConfig } from "../../core/write-check.ts";
28
28
  import { nowSec, strftime } from "../../core/clock.ts";
29
29
  import { runDetectors, type DetectorInput } from "../../core/incident-detectors.ts";
30
+ import { fileClaimStore } from "../../core/claims.ts";
30
31
  import { appendOwnerAnswer, readOwnerAnswers, readOwnerMessages } from "../../core/incidents.ts";
31
- import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, newProgressEntries, planReadNote, recordMainResult, resetMainCalls, revertMainEdit, rekeySpawnFile, reviewSpawnEnd, STOP_PLAN_OFFER_REFUSAL } from "../../core/guards.ts";
32
+ import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, mainId, mainStateDir, newProgressEntries, planReadNote, recordMainResult, resetMainCalls, revertMainEdit, rekeySpawnFile, reviewSpawnEnd, STOP_PLAN_OFFER_REFUSAL } from "../../core/guards.ts";
32
33
  import { rateLimitWait } from "../../core/rate-limit.ts";
33
34
  import { notifyProviders, ownerAnswerHandback, ownerAnswerSteer, postReply } from "../../core/notify.ts";
34
35
  import { loadKnownSecrets, redactSecrets, redactSummary } from "../../core/secret-redact.ts";
35
36
  import { inboxPath } from "../../core/owner-ui.ts";
36
37
  import { realTailscale } from "../../core/tailscale.ts";
38
+ import { briefPaths } from "../../core/brief-lint.ts";
37
39
  import { actionsRules, ownedRepoOf, suspiciousActions, unreportedFindings } from "../../core/trace-actions.ts";
38
40
  import { applyQueueEnv } from "../../core/queue/env.ts";
39
41
  import { mainDetectors, mainStartText } from "../../core/main-start.ts";
@@ -154,6 +156,20 @@ const PUSH_MERGE = /\bgit\b[^\n;|&]*\bpush\b|\b(glab\s+mr|gh\s+pr)\s+merge\b/;
154
156
 
155
157
  export { adapterLog };
156
158
 
159
+ /**
160
+ * Paths named inside the one configured method doc (brief.method_read): Main-owned and outside
161
+ * every run's write scope, so its named paths are trusted one hop past the brief text (P10c).
162
+ * Unset or unreadable doc allows nothing.
163
+ */
164
+ const methodDocPaths = (cfg: Config): string[] => {
165
+ if (!cfg.brief.method_read) return [];
166
+ try {
167
+ return briefPaths(readFileSync(q.expandHome(cfg.brief.method_read), "utf8"), cfg);
168
+ } catch {
169
+ return [];
170
+ }
171
+ };
172
+
157
173
  /**
158
174
  * D6 + D7 over a subagent's own trace, right after an allowed Progress edit (plan
159
175
  * 20261024_0301 P6): the sub's session file (its harness session manager hands it out) is
@@ -164,7 +180,7 @@ export { adapterLog };
164
180
  * (Progress runs newest-first). Best effort: a failure is logged, never thrown — a broken
165
181
  * detector must not break the verified edit.
166
182
  */
167
- function subActionDetectors(cfg: Config, ctx: unknown, planFile: string, before: string, after: string): void {
183
+ function subActionDetectors(cfg: Config, ctx: unknown, planFile: string, before: string, after: string, allowedText: string): void {
168
184
  try {
169
185
  const entries = newProgressEntries(before, after);
170
186
  if (entries.length === 0) return;
@@ -177,10 +193,14 @@ function subActionDetectors(cfg: Config, ctx: unknown, planFile: string, before:
177
193
  // The plan's repo spelled like its owned_repos entry: a checkout named "pm-mr196" is "pm",
178
194
  // so the run's reads of its own repo never count as another product's.
179
195
  const repoDir = q.planRepo(planFile);
196
+ // P10c: reads the brief or the method doc names are exempt — the detector stays pure,
197
+ // the adapter extracts both lists.
198
+ const allowedPaths = [...(allowedText ? briefPaths(allowedText, cfg) : []), ...methodDocPaths(cfg)];
180
199
  input.unreported = unreportedFindings(events, rules, {
181
200
  repo: ownedRepoOf(`${repoDir}/`, rules.owned_repos) ?? basename(repoDir),
182
201
  plan: planFile,
183
202
  claimedNone: true,
203
+ allowed: allowedPaths,
184
204
  });
185
205
  }
186
206
  runDetectors(cfg, input);
@@ -420,25 +440,30 @@ function sizeOf(path: string): number {
420
440
 
421
441
  /** Idle-poll interval for the owner inbox. */
422
442
  export const OWNER_INBOX_POLL_MS = 15_000;
443
+ /** How often the adapter heartbeats every claim this Main holds (plan 20261027_1300 P3). */
444
+ export const CLAIM_BEAT_MS = 60_000;
423
445
 
424
- /** The delivered cursor: how many owner-inbox rows Main's session has consumed. */
425
- export function ownerInboxCursorPath(): string {
426
- return `${q.stateDirPath()}/owner-inbox.cursor`;
446
+ /** The delivered cursor: how many owner-inbox rows this Main's session has consumed (P5: one file per Main, under its mainStateDir). */
447
+ export function ownerInboxCursorPath(cfg?: Config): string {
448
+ return `${mainStateDir(cfg)}/inbox-cursor`;
427
449
  }
428
450
 
429
- function readOwnerInboxCursor(): number {
451
+ /** Rows this Main starts past when it has never delivered (P5): set at adapter creation so a Main that registers late does not replay old rows. null = adopt the file or 0. */
452
+ let inboxFloor: number | null = null;
453
+
454
+ function readOwnerInboxCursor(cfg: Config): number {
430
455
  try {
431
- const n = Number(readFileSync(ownerInboxCursorPath(), "utf8").trim());
432
- return Number.isInteger(n) && n >= 0 ? n : 0;
456
+ const n = Number(readFileSync(ownerInboxCursorPath(cfg), "utf8").trim());
457
+ return Number.isInteger(n) && n >= 0 ? n : inboxFloor ?? 0;
433
458
  } catch {
434
- return 0;
459
+ return inboxFloor ?? 0;
435
460
  }
436
461
  }
437
462
 
438
- function writeOwnerInboxCursor(n: number): void {
463
+ function writeOwnerInboxCursor(cfg: Config, n: number): void {
439
464
  try {
440
- mkdirSync(q.stateDirPath(), { recursive: true });
441
- writeFileSync(ownerInboxCursorPath(), `${n}\n`);
465
+ mkdirSync(mainStateDir(cfg), { recursive: true });
466
+ writeFileSync(ownerInboxCursorPath(cfg), `${n}\n`);
442
467
  } catch {}
443
468
  }
444
469
 
@@ -552,17 +577,19 @@ export function deliverOwnerInbox(pi: ExtensionHost, cfg: Config): void {
552
577
  } catch {
553
578
  return; // no inbox yet: nothing to deliver
554
579
  }
555
- const cursor = readOwnerInboxCursor();
580
+ const cursor = readOwnerInboxCursor(cfg);
556
581
  const { records, next } = pendingInboxRecords(text, cursor);
557
582
  if (next === cursor) return;
558
583
  let delivered = 0;
559
584
  for (const rec of records) {
585
+ // P5: a row addressed to another Main (`to` set and not this Main's id) is consumed but not delivered here.
586
+ if (typeof rec.to === "string" && rec.to !== "" && rec.to !== mainId()) continue;
560
587
  const msg = ownerInboxMessage(rec);
561
588
  if (msg === null) continue;
562
589
  pi.sendUserMessage(msg);
563
590
  delivered++;
564
591
  }
565
- writeOwnerInboxCursor(next);
592
+ writeOwnerInboxCursor(cfg, next);
566
593
  adapterLog(cfg, `owner inbox: delivered ${delivered} answer(s) (cursor ${cursor} → ${next})`);
567
594
  }
568
595
 
@@ -574,6 +601,26 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
574
601
  let cfg = initial;
575
602
  // The queue library resolves its paths from env snapshots; point them at this config first.
576
603
  applyQueueEnv(cfg);
604
+ // P5: seed the per-Main inbox floor once — a Main that has never delivered starts past rows
605
+ // that predate its registration; the pre-multi-main cursor file belongs to the default id's
606
+ // first start. Later reads/writes own the file, so the floor is only a creation-time default.
607
+ try {
608
+ if (!existsSync(ownerInboxCursorPath(cfg))) {
609
+ mkdirSync(mainStateDir(cfg), { recursive: true });
610
+ if (mainId() === "main") {
611
+ try {
612
+ renameSync(`${q.stateDirPath()}/owner-inbox.cursor`, ownerInboxCursorPath(cfg));
613
+ } catch {}
614
+ }
615
+ if (!existsSync(ownerInboxCursorPath(cfg))) {
616
+ try {
617
+ inboxFloor = pendingInboxRecords(readFileSync(inboxPath(), "utf8"), 0).next;
618
+ } catch {
619
+ inboxFloor = 0;
620
+ }
621
+ }
622
+ }
623
+ } catch {}
577
624
  // Main's rules ride its system prompt each turn; they are never written into the owner's AGENTS.md.
578
625
  const mainRules = renderBlock(cfg);
579
626
 
@@ -586,6 +633,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
586
633
  const deferredWrite = new Map<string, Map<string, string | null>>(); // agent id -> files that added deferred findings this turn -> text before the first one (null: new file); judged at that session's own agent_end
587
634
  const pendingRules = new Set<string>(); // repos Main worked in, rules to hand over at the next prompt
588
635
  const pendingReviewNotes: string[] = []; // P4k: review spawns that ended with no verdict; Main hears at its next prompt
636
+ const subBriefs = new Map<string, string>(); // task spawn name -> its brief text (P10c)
589
637
  // Chat notify (plans 20261024_2155, 20261025_0130): the text a hand-back already posted
590
638
  // (attempted) — one post per distinct text, never a retry loop. The reply itself comes from
591
639
  // the stop/agent_end event, never the session file (session_stop fires BEFORE agent_end, and
@@ -764,6 +812,16 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
764
812
  ? c.setInterval(() => deliverOwnerInbox(pi, cfg), OWNER_INBOX_POLL_MS)
765
813
  : setInterval(() => deliverOwnerInbox(pi, cfg), OWNER_INBOX_POLL_MS);
766
814
  if (it && typeof it === "object" && "unref" in it && typeof it.unref === "function") it.unref();
815
+ // Multi-main P3: every held claim heartbeats once a minute while this Main session lives,
816
+ // so a live Main never loses a plan to queue.claim_ttl_min. session_shutdown releases
817
+ // nothing: the TTL frees a crashed or restarted Main's claims the same way.
818
+ const beat = (): void => {
819
+ const store = fileClaimStore(cfg.paths.queue_state, nowSec, cfg.queue.claim_ttl_min);
820
+ const id = mainId();
821
+ for (const claim of store.list()) if (claim.main === id) store.heartbeat(claim.plan, id);
822
+ };
823
+ const hb: unknown = c.setInterval ? c.setInterval(beat, CLAIM_BEAT_MS) : setInterval(beat, CLAIM_BEAT_MS);
824
+ if (hb && typeof hb === "object" && "unref" in hb && typeof hb.unref === "function") hb.unref();
767
825
  });
768
826
 
769
827
  // What a subagent is still missing (plan 20261027_1530 P2): the rules of the repo its plan is
@@ -894,6 +952,16 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
894
952
  }
895
953
  }
896
954
  }
955
+ // P10c: remember each spawn's brief text by its spawn name — tasks[].name, which is the
956
+ // sub's ctx.agent.id (tasks[].agent is the agent type, never the key) — so D7 can skip
957
+ // reads the owner deliberately named in the brief (paths extracted via briefPaths).
958
+ if (!isSub && tool === "task") {
959
+ for (const t of Array.isArray(input.tasks) ? input.tasks : []) {
960
+ const name = asString(asRecord(t).name);
961
+ const brief = asString(asRecord(t).task);
962
+ if (name && brief) subBriefs.set(name, brief);
963
+ }
964
+ }
897
965
  const d = checkTool(
898
966
  { tool, input, cwd, agent, agentId: id, calls: n - 1, paths: [], writes: [], command: asString(input.command), runningJobs },
899
967
  cfg,
@@ -983,7 +1051,7 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
983
1051
  if (note) notes.push(note);
984
1052
  }
985
1053
  // Live D6+D7 over the sub's own session as soon as it reports into the plan (P6).
986
- if (d.allow && c.kind === "sub") subActionDetectors(cfg, ctx, file, before, after);
1054
+ if (d.allow && c.kind === "sub") subActionDetectors(cfg, ctx, file, before, after, subBriefs.get(c.id ?? "main") ?? "");
987
1055
  }
988
1056
  }
989
1057
  // Write-time checks (plan 20261028_1228): a lint finding the call added is undone here, file by file.
@@ -12,6 +12,8 @@ import { readOwnerAnswers, readOwnerMessages } from "../../core/incidents.ts";
12
12
  import { mainStartText } from "../../core/main-start.ts";
13
13
  import { appendMetric } from "../../core/metrics.ts";
14
14
  import { applyQueueEnv } from "../../core/queue/env.ts";
15
+ import { tryLock } from "../../core/file-lock.ts";
16
+ import { MAIN_ID_RE, mainStateDir } from "../../core/guards.ts";
15
17
  import * as q from "../../core/queue/lib.ts";
16
18
  import { buildHandoff, holdsBlock, MAX_NOTE_AGE_MS, OWNER_AWAY, relaunchPath, unansweredOwnerMessages } from "../../core/rollover.ts";
17
19
  import { PROXY_BIN, proxyOnPath } from "../../core/secret-redact.ts";
@@ -108,6 +110,32 @@ export function carriedArgs(args: string[]): string[] {
108
110
  return out;
109
111
  }
110
112
 
113
+ /**
114
+ * Splits `--name <id>` / `--name=<id>` — this launcher's Main identity — out of the args; the rest
115
+ * is what the harness gets on the first run and what a relaunch carries. The last --name wins.
116
+ */
117
+ export function stripNameFlag(args: string[]): { args: string[]; name: string | undefined } {
118
+ const rest: string[] = [];
119
+ let name: string | undefined;
120
+ for (let i = 0; i < args.length; i++) {
121
+ const arg = args[i] ?? "";
122
+ if (arg === "--name") {
123
+ const next = args[i + 1];
124
+ // A bare `--name` with no value (next token missing or another flag) has none: fall back
125
+ // to the env/default id instead of eating the next flag as the id (I-20261031-225).
126
+ if (next !== undefined && !next.startsWith("-")) {
127
+ name = next;
128
+ i++;
129
+ }
130
+ } else if (arg.startsWith("--name=")) {
131
+ name = arg.slice("--name=".length);
132
+ } else {
133
+ rest.push(arg);
134
+ }
135
+ }
136
+ return { args: rest, name };
137
+ }
138
+
111
139
  /** Handoffs up to this many bytes go in the first message; larger ones go to a file. */
112
140
  const MAX_INLINE_HANDOFF = 100_000;
113
141
 
@@ -141,65 +169,90 @@ interface RelaunchRequest {
141
169
  */
142
170
  export async function runMainLauncher(args: string[], cfg: Config, opts: LaunchOptions = {}): Promise<number> {
143
171
  applyQueueEnv(cfg);
144
- const harness = opts.harness ?? OMP_BIN;
145
- const proxy = proxyPlan(harness, cfg);
146
- if (proxy.warning) console.error(proxy.warning);
147
- const mainStart = opts.mainStart ?? mainStartText;
148
- const carried = carriedArgs(args);
149
- const loaded = packageVersion(packageJsonPath());
150
- // Set only in a fresh launcher the previous one started: its first step is the request that run left.
172
+ // --name names this launcher's Main and never reaches the harness: stripped before the first
173
+ // run's args and a relaunch's carriedArgs are built.
174
+ const { args: harnessArgs, name } = stripNameFlag(args);
175
+ const id = name ?? process.env.NEURASTREAM_MAIN_ID ?? "main";
176
+ if (!MAIN_ID_RE.test(id)) {
177
+ console.error(`neurastream: bad main id "${id}": must match [a-z0-9-]{1,24}`);
178
+ return 2;
179
+ }
180
+ // The env, not a flag: the omp child and every relaunch inherit it, and the guards running in
181
+ // this process store this Main's state under it.
182
+ process.env.NEURASTREAM_MAIN_ID = id;
183
+ const stateDir = mainStateDir(cfg);
184
+ mkdirSync(stateDir, { recursive: true });
185
+ // Set only in a fresh launcher the previous one started: its first step is the request that run
186
+ // left. It replaces the launcher that holds the lock, so it skips the lock.
151
187
  const handedOver = process.env.NEURASTREAM_RELAUNCH_SINCE;
152
188
  delete process.env.NEURASTREAM_RELAUNCH_SINCE;
153
- let runArgs = args;
154
- const since = handedOver === undefined ? Number.NaN : Number(handedOver);
155
- if (Number.isFinite(since)) {
156
- const req = readRequest(since, cfg);
157
- if (req !== null) {
158
- console.error(HANDOFF_PENDING_LINE);
159
- const message = await nextMessage(req, cfg, mainStart);
160
- if (message === null) return 1;
161
- // The request is removed only once its message exists: a kill during main-start
162
- // (I-20261024-4) must leave it for the next launcher to continue.
163
- rmSync(relaunchPath(), { force: true });
164
- runArgs = [...carried, message];
165
- }
166
- } else if (!hasPositional(args)) {
167
- // A fresh start with no message of its own continues a rollover a killed launcher left
168
- // behind: the request counts while it is at most MAX_NOTE_AGE_MS old, like a note. An
169
- // older or unreadable one is left alone.
170
- const req = readRequest(Date.now() - MAX_NOTE_AGE_MS, cfg);
171
- if (req !== null) {
172
- console.error(`neurastream: continuing the interrupted rollover from ${req.previousSessionFile}`);
173
- console.error(HANDOFF_PENDING_LINE);
174
- const message = await nextMessage(req, cfg, mainStart);
175
- if (message !== null) {
189
+ // One live launcher per id: the kernel frees the flock when the launcher dies, so there is no
190
+ // pid file and no takeover code.
191
+ const running = handedOver === undefined ? tryLock(join(stateDir, "running.lock")) : { release: () => {} };
192
+ if (!running) {
193
+ console.error(`Main ${id} is already running`);
194
+ return 1;
195
+ }
196
+ try {
197
+ const harness = opts.harness ?? OMP_BIN;
198
+ const proxy = proxyPlan(harness, cfg);
199
+ if (proxy.warning) console.error(proxy.warning);
200
+ const mainStart = opts.mainStart ?? mainStartText;
201
+ const carried = carriedArgs(harnessArgs);
202
+ const loaded = packageVersion(packageJsonPath());
203
+ let runArgs = harnessArgs;
204
+ const since = handedOver === undefined ? Number.NaN : Number(handedOver);
205
+ if (Number.isFinite(since)) {
206
+ const req = readRequest(since, cfg);
207
+ if (req !== null) {
208
+ console.error(HANDOFF_PENDING_LINE);
209
+ const message = await nextMessage(req, cfg, mainStart);
210
+ if (message === null) return 1;
211
+ // The request is removed only once its message exists: a kill during main-start
212
+ // (I-20261024-4) must leave it for the next launcher to continue.
176
213
  rmSync(relaunchPath(), { force: true });
177
214
  runArgs = [...carried, message];
178
215
  }
216
+ } else if (!hasPositional(harnessArgs)) {
217
+ // A fresh start with no message of its own continues a rollover a killed launcher left
218
+ // behind: the request counts while it is at most MAX_NOTE_AGE_MS old, like a note. An
219
+ // older or unreadable one is left alone.
220
+ const req = readRequest(Date.now() - MAX_NOTE_AGE_MS, cfg);
221
+ if (req !== null) {
222
+ console.error(`neurastream: continuing the interrupted rollover from ${req.previousSessionFile}`);
223
+ console.error(HANDOFF_PENDING_LINE);
224
+ const message = await nextMessage(req, cfg, mainStart);
225
+ if (message !== null) {
226
+ rmSync(relaunchPath(), { force: true });
227
+ runArgs = [...carried, message];
228
+ }
229
+ }
179
230
  }
180
- }
181
- for (;;) {
182
- const started = Date.now();
183
- // The env, not a flag: the child inherits it, so an omp started from inside Main stays guarded.
184
- const code = await runChild(proxy.cmd, [...proxy.prefix, ...runArgs], { ...process.env, [MAIN_ENV]: "1" });
185
- const req = readRequest(started, cfg);
186
- if (req === null) return code;
187
- const installed = packageVersion(packageJsonPath());
188
- const changed = loaded === null || installed === null || loaded !== installed;
189
- if (changed && noteReadable(req.notePath)) {
190
- adapterLog(cfg, `rollover: relaunch handed to a fresh launcher (${loaded ?? "unknown"} → ${installed ?? "unknown"})`);
191
- // P11: one version-change ledger event per relaunch on a version change; the release verdict reads a to < from event as a downgrade.
192
- appendMetric(cfg, { type: "version-change", from: loaded ?? "unknown", to: installed ?? "unknown", ts: Math.floor(Date.now() / 1000) });
193
- return runChild(process.execPath, [join(PACKAGE_ROOT, "src", "cli", "main.ts"), "main", ...carried], {
194
- ...process.env,
195
- NEURASTREAM_RELAUNCH_SINCE: String(started),
196
- });
231
+ for (;;) {
232
+ const started = Date.now();
233
+ // The env, not a flag: the child inherits it, so an omp started from inside Main stays guarded.
234
+ const code = await runChild(proxy.cmd, [...proxy.prefix, ...runArgs], { ...process.env, [MAIN_ENV]: "1" });
235
+ const req = readRequest(started, cfg);
236
+ if (req === null) return code;
237
+ const installed = packageVersion(packageJsonPath());
238
+ const changed = loaded === null || installed === null || loaded !== installed;
239
+ if (changed && noteReadable(req.notePath)) {
240
+ adapterLog(cfg, `rollover: relaunch handed to a fresh launcher (${loaded ?? "unknown"} → ${installed ?? "unknown"})`);
241
+ // P11: one version-change ledger event per relaunch on a version change; the release verdict reads a to < from event as a downgrade.
242
+ appendMetric(cfg, { type: "version-change", from: loaded ?? "unknown", to: installed ?? "unknown", ts: Math.floor(Date.now() / 1000) });
243
+ return runChild(process.execPath, [join(PACKAGE_ROOT, "src", "cli", "main.ts"), "main", ...carried], {
244
+ ...process.env,
245
+ NEURASTREAM_RELAUNCH_SINCE: String(started),
246
+ });
247
+ }
248
+ console.error(HANDOFF_PENDING_LINE);
249
+ const message = await nextMessage(req, cfg, mainStart);
250
+ if (message === null) return code;
251
+ rmSync(relaunchPath(), { force: true });
252
+ runArgs = [...carried, message];
197
253
  }
198
- console.error(HANDOFF_PENDING_LINE);
199
- const message = await nextMessage(req, cfg, mainStart);
200
- if (message === null) return code;
201
- rmSync(relaunchPath(), { force: true });
202
- runArgs = [...carried, message];
254
+ } finally {
255
+ running.release();
203
256
  }
204
257
  }
205
258
 
@@ -0,0 +1,79 @@
1
+ // `neurastream claim` (plan 20261027_1300 P4): picking work across several Mains over one queue.
2
+ // `next` claims the highest free plan in index order with the queue's own skip rules — open only,
3
+ // not WAITING on the owner, not waiting on another open plan (the queueSummary waits-on rule), not
4
+ // held by another live Main; `list` prints the live claims; `release <plan>` frees this Main's
5
+ // claim and `--force` frees another Main's, refused for agents by the guard (the owner runs it in
6
+ // a terminal).
7
+ import path from "node:path";
8
+ import { fileClaimStore } from "../core/claims.ts";
9
+ import { nowSec, strftime } from "../core/clock.ts";
10
+ import { mainId } from "../core/guards.ts";
11
+ import { applyQueueEnv } from "../core/queue/env.ts";
12
+ import { activePlans, openWaits } from "../core/queue/lib.ts";
13
+ import type { Config } from "../core/config.ts";
14
+
15
+ const USAGE = [
16
+ "usage: neurastream claim next",
17
+ " neurastream claim list",
18
+ " neurastream claim release <plan> [--force]",
19
+ ].join("\n");
20
+
21
+ export function claimCli(args: string[], cfg: Config): number {
22
+ applyQueueEnv(cfg);
23
+ const store = fileClaimStore(cfg.paths.queue_state, nowSec, cfg.queue.claim_ttl_min);
24
+ const me = mainId();
25
+
26
+ if (args[0] === "next") {
27
+ // Index order IS priority; the skips are queueSummary's flags minus plans another live
28
+ // Main holds. A claim that races away mid-loop just moves the pick to the next plan.
29
+ const plans = activePlans();
30
+ const rank = new Map(plans.map((p, i) => [p.file, i + 1] as const));
31
+ for (const p of plans) {
32
+ if (p.status !== "open" || p.waiting || openWaits(p, plans, rank).length) continue;
33
+ const h = store.holder(p.file);
34
+ if (h && h.main !== me) continue;
35
+ const c = store.claim(p.file, me);
36
+ if ("heldBy" in c) continue;
37
+ console.log(`claim: ${p.file} for Main ${me} since ${strftime(c.since, "%H:%M")}`);
38
+ return 0;
39
+ }
40
+ console.error("claim: no free plan (open plans are held by another Main, WAITING on the owner, or waiting on another open plan)");
41
+ return 1;
42
+ }
43
+
44
+ if (args[0] === "list") {
45
+ // holder() applies the store's own liveness rule (claim_ttl_min), so list and next agree.
46
+ const live = store
47
+ .list()
48
+ .filter(c => store.holder(c.plan)?.main === c.main)
49
+ .toSorted((a, b) => a.since - b.since || a.plan.localeCompare(b.plan));
50
+ if (!live.length) console.log("claim: no live claims");
51
+ for (const c of live) console.log(`${c.plan} — held by Main ${c.main} since ${strftime(c.since, "%H:%M")}`);
52
+ return 0;
53
+ }
54
+
55
+ if (args[0] === "release") {
56
+ const force = args.includes("--force");
57
+ const planArg = args.slice(1).find(a => !a.startsWith("-"));
58
+ if (!planArg) {
59
+ console.error(USAGE);
60
+ return 2;
61
+ }
62
+ const file = path.resolve(planArg);
63
+ const h = store.holder(file);
64
+ if (!h) {
65
+ console.log(`claim: ${file} is free`);
66
+ return 0;
67
+ }
68
+ if (h.main !== me && !force) {
69
+ console.error(`claim: ${file} is held by Main ${h.main} since ${strftime(h.since, "%H:%M")}; freeing another Main's claim needs --force and is the owner's move, in a terminal.`);
70
+ return 1;
71
+ }
72
+ store.release(file, h.main);
73
+ console.log(`claim: released ${file}${h.main !== me ? ` (held by Main ${h.main})` : ""}`);
74
+ return 0;
75
+ }
76
+
77
+ console.error(USAGE);
78
+ return 2;
79
+ }
@@ -20,6 +20,7 @@ import { wipCheck } from "../core/wip-check.ts";
20
20
  import { wipSnapshot } from "../core/wip-snapshot.ts";
21
21
  import { withHeartbeat } from "../core/heartbeat.ts";
22
22
  import { runtime } from "./runtime.ts";
23
+ import { claimCli } from "./claim.ts";
23
24
  import { getAdapter } from "../adapters/index.ts";
24
25
 
25
26
  export const PORTED = [
@@ -36,6 +37,7 @@ export const PORTED = [
36
37
  "queue-close",
37
38
  "queue-finished",
38
39
  "queue-cancel",
40
+ "claim",
39
41
  "main-start",
40
42
  "machine-guard",
41
43
  "quota-reset",
@@ -79,6 +81,8 @@ export async function runPorted(cmd: string, args: string[]): Promise<number> {
79
81
  return queueFinished(args, rt.cfg);
80
82
  case "queue-cancel":
81
83
  return queueCancel(args, rt.cfg);
84
+ case "claim":
85
+ return claimCli(args, rt.cfg);
82
86
  case "main-start": {
83
87
  const a = getAdapter(rt.cfg);
84
88
  return mainStart(args, rt.cfg, { source: a.runSource(rt.cfg), results: a.completedResults(rt.cfg) });
@@ -74,6 +74,10 @@ export function helpText(): string {
74
74
  " neurastream redact filter stdin through the secret redactor: stdout gets the text,",
75
75
  " stderr the hit summary (types and counts only)",
76
76
  " neurastream queue migrate fold the old repo INDEX.md files into the one main index",
77
+ " neurastream claim next|list|release <plan> [--force]",
78
+ " claim the highest free plan for this Main, list the holders,",
79
+ " free this Main's claim; --force frees another Main's claim —",
80
+ " the owner's move in a terminal (the guard refuses agents)",
77
81
  " neurastream queue add <plan.md> [--rank N]",
78
82
  " add a plan to the index (append, or insert at 1-based rank N)",
79
83
  " neurastream queue move <plan.md> <rank>",
@@ -36,6 +36,18 @@ function escapeReg(s: string): string {
36
36
 
37
37
  /** A scanned path without its trailing sentence punctuation (the path loop's cleaning). */
38
38
  const clean = (raw: string): string => raw.replace(/[.,)]+$/, "");
39
+ /** Extract the paths a brief text names via cfg.brief.path_prefixes (the brief-lint way),
40
+ * reused by the D7 detector so a read the run's brief deliberately points at is not flagged.
41
+ */
42
+ export function briefPaths(text: string, cfg: Config): string[] {
43
+ const paths = new Set<string>();
44
+ const scan = liveText(text);
45
+ for (const prefix of cfg.brief.path_prefixes) {
46
+ const re = new RegExp(`(${escapeReg(prefix)}[\\w./\\-]+)`, "g");
47
+ for (const hit of scan.matchAll(re)) paths.add(hit[1]!);
48
+ }
49
+ return [...paths].toSorted();
50
+ }
39
51
 
40
52
  /** The same rules on a file on disk; the guard's spawn verdict lints the named plan files (plan 20261031_1207 P4). */
41
53
  export function lint(path: string, cfg: Config): { errs: string[]; warns: string[] } {
@@ -73,12 +85,7 @@ export function lintText(text: string, cfg: Config): { errs: string[]; warns: st
73
85
  }
74
86
 
75
87
 
76
- const paths = new Set<string>();
77
- const scan = liveText(text);
78
- for (const prefix of cfg.brief.path_prefixes) {
79
- const re = new RegExp(`(${escapeReg(prefix)}[\\w./\\-]+)`, "g");
80
- for (const hit of scan.matchAll(re)) paths.add(hit[1]!);
81
- }
88
+ const paths = briefPaths(text, cfg);
82
89
  for (const raw of [...paths].toSorted()) {
83
90
  const p = clean(raw);
84
91
  if (p.endsWith("-") || p.endsWith("_")) continue;