neurastream 0.3.18 → 0.3.21

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.
Files changed (66) hide show
  1. package/README.md +88 -490
  2. package/package.json +1 -1
  3. package/src/adapters/index.ts +3 -2
  4. package/src/adapters/omp/adapter.ts +2 -1
  5. package/src/adapters/omp/auto-close.ts +64 -0
  6. package/src/adapters/omp/chat-commands.ts +161 -0
  7. package/src/adapters/omp/inbox.ts +221 -0
  8. package/src/adapters/omp/index.ts +138 -1050
  9. package/src/adapters/omp/launch.ts +35 -9
  10. package/src/adapters/omp/rate-limit-controller.ts +196 -0
  11. package/src/adapters/omp/rollover-controller.ts +334 -0
  12. package/src/adapters/omp/types.ts +143 -0
  13. package/src/cli/claim.ts +1 -3
  14. package/src/cli/commands.ts +33 -2
  15. package/src/cli/dispatch.ts +55 -30
  16. package/src/cli/guard.ts +0 -3
  17. package/src/cli/incident.ts +2 -2
  18. package/src/cli/metrics.ts +1 -1
  19. package/src/cli/recall.ts +6 -8
  20. package/src/cli/results-build.ts +2 -4
  21. package/src/cli/workspace.ts +13 -5
  22. package/src/core/adapter.ts +16 -0
  23. package/src/core/autonomy.ts +24 -21
  24. package/src/core/blockers.ts +326 -30
  25. package/src/core/file-lock.ts +71 -12
  26. package/src/core/guards/plan-edit.ts +338 -0
  27. package/src/core/guards/planner.ts +70 -0
  28. package/src/core/guards/review.ts +391 -0
  29. package/src/core/guards/spawn.ts +699 -0
  30. package/src/core/guards/state.ts +581 -0
  31. package/src/core/guards/stop.ts +235 -0
  32. package/src/core/guards/tool.ts +541 -0
  33. package/src/core/guards.ts +12 -2661
  34. package/src/core/incidents.ts +134 -99
  35. package/src/core/machine-guard.ts +23 -5
  36. package/src/core/main-start.ts +11 -9
  37. package/src/core/mr-sweep.ts +4 -2
  38. package/src/core/notify.ts +15 -15
  39. package/src/core/owner-log.ts +19 -17
  40. package/src/core/owner-topics.ts +38 -48
  41. package/src/core/owner-ui/auth.ts +164 -0
  42. package/src/core/owner-ui/data.ts +437 -0
  43. package/src/core/owner-ui/handlers.ts +250 -0
  44. package/src/core/owner-ui/messages.ts +209 -0
  45. package/src/core/owner-ui/render.ts +714 -0
  46. package/src/core/owner-ui/results.ts +266 -0
  47. package/src/core/owner-ui/server.ts +142 -0
  48. package/src/core/owner-ui.ts +11 -2118
  49. package/src/core/page-notes.ts +25 -0
  50. package/src/core/pages.ts +452 -78
  51. package/src/core/plan-approval.ts +24 -26
  52. package/src/core/queue/lib.ts +170 -137
  53. package/src/core/queue-cancel.ts +29 -15
  54. package/src/core/queue-check.ts +5 -7
  55. package/src/core/queue-close.ts +54 -29
  56. package/src/core/queue-finished.ts +9 -10
  57. package/src/core/queue-migrate.ts +1 -3
  58. package/src/core/queue-trim.ts +2 -4
  59. package/src/core/results.ts +0 -2
  60. package/src/core/rollover.ts +2 -3
  61. package/src/core/secret-redact.ts +65 -14
  62. package/src/core/tailscale.ts +79 -3
  63. package/src/core/team-client.ts +18 -6
  64. package/src/core/uninstall.ts +2 -0
  65. package/src/core/watch.ts +3 -2
  66. package/src/core/queue/env.ts +0 -14
@@ -0,0 +1,581 @@
1
+ // Shared guard state, primitives, and pure helpers.
2
+ // Zero imports from team-client.ts or sibling guards/* modules so the barrel export order is TDZ-safe.
3
+
4
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync } from "node:fs";
5
+ import path from "node:path";
6
+ import type { Decision } from "../adapter.ts";
7
+ import type { Claim, Unreachable } from "../claims.ts";
8
+ import { nowSec, strftime } from "../clock.ts";
9
+ import type { Config } from "../config.ts";
10
+ import { withFileLock, writeAtomicSync } from "../file-lock.ts";
11
+ import { appendOwnerMessage, openIncidents, ownerMessagesFile, type IncidentView } from "../incidents.ts";
12
+ import { ownerLogFile, recordOwnerLog } from "../owner-log.ts";
13
+ import { MAIN_ONLY_LINE } from "../plan-approval.ts";
14
+ import * as q from "../queue/lib.ts";
15
+ import type { Plan } from "../queue/lib.ts";
16
+ import { ownerText, UNANSWERED_PREFIX } from "../rollover.ts";
17
+ import { levelFor, readLevels } from "../rule-levels.ts";
18
+
19
+ export const ALLOW: Decision = { allow: true, reason: "" };
20
+
21
+ /**
22
+ * The plan-edit decision: a Decision plus the allow-with-amendment fields of the plan-read guard
23
+ * (I-20261025-208). On allow, `rewrite` names the file the caller writes back (the auto-listed
24
+ * read section) and `note` is the receipt for the tool result; both travel through the guard
25
+ * CLI's JSON output. They live here, not on the shared Decision, so every other check keeps the
26
+ * plain shape.
27
+ */
28
+ export interface PlanEditDecision extends Decision {
29
+ rewrite?: { path: string; text: string };
30
+ note?: string;
31
+ }
32
+
33
+ /** Who launches an agent: Main's launch may use a plan review's exemption, a sub's never may (plan 20261028_1600 P4i). */
34
+ export type Spawner = "main" | "sub";
35
+
36
+ /** Every refusal names its guard rule id (plan 20261110_1746 P8a); the id ends the text as ` [rule <id>]`. */
37
+ export function deny(reason: string, rule: string): Decision {
38
+ return { allow: false, reason: `${reason} [rule ${rule}]` };
39
+ }
40
+
41
+ /** Guard-log line, `<ISO UTC> [<main id>] <line>`; a failed append is swallowed. */
42
+ export function log(file: string, line: string): void {
43
+ try {
44
+ appendFileSync(file, `${new Date().toISOString()} [${mainId()}] ${line}\n`);
45
+ } catch {}
46
+ }
47
+
48
+ // Owner message that may call work off ("don't do X" must hold even if no plan
49
+ // exists yet). Flagged until Main records it with queue-cancel; no spawn and no stop until then.
50
+ export const CANCEL_TODO =
51
+ 'the owner\'s message may call work off. Record it first: an indexed plan → `queue-cancel <plan> "<owner words>"`; ' +
52
+ 'work with no plan (yet) → `queue-cancel --never "<what must not be done>" "<owner words>" [--repo <repo>]`; ' +
53
+ 'nothing was called off → `queue-cancel --not-a-cancel "<why>"`.';
54
+
55
+ /** A live plan file (archived plans excluded); Main's plan-text checks run on these. Subfolders like docs/plans/immediate/ hold live plans too. */
56
+ export const MAIN_PLAN_FILE = /\/docs\/plans\/(?!archive\/)(?:[^/]+\/)*[^/]+\.md$/;
57
+
58
+ // --- state the decisions keep in the queue state dir (survives one-shot CLI calls) ---
59
+
60
+ export interface EditWindow {
61
+ used: string[];
62
+ windowStart: number;
63
+ /** Main tool calls since the last owner prompt or terminal hand-back (main_call_exempt_tools never count). */
64
+ mainCalls: number;
65
+ /** When the first of those calls was counted; the count expires MAIN_CALLS_RESET_SEC later. */
66
+ mainCallsStart?: number;
67
+ }
68
+
69
+ // --- this Main's identity (plan 20261027_1300_multi_main P2) ---
70
+
71
+ /** What `neurastream main --name` accepts and what `NEURASTREAM_MAIN_ID` may hold. */
72
+ export const MAIN_ID_RE = /^[a-z0-9-]{1,24}$/;
73
+
74
+ /** This Main's id: the launcher sets `NEURASTREAM_MAIN_ID` (default `main`); a bogus value falls back to `main`. */
75
+ export function mainId(): string {
76
+ const id = process.env.NEURASTREAM_MAIN_ID ?? "main";
77
+ return MAIN_ID_RE.test(id) ? id : "main";
78
+ }
79
+
80
+ /** One-time move of the pre-multi-main top-level state into `mains/main/` (renameSync, idempotent). */
81
+ function moveLegacyState(stateDir: string, dir: string): void {
82
+ if (existsSync(dir)) return;
83
+ mkdirSync(dir, { recursive: true });
84
+ for (const name of ["edit-window.json", "rollover"]) {
85
+ try {
86
+ renameSync(path.join(stateDir, name), path.join(dir, name));
87
+ } catch {}
88
+ }
89
+ }
90
+
91
+ /** This Main's own state dir, `<queue_state>/mains/<id>/`: edit window, rollover notes, running lock. */
92
+ export function mainStateDir(cfgOrPaths: Config | Pick<q.QueuePaths, "queue_state">): string {
93
+ const stateDir = "paths" in cfgOrPaths ? cfgOrPaths.paths.queue_state : cfgOrPaths.queue_state;
94
+ const id = mainId();
95
+ const dir = path.join(stateDir, "mains", id);
96
+ if (id === "main") moveLegacyState(stateDir, dir);
97
+ return dir;
98
+ }
99
+
100
+ function windowFile(paths: Pick<q.QueuePaths, "queue_state">): string {
101
+ return path.join(mainStateDir(paths), "edit-window.json");
102
+ }
103
+
104
+ export function readWindow(paths: Pick<q.QueuePaths, "queue_state">): EditWindow {
105
+ try {
106
+ const w = JSON.parse(readFileSync(windowFile(paths), "utf8")) as Partial<EditWindow>;
107
+ if (Array.isArray(w.used) && typeof w.windowStart === "number")
108
+ return { used: w.used, windowStart: w.windowStart, mainCalls: typeof w.mainCalls === "number" ? w.mainCalls : 0, mainCallsStart: typeof w.mainCallsStart === "number" ? w.mainCallsStart : 0 };
109
+ } catch {}
110
+ return { used: [], windowStart: 0, mainCalls: 0 };
111
+ }
112
+
113
+ export function writeWindow(w: EditWindow, paths: Pick<q.QueuePaths, "queue_state">): void {
114
+ const file = windowFile(paths);
115
+ try {
116
+ withFileLock(`${file}.lock`, () => {
117
+ writeAtomicSync(file, JSON.stringify(w, null, 1));
118
+ });
119
+ } catch (err) {
120
+ log(`${paths.queue_state}/../main-guard.log`, `cannot write ${file}: ${err}`);
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Locked read-modify-write helper for `edit-window.json`.
126
+ *
127
+ * Args:
128
+ * paths (Pick<q.QueuePaths, "queue_state">): Queue state paths
129
+ * mutate ((w: EditWindow) => { write: boolean; result: T }): Mutation callback executed under lock
130
+ *
131
+ * Returns:
132
+ * T: Callback result
133
+ */
134
+ export function updateWindow<T>(paths: Pick<q.QueuePaths, "queue_state">, mutate: (w: EditWindow) => { write: boolean; result: T }): T {
135
+ const file = windowFile(paths);
136
+ try {
137
+ return withFileLock(`${file}.lock`, () => {
138
+ const w = readWindow(paths);
139
+ const { write, result } = mutate(w);
140
+ if (write) writeAtomicSync(file, JSON.stringify(w, null, 1));
141
+ return result;
142
+ });
143
+ } catch (err) {
144
+ log(`${paths.queue_state}/../main-guard.log`, `cannot write ${file}: ${err}`);
145
+ return mutate(readWindow(paths)).result;
146
+ }
147
+ }
148
+
149
+ /**
150
+ * A count older than this starts over, even with no owner message or hand-back: a blocked stop is
151
+ * a continuation, not a hand-back, so without it a capped Main with no owner awake stays refused
152
+ * all night.
153
+ */
154
+ export const MAIN_CALLS_RESET_SEC = 15 * 60;
155
+
156
+ export function mainCallsExpired(w: EditWindow): boolean {
157
+ return w.mainCalls > 0 && nowSec() - (w.mainCallsStart ?? 0) >= MAIN_CALLS_RESET_SEC;
158
+ }
159
+
160
+ /** Main's terminal hand-back (the adapter's agent_end without willContinue): the turn is over, so
161
+ * the next one starts at 0 calls. The edit window keeps its own reset rules. */
162
+ export function resetMainCalls(paths: Pick<q.QueuePaths, "queue_state">): void {
163
+ updateWindow(paths, (w) => {
164
+ if (w.mainCalls === 0) return { write: false, result: undefined };
165
+ w.mainCalls = 0;
166
+ return { write: true, result: undefined };
167
+ });
168
+ }
169
+
170
+ // --- spawn & staffing persistence ---
171
+
172
+ function spawnsFile(paths: Pick<q.QueuePaths, "queue_state">): string {
173
+ return path.join(paths.queue_state, "spawns.json");
174
+ }
175
+
176
+ function staffingFile(paths: Pick<q.QueuePaths, "queue_state">): string {
177
+ return path.join(paths.queue_state, "staffing.json");
178
+ }
179
+
180
+ /** One staffing.json entry: the task names of a plan's newest spawn and when it was spawned (epoch sec). An old bare-array entry has no spawn time and reads as at 0. */
181
+ export interface StaffingEntry {
182
+ names: string[];
183
+ at: number;
184
+ }
185
+
186
+ /** plan → its staffing entry (staffing.json). */
187
+ export function readStaffingEntries(paths: Pick<q.QueuePaths, "queue_state">): Record<string, StaffingEntry> {
188
+ try {
189
+ const raw: unknown = JSON.parse(readFileSync(staffingFile(paths), "utf8"));
190
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
191
+ const out: Record<string, StaffingEntry> = {};
192
+ for (const [k, v] of Object.entries(raw)) {
193
+ if (Array.isArray(v)) out[k] = { names: v.map(String), at: 0 };
194
+ else if (v && typeof v === "object" && "names" in v && Array.isArray(v.names)) {
195
+ out[k] = { names: v.names.map(String), at: "at" in v ? Number(v.at) || 0 : 0 };
196
+ }
197
+ }
198
+ return out;
199
+ } catch {
200
+ return {};
201
+ }
202
+ }
203
+
204
+ /** plan → the task names of its newest spawn (staffing.json); read for the staffed check. */
205
+ export function readStaffing(paths: Pick<q.QueuePaths, "queue_state">): Record<string, string[]> {
206
+ return Object.fromEntries(Object.entries(readStaffingEntries(paths)).map(([f, e]) => [f, e.names]));
207
+ }
208
+
209
+ export function readSpawns(paths: Pick<q.QueuePaths, "queue_state">): Record<string, string> {
210
+ try {
211
+ const raw: unknown = JSON.parse(readFileSync(spawnsFile(paths), "utf8"));
212
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
213
+ const out: Record<string, string> = {};
214
+ for (const [k, v] of Object.entries(raw)) out[k] = String(v);
215
+ return out;
216
+ } catch {
217
+ return {};
218
+ }
219
+ }
220
+
221
+ /** Remember the "## Progress" hash of the plans an agent was just spawned on. With `staffing`, also record the spawn's task names per plan (staffing.json); a plan's entry is replaced by the newest spawn that names it. */
222
+ export function recordSpawns(files: string[], paths: Pick<q.QueuePaths, "queue_state">, staffing: Record<string, string[]> = {}): void {
223
+ const spFile = spawnsFile(paths);
224
+ try {
225
+ withFileLock(`${spFile}.lock`, () => {
226
+ const s = readSpawns(paths);
227
+ for (const f of files) {
228
+ try {
229
+ s[f] = q.sha(q.progressBody(readFileSync(f, "utf8")));
230
+ } catch {}
231
+ }
232
+ writeAtomicSync(spFile, JSON.stringify(s, null, 1));
233
+ });
234
+ } catch (err) {
235
+ log(`${paths.queue_state}/../main-guard.log`, `cannot write ${spFile}: ${err}`);
236
+ }
237
+ if (!Object.keys(staffing).length) return;
238
+ const stFile = staffingFile(paths);
239
+ try {
240
+ withFileLock(`${stFile}.lock`, () => {
241
+ const st = readStaffingEntries(paths);
242
+ const at = nowSec();
243
+ for (const [f, names] of Object.entries(staffing)) if (names.length) st[f] = { names: [...names], at };
244
+ writeAtomicSync(stFile, JSON.stringify(st, null, 1));
245
+ });
246
+ } catch (err) {
247
+ log(`${paths.queue_state}/../main-guard.log`, `cannot write ${stFile}: ${err}`);
248
+ }
249
+ }
250
+
251
+ /**
252
+ * Remove one plan's entry from `spawns.json` atomically under its file lock.
253
+ *
254
+ * Args:
255
+ * file (string): Absolute plan file path to remove
256
+ * paths (Pick<q.QueuePaths, "queue_state">): Queue state paths
257
+ *
258
+ * Returns:
259
+ * void
260
+ */
261
+ export function deleteSpawnRecord(file: string, paths: Pick<q.QueuePaths, "queue_state">): void {
262
+ const spFile = spawnsFile(paths);
263
+ try {
264
+ withFileLock(`${spFile}.lock`, () => {
265
+ if (!existsSync(spFile)) return;
266
+ const s = readSpawns(paths);
267
+ if (!(file in s)) return;
268
+ delete s[file];
269
+ writeAtomicSync(spFile, JSON.stringify(s, null, 1));
270
+ });
271
+ } catch {}
272
+ }
273
+
274
+ /** Plans with a running subagent: one of the plan's staffing names equals a running job label, or the label is that name with the spawner's uniqueness suffix ("-2", "-3", …; real snapshot 2026-10-25: `allocate()` keeps the exact name first, then appends). Pure; no job info staffs nothing. */
275
+ export function staffedPlans(staffing: Record<string, string[]>, runningJobs: string[] | undefined): string[] {
276
+ if (!runningJobs?.length) return [];
277
+ return Object.entries(staffing)
278
+ .filter(([, names]) => names.some(n => runningJobs.some(j => j === n || j.startsWith(`${n}-`))))
279
+ .map(([file]) => file);
280
+ }
281
+
282
+ /** Re-key a plan's spawn hash after its Progress body was trimmed. Only a hash that matched the old body moves. Pure. */
283
+ export function rekeySpawns(spawns: Record<string, string>, file: string, before: string, after: string): boolean {
284
+ if (spawns[file] !== q.sha(before)) return false;
285
+ spawns[file] = q.sha(after);
286
+ return true;
287
+ }
288
+
289
+ /** Apply rekeySpawns to the stored spawn hashes under the spawns.json lock. */
290
+ export function rekeySpawnFile(file: string, before: string, after: string, paths: Pick<q.QueuePaths, "queue_state">): void {
291
+ const spFile = spawnsFile(paths);
292
+ try {
293
+ withFileLock(`${spFile}.lock`, () => {
294
+ const s = readSpawns(paths);
295
+ if (!rekeySpawns(s, file, before, after)) return;
296
+ writeAtomicSync(spFile, JSON.stringify(s, null, 1));
297
+ });
298
+ } catch (err) {
299
+ log(`${paths.queue_state}/../main-guard.log`, `cannot write ${spFile}: ${err}`);
300
+ }
301
+ }
302
+
303
+ // --- per-spawn call budgets ---
304
+
305
+ // A per-spawn call budget: `Call budget: <N>` on its own line in a task brief (the task's own
306
+ // text wins over the shared context). Main sets it at spawn time; the run's hard stop is N and
307
+ // its warning band has the global width (sub_max_calls - sub_warn_calls), floored at 1.
308
+ const BUDGET_LINE = /^\s*(?:[-*]\s+)?call budget:\s*(\d{1,4})\s*$/im;
309
+
310
+ /** The first `Call budget: <N>` line of a brief, or null. */
311
+ export function briefBudget(brief: string): number | null {
312
+ const m = BUDGET_LINE.exec(brief);
313
+ return m ? Number(m[1]) : null;
314
+ }
315
+
316
+ function budgetsFile(paths: Pick<q.QueuePaths, "queue_state">): string {
317
+ return path.join(paths.queue_state, "spawn-budgets.json");
318
+ }
319
+
320
+ /** The budgets recorded at spawn: task name → calls (next to the spawn hashes). */
321
+ export function readBudgets(dir: string): Record<string, number> {
322
+ try {
323
+ const raw: unknown = JSON.parse(readFileSync(path.join(dir, "spawn-budgets.json"), "utf8"));
324
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
325
+ const out: Record<string, number> = {};
326
+ for (const [k, v] of Object.entries(raw)) if (typeof v === "number" && Number.isFinite(v)) out[k] = v;
327
+ return out;
328
+ } catch {
329
+ return {};
330
+ }
331
+ }
332
+
333
+ /** Remember the named tasks' call budgets atomically under lock; a name's old budget is replaced, a null one removed. */
334
+ export function recordBudgets(entries: Record<string, number | null>, paths: Pick<q.QueuePaths, "queue_state">): void {
335
+ const names = Object.keys(entries);
336
+ if (!names.length) return;
337
+ const bFile = budgetsFile(paths);
338
+ try {
339
+ withFileLock(`${bFile}.lock`, () => {
340
+ const budgets = readBudgets(paths.queue_state);
341
+ for (const n of names) {
342
+ const b = entries[n];
343
+ if (b == null) delete budgets[n];
344
+ else budgets[n] = b;
345
+ }
346
+ writeAtomicSync(bFile, JSON.stringify(budgets, null, 1));
347
+ });
348
+ } catch (err) {
349
+ log(`${paths.queue_state}/../main-guard.log`, `cannot write ${bFile}: ${err}`);
350
+ }
351
+ }
352
+
353
+ /** A sub's hard call cap: the budget recorded for its task name at spawn, else the global cap. */
354
+ export function subCallCap(agentId: string, cfg: Config): number {
355
+ return readBudgets(cfg.paths.queue_state)[agentId] ?? cfg.guards.sub_max_calls;
356
+ }
357
+
358
+ // --- Main's read log (`main-reads.json` in the queue state dir): files Main has read itself ---
359
+
360
+ const MAIN_READ_KEEP_MS = 7 * 86_400_000;
361
+ const GREP_LINE = /^([^\s:]+):\d+:/gm;
362
+
363
+ /** Logs existing files as read now atomically under lock; entries older than 7 days are dropped on each write. */
364
+ export function recordMainReads(files: string[], paths: Pick<q.QueuePaths, "queue_state">, now = Date.now()): void {
365
+ const file = path.join(paths.queue_state, "main-reads.json");
366
+ const existing = files.filter(f => {
367
+ try {
368
+ return statSync(f).isFile();
369
+ } catch {
370
+ return false;
371
+ }
372
+ });
373
+ if (existing.length === 0) return;
374
+ try {
375
+ withFileLock(`${file}.lock`, () => {
376
+ let reads: Record<string, string> = {};
377
+ try {
378
+ const parsed = JSON.parse(readFileSync(file, "utf8")) as unknown;
379
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) reads = parsed as Record<string, string>;
380
+ } catch {}
381
+ const stamp = new Date(now).toISOString();
382
+ for (const f of existing) reads[f] = stamp;
383
+ const cutoff = now - MAIN_READ_KEEP_MS;
384
+ for (const [f, t] of Object.entries(reads)) if (!(Date.parse(t) >= cutoff)) delete reads[f];
385
+ writeAtomicSync(file, JSON.stringify(reads, null, 2));
386
+ });
387
+ } catch {}
388
+ }
389
+
390
+ export function readMainReads(paths: Pick<q.QueuePaths, "queue_state">): Record<string, string> {
391
+ try {
392
+ return JSON.parse(readFileSync(path.join(paths.queue_state, "main-reads.json"), "utf8")) as Record<string, string>;
393
+ } catch {
394
+ return {};
395
+ }
396
+ }
397
+
398
+ export function recordMainResult(tool: string, input: Record<string, unknown>, cwd: string, text: string, paths: Pick<q.QueuePaths, "queue_state">): void {
399
+ const base = typeof input.cwd === "string" ? path.resolve(cwd, q.expandHome(input.cwd)) : cwd;
400
+ const dir = q.shellCwd(String(input.command ?? input.code ?? ""), base);
401
+ recordMainReads([...text.matchAll(GREP_LINE)].map(m => path.resolve(dir, m[1] ?? "")), paths);
402
+ }
403
+
404
+ // --- shared pure helpers used across multiple guard submodules ---
405
+
406
+ /** Applies the owner's rule level to a refusal. Only with `tuning.guards` on; a refusal with no `[rule <id>]` suffix, or a pinned, unset or corrupt id, stays `block`. */
407
+ export function tuned(d: Decision, cfg: Config): Decision {
408
+ if (d.allow || !cfg.tuning.guards) return d;
409
+ const id = /\[rule ([\w.-]+)\]$/.exec(d.reason)?.[1];
410
+ if (!id) return d;
411
+ const level = levelFor(readLevels(cfg), id);
412
+ if (level === "block") return d;
413
+ return { allow: true, reason: level === "tell" ? d.reason : "" };
414
+ }
415
+
416
+ /** Epoch ms when the owner's open unlock window closes, or null when the guard is locked. */
417
+ export function unlockUntilMs(cfg: Config): number | null {
418
+ try {
419
+ const until = statSync(cfg.paths.unlock).mtimeMs + cfg.guards.unlock_minutes * 60_000;
420
+ return Date.now() < until ? until : null;
421
+ } catch {
422
+ return null;
423
+ }
424
+ }
425
+
426
+ /**
427
+ * One line for Main's prompt while the owner's unlock is open. A chat "unlock" is swallowed by the
428
+ * input handler (the model never sees the message), so the adapter also wakes Main with a message.
429
+ */
430
+ export function unlockLine(cfg: Config): string {
431
+ const until = unlockUntilMs(cfg);
432
+ if (until === null) return "";
433
+ const hhmm = new Date(until).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" });
434
+ return `\nguards: UNLOCKED until ${hhmm} — guard files are open; do the step that waited on the unlock now.`;
435
+ }
436
+
437
+ // Text files never count: only files apart from .md or .txt do.
438
+ function freeExt(cfg: Config): RegExp {
439
+ return new RegExp(cfg.guards.free_ext, "i");
440
+ }
441
+
442
+ export function isProjectPath(p: string, cfg: Config): boolean {
443
+ const roots = cfg.paths.work_roots.map(r => q.expandHome(r));
444
+ const free = cfg.guards.free_prefixes.map(f => q.expandHome(f));
445
+ return (
446
+ roots.some(r => p.startsWith(r) && p.length > r.length) &&
447
+ !free.some(f => p.startsWith(f) || `${p}/` === f) &&
448
+ !q.isOrchestrationPath(p, q.activePlans(cfg.paths), cfg.paths.queue_index)
449
+ );
450
+ }
451
+
452
+ // Project files this call would change; empty = the call does not count toward the limit.
453
+ // Only real write targets count: reads, git landing commands (commit, push, merge, pull, rebase,
454
+ // cherry-pick, worktree) and paths merely mentioned in a body or command are free.
455
+ export function changedProjectFiles(toolName: string, input: Record<string, unknown>, cwd: string, cfg: Config): string[] {
456
+ return q
457
+ .writeTargets(toolName, input ?? {}, cwd, cfg.paths)
458
+ .filter(p => !freeExt(cfg).test(p) && isProjectPath(p, cfg));
459
+ }
460
+
461
+ /**
462
+ * Main's tool result: each `path:line:` at a line start (grep -n / grep -rn output) names a file
463
+ * Main read. Paths resolve against the directory the call ran in (its `cwd`, then any `cd`).
464
+ */
465
+ export function revertMainEdit(tool: string, input: Record<string, unknown>, cwd: string, cfg: Config): void {
466
+ const files = changedProjectFiles(tool, input, cwd, cfg);
467
+ if (!files.length) return;
468
+ const entry = `${tool}:${files[0]!}`;
469
+ updateWindow(cfg.paths, (w) => {
470
+ const idx = w.used.lastIndexOf(entry);
471
+ if (idx < 0) return { write: false, result: undefined };
472
+ w.used.splice(idx, 1);
473
+ return { write: true, result: undefined };
474
+ });
475
+ }
476
+
477
+ // A bypass launch goes around the harness guards (today's config entry names a CLI runner), so it
478
+ // needs an open plan: first word ... last word of the config entry must appear in the command line.
479
+ export function bypassRegExp(entry: string): RegExp {
480
+ const words = entry.trim().split(/\s+/).filter(Boolean);
481
+ if (words.length === 1) return new RegExp(`\\b${(words[0] ?? "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`);
482
+ const head = (words[0] ?? "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
483
+ const tail = (words[words.length - 1] ?? "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
484
+ return new RegExp(`\\b${head}\\b[^\\n]*\\b${tail}\\b`);
485
+ }
486
+
487
+ // --- owner prose & incidents helpers ---
488
+
489
+ /** P3 (plan 20261031_1207): the text is owner prose — not Main's own guard output, a system notice, a task result — so its words are the owner's. Gates both the owner-message store and the cancel flag. The P5b resume prefix makes a wrapped machine prompt owner-shaped, so it is excluded here like its unwrapped form. */
490
+ export function isOwnerProse(text: string): boolean {
491
+ const t = text.trimStart();
492
+ return !(t.startsWith("main-guard:") || t.startsWith(UNANSWERED_PREFIX) || t.startsWith("<system-notice>") || text.includes("<task-result"));
493
+ }
494
+
495
+ export function recordOwnerMessage(text: string, cfg: Config): void {
496
+ if (!isOwnerProse(text)) return;
497
+ const owner = ownerText(text);
498
+ if (owner) {
499
+ try {
500
+ recordOwnerLog(cfg, "owner", owner);
501
+ } catch (err) {
502
+ log(cfg.paths.guard_log, `cannot write ${ownerLogFile(cfg.paths)}: ${err}`);
503
+ }
504
+ }
505
+ try {
506
+ appendOwnerMessage(text, cfg.paths, nowSec());
507
+ } catch (err) {
508
+ log(cfg.paths.guard_log, `cannot write ${ownerMessagesFile(cfg.paths)}: ${err}`);
509
+ }
510
+ }
511
+
512
+ export function openIncidentList(cfg: Config): IncidentView[] {
513
+ try {
514
+ return openIncidents(cfg);
515
+ } catch (err) {
516
+ log(cfg.paths.guard_log, `cannot read incidents: ${err}`);
517
+ return [];
518
+ }
519
+ }
520
+
521
+ /** The injected prompt line for one open incident, with the two ways to clear it. */
522
+ export function incidentLine(i: IncidentView): string {
523
+ return (
524
+ `INCIDENT ${i.id} [${i.source}/${i.kind}]: ${i.summary} — plan the fix: \`neurastream incident plan ${i.id} <plan.md>\`` +
525
+ ` (the plan must contain "INCIDENT ${i.id}"), or dismiss: \`neurastream incident dismiss ${i.id} --why "<text>"\``
526
+ );
527
+ }
528
+
529
+ /** The held refusal (plan 20261027_1300 P3, widened 20261027_1305 P3): a down team server, another member's row, or today's "plan X is held by Main B since HH:MM" (HH:MM local). */
530
+ export function heldProblem(file: string, held: Claim | Unreachable): string {
531
+ if ("unreachable" in held) return `team server ${held.unreachable} unreachable; plan ${file} is refused until it answers`;
532
+ if (held.mine === false) return `plan ${file} is held by another member's Main ${held.main} since ${strftime(held.since, "%H:%M")}`;
533
+ return `plan ${file} is held by Main ${held.main} since ${strftime(held.since, "%H:%M")}`;
534
+ }
535
+
536
+ // --- plan progress & phase helpers ---
537
+
538
+ // Phase ids (P1, P2, P4a ...) in the plan's Phases section that are not ticked yet.
539
+ export function unticked(p: Plan): string[] {
540
+ const phases = q.sections(p.text).get("phases") ?? "";
541
+ return [...phases.matchAll(/^\s*[-*]\s+\[ \]\s+(P\d+[a-z]?)\b/gm)].map(m => m[1]!);
542
+ }
543
+
544
+ /** Phase ids an edit newly ticks: `[ ]` in `before`, `[x]` in `after` (P6, read from the Phases section like unticked). */
545
+ export function newlyTicked(before: string, after: string): string[] {
546
+ const was = new Set([...(q.sections(before).get("phases") ?? "").matchAll(/^\s*[-*]\s+\[ \]\s+(P\d+[a-z]?)\b/gm)].map(m => m[1]!));
547
+ return [...(q.sections(after).get("phases") ?? "").matchAll(/^\s*[-*]\s+\[[xX]\]\s+(P\d+[a-z]?)\b/gm)].map(m => m[1]!).filter(id => was.has(id));
548
+ }
549
+
550
+ /** One "## Progress" entry: its "- " line plus indented continuation lines (trimProgressBody's entry rule). */
551
+ export function progressEntries(text: string): string[] {
552
+ const blocks: string[] = [];
553
+ const lines = q.progressBody(text).split("\n");
554
+ for (let i = 0; i < lines.length; i++) {
555
+ const head = lines[i];
556
+ if (head === undefined || !head.startsWith("- ") || MAIN_ONLY_LINE.test(head)) continue;
557
+ const block = [head];
558
+ while (i + 1 < lines.length) {
559
+ const cont = lines[i + 1];
560
+ if (cont === undefined || !/^[ \t]/.test(cont)) break;
561
+ block.push(cont);
562
+ i++;
563
+ }
564
+ blocks.push(block.join("\n"));
565
+ }
566
+ return blocks;
567
+ }
568
+
569
+ /** Entries an edit adds or rewrites: blocks whose text was not in the Progress section before. */
570
+ export function newProgressEntries(before: string, after: string): string[] {
571
+ const old = new Set(progressEntries(before));
572
+ return progressEntries(after).filter(b => !old.has(b));
573
+ }
574
+
575
+ /** The value after the entry's last "Findings:", or null when it has no Findings line with content. A "Findings:"
576
+ * quoted earlier in the entry (e.g. inside resume steps) is entry text, never the findings (I-20261025-51). */
577
+ export function findingsValue(block: string): string | null {
578
+ const line = block.split("\n").findLast(l => l.includes("Findings:"));
579
+ if (!line) return null;
580
+ return line.slice(line.lastIndexOf("Findings:") + "Findings:".length).trim() || null;
581
+ }