neurastream 0.2.61 → 0.2.63
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 +36 -0
- package/package.json +1 -1
- package/src/adapters/omp/index.ts +36 -30
- package/src/adapters/omp/launch.ts +6 -1
- package/src/cli/commands.ts +3 -2
- package/src/cli/dispatch.ts +76 -1
- package/src/cli/init.ts +8 -0
- package/src/cli/metrics.ts +15 -55
- package/src/cli/pages.ts +10 -3
- package/src/cli/ui.ts +8 -1
- package/src/cli/watch-setup.ts +74 -0
- package/src/core/brief-lint.ts +4 -0
- package/src/core/ci.ts +271 -0
- package/src/core/config.ts +73 -1
- package/src/core/guards.ts +146 -42
- package/src/core/heartbeat.ts +79 -0
- package/src/core/incident-detectors.ts +104 -17
- package/src/core/incidents.ts +31 -4
- package/src/core/main-start.ts +83 -2
- package/src/core/metrics.ts +3 -2
- package/src/core/mr-sweep.ts +14 -7
- package/src/core/owner-ui.ts +4 -2
- package/src/core/plan-approval.ts +1 -1
- package/src/core/queue/lib.ts +85 -10
- package/src/core/queue-cancel.ts +1 -1
- package/src/core/queue-check.ts +8 -2
- package/src/core/queue-close.ts +19 -2
- package/src/core/queue-trim.ts +4 -0
- package/src/core/report.ts +88 -6
- package/src/core/rollover.ts +47 -5
- package/src/core/ui-setup.ts +5 -3
- package/src/core/waiting-check.ts +131 -0
- package/src/core/watch.ts +509 -0
- package/templates/config.yml +27 -4
- package/templates/help/watch.txt +45 -0
- package/templates/launchd/neurastream-watch.plist +17 -0
- package/templates/queue/TEMPLATE.md +5 -1
- package/templates/systemd/neurastream-watch.service +6 -0
- package/templates/systemd/neurastream-watch.timer +10 -0
package/src/core/guards.ts
CHANGED
|
@@ -30,10 +30,12 @@ import { currentTier, takeGo } from "./autonomy.ts";
|
|
|
30
30
|
import { approvalProblem, MAIN_ONLY_LINE, reviewHash } from "./plan-approval.ts";
|
|
31
31
|
export { reviewHash };
|
|
32
32
|
import type { Config } from "./config.ts";
|
|
33
|
-
import { openIncidents, ownerMessagesFile, ownerSaid, readOwnerMessages, type IncidentView, type OwnerMessage } from "./incidents.ts";
|
|
33
|
+
import { openIncidents, ownerMessagesFile, ownerSaid, readOwnerAnswers, readOwnerMessages, type IncidentView, type OwnerMessage, writeOwnerStore } from "./incidents.ts";
|
|
34
|
+
import { UNANSWERED_PREFIX } from "./rollover.ts";
|
|
34
35
|
import { notifyProtectedPaths, notifySecretReadHit } from "./notify.ts";
|
|
35
36
|
import { defaultRunner, listOpenMrs, mentioned, type CommandRunner, type OpenMr } from "./mr-sweep.ts";
|
|
36
37
|
import { unlandedRows } from "./wip-check.ts";
|
|
38
|
+
import { recheckHolds, staleFiles } from "./waiting-check.ts";
|
|
37
39
|
import * as q from "./queue/lib.ts";
|
|
38
40
|
import type { Plan } from "./queue/lib.ts";
|
|
39
41
|
|
|
@@ -149,6 +151,11 @@ interface PlanReview {
|
|
|
149
151
|
by?: string;
|
|
150
152
|
}
|
|
151
153
|
|
|
154
|
+
/** A CODE REVIEW record (P6): the plan phase ids (P1, P4a, …) the entry names, for the tick gate. */
|
|
155
|
+
interface CodeReview extends PlanReview {
|
|
156
|
+
phases: string[];
|
|
157
|
+
}
|
|
158
|
+
|
|
152
159
|
function planReviewsFile(): string {
|
|
153
160
|
return path.join(q.STATE_DIR, "plan-reviews.json");
|
|
154
161
|
}
|
|
@@ -161,19 +168,27 @@ function readPlanReviews(): Record<string, PlanReview> {
|
|
|
161
168
|
return {};
|
|
162
169
|
}
|
|
163
170
|
|
|
164
|
-
function
|
|
171
|
+
function readCodeReviews(): Record<string, CodeReview> {
|
|
172
|
+
try {
|
|
173
|
+
const r = JSON.parse(readFileSync(planReviewsFile(), "utf8")) as { code?: Record<string, CodeReview> };
|
|
174
|
+
if (r.code && typeof r.code === "object") return r.code;
|
|
175
|
+
} catch {}
|
|
176
|
+
return {};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function writePlanReviews(reviews: Record<string, PlanReview>, code: Record<string, CodeReview>, cfg: Config): void {
|
|
165
180
|
try {
|
|
166
181
|
mkdirSync(q.STATE_DIR, { recursive: true });
|
|
167
|
-
writeFileSync(planReviewsFile(), JSON.stringify({ reviews }, null, 1));
|
|
182
|
+
writeFileSync(planReviewsFile(), JSON.stringify({ reviews, code }, null, 1));
|
|
168
183
|
} catch (err) {
|
|
169
184
|
log(cfg.paths.plan_guard_log, `cannot write ${planReviewsFile()}: ${err}`);
|
|
170
185
|
}
|
|
171
186
|
}
|
|
172
187
|
|
|
173
|
-
/** The progress entry that records a review; only a subagent's edit can carry one. The verdict is the match, never a substring. */
|
|
174
|
-
const REVIEW_LINE = /^- (?:\d{4}-\d{2}-\d{2} \d{2}:\d{2} [^\s:]+: )?PLAN REVIEW: (PASS|FAIL)\b/;
|
|
188
|
+
/** The progress entry that records a review — PLAN for the spawn gate, CODE for the phase tick gate (P6); only a subagent's edit can carry one. The verdict is the match, never a substring. */
|
|
189
|
+
const REVIEW_LINE = /^- (?:\d{4}-\d{2}-\d{2} \d{2}:\d{2} [^\s:]+: )?(PLAN|CODE) REVIEW: (PASS|FAIL)\b/;
|
|
175
190
|
/** Any entry that opens like a review line; one that REVIEW_LINE does not match is restored, not recorded. */
|
|
176
|
-
const REVIEW_LOOKALIKE = /^- (?:\d{4}-\d{2}-\d{2} \d{2}:\d{2} [^\s:]+: )?PLAN REVIEW\b/;
|
|
191
|
+
const REVIEW_LOOKALIKE = /^- (?:\d{4}-\d{2}-\d{2} \d{2}:\d{2} [^\s:]+: )?(PLAN|CODE) REVIEW\b/;
|
|
177
192
|
|
|
178
193
|
/** Who launches an agent: Main's launch may use a plan review's exemption, a sub's never may (plan 20261028_1600 P4i). */
|
|
179
194
|
export type Spawner = "main" | "sub";
|
|
@@ -183,10 +198,11 @@ export type Spawner = "main" | "sub";
|
|
|
183
198
|
* matches the plan text — progress-only edits keep a PASS valid, any other change expires it,
|
|
184
199
|
* a FAIL is denied with its first finding. A review spawn itself — an agent from review.agents
|
|
185
200
|
* whose brief has the `Plan review: <plan>` line — is exempt when Main launches it. P5 removed
|
|
186
|
-
* the cutover: every named plan is gated.
|
|
201
|
+
* the cutover: every named plan is gated. review.plan: false skips the gate (P6); an empty
|
|
202
|
+
* review.agents list no longer turns it off.
|
|
187
203
|
*/
|
|
188
204
|
export function reviewPassProblem(named: string[], brief: string, agent: string, cfg: Config, spawner: Spawner): string | null {
|
|
189
|
-
if (!cfg.review.
|
|
205
|
+
if (!cfg.review.plan) return null; // P6: review.plan: false skips the PASS gate; an empty review.agents list no longer does
|
|
190
206
|
const reviews = readPlanReviews();
|
|
191
207
|
for (const file of named) {
|
|
192
208
|
if (isReviewSpawn(file, brief, agent, cfg, spawner)) continue;
|
|
@@ -204,7 +220,7 @@ export function reviewPassProblem(named: string[], brief: string, agent: string,
|
|
|
204
220
|
return null;
|
|
205
221
|
}
|
|
206
222
|
|
|
207
|
-
/** A subagent's `PLAN REVIEW
|
|
223
|
+
/** A subagent's `PLAN REVIEW` or `CODE REVIEW` (P6) entry records the review of the plan it edited; Main's edit path never reaches this. */
|
|
208
224
|
function recordReviews(e: PlanEditEvent, cfg: Config): void {
|
|
209
225
|
const entries = newProgressEntries(e.before, e.after).filter(b => REVIEW_LINE.test(b));
|
|
210
226
|
if (!entries.length) return;
|
|
@@ -213,16 +229,25 @@ function recordReviews(e: PlanEditEvent, cfg: Config): void {
|
|
|
213
229
|
if (!found) return;
|
|
214
230
|
const { name, spawn } = found;
|
|
215
231
|
const reviews = readPlanReviews();
|
|
232
|
+
const code = readCodeReviews();
|
|
216
233
|
for (const block of entries) {
|
|
234
|
+
const kind = REVIEW_LINE.exec(block)![1];
|
|
217
235
|
const repeat = spawn.verdicts > 0;
|
|
218
236
|
spawn.verdicts++;
|
|
219
237
|
const at = nowSec();
|
|
220
238
|
// Judged against the plan as the spawn first saw it (P4k): a plan that moved during the review cannot pass.
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
239
|
+
const record: PlanReview = repeat
|
|
240
|
+
? { verdict: "FAIL", hash: spawn.hash, finding: "review spawn wrote 2 verdicts", at, by: name }
|
|
241
|
+
: reviewHash(e.after) !== spawn.hash
|
|
242
|
+
? { verdict: "FAIL", hash: spawn.hash, finding: "plan changed during review", at, by: name }
|
|
243
|
+
: { verdict: REVIEW_LINE.exec(block)![2] === "PASS" ? "PASS" : "FAIL", hash: spawn.hash, finding: findingsValue(block) ?? "", at, by: name };
|
|
244
|
+
// A CODE REVIEW record covers only the phases the verdict names before its Findings line: a phase in the Findings text ("see P2") is a reference, not coverage; an entry without a Findings line covers nothing.
|
|
245
|
+
if (kind === "CODE") {
|
|
246
|
+
const head = block.slice(0, Math.max(block.indexOf("Findings:"), 0));
|
|
247
|
+
code[e.path] = { ...record, phases: [...new Set([...head.matchAll(/\bP\d+[a-z]?\b/g)].map(m => m[0]))] };
|
|
248
|
+
} else reviews[e.path] = record;
|
|
249
|
+
}
|
|
250
|
+
writePlanReviews(reviews, code, cfg);
|
|
226
251
|
writeReviewSpawns(spawns);
|
|
227
252
|
}
|
|
228
253
|
|
|
@@ -316,6 +341,32 @@ function secretPath(p: string, cfg: Config, cwd: string): boolean {
|
|
|
316
341
|
);
|
|
317
342
|
}
|
|
318
343
|
|
|
344
|
+
// P7 (plan 20261028_1600): option tokens that write or execute on an otherwise allowed command;
|
|
345
|
+
// `-w`/`--web` are denied on gh/glab segments only (they open a browser), `-c` only right after
|
|
346
|
+
// `git` (config injection, e.g. core.pager=sh).
|
|
347
|
+
const SHELL_DENY_OPTS = ["--output", "--pre", "--ext-diff", "--textconv", "--open-files-in-pager", "--exec", "-O"];
|
|
348
|
+
|
|
349
|
+
/** P7 (plan 20261028_1600): why a review spawn's bash command is not allowed, or null. Single
|
|
350
|
+
* line, no `$(`/backtick/`<(`/`>(`, no `>` outside quotes (quoted text stripped the way
|
|
351
|
+
* withoutQuotedRedirects does), and every `|`/`&&`/`||`/`;`/`&` segment starts with a
|
|
352
|
+
* review.shell_allow entry followed by a word boundary. */
|
|
353
|
+
function reviewShellProblem(command: string, cfg: Config): string | null {
|
|
354
|
+
if (/[\r\n]/.test(command)) return "a multi-line command";
|
|
355
|
+
if (command.includes("`") || command.includes("$(") || command.includes("<(") || command.includes(">(")) return "command substitution";
|
|
356
|
+
if (q.withoutQuotedRedirects(command).includes(">")) return "a shell redirect";
|
|
357
|
+
for (const raw of command.split(/&&|\|\||[|;&]/)) {
|
|
358
|
+
const seg = raw.trim();
|
|
359
|
+
const toks = seg.split(/\s+/);
|
|
360
|
+
const pre = cfg.review.shell_allow.find(p => seg.startsWith(p) && (seg.length === p.length || /\s/.test(seg.charAt(p.length))));
|
|
361
|
+
if (!pre) return `${toks[0] || "an empty segment"} is not a review.shell_allow command`;
|
|
362
|
+
const opt = toks.find(t => SHELL_DENY_OPTS.some(o => t === o || t.startsWith(`${o}=`)));
|
|
363
|
+
if (opt) return `the writing/executing option ${opt}`;
|
|
364
|
+
if ((toks[0] === "gh" || toks[0] === "glab") && toks.some(t => t === "-w" || t === "--web")) return "gh/glab --web opens a browser";
|
|
365
|
+
if (toks.some((t, i) => i > 0 && t === "-c" && toks[i - 1] === "git")) return "git -c config injection";
|
|
366
|
+
}
|
|
367
|
+
return null;
|
|
368
|
+
}
|
|
369
|
+
|
|
319
370
|
/** P4f: a named review spawn may read, use todo, and edit only its own plan. Shell, spawn, cancel and MCP tools are denied; so are secret reads. */
|
|
320
371
|
function reviewLockProblem(e: ToolEvent, cfg: Config): string | null {
|
|
321
372
|
const plan = matchReviewSpawn(readReviewSpawns(), e.agentId ?? "")?.spawn.plan ?? null;
|
|
@@ -330,12 +381,16 @@ function reviewLockProblem(e: ToolEvent, cfg: Config): string | null {
|
|
|
330
381
|
const reads = [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)];
|
|
331
382
|
return reads.some(p => secretPath(p, cfg, e.cwd)) ? `review spawn ${e.agentId} may not read credentials or env files.` : null;
|
|
332
383
|
}
|
|
333
|
-
//
|
|
334
|
-
//
|
|
384
|
+
// P7 (plan 20261028_1600): the reviewer's shell is an allow list, not a ban list — eval never
|
|
385
|
+
// (it runs code), and bash only when every |/&&/||/;/& segment starts with a review.shell_allow
|
|
386
|
+
// command: single-line, no substitution or redirect characters, no writing/executing option
|
|
387
|
+
// tokens. The secret-path deny stays. (I-20261031-348: the old MUTATING ban missed
|
|
388
|
+
// fs.renameSync-style writes; I-20261031-350: a reviewer's shell ran anything unlisted.)
|
|
335
389
|
if (cfg.guards.shell_tools.includes(e.tool)) {
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
390
|
+
if (e.tool === "eval")
|
|
391
|
+
return `review spawn ${e.agentId} may not run eval; use the read tools or a bash command from review.shell_allow.`;
|
|
392
|
+
const problem = reviewShellProblem(String(input.command ?? ""), cfg);
|
|
393
|
+
if (problem) return `review spawn ${e.agentId} may run only review.shell_allow commands: ${problem}.`;
|
|
339
394
|
const reads = [...(e.paths ?? []), ...q.touchedPaths(e.tool, input, e.cwd)];
|
|
340
395
|
return reads.some(p => secretPath(p, cfg, e.cwd)) ? `review spawn ${e.agentId} may not read credentials or env files.` : null;
|
|
341
396
|
}
|
|
@@ -353,37 +408,50 @@ function staffingFile(): string {
|
|
|
353
408
|
// The owner-message store (owner-messages.jsonl) and its matcher live in src/core/incidents.ts
|
|
354
409
|
// (20261028_0900 P3): dismissIncident needs them too, and guards already imports incidents.
|
|
355
410
|
|
|
356
|
-
/** 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. */
|
|
411
|
+
/** 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. */
|
|
357
412
|
function isOwnerProse(text: string): boolean {
|
|
358
|
-
|
|
413
|
+
const t = text.trimStart();
|
|
414
|
+
return !(t.startsWith("main-guard:") || t.startsWith(UNANSWERED_PREFIX) || t.startsWith("<system-notice>") || text.includes("<task-result"));
|
|
359
415
|
}
|
|
360
416
|
|
|
361
417
|
function recordOwnerMessage(text: string, cfg: Config): void {
|
|
362
418
|
if (!isOwnerProse(text)) return;
|
|
363
|
-
const file = ownerMessagesFile();
|
|
364
419
|
try {
|
|
365
|
-
|
|
366
|
-
const messages = readOwnerMessages();
|
|
367
|
-
messages.push({ at: nowSec(), text });
|
|
368
|
-
writeFileSync(file, `${messages.slice(-50).map(m => JSON.stringify(m)).join("\n")}\n`);
|
|
420
|
+
writeOwnerStore([...readOwnerMessages(), { at: nowSec(), text }], readOwnerAnswers());
|
|
369
421
|
} catch (err) {
|
|
370
|
-
log(cfg.paths.guard_log, `cannot write ${
|
|
422
|
+
log(cfg.paths.guard_log, `cannot write ${ownerMessagesFile()}: ${err}`);
|
|
371
423
|
}
|
|
372
424
|
}
|
|
373
425
|
|
|
374
|
-
/**
|
|
375
|
-
export
|
|
426
|
+
/** 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. */
|
|
427
|
+
export interface StaffingEntry {
|
|
428
|
+
names: string[];
|
|
429
|
+
at: number;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** plan → its staffing entry (staffing.json). */
|
|
433
|
+
export function readStaffingEntries(): Record<string, StaffingEntry> {
|
|
376
434
|
try {
|
|
377
435
|
const raw: unknown = JSON.parse(readFileSync(staffingFile(), "utf8"));
|
|
378
436
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
|
|
379
|
-
const out: Record<string,
|
|
380
|
-
for (const [k, v] of Object.entries(raw))
|
|
437
|
+
const out: Record<string, StaffingEntry> = {};
|
|
438
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
439
|
+
if (Array.isArray(v)) out[k] = { names: v.map(String), at: 0 };
|
|
440
|
+
else if (v && typeof v === "object" && "names" in v && Array.isArray(v.names)) {
|
|
441
|
+
out[k] = { names: v.names.map(String), at: "at" in v ? Number(v.at) || 0 : 0 };
|
|
442
|
+
}
|
|
443
|
+
}
|
|
381
444
|
return out;
|
|
382
445
|
} catch {
|
|
383
446
|
return {};
|
|
384
447
|
}
|
|
385
448
|
}
|
|
386
449
|
|
|
450
|
+
/** plan → the task names of its newest spawn (staffing.json); read for the staffed check. */
|
|
451
|
+
export function readStaffing(): Record<string, string[]> {
|
|
452
|
+
return Object.fromEntries(Object.entries(readStaffingEntries()).map(([f, e]) => [f, e.names]));
|
|
453
|
+
}
|
|
454
|
+
|
|
387
455
|
function readSpawns(): Record<string, string> {
|
|
388
456
|
try {
|
|
389
457
|
const raw: unknown = JSON.parse(readFileSync(spawnsFile(), "utf8"));
|
|
@@ -411,8 +479,9 @@ export function recordSpawns(files: string[], staffing: Record<string, string[]>
|
|
|
411
479
|
log(`${q.STATE_DIR}/../main-guard.log`, `cannot write ${spawnsFile()}: ${err}`);
|
|
412
480
|
}
|
|
413
481
|
if (!Object.keys(staffing).length) return;
|
|
414
|
-
const st =
|
|
415
|
-
|
|
482
|
+
const st = readStaffingEntries();
|
|
483
|
+
const at = nowSec();
|
|
484
|
+
for (const [f, names] of Object.entries(staffing)) if (names.length) st[f] = { names: [...names], at };
|
|
416
485
|
try {
|
|
417
486
|
mkdirSync(q.STATE_DIR, { recursive: true });
|
|
418
487
|
writeFileSync(staffingFile(), JSON.stringify(st, null, 1));
|
|
@@ -566,6 +635,12 @@ function unticked(p: Plan): string[] {
|
|
|
566
635
|
return [...phases.matchAll(/^\s*[-*]\s+\[ \]\s+(P\d+[a-z]?)\b/gm)].map(m => m[1]!);
|
|
567
636
|
}
|
|
568
637
|
|
|
638
|
+
/** Phase ids an edit newly ticks: `[ ]` in `before`, `[x]` in `after` (P6, read from the Phases section like unticked). */
|
|
639
|
+
function newlyTicked(before: string, after: string): string[] {
|
|
640
|
+
const was = new Set([...(q.sections(before).get("phases") ?? "").matchAll(/^\s*[-*]\s+\[ \]\s+(P\d+[a-z]?)\b/gm)].map(m => m[1]!));
|
|
641
|
+
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));
|
|
642
|
+
}
|
|
643
|
+
|
|
569
644
|
/** The open plans the text names — a `Priority skip: <path> — <why>` line names a plan it does NOT run on (20261025_0215 P3), so only the remaining text decides. planGate's targeting, shared with the spawn verdict's brief-lint and cap notes (plan 20261031_1207 P4). */
|
|
570
645
|
function briefPlans(text: string, cfg?: Config): Plan[] {
|
|
571
646
|
const body = text.replace(/^\s*(?:[-*]\s+)?priority skip:.*$/gim, "");
|
|
@@ -706,9 +781,10 @@ export function priorityProblem(plans: Plan[], named: string[], staffed: string[
|
|
|
706
781
|
return skips.length ? { skips } : null;
|
|
707
782
|
}
|
|
708
783
|
|
|
709
|
-
/** Load staffing and the owner's recorded words, run the pure priority gate and log its outcome; the refusal comes back with the caller's label, or null. */
|
|
710
|
-
function priorityGate(named: string[], runningJobs: string[] | undefined, brief: string, cfg: Config, label: string): string | null {
|
|
711
|
-
const
|
|
784
|
+
/** Load staffing and the owner's recorded words, run the pure priority gate and log its outcome; the refusal comes back with the caller's label, or null. P8 (I-20261031-353): the plans a Main-authored brief reviews drop out first — a plan waiting for its reviewer is not a priority slot, so a call naming only reviewed plans passes with no skip line; implementer plans keep the gate. */
|
|
785
|
+
function priorityGate(named: string[], runningJobs: string[] | undefined, brief: string, cfg: Config, label: string, agent: string, spawner: Spawner): string | null {
|
|
786
|
+
const implementer = named.filter(f => !isReviewSpawn(f, brief, agent, cfg, spawner));
|
|
787
|
+
const outcome = priorityProblem(q.activePlans(), implementer, runningJobs === undefined ? undefined : staffedPlans(readStaffing(), runningJobs), brief, readOwnerMessages(), nowSec(), cfg);
|
|
712
788
|
if (outcome?.unknown) log(cfg.paths.guard_log, "PRIORITY unknown jobs");
|
|
713
789
|
for (const s of outcome?.skips ?? []) log(cfg.paths.guard_log, `PRIORITY skip ${s.plan}: ${s.why}`);
|
|
714
790
|
return outcome?.problem ? `${label}: ${outcome.problem}` : null;
|
|
@@ -934,6 +1010,8 @@ export function spawnProblem(
|
|
|
934
1010
|
joined,
|
|
935
1011
|
cfg,
|
|
936
1012
|
String((tasks[0] && (tasks[0].name ?? tasks[0].agent)) ?? "task"),
|
|
1013
|
+
String((tasks[0] && tasks[0].agent) ?? "task"),
|
|
1014
|
+
spawner,
|
|
937
1015
|
);
|
|
938
1016
|
if (gate) problems.push(gate);
|
|
939
1017
|
const inc = incidentSpawnProblem("spawn", JSON.stringify(input), files, cfg);
|
|
@@ -1535,7 +1613,7 @@ export function checkSpawn(e: SpawnEvent, cfg: Config, runner: CommandRunner = d
|
|
|
1535
1613
|
const problems: string[] = [];
|
|
1536
1614
|
const [why, named] = planGate(e.brief, e.agent, cfg);
|
|
1537
1615
|
if (why) problems.push(why);
|
|
1538
|
-
const gate = priorityGate(named, e.runningJobs, e.brief, cfg, e.agent);
|
|
1616
|
+
const gate = priorityGate(named, e.runningJobs, e.brief, cfg, e.agent, e.agent, "main");
|
|
1539
1617
|
if (gate) problems.push(gate);
|
|
1540
1618
|
const pendingWork = pendingWorkProblem(named, e.brief, cfg, runner);
|
|
1541
1619
|
if (pendingWork) problems.push(pendingWork);
|
|
@@ -1599,7 +1677,7 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
|
|
|
1599
1677
|
recordOwnerMessage(e.inject, cfg);
|
|
1600
1678
|
let summary: string;
|
|
1601
1679
|
try {
|
|
1602
|
-
summary = q.queueSummary(undefined, cfg.review.agents);
|
|
1680
|
+
summary = q.queueSummary(undefined, cfg.review.agents, staleFiles(recheckHolds(cfg, q.activePlans())));
|
|
1603
1681
|
} catch (err) {
|
|
1604
1682
|
summary = `Queue unreadable (${q.INDEX}): ${err}`;
|
|
1605
1683
|
}
|
|
@@ -1662,13 +1740,13 @@ export function checkPlanEdit(e: PlanEditEvent, cfg: Config): PlanEditDecision {
|
|
|
1662
1740
|
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (review line)`);
|
|
1663
1741
|
return {
|
|
1664
1742
|
allow: false,
|
|
1665
|
-
reason: `plan-guard: a PLAN REVIEW line in ${e.path} does not match "- [<date> <time> <name>: ]PLAN REVIEW: PASS|FAIL — …". The file was restored.`,
|
|
1743
|
+
reason: `plan-guard: a PLAN REVIEW or CODE REVIEW line in ${e.path} does not match "- [<date> <time> <name>: ]PLAN REVIEW|CODE REVIEW: PASS|FAIL — …". The file was restored.`,
|
|
1666
1744
|
restore: { path: e.path, text: e.before },
|
|
1667
1745
|
};
|
|
1668
1746
|
}
|
|
1669
1747
|
if (e.agent === "sub" && newProgressEntries(e.before, e.after).some(b => REVIEW_LINE.test(b)) && matchReviewSpawn(readReviewSpawns(), e.agentId ?? "")?.spawn.plan !== e.path) {
|
|
1670
1748
|
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} review line from a spawn that is not its named review spawn`);
|
|
1671
|
-
return { allow: false, reason: `plan-guard: a PLAN REVIEW line counts only from the named review spawn of ${e.path}; the file was restored.`, restore: { path: e.path, text: e.before } };
|
|
1749
|
+
return { allow: false, reason: `plan-guard: a PLAN REVIEW or CODE REVIEW line counts only from the named review spawn of ${e.path}; the file was restored.`, restore: { path: e.path, text: e.before } };
|
|
1672
1750
|
}
|
|
1673
1751
|
recordReviews(e, cfg);
|
|
1674
1752
|
return ALLOW;
|
|
@@ -1707,18 +1785,44 @@ export function findingsValue(block: string): string | null {
|
|
|
1707
1785
|
return line.slice(line.lastIndexOf("Findings:") + "Findings:".length).trim() || null;
|
|
1708
1786
|
}
|
|
1709
1787
|
|
|
1788
|
+
/** P6 (plan 20261028_1600): the refusal for ticking `ids` with review.code on. Each phase needs a recorded CODE REVIEW: PASS from a named review spawn (the `code` map of plan-reviews.json), and its entry must still be the plan's last Progress entry naming the phase — last by the entry's `<YYYY-MM-DD HH:MM>` stamp, not file order (live plans are newest-first or appended): implementer work after the review voids it. */
|
|
1789
|
+
function codeReviewProblem(file: string, after: string, ids: string[]): string | null {
|
|
1790
|
+
const rec = readCodeReviews()[file];
|
|
1791
|
+
// toSorted is stable: ties and unstamped entries ("") keep file order.
|
|
1792
|
+
const entries = progressEntries(after)
|
|
1793
|
+
.map(b => [b, /^\s*-\s*(\d{4}-\d{2}-\d{2} \d{2}:\d{2})/.exec(b)?.[1] ?? ""] as const)
|
|
1794
|
+
.toSorted((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0))
|
|
1795
|
+
.map(([b]) => b);
|
|
1796
|
+
for (const id of ids) {
|
|
1797
|
+
const last = entries.findLast(b => new RegExp(`\\b${id}\\b`).test(b));
|
|
1798
|
+
const valid = last !== undefined && REVIEW_LINE.test(last) && REVIEW_LINE.exec(last)![1] === "CODE" && REVIEW_LINE.exec(last)![2] === "PASS";
|
|
1799
|
+
if (!(rec?.verdict === "PASS" && rec.phases.includes(id) && valid))
|
|
1800
|
+
return `plan-guard: phase ${id} was ticked but has no current CODE REVIEW: PASS from a review spawn after its last implementer entry — spawn a code reviewer or set review.code: false. The file was restored.`;
|
|
1801
|
+
}
|
|
1802
|
+
return null;
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1710
1805
|
// Main's plan text outside "## Progress" must rest on files Main read itself (planReadProblems).
|
|
1711
1806
|
// An empty `before` means the plan file did not exist yet; a refusal then deletes it.
|
|
1712
1807
|
function checkMainPlan(e: PlanEditEvent, cfg: Config): PlanEditDecision {
|
|
1713
|
-
// A PLAN REVIEW line is a review spawn's verdict (P4k): Main writes none, so its edit is restored.
|
|
1808
|
+
// A PLAN REVIEW or CODE REVIEW line (P6) is a review spawn's verdict (P4k): Main writes none, so its edit is restored.
|
|
1714
1809
|
if (newProgressEntries(e.before, e.after).some(b => REVIEW_LINE.test(b))) {
|
|
1715
1810
|
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (Main wrote a review line)`);
|
|
1716
1811
|
return {
|
|
1717
1812
|
allow: false,
|
|
1718
|
-
reason: `plan-guard: a PLAN REVIEW line is written only by the named review spawn of ${e.path}, never by Main. The file was restored.`,
|
|
1813
|
+
reason: `plan-guard: a PLAN REVIEW or CODE REVIEW line is written only by the named review spawn of ${e.path}, never by Main. The file was restored.`,
|
|
1719
1814
|
restore: { path: e.path, text: e.before || null },
|
|
1720
1815
|
};
|
|
1721
1816
|
}
|
|
1817
|
+
// P6 (plan 20261028_1600): with review.code on, ticking a phase needs a named review spawn's CODE REVIEW: PASS behind it — the recorded verdict counts, never Main's own line.
|
|
1818
|
+
if (cfg.review.code) {
|
|
1819
|
+
const ticks = newlyTicked(e.before, e.after);
|
|
1820
|
+
const problem = ticks.length ? codeReviewProblem(e.path, e.after, ticks) : null;
|
|
1821
|
+
if (problem) {
|
|
1822
|
+
log(cfg.paths.plan_guard_log, `RESTORE ${e.path} (code review: ${ticks.join(", ")})`);
|
|
1823
|
+
return { allow: false, reason: problem, restore: { path: e.path, text: e.before || null } };
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1722
1826
|
if (q.outsideProgress(e.after) === q.outsideProgress(e.before)) {
|
|
1723
1827
|
return ALLOW;
|
|
1724
1828
|
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import type { Config } from "./config.ts";
|
|
4
|
+
|
|
5
|
+
/** Maximum detail characters stored per heartbeat. */
|
|
6
|
+
const MAX_DETAIL = 200;
|
|
7
|
+
|
|
8
|
+
/** On-disk heartbeat: last known state of one scheduled job. */
|
|
9
|
+
export interface Heartbeat {
|
|
10
|
+
/** Job name (also the file stem). */
|
|
11
|
+
name: string;
|
|
12
|
+
ok: boolean;
|
|
13
|
+
detail: string;
|
|
14
|
+
/** ISO timestamp of when beat() wrote this record. */
|
|
15
|
+
at: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Input to beat(): ok plus an optional human-readable detail (already <200 chars or cut). */
|
|
19
|
+
export interface JobResult {
|
|
20
|
+
ok: boolean;
|
|
21
|
+
detail?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** <queue_state>/heartbeats/ — one JSON file per job name. */
|
|
25
|
+
function heartbeatsDir(cfg: Config): string {
|
|
26
|
+
return join(cfg.paths.queue_state, "heartbeats");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Write one heartbeat for *name*. Never throws: a heartbeat write failure must never
|
|
30
|
+
* fail the job that owns the heartbeat. */
|
|
31
|
+
export function beat(cfg: Config, name: string, result: JobResult): void {
|
|
32
|
+
const detail = (result.detail ?? "").slice(0, MAX_DETAIL);
|
|
33
|
+
const hb: Heartbeat = { name, ok: result.ok, detail, at: new Date().toISOString() };
|
|
34
|
+
try {
|
|
35
|
+
mkdirSync(heartbeatsDir(cfg), { recursive: true });
|
|
36
|
+
writeFileSync(join(heartbeatsDir(cfg), `${name}.json`), JSON.stringify(hb));
|
|
37
|
+
} catch {
|
|
38
|
+
// intentionally silent — heartbeat write must never crash the job
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Read every heartbeat JSON file, keyed by job name. Returns {} if the dir is unwritable/absent. */
|
|
43
|
+
export function readBeats(cfg: Config): Record<string, Heartbeat> {
|
|
44
|
+
const dir = heartbeatsDir(cfg);
|
|
45
|
+
try {
|
|
46
|
+
const out: Record<string, Heartbeat> = {};
|
|
47
|
+
for (const f of readdirSync(dir)) {
|
|
48
|
+
if (!f.endsWith(".json")) continue;
|
|
49
|
+
try {
|
|
50
|
+
out[f.slice(0, -5)] = JSON.parse(readFileSync(join(dir, f), "utf8")) as Heartbeat;
|
|
51
|
+
} catch {
|
|
52
|
+
// skip unreadable / corrupt files
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
} catch {
|
|
57
|
+
return {};
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Extract the first line of an unknown thrown value — used as the heartbeat detail on crash. */
|
|
62
|
+
export function errorLine(e: unknown): string {
|
|
63
|
+
if (e instanceof Error) return e.message.split("\n")[0] ?? "";
|
|
64
|
+
return String(e).split("\n")[0] ?? "";
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Wrap a synchronous job so it beats AFTER the job — ok = (exit code === 0) — and
|
|
68
|
+
* ok:false (first error line) on a crash, then re-throws so the process exit
|
|
69
|
+
* behaviour is unchanged. No beat on entry: a job that hangs reads as stale, not ok. */
|
|
70
|
+
export function withHeartbeat(cfg: Config, name: string, job: () => number): number {
|
|
71
|
+
try {
|
|
72
|
+
const code = job();
|
|
73
|
+
beat(cfg, name, { ok: code === 0 });
|
|
74
|
+
return code;
|
|
75
|
+
} catch (e) {
|
|
76
|
+
beat(cfg, name, { ok: false, detail: errorLine(e) });
|
|
77
|
+
throw e;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
// "traces" and records an agent-score penalty event for that agent on the plan.
|
|
21
21
|
|
|
22
22
|
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
23
|
+
import { createHash } from "node:crypto";
|
|
23
24
|
import { dirname, join } from "node:path";
|
|
24
25
|
import { fileURLToPath } from "node:url";
|
|
25
26
|
import type { Run, TraceEvent } from "./adapter.ts";
|
|
@@ -28,7 +29,7 @@ import { nowSec, strftime } from "./clock.ts";
|
|
|
28
29
|
import { log } from "./guards.ts";
|
|
29
30
|
import { addIncident, type IncidentView } from "./incidents.ts";
|
|
30
31
|
import type { GuardBlock } from "./metrics.ts";
|
|
31
|
-
import { verifyClaims, type Claim, type RelatedRun } from "./trace-claims.ts";
|
|
32
|
+
import { maskEvidence, verifyClaims, type Claim, type RelatedRun } from "./trace-claims.ts";
|
|
32
33
|
import { recordPenalty } from "./agent-score.ts";
|
|
33
34
|
import type { SuspiciousAction, UnreportedFinding } from "./trace-actions.ts";
|
|
34
35
|
|
|
@@ -135,6 +136,55 @@ export function blockLoop(blocks: GuardBlock[], now: number, repeat: number, win
|
|
|
135
136
|
}));
|
|
136
137
|
}
|
|
137
138
|
|
|
139
|
+
// ---- D8: a guard block the same action got past ----
|
|
140
|
+
|
|
141
|
+
const GUARD_BLOCK = /^(main|plan)-guard:/;
|
|
142
|
+
|
|
143
|
+
/** Token-set Jaccard similarity in [0, 1]. */
|
|
144
|
+
function jaccard(a: Set<string>, b: Set<string>): number {
|
|
145
|
+
let shared = 0;
|
|
146
|
+
for (const t of a) if (b.has(t)) shared++;
|
|
147
|
+
const union = a.size + b.size - shared;
|
|
148
|
+
return union === 0 ? 0 : shared / union;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* A Main call a guard refused (an error result whose text starts main-guard:/plan-guard:) and the
|
|
153
|
+
* first later call of the same tool, within windowSec, whose result is not an error and whose args
|
|
154
|
+
* are token-similar (≥ similarity): a possible guard false positive. One finding per refused call.
|
|
155
|
+
*/
|
|
156
|
+
export function blockThenBypass(events: TraceEvent[], windowSec: number, similarity: number, since = -Infinity): Finding[] {
|
|
157
|
+
const results = new Map<string, TraceEvent>();
|
|
158
|
+
for (const e of events) if (e.kind === "toolResult" && e.callId) results.set(e.callId, e);
|
|
159
|
+
// A call with no timestamp cannot be placed in the window, so it is neither a block nor a bypass.
|
|
160
|
+
const calls = events.filter((e): e is TraceEvent & { callId: string; ts: number } => e.kind === "toolCall" && !!e.callId && e.ts !== null);
|
|
161
|
+
const tokens = new Map(calls.map(c => [c.callId, new Set(JSON.stringify(c.args ?? null).toLowerCase().split(/\W+/).filter(Boolean))]));
|
|
162
|
+
const out: Finding[] = [];
|
|
163
|
+
for (const block of calls) {
|
|
164
|
+
// Blocks at or before `since` were decided by an earlier gated scan (the D8 frontier).
|
|
165
|
+
if (block.ts <= since) continue;
|
|
166
|
+
const refused = results.get(block.callId!);
|
|
167
|
+
if (!refused?.isError || !GUARD_BLOCK.test(refused.text ?? "")) continue;
|
|
168
|
+
const bypass = calls.find(c => {
|
|
169
|
+
const dt = c.ts - block.ts;
|
|
170
|
+
const r = results.get(c.callId!);
|
|
171
|
+
return c.callId !== block.callId && c.tool === block.tool && dt >= 0 && dt <= windowSec && r !== undefined && !r.isError && jaccard(tokens.get(block.callId!)!, tokens.get(c.callId!)!) >= similarity;
|
|
172
|
+
});
|
|
173
|
+
if (!bypass) continue;
|
|
174
|
+
const head = (refused.text ?? "").replace(/\s+/g, " ").trim();
|
|
175
|
+
const sha = createHash("sha256").update(head).digest("hex").slice(0, 16);
|
|
176
|
+
const blockedArgs = maskEvidence(JSON.stringify(block.args).slice(0, 200));
|
|
177
|
+
const allowedArgs = maskEvidence(JSON.stringify(bypass.args).slice(0, 200));
|
|
178
|
+
out.push({
|
|
179
|
+
kind: "block-then-bypass",
|
|
180
|
+
summary: `possible guard false positive: ${head.slice(0, 120)}`,
|
|
181
|
+
evidence: `blocked ${block.tool} at ${iso(block.ts)}: ${blockedArgs}; same tool allowed at ${iso(bypass.ts)}: ${allowedArgs}`,
|
|
182
|
+
fingerprint: `block-then-bypass:${block.tool}:${sha}`,
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
return out;
|
|
186
|
+
}
|
|
187
|
+
|
|
138
188
|
// ---- D4: an owner message that corrects Main ----
|
|
139
189
|
|
|
140
190
|
/** An owner message matching an M4 correction pattern, folded per day so a bad afternoon is one incident. */
|
|
@@ -216,6 +266,10 @@ export interface DetectorInput {
|
|
|
216
266
|
actions?: SuspiciousAction[];
|
|
217
267
|
/** D7: cross-product reads a subagent run hid behind a Findings: none line (src/core/trace-actions.ts). */
|
|
218
268
|
unreported?: UnreportedFinding[];
|
|
269
|
+
/** D8: Main's session trace events, gathered behind the scan gate (runDetectorsGated). */
|
|
270
|
+
mainEvents?: TraceEvent[];
|
|
271
|
+
/** D8 frontier: the newest Main event time an earlier gated scan already saw (incident-scan.json mainTs). */
|
|
272
|
+
mainSince?: number;
|
|
219
273
|
}
|
|
220
274
|
|
|
221
275
|
/**
|
|
@@ -266,6 +320,9 @@ export function runDetectors(cfg: Config, input: DetectorInput, now = nowSec()):
|
|
|
266
320
|
if (input.actions) {
|
|
267
321
|
attempt("suspicious-action", () => suspiciousAction(input.actions!));
|
|
268
322
|
}
|
|
323
|
+
if (input.mainEvents) {
|
|
324
|
+
attempt("block-then-bypass", () => blockThenBypass(input.mainEvents!, cfg.incidents.bypass_window_sec, cfg.incidents.bypass_similarity, input.mainSince));
|
|
325
|
+
}
|
|
269
326
|
if (input.unreported) {
|
|
270
327
|
for (const f of input.unreported!) {
|
|
271
328
|
try {
|
|
@@ -293,26 +350,42 @@ export interface GatedInputs {
|
|
|
293
350
|
results: TaskResult[];
|
|
294
351
|
runs: Run[];
|
|
295
352
|
blocks: GuardBlock[];
|
|
353
|
+
/** D8: Main's session trace events (optional: a caller without a session file omits them). */
|
|
354
|
+
mainEvents?: TraceEvent[];
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** The scan gate state in <queue_state>/incident-scan.json: `lastScan` is the time of the last gated
|
|
358
|
+
* scan; `mainTs` is the newest Main session event time that scan saw (the D8 frontier). */
|
|
359
|
+
interface ScanState {
|
|
360
|
+
lastScan: number;
|
|
361
|
+
mainTs: number;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function readScan(file: string): ScanState {
|
|
365
|
+
const st: ScanState = { lastScan: 0, mainTs: 0 };
|
|
366
|
+
try {
|
|
367
|
+
const raw = JSON.parse(readFileSync(file, "utf8")) as { lastScan?: unknown; mainTs?: unknown };
|
|
368
|
+
if (typeof raw.lastScan === "number") st.lastScan = raw.lastScan;
|
|
369
|
+
if (typeof raw.mainTs === "number") st.mainTs = raw.mainTs;
|
|
370
|
+
} catch {}
|
|
371
|
+
return st;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function writeScan(file: string, st: ScanState): void {
|
|
375
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
376
|
+
writeFileSync(file, `${JSON.stringify(st)}\n`);
|
|
296
377
|
}
|
|
297
378
|
|
|
298
379
|
/**
|
|
299
|
-
*
|
|
300
|
-
*
|
|
301
|
-
*
|
|
302
|
-
* next attempt is a full interval away (a failed scan retries then, not at the next event). An
|
|
303
|
-
* unreadable state counts as never scanned; an unwritable one throws (the caller logs it and
|
|
304
|
-
* runs the cheap detectors only).
|
|
380
|
+
* Whether a gated scan is due. The stamp is written BEFORE the inputs are read, so a slow or
|
|
381
|
+
* crashing scan cannot stack: the next attempt is a full interval away. An unreadable state counts
|
|
382
|
+
* as never scanned; an unwritable one throws (the caller logs it and runs the cheap detectors only).
|
|
305
383
|
*/
|
|
306
384
|
export function scanDue(cfg: Config, now: number): boolean {
|
|
307
385
|
const file = join(cfg.paths.queue_state, "incident-scan.json");
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
if (typeof st.lastScan === "number") last = st.lastScan;
|
|
312
|
-
} catch {}
|
|
313
|
-
if (now - last < cfg.incidents.scan_interval_sec) return false;
|
|
314
|
-
mkdirSync(dirname(file), { recursive: true });
|
|
315
|
-
writeFileSync(file, `${JSON.stringify({ lastScan: now })}\n`);
|
|
386
|
+
const st = readScan(file);
|
|
387
|
+
if (now - st.lastScan < cfg.incidents.scan_interval_sec) return false;
|
|
388
|
+
writeScan(file, { ...st, lastScan: now });
|
|
316
389
|
return true;
|
|
317
390
|
}
|
|
318
391
|
|
|
@@ -321,6 +394,11 @@ export function scanDue(cfg: Config, now: number): boolean {
|
|
|
321
394
|
* file, the ledger runs and both guard logs — seconds on a real machine — so they run at most
|
|
322
395
|
* once per incidents.scan_interval_sec and `gather` is never called inside the interval. A
|
|
323
396
|
* failed gate or gather is logged and the cheap detectors still run.
|
|
397
|
+
*
|
|
398
|
+
* D8 frontier: a gated scan records the newest Main event time it saw; the next scan's
|
|
399
|
+
* block-then-bypass only considers blocks after it, so a pair already seen is never raised twice.
|
|
400
|
+
* A bypass that lands only in a later scan than its block is not caught (the retry normally
|
|
401
|
+
* lands in the same turn, before the next prompt-start scan).
|
|
324
402
|
*/
|
|
325
403
|
export function runDetectorsGated(
|
|
326
404
|
cfg: Config,
|
|
@@ -328,11 +406,20 @@ export function runDetectorsGated(
|
|
|
328
406
|
gather: () => GatedInputs,
|
|
329
407
|
now = nowSec(),
|
|
330
408
|
): IncidentView[] {
|
|
409
|
+
const file = join(cfg.paths.queue_state, "incident-scan.json");
|
|
331
410
|
const input: DetectorInput = { ...cheap };
|
|
411
|
+
let frontier: number | null = null;
|
|
332
412
|
try {
|
|
333
|
-
if (scanDue(cfg, now))
|
|
413
|
+
if (scanDue(cfg, now)) {
|
|
414
|
+
const since = readScan(file).mainTs;
|
|
415
|
+
const gathered = gather();
|
|
416
|
+
Object.assign(input, gathered, { mainSince: since });
|
|
417
|
+
frontier = (gathered.mainEvents ?? []).reduce((m, e) => Math.max(m, e.ts ?? 0), since);
|
|
418
|
+
}
|
|
334
419
|
} catch (err) {
|
|
335
420
|
log(cfg.paths.guard_log, `incident scan skipped: ${err instanceof Error ? err.message : String(err)}`);
|
|
336
421
|
}
|
|
337
|
-
|
|
422
|
+
const out = runDetectors(cfg, input, now);
|
|
423
|
+
if (frontier !== null) writeScan(file, { ...readScan(file), mainTs: frontier });
|
|
424
|
+
return out;
|
|
338
425
|
}
|