neurastream 0.2.62 → 0.2.64
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 +47 -32
- 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 +65 -1
- package/src/core/guards.ts +75 -21
- 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/notify.ts +74 -5
- package/src/core/owner-ui.ts +4 -2
- package/src/core/queue/lib.ts +84 -9
- 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 +521 -0
- package/templates/config.yml +24 -3
- 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
|
@@ -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
|
}
|
package/src/core/incidents.ts
CHANGED
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
// not remembered. A repeat sighting of an open fingerprint updates count and lastSeen on the
|
|
7
7
|
// existing record instead of adding a second incident; after a resolution the same fingerprint
|
|
8
8
|
// opens a new incident. Sources: realtime (detectors), daily, weekly, main (`incident add`),
|
|
9
|
-
// findings (plan-guard: the Findings: items of a subagent's new Progress entry)
|
|
9
|
+
// findings (plan-guard: the Findings: items of a subagent's new Progress entry), watch (the
|
|
10
|
+
// src/core/watch.ts watcher: failed/stale heartbeats, failed units).
|
|
10
11
|
|
|
11
12
|
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
12
13
|
import { dirname, join, resolve } from "node:path";
|
|
@@ -14,7 +15,7 @@ import { nowSec, strftime } from "./clock.ts";
|
|
|
14
15
|
import type { Config } from "./config.ts";
|
|
15
16
|
import * as q from "./queue/lib.ts";
|
|
16
17
|
|
|
17
|
-
export type IncidentSource = "realtime" | "daily" | "weekly" | "main" | "findings" | "traces";
|
|
18
|
+
export type IncidentSource = "realtime" | "daily" | "weekly" | "main" | "findings" | "traces" | "watch";
|
|
18
19
|
|
|
19
20
|
export interface IncidentRec {
|
|
20
21
|
id: string;
|
|
@@ -94,7 +95,7 @@ function parseLine(line: string): IncidentRec | ResolutionRec | ProposalRec | nu
|
|
|
94
95
|
if (rec.type !== undefined) return null;
|
|
95
96
|
if (typeof rec.fingerprint !== "string" || typeof rec.kind !== "string" || typeof rec.summary !== "string" || typeof rec.ts !== "number")
|
|
96
97
|
return null;
|
|
97
|
-
const source = rec.source === "realtime" || rec.source === "daily" || rec.source === "weekly" || rec.source === "findings" || rec.source === "traces" ? rec.source : "main";
|
|
98
|
+
const source = rec.source === "realtime" || rec.source === "daily" || rec.source === "weekly" || rec.source === "findings" || rec.source === "traces" || rec.source === "watch" ? rec.source : "main";
|
|
98
99
|
return {
|
|
99
100
|
id: rec.id,
|
|
100
101
|
fingerprint: rec.fingerprint,
|
|
@@ -232,6 +233,12 @@ export interface OwnerMessage {
|
|
|
232
233
|
text: string;
|
|
233
234
|
}
|
|
234
235
|
|
|
236
|
+
/** A real Main turn end, stored beside the messages (the page's lastAnswerFor shape, P5b): a message with a turn end after it is answered. */
|
|
237
|
+
export interface OwnerAnswer {
|
|
238
|
+
at: number;
|
|
239
|
+
answer: string;
|
|
240
|
+
}
|
|
241
|
+
|
|
235
242
|
export function ownerMessagesFile(): string {
|
|
236
243
|
return join(q.STATE_DIR, "owner-messages.jsonl");
|
|
237
244
|
}
|
|
@@ -239,12 +246,32 @@ export function ownerMessagesFile(): string {
|
|
|
239
246
|
export function readOwnerMessages(): OwnerMessage[] {
|
|
240
247
|
try {
|
|
241
248
|
return readFileSync(ownerMessagesFile(), "utf8").split("\n").filter(Boolean)
|
|
242
|
-
.map(line => JSON.parse(line) as OwnerMessage);
|
|
249
|
+
.map(line => JSON.parse(line) as OwnerMessage).filter(m => typeof m.text === "string");
|
|
250
|
+
} catch {
|
|
251
|
+
return [];
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export function readOwnerAnswers(): OwnerAnswer[] {
|
|
256
|
+
try {
|
|
257
|
+
return readFileSync(ownerMessagesFile(), "utf8").split("\n").filter(Boolean)
|
|
258
|
+
.map(line => JSON.parse(line) as OwnerAnswer).filter(a => typeof a.answer === "string");
|
|
243
259
|
} catch {
|
|
244
260
|
return [];
|
|
245
261
|
}
|
|
246
262
|
}
|
|
247
263
|
|
|
264
|
+
/** Rewrites the store: the newest 50 messages, then the newest 20 answers. */
|
|
265
|
+
export function writeOwnerStore(messages: OwnerMessage[], answers: OwnerAnswer[]): void {
|
|
266
|
+
mkdirSync(dirname(ownerMessagesFile()), { recursive: true });
|
|
267
|
+
writeFileSync(ownerMessagesFile(), [...messages.slice(-50).map(m => JSON.stringify(m)), ...answers.slice(-20).map(a => JSON.stringify(a))].join("\n") + "\n");
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Records a real Main turn end as an answer in the same store (P5b); throws so the caller logs the failure. */
|
|
271
|
+
export function appendOwnerAnswer(answer: string, at = nowSec()): void {
|
|
272
|
+
writeOwnerStore(readOwnerMessages(), [...readOwnerAnswers(), { at, answer }]);
|
|
273
|
+
}
|
|
274
|
+
|
|
248
275
|
export function ownerSaid(words: string, messages: OwnerMessage[], now: number): boolean {
|
|
249
276
|
const quote = words.toLowerCase().replace(/\s+/g, " ").trim();
|
|
250
277
|
if (quote.split(" ").length < 4) return false;
|
package/src/core/main-start.ts
CHANGED
|
@@ -2,11 +2,11 @@ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "no
|
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
|
-
import type { RunSource } from "./adapter.ts";
|
|
5
|
+
import type { RunSource, TraceEvent } from "./adapter.ts";
|
|
6
6
|
import { readEvents } from "./agent-score.ts";
|
|
7
7
|
import type { Config } from "./config.ts";
|
|
8
8
|
import { nowSec, strftime } from "./clock.ts";
|
|
9
|
-
import { runDetectors, type TaskResult } from "./incident-detectors.ts";
|
|
9
|
+
import { runDetectors, runDetectorsGated, type GatedInputs, type TaskResult } from "./incident-detectors.ts";
|
|
10
10
|
import { addIncident, type IncidentView } from "./incidents.ts";
|
|
11
11
|
import { log as logGuard } from "./guards.ts";
|
|
12
12
|
import { dailyChecks, readBlocks, readMetricEvents, worseThanMean } from "./metrics.ts";
|
|
@@ -14,6 +14,7 @@ import { buildReport } from "./report.ts";
|
|
|
14
14
|
import { loadavgLine } from "./host.ts";
|
|
15
15
|
import { providersLine } from "./provider-state.ts";
|
|
16
16
|
import { mrSweep } from "./mr-sweep.ts";
|
|
17
|
+
import { watchHealth } from "./watch.ts";
|
|
17
18
|
|
|
18
19
|
function bin(name: string, cfg: Config): string {
|
|
19
20
|
return join(cfg.paths.home, ".local/bin", name);
|
|
@@ -112,6 +113,32 @@ export async function mainStartText(args: string[], cfg: Config, opts: { inherit
|
|
|
112
113
|
const due = metricsDueLine(cfg, Date.now());
|
|
113
114
|
if (due) say(due);
|
|
114
115
|
}
|
|
116
|
+
// Watcher health (plan 20261027_1430 P4): silent unless `watch on` installed the timer. A run older
|
|
117
|
+
// than 3 intervals (or never) prints NOT RUNNING and opens a watch incident; watchOnce closes it
|
|
118
|
+
// again on the next successful pass.
|
|
119
|
+
const watchState = watchHealth(cfg, Date.now());
|
|
120
|
+
if (watchState.installed) {
|
|
121
|
+
if (watchState.lastRunMin !== null && watchState.lastRunMin <= 3 * watchState.intervalMin) {
|
|
122
|
+
say(`watch: last run ${watchState.lastRunMin} min ago`);
|
|
123
|
+
} else {
|
|
124
|
+
say(`watch: NOT RUNNING since ${watchState.lastRunAt ?? "never"}`);
|
|
125
|
+
try {
|
|
126
|
+
addIncident(
|
|
127
|
+
cfg,
|
|
128
|
+
{
|
|
129
|
+
source: "watch",
|
|
130
|
+
kind: "not-running",
|
|
131
|
+
summary: `watcher has not run since ${watchState.lastRunAt ?? "install"} (interval ${watchState.intervalMin} min)`,
|
|
132
|
+
evidence: `last watch heartbeat: ${watchState.lastRunAt ?? "none"}`,
|
|
133
|
+
fingerprint: "watch:not-running",
|
|
134
|
+
},
|
|
135
|
+
nowSec(),
|
|
136
|
+
);
|
|
137
|
+
} catch (err) {
|
|
138
|
+
logGuard(cfg.paths.guard_log, `watch incident failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
115
142
|
say("=== machine");
|
|
116
143
|
const mg = await run(bin("machine-guard", cfg), [], { stderr: "ignore" });
|
|
117
144
|
const mgLines = mg.stdout.trim().split("\n");
|
|
@@ -195,6 +222,46 @@ function fmtMetric(v: number | null): string {
|
|
|
195
222
|
return v === null ? "n/a" : v >= 10 ? String(Math.round(v)) : v.toFixed(2);
|
|
196
223
|
}
|
|
197
224
|
|
|
225
|
+
/** Where the expensive detector inputs come from: the harness adapter's session readers
|
|
226
|
+
* (src/adapters/<harness>; core never imports one — the caller hands the seam in). */
|
|
227
|
+
export interface DetectorSeam {
|
|
228
|
+
runSource(cfg: Config): RunSource;
|
|
229
|
+
completedResults(cfg: Config): TaskResult[];
|
|
230
|
+
/** D8 input. A seam without it gives the detectors no main events, so D8 stays silent. */
|
|
231
|
+
mainEvents?(cfg: Config): TraceEvent[];
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* The gather the prompt-time detectors and the watcher (src/core/watch.ts) share: fresh
|
|
236
|
+
* completed task-results, the last two days of ledger runs and the guard-log blocks — read
|
|
237
|
+
* only when runDetectorsGated's scan gate opens (incidents.scan_interval_sec).
|
|
238
|
+
*/
|
|
239
|
+
export function defaultGather(cfg: Config, seam: DetectorSeam): () => GatedInputs {
|
|
240
|
+
return () => ({
|
|
241
|
+
results: seam.completedResults(cfg),
|
|
242
|
+
runs: seam.runSource(cfg).listRuns(nowSec() - 2 * 86400),
|
|
243
|
+
blocks: readBlocks(cfg),
|
|
244
|
+
mainEvents: seam.mainEvents?.(cfg) ?? [],
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Real-time incident detectors (plan 20261022_2330 P3) at Main's prompt and after each Main bash
|
|
250
|
+
* result, plus the once-per-day metrics check (P4, retried until it marks the day). The cheap
|
|
251
|
+
* detectors (D2 bash, D4 prompt) run on every call; D1/D3 and their inputs — Main's session
|
|
252
|
+
* file, the ledger runs, both guard logs — are gathered behind the scan interval
|
|
253
|
+
* (incidents.scan_interval_sec, see runDetectorsGated). Best effort: a failed check is logged,
|
|
254
|
+
* never thrown.
|
|
255
|
+
*/
|
|
256
|
+
export function mainDetectors(cfg: Config, seam: DetectorSeam, extra: { prompt?: string; bash?: { command: string; output: string } }): void {
|
|
257
|
+
try {
|
|
258
|
+
runDetectorsGated(cfg, extra, defaultGather(cfg, seam));
|
|
259
|
+
runDailyCheck(cfg, seam.runSource(cfg), nowSec());
|
|
260
|
+
} catch (err) {
|
|
261
|
+
logGuard(cfg.paths.guard_log, `incident detectors failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
198
265
|
/**
|
|
199
266
|
* Once per calendar day (state file in queue_state), at the first main-start or Main
|
|
200
267
|
* before_agent_start: M1-M5 for the last 24h against the mean of the 7 days before; each metric
|
|
@@ -249,6 +316,20 @@ export function runWeeklyCheck(cfg: Config, source: RunSource, now: number): str
|
|
|
249
316
|
const rep = buildReport(cfg, source, cfg.metrics.report_days, now);
|
|
250
317
|
mkdirSync(cfg.paths.notes, { recursive: true });
|
|
251
318
|
writeFileSync(join(cfg.paths.notes, "metrics.md"), rep.md);
|
|
319
|
+
for (const n of rep.noisy) {
|
|
320
|
+
const { incident: noisy } = addIncident(
|
|
321
|
+
cfg,
|
|
322
|
+
{
|
|
323
|
+
source: "weekly",
|
|
324
|
+
kind: n.kind,
|
|
325
|
+
summary: n.summary,
|
|
326
|
+
evidence: n.evidence,
|
|
327
|
+
fingerprint: `noisy:${n.detector}:${strftime(now, "%Y%m%d")}`,
|
|
328
|
+
},
|
|
329
|
+
now,
|
|
330
|
+
);
|
|
331
|
+
logGuard(cfg.paths.guard_log, `incident ${noisy.id} [weekly/${noisy.kind}] opened: ${noisy.summary}`);
|
|
332
|
+
}
|
|
252
333
|
const w = rep.worst;
|
|
253
334
|
if (!w || w.change === null) {
|
|
254
335
|
return `metrics: report due (last: ${last}) — wrote ${join(cfg.paths.notes, "metrics.md")}; no ranked metric moved this window`;
|
package/src/core/metrics.ts
CHANGED
|
@@ -222,8 +222,9 @@ export interface GuardBlock {
|
|
|
222
222
|
}
|
|
223
223
|
|
|
224
224
|
/** Groups reasons by shape: paths cut to 40 chars, digit runs collapsed to N, and every
|
|
225
|
-
* `open: <plan list>` tail collapsed to one key: the lists differ per plan set, the reason is one.
|
|
226
|
-
|
|
225
|
+
* `open: <plan list>` tail collapsed to one key: the lists differ per plan set, the reason is one.
|
|
226
|
+
* Exported for the release verdict, which compares M5 blocks per reason (P11). */
|
|
227
|
+
export function reasonKey(text: string): string {
|
|
227
228
|
const shaped = text.replace(/\S*\/\S*/g, (p) => (p.length > 40 ? `${p.slice(0, 40)}…` : p)).replace(/\d+/g, "N");
|
|
228
229
|
const at = shaped.indexOf("open: ");
|
|
229
230
|
return at === -1 ? shaped : `${shaped.slice(0, at)}open: <list>`;
|
package/src/core/mr-sweep.ts
CHANGED
|
@@ -109,7 +109,7 @@ function asNumber(v: unknown): number | null {
|
|
|
109
109
|
}
|
|
110
110
|
|
|
111
111
|
/** Parse a JSON list. Null means the CLI answered but not with a list — treat as unreachable, never as "no MRs". */
|
|
112
|
-
function parseList(stdout: string): Record<string, unknown>[] | null {
|
|
112
|
+
export function parseList(stdout: string): Record<string, unknown>[] | null {
|
|
113
113
|
const t = stdout.trim();
|
|
114
114
|
if (!t) return [];
|
|
115
115
|
const from = (v: unknown): Record<string, unknown>[] | null => {
|
|
@@ -208,17 +208,24 @@ export interface OpenMr {
|
|
|
208
208
|
/** `{ ok: false, why }` is the sweep's degrade: the caller logs it and never treats it as "no MRs". */
|
|
209
209
|
export type OpenMrs = { ok: true; mrs: OpenMr[] } | { ok: false; why: string };
|
|
210
210
|
|
|
211
|
+
/** The forge behind a repo's origin remote: `{ forge }`, or `{ why }` (the sweep's degrade reason). */
|
|
212
|
+
export function repoForge(repo: string, run: CommandRunner = defaultRunner, env?: NodeJS.ProcessEnv): { forge: Forge } | { why: string } {
|
|
213
|
+
const remote = run(["git", "-C", repo, "remote", "get-url", "origin"], { env });
|
|
214
|
+
const url = remote.code === 0 ? remote.stdout.trim() : "";
|
|
215
|
+
if (!url) return { why: "no origin remote" };
|
|
216
|
+
const host = remoteHost(url);
|
|
217
|
+
const forge = host ? forgeOf(host) : null;
|
|
218
|
+
return forge ? { forge } : { why: "unknown forge" };
|
|
219
|
+
}
|
|
220
|
+
|
|
211
221
|
/**
|
|
212
222
|
* Open MRs of one repo (the sweep's lister, single-repo): `!N` / `#N` token plus source branch.
|
|
213
223
|
* Everything — origin lookup included — goes through the runner, so callers can inject it.
|
|
214
224
|
*/
|
|
215
225
|
export function listOpenMrs(repo: string, run: CommandRunner = defaultRunner, env?: NodeJS.ProcessEnv): OpenMrs {
|
|
216
|
-
const
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
const host = remoteHost(url);
|
|
220
|
-
const forge = host ? forgeOf(host) : null;
|
|
221
|
-
if (!forge) return { ok: false, why: "unknown forge" };
|
|
226
|
+
const found = repoForge(repo, run, env);
|
|
227
|
+
if ("why" in found) return { ok: false, why: found.why };
|
|
228
|
+
const forge = found.forge;
|
|
222
229
|
const listed = forge === "gitlab" ? listGitlab(repo, run, env) : listGithub(repo, run, env);
|
|
223
230
|
if (listed.missing) return { ok: false, why: "no forge CLI" };
|
|
224
231
|
if (listed.fail) return { ok: false, why: "forge unreachable" };
|
package/src/core/notify.ts
CHANGED
|
@@ -4,8 +4,11 @@
|
|
|
4
4
|
// from them (guard rules in guards.ts), and does the posting. Plain TypeScript, no harness here.
|
|
5
5
|
|
|
6
6
|
import { dirname } from "node:path";
|
|
7
|
-
import { readFileSync, statSync } from "node:fs";
|
|
7
|
+
import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
8
8
|
import { configFile, type Config } from "./config.ts";
|
|
9
|
+
import { strftime } from "./clock.ts";
|
|
10
|
+
import { recentOwnerMessages, type MessageRow } from "./owner-ui.ts";
|
|
11
|
+
import { stateDirPath } from "./queue/lib.ts";
|
|
9
12
|
import { loadKnownSecrets, redactSecrets } from "./secret-redact.ts";
|
|
10
13
|
|
|
11
14
|
export type NotifyProviderName = "discord" | "slack";
|
|
@@ -42,10 +45,14 @@ function hitsSecret(p: string, file: string): boolean {
|
|
|
42
45
|
const m = GLOB_META.exec(p);
|
|
43
46
|
if (!m) return false;
|
|
44
47
|
const base = p.slice(0, m.index).replace(/\/+$/, "");
|
|
45
|
-
|
|
46
|
-
//
|
|
47
|
-
|
|
48
|
-
|
|
48
|
+
// The glob's literal prefix is the secrets dir or sits inside it: every match it can name is a
|
|
49
|
+
// secret (or reveals the directory listing).
|
|
50
|
+
if (base && (base === dir || base.startsWith(`${dir}/`))) return true;
|
|
51
|
+
// P5g: a wider glob refuses only when it actually matches a secret file or the secrets dir
|
|
52
|
+
// (Bun.Glob, filesystem-free, asked once per secret file and once per its directory), never
|
|
53
|
+
// by its prefix alone — a home-wide glob hunting an unrelated folder passes, and the cost
|
|
54
|
+
// stays bounded by the number of secret files, not by what the glob would expand to.
|
|
55
|
+
return new Bun.Glob(p).match(file) || new Bun.Glob(p).match(dir);
|
|
49
56
|
}
|
|
50
57
|
|
|
51
58
|
/** The first touched read path that hits a configured secret file, its directory, or a glob over
|
|
@@ -225,3 +232,65 @@ export function postReply(text: string, cfg: Config): Promise<NotifyPostResult[]
|
|
|
225
232
|
return out;
|
|
226
233
|
});
|
|
227
234
|
}
|
|
235
|
+
|
|
236
|
+
// ---- Owner answer steer (plan 20261027_1430 P9): a phone-page owner message must be answered
|
|
237
|
+
// by the next hand-back within notify.answer_within_min. The rule is host-neutral: core decides
|
|
238
|
+
// who is waiting and keeps the once-per-message markers; the harness adapter injects the steer
|
|
239
|
+
// at its tool_result hook and records the hand-back at its turn end. The markers live in a file
|
|
240
|
+
// under the queue state, not in session memory: one-shot CLI calls and a reloaded plugin must
|
|
241
|
+
// agree, like the guard window file.
|
|
242
|
+
|
|
243
|
+
function ownerAnswerStatePath(): string {
|
|
244
|
+
return `${stateDirPath()}/owner-answer.json`;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
interface OwnerAnswerState {
|
|
248
|
+
/** Unix seconds of the last hand-back; a message older than this was answered by it. */
|
|
249
|
+
lastHandBack: number;
|
|
250
|
+
/** Message ids this turn already steered, so a message steers once per turn. */
|
|
251
|
+
steered: string[];
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function readOwnerAnswerState(): OwnerAnswerState {
|
|
255
|
+
try {
|
|
256
|
+
const s = JSON.parse(readFileSync(ownerAnswerStatePath(), "utf8")) as Partial<OwnerAnswerState>;
|
|
257
|
+
return {
|
|
258
|
+
lastHandBack: Number(s.lastHandBack) || 0,
|
|
259
|
+
steered: Array.isArray(s.steered) ? s.steered.filter((x): x is string => typeof x === "string") : [],
|
|
260
|
+
};
|
|
261
|
+
} catch {
|
|
262
|
+
return { lastHandBack: 0, steered: [] };
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function writeOwnerAnswerState(state: OwnerAnswerState): void {
|
|
267
|
+
mkdirSync(stateDirPath(), { recursive: true });
|
|
268
|
+
writeFileSync(ownerAnswerStatePath(), `${JSON.stringify(state)}\n`);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Phone-page owner messages waiting past notify.answer_within_min with no hand-back after them; none when the limit is 0. */
|
|
272
|
+
export function waitingOwnerMessages(cfg: Config, now: number): MessageRow[] {
|
|
273
|
+
const limit = cfg.notify.answer_within_min * 60;
|
|
274
|
+
if (!(limit > 0)) return [];
|
|
275
|
+
const { lastHandBack } = readOwnerAnswerState();
|
|
276
|
+
return recentOwnerMessages(now).filter((m) => now - m.ts > limit && m.ts > lastHandBack);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** The steer for every waiting message this turn has not steered yet — one line per message, so
|
|
280
|
+
* each owner ask lands once — or null when nobody is waiting. Marks the messages steered. */
|
|
281
|
+
export function ownerAnswerSteer(cfg: Config, now: number): string | null {
|
|
282
|
+
const limit = cfg.notify.answer_within_min * 60;
|
|
283
|
+
if (!(limit > 0)) return null;
|
|
284
|
+
const state = readOwnerAnswerState();
|
|
285
|
+
const due = recentOwnerMessages(now).filter((m) => now - m.ts > limit && m.ts > state.lastHandBack && !state.steered.includes(m.id));
|
|
286
|
+
if (due.length === 0) return null;
|
|
287
|
+
state.steered.push(...due.map((m) => m.id));
|
|
288
|
+
writeOwnerAnswerState(state);
|
|
289
|
+
return due.map((m) => `Owner asked at ${strftime(m.ts, "%H:%M")}; end your turn with the answer now`).join("\n");
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** A hand-back ends the wait: the reply just posted answers whatever waited, so the wait clears
|
|
293
|
+
* and the next owner message starts fresh. */
|
|
294
|
+
export function ownerAnswerHandback(now: number): void {
|
|
295
|
+
writeOwnerAnswerState({ lastHandBack: now, steered: [] });
|
|
296
|
+
}
|
package/src/core/owner-ui.ts
CHANGED
|
@@ -24,6 +24,7 @@ import { readMetricEvents } from "./metrics.ts";
|
|
|
24
24
|
import { activePlans, chatUnlock, dependencyOrderProblems, expandHome, gitTop, stateDirPath, unlockPath, writeIndex, type Plan } from "./queue/lib.ts";
|
|
25
25
|
import { featuresReport, gatherTags, loadPlans, releasesReport, type FeaturesReport, type ReleaseRow, type ReleaseSideStats, type ReleasesReport } from "./results.ts";
|
|
26
26
|
import type { Tailscale } from "./tailscale.ts";
|
|
27
|
+
import { recheckHolds, staleFiles, type HoldRunner } from "./waiting-check.ts";
|
|
27
28
|
|
|
28
29
|
const ANSWER_MAX = 2000;
|
|
29
30
|
const MESSAGE_MAX = 4000;
|
|
@@ -189,11 +190,12 @@ export interface MachineRow {
|
|
|
189
190
|
cores: number;
|
|
190
191
|
}
|
|
191
192
|
|
|
192
|
-
export function questionRows(cfg: Config): QuestionRow[] {
|
|
193
|
+
export function questionRows(cfg: Config, run?: HoldRunner): QuestionRow[] {
|
|
193
194
|
const now = Date.now();
|
|
194
195
|
const plans = activePlans(cfg.paths.queue_index);
|
|
196
|
+
const stale = staleFiles(recheckHolds(cfg, plans, run));
|
|
195
197
|
return plans
|
|
196
|
-
.filter(p => p.waiting && p.status === "open" && p.waitingLine)
|
|
198
|
+
.filter(p => p.waiting && p.status === "open" && p.waitingLine && !stale.has(p.file))
|
|
197
199
|
.map(p => {
|
|
198
200
|
let waitingMin = 0;
|
|
199
201
|
try {
|