neurastream 0.1.14 → 0.1.16

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.
@@ -0,0 +1,251 @@
1
+ // Real-time incident detectors (plan 20261022_2330 P3): every detector is a pure function over
2
+ // plain inputs, so tests feed fixtures and the callers (the harness adapter at Main's prompt and
3
+ // after each Main bash result, and main-start) gather the real ones. runDetectors folds each
4
+ // finding into the incident store (src/core/incidents.ts) as source "realtime"; a detector
5
+ // failure is logged to the guard log and swallowed — a broken detector must never break the
6
+ // turn it runs in. Kinds:
7
+ // D1 ledger-contradiction: a subagent's task-result said done, the ledger run source
8
+ // still shows it RUNNING/WAITING past incidents.contradiction_grace_min.
9
+ // D2 tool-crash: a Main bash command running one of this package's bins printed a JS stack
10
+ // frame from the neurastream package or "internal error".
11
+ // D3 block-loop: the same guard BLOCK reason (keyed like M5) logged incidents.block_repeat
12
+ // times within one hour.
13
+ // D4 owner-correction: an owner message matching the M4 correction patterns.
14
+
15
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
16
+ import { dirname, join } from "node:path";
17
+ import { fileURLToPath } from "node:url";
18
+ import type { Run } from "./adapter.ts";
19
+ import type { Config } from "./config.ts";
20
+ import { nowSec, strftime } from "./clock.ts";
21
+ import { log } from "./guards.ts";
22
+ import { addIncident, type IncidentView } from "./incidents.ts";
23
+ import type { GuardBlock } from "./metrics.ts";
24
+
25
+ const HERE = dirname(fileURLToPath(import.meta.url));
26
+
27
+ export interface Finding {
28
+ kind: string;
29
+ summary: string;
30
+ evidence?: string;
31
+ /** Stable identity of the problem; an open incident with it dedupes (count + last seen). */
32
+ fingerprint?: string;
33
+ }
34
+
35
+ function iso(t: number): string {
36
+ return new Date(t * 1000).toISOString();
37
+ }
38
+
39
+ // ---- D1: the ledger contradicts the finished task-result ----
40
+
41
+ export interface TaskResult {
42
+ /** The `<task-result id="…">` agent name, as the ledger spells it. */
43
+ agent: string;
44
+ /** Unix seconds of the async-result line that announced the result. */
45
+ ts: number;
46
+ }
47
+
48
+ /**
49
+ * Finished task-results the ledger still shows as RUNNING/WAITING more than `graceMin` minutes
50
+ * after the result. A result with no ledger row at all is fine: the row may have aged out.
51
+ */
52
+ export function ledgerContradictions(results: TaskResult[], runs: Run[], now: number, graceMin: number): Finding[] {
53
+ const newest: Record<string, TaskResult> = {};
54
+ for (const r of results) {
55
+ const prev = newest[r.agent];
56
+ if (!prev || r.ts > prev.ts) newest[r.agent] = r;
57
+ }
58
+ const byId: Record<string, Run> = Object.fromEntries(runs.map(r => [r.id, r]));
59
+ const out: Finding[] = [];
60
+ for (const agent of Object.keys(newest)) {
61
+ const res = newest[agent]!;
62
+ const run = byId[agent];
63
+ if (!run || (run.status !== "running" && run.status !== "waiting")) continue;
64
+ if (now - res.ts <= graceMin * 60) continue;
65
+ const lateMin = Math.round((now - res.ts) / 60);
66
+ out.push({
67
+ kind: "ledger-contradiction",
68
+ summary: `ledger still shows ${agent} ${run.status} ${lateMin}m after its task-result said done`,
69
+ evidence: `task-result finished at ${iso(res.ts)}; ledger: ${run.statusDetail || run.status}, last write ${iso(run.lastWriteAt)}`,
70
+ fingerprint: `ledger-contradiction:${agent}`,
71
+ });
72
+ }
73
+ return out;
74
+ }
75
+
76
+ // ---- D2: a neurastream tool crashed in a Main bash result ----
77
+
78
+ /** The package's own CLI bin names (package.json "bin"), for D2's "runs a neurastream tool". */
79
+ export function toolBins(packageJson = join(HERE, "../../package.json")): string[] {
80
+ try {
81
+ const bin = (JSON.parse(readFileSync(packageJson, "utf8")) as Record<string, unknown>).bin as unknown;
82
+ return bin && typeof bin === "object" ? Object.keys(bin) : [];
83
+ } catch {
84
+ return [];
85
+ }
86
+ }
87
+
88
+ /** One Main bash result: a neurastream tool whose output shows this package in a JS stack frame, or "internal error". */
89
+ export function toolCrash(command: string, output: string, bins: string[]): Finding | null {
90
+ const tool = bins.find(b => new RegExp(`\\b${b.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\w-])`).test(command));
91
+ if (!tool) return null;
92
+ const lines = output.split("\n");
93
+ const frame = lines.find(l => /^\s*at\s/.test(l) && /neurastream/.test(l));
94
+ const internal = lines.find(l => /internal error/i.test(l));
95
+ if (!frame && !internal) return null;
96
+ const first = (frame ?? internal!).trim().slice(0, 200);
97
+ return {
98
+ kind: "tool-crash",
99
+ summary: `${tool} crashed: ${first}`,
100
+ evidence: frame ? `stack frame: ${frame.trim()}` : `output line: ${internal!.trim()}`,
101
+ fingerprint: `tool-crash:${tool}:${first.replace(/\s+/g, " ").trim()}`,
102
+ };
103
+ }
104
+
105
+ // ---- D3: the same guard block reason in a loop ----
106
+
107
+ /** How far back one block-loop sighting looks. */
108
+ export const BLOCK_LOOP_WINDOW_SEC = 3600;
109
+
110
+ /** The same reason (keyed like M5) logged `repeat` times within `windowSec` ending at `now`. */
111
+ export function blockLoop(blocks: GuardBlock[], now: number, repeat: number, windowSec = BLOCK_LOOP_WINDOW_SEC): Finding[] {
112
+ const counts: Record<string, number> = {};
113
+ for (const b of blocks) {
114
+ if (b.ts <= now - windowSec || b.ts > now) continue;
115
+ counts[b.reason] = (counts[b.reason] ?? 0) + 1;
116
+ }
117
+ return Object.entries(counts)
118
+ .filter(([, count]) => count >= repeat)
119
+ .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))
120
+ .map(([reason, count]) => ({
121
+ kind: "block-loop",
122
+ summary: `the same guard block fired ${count}× in ${Math.round(windowSec / 60)}m: ${reason.slice(0, 160)}`,
123
+ evidence: `${count} BLOCK lines for this reason between ${iso(now - windowSec)} and ${iso(now)}`,
124
+ fingerprint: `block-loop:${reason}`,
125
+ }));
126
+ }
127
+
128
+ // ---- D4: an owner message that corrects Main ----
129
+
130
+ /** An owner message matching an M4 correction pattern, folded per day so a bad afternoon is one incident. */
131
+ export function ownerCorrection(text: string, patterns: RegExp[], now: number): Finding | null {
132
+ const flat = text.replace(/\s+/g, " ").trim();
133
+ if (!flat) return null;
134
+ const matched = patterns.filter(p => p.test(flat));
135
+ if (matched.length === 0) return null;
136
+ return {
137
+ kind: "owner-correction",
138
+ summary: flat.slice(0, 200),
139
+ evidence: `matched: ${matched.map(p => `/${p.source}/`).join(", ")}`,
140
+ fingerprint: `owner-correction:${strftime(now, "%Y%m%d")}`,
141
+ };
142
+ }
143
+
144
+ // ---- the runner ----
145
+
146
+ /** The plain inputs the callers gather; a detector without its input does not run. */
147
+ export interface DetectorInput {
148
+ /** D1: finished task results (the harness adapter parses Main's session file) and the ledger runs. */
149
+ results?: TaskResult[];
150
+ runs?: Run[];
151
+ /** D3: the guard BLOCK lines, gathered by the caller behind the scan gate (runDetectorsGated). */
152
+ blocks?: GuardBlock[];
153
+ /** D2: the last Main bash tool result. */
154
+ bash?: { command: string; output: string };
155
+ /** D4: the owner prompt at before_agent_start; never a main-guard continuation. */
156
+ prompt?: string;
157
+ }
158
+
159
+ /**
160
+ * Runs every detector that has its inputs, folds findings into the incident store and logs each
161
+ * one. Detector failures are logged, never thrown. Returns the incidents (new or deduped).
162
+ */
163
+ export function runDetectors(cfg: Config, input: DetectorInput, now = nowSec()): IncidentView[] {
164
+ const out: IncidentView[] = [];
165
+ const attempt = (name: string, findings: () => Finding[]): void => {
166
+ try {
167
+ for (const f of findings()) {
168
+ const { incident, deduped } = addIncident(
169
+ cfg,
170
+ { source: "realtime", kind: f.kind, summary: f.summary, evidence: f.evidence, fingerprint: f.fingerprint },
171
+ now,
172
+ );
173
+ log(
174
+ cfg.paths.guard_log,
175
+ `incident ${incident.id} [realtime/${incident.kind}]${deduped ? ` sighting #${incident.count}` : " opened"}: ${incident.summary}`,
176
+ );
177
+ out.push(incident);
178
+ }
179
+ } catch (err) {
180
+ log(cfg.paths.guard_log, `detector ${name} failed: ${err instanceof Error ? err.message : String(err)}`);
181
+ }
182
+ };
183
+ if (input.results && input.runs) {
184
+ attempt("ledger-contradiction", () => ledgerContradictions(input.results!, input.runs!, now, cfg.incidents.contradiction_grace_min));
185
+ }
186
+ if (input.bash) {
187
+ attempt("tool-crash", () => {
188
+ const f = toolCrash(input.bash!.command, input.bash!.output, toolBins());
189
+ return f ? [f] : [];
190
+ });
191
+ }
192
+ if (input.blocks) {
193
+ attempt("block-loop", () => blockLoop(input.blocks!, now, cfg.incidents.block_repeat));
194
+ }
195
+ if (input.prompt !== undefined) {
196
+ attempt("owner-correction", () => {
197
+ const f = ownerCorrection(input.prompt!, cfg.metrics.correction_patterns.map(p => new RegExp(p, "i")), now);
198
+ return f ? [f] : [];
199
+ });
200
+ }
201
+ return out;
202
+ }
203
+
204
+ /** The expensive detector inputs (D1 ledger contradiction, D3 block loop): read in one scan. */
205
+ export interface GatedInputs {
206
+ results: TaskResult[];
207
+ runs: Run[];
208
+ blocks: GuardBlock[];
209
+ }
210
+
211
+ /**
212
+ * True when the expensive detectors (D1/D3) may run: at most once per
213
+ * incidents.scan_interval_sec, tracked by a timestamp in <queue_state>/incident-scan.json. The
214
+ * stamp is written BEFORE the inputs are read, so a slow or crashing scan cannot stack — the
215
+ * next attempt is a full interval away (a failed scan retries then, not at the next event). An
216
+ * unreadable state counts as never scanned; an unwritable one throws (the caller logs it and
217
+ * runs the cheap detectors only).
218
+ */
219
+ export function scanDue(cfg: Config, now: number): boolean {
220
+ const file = join(cfg.paths.queue_state, "incident-scan.json");
221
+ let last = 0;
222
+ try {
223
+ const st = JSON.parse(readFileSync(file, "utf8")) as { lastScan?: unknown };
224
+ if (typeof st.lastScan === "number") last = st.lastScan;
225
+ } catch {}
226
+ if (now - last < cfg.incidents.scan_interval_sec) return false;
227
+ mkdirSync(dirname(file), { recursive: true });
228
+ writeFileSync(file, `${JSON.stringify({ lastScan: now })}\n`);
229
+ return true;
230
+ }
231
+
232
+ /**
233
+ * The cheap detectors (D2 bash, D4 prompt) run on every call; D1 and D3 read Main's session
234
+ * file, the ledger runs and both guard logs — seconds on a real machine — so they run at most
235
+ * once per incidents.scan_interval_sec and `gather` is never called inside the interval. A
236
+ * failed gate or gather is logged and the cheap detectors still run.
237
+ */
238
+ export function runDetectorsGated(
239
+ cfg: Config,
240
+ cheap: { bash?: { command: string; output: string }; prompt?: string },
241
+ gather: () => GatedInputs,
242
+ now = nowSec(),
243
+ ): IncidentView[] {
244
+ const input: DetectorInput = { ...cheap };
245
+ try {
246
+ if (scanDue(cfg, now)) Object.assign(input, gather());
247
+ } catch (err) {
248
+ log(cfg.paths.guard_log, `incident scan skipped: ${err instanceof Error ? err.message : String(err)}`);
249
+ }
250
+ return runDetectors(cfg, input, now);
251
+ }
@@ -0,0 +1,225 @@
1
+ // Incidents: problems the system itself finds, in one JSONL store under the queue state dir
2
+ // (<paths.queue_state>/incidents.jsonl, the directory cancel-pending.json lives in). An incident
3
+ // record starts the story; resolution records ({type:"plan"|"dismiss"|"fixed", id, ...}) end it.
4
+ // While an incident is open (no resolution yet) the guards inject it into every Main prompt and
5
+ // refuse spawns and the stop (src/core/guards.ts), so a found bug is deterministically pushed,
6
+ // not remembered. A repeat sighting of an open fingerprint updates count and lastSeen on the
7
+ // existing record instead of adding a second incident; after a resolution the same fingerprint
8
+ // opens a new incident. Sources: realtime (detectors), daily, weekly, main (`incident add`).
9
+
10
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
11
+ import { dirname, join, resolve } from "node:path";
12
+ import { nowSec, strftime } from "./clock.ts";
13
+ import type { Config } from "./config.ts";
14
+ import * as q from "./queue/lib.ts";
15
+
16
+ export type IncidentSource = "realtime" | "daily" | "weekly" | "main";
17
+
18
+ export interface IncidentRec {
19
+ id: string;
20
+ fingerprint: string;
21
+ source: IncidentSource;
22
+ kind: string;
23
+ summary: string;
24
+ evidence: string;
25
+ ts: number;
26
+ count: number;
27
+ lastSeen: number;
28
+ }
29
+
30
+ export type ResolutionRec =
31
+ | { type: "plan"; id: string; plan: string }
32
+ | { type: "dismiss"; id: string; why: string }
33
+ /** `ts` is the close time; older records (written before plan P5) may lack it. */
34
+ | { type: "fixed"; id: string; plan: string; ts?: number };
35
+
36
+ export interface IncidentView extends IncidentRec {
37
+ /** Last resolution record for the id; null while the incident is open. */
38
+ resolution: ResolutionRec | null;
39
+ }
40
+
41
+ export interface IncidentInput {
42
+ source: IncidentSource;
43
+ kind: string;
44
+ summary: string;
45
+ evidence?: string;
46
+ /** Stable identity of the problem; detectors pass one, `incident add` derives it from the text. */
47
+ fingerprint?: string;
48
+ }
49
+
50
+ export function incidentsFile(cfg: Config): string {
51
+ return join(cfg.paths.queue_state, "incidents.jsonl");
52
+ }
53
+
54
+ /** Default fingerprint: the finding's own text, normalized, so re-reporting the same bug dedupes. */
55
+ export function defaultFingerprint(input: Pick<IncidentInput, "source" | "kind" | "summary">): string {
56
+ return q.sha(`${input.source}|${input.kind}|${input.summary.replace(/\s+/g, " ").trim().toLowerCase()}`);
57
+ }
58
+
59
+ function parseLine(line: string): IncidentRec | ResolutionRec | null {
60
+ let rec: Record<string, unknown>;
61
+ try {
62
+ const parsed: unknown = JSON.parse(line);
63
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
64
+ rec = parsed as Record<string, unknown>;
65
+ } catch {
66
+ return null;
67
+ }
68
+ if (typeof rec.id !== "string") return null;
69
+ if (rec.type === "plan" || rec.type === "fixed") {
70
+ if (typeof rec.plan !== "string") return null;
71
+ return rec.type === "fixed" && typeof rec.ts === "number"
72
+ ? { type: "fixed", id: rec.id, plan: rec.plan, ts: rec.ts }
73
+ : { type: rec.type, id: rec.id, plan: rec.plan };
74
+ }
75
+ if (rec.type === "dismiss") {
76
+ if (typeof rec.why !== "string") return null;
77
+ return { type: "dismiss", id: rec.id, why: rec.why };
78
+ }
79
+ if (rec.type !== undefined) return null;
80
+ if (typeof rec.fingerprint !== "string" || typeof rec.kind !== "string" || typeof rec.summary !== "string" || typeof rec.ts !== "number")
81
+ return null;
82
+ const source = rec.source === "realtime" || rec.source === "daily" || rec.source === "weekly" ? rec.source : "main";
83
+ return {
84
+ id: rec.id,
85
+ fingerprint: rec.fingerprint,
86
+ source,
87
+ kind: rec.kind,
88
+ summary: rec.summary,
89
+ evidence: typeof rec.evidence === "string" ? rec.evidence : "",
90
+ ts: rec.ts,
91
+ count: typeof rec.count === "number" && rec.count >= 1 ? rec.count : 1,
92
+ lastSeen: typeof rec.lastSeen === "number" ? rec.lastSeen : rec.ts,
93
+ };
94
+ }
95
+
96
+ function readStore(file: string): { incidents: IncidentRec[]; resolutions: ResolutionRec[]; lines: string[] } {
97
+ let lines: string[] = [];
98
+ try {
99
+ lines = readFileSync(file, "utf8").split("\n").filter(l => l.trim());
100
+ } catch {}
101
+ const incidents: IncidentRec[] = [];
102
+ const resolutions: ResolutionRec[] = [];
103
+ for (const line of lines) {
104
+ const rec = parseLine(line);
105
+ if (!rec) continue;
106
+ if ("type" in rec) resolutions.push(rec);
107
+ else incidents.push(rec);
108
+ }
109
+ return { incidents, resolutions, lines };
110
+ }
111
+
112
+ function writeFile(cfg: Config, file: string, lines: string[]): void {
113
+ mkdirSync(dirname(file), { recursive: true });
114
+ writeFileSync(file, `${lines.join("\n")}\n`);
115
+ }
116
+
117
+ /** Every incident in file order, each folded with its last resolution record (if any). */
118
+ export function readIncidents(cfg: Config): IncidentView[] {
119
+ const store = readStore(incidentsFile(cfg));
120
+ const views = new Map<string, IncidentView>();
121
+ for (const rec of store.incidents) views.set(rec.id, { ...rec, resolution: null });
122
+ for (const res of store.resolutions) {
123
+ const v = views.get(res.id);
124
+ if (v) v.resolution = res;
125
+ }
126
+ return [...views.values()];
127
+ }
128
+
129
+ /** Incidents with no plan, no dismissal and no fixed record: the ones the guards push on Main. */
130
+ export function openIncidents(cfg: Config): IncidentView[] {
131
+ return readIncidents(cfg).filter(i => !i.resolution);
132
+ }
133
+
134
+ /** Records a sighting. Returns the (open) incident; `deduped` says an open one was updated. */
135
+ export function addIncident(cfg: Config, input: IncidentInput, now = nowSec()): { incident: IncidentView; deduped: boolean } {
136
+ const file = incidentsFile(cfg);
137
+ const store = readStore(file);
138
+ const fingerprint = input.fingerprint ?? defaultFingerprint(input);
139
+ const open = store.incidents.find(
140
+ i => i.fingerprint === fingerprint && !store.resolutions.some(r => r.id === i.id),
141
+ );
142
+ if (open) {
143
+ open.count += 1;
144
+ open.lastSeen = now;
145
+ const lines = store.lines.map(line => {
146
+ const rec = parseLine(line);
147
+ return rec && !("type" in rec) && rec.id === open.id ? JSON.stringify(open) : line;
148
+ });
149
+ writeFile(cfg, file, lines);
150
+ return { incident: { ...open, resolution: null }, deduped: true };
151
+ }
152
+ const day = strftime(now, "%Y%m%d");
153
+ const prefix = `I-${day}-`;
154
+ const used = store.incidents.filter(i => i.id.startsWith(prefix)).map(i => Number(i.id.slice(prefix.length)) || 0);
155
+ const rec: IncidentRec = {
156
+ id: `${prefix}${(used.length ? Math.max(...used) : 0) + 1}`,
157
+ fingerprint,
158
+ source: input.source,
159
+ kind: input.kind,
160
+ summary: input.summary,
161
+ evidence: input.evidence ?? "",
162
+ ts: now,
163
+ count: 1,
164
+ lastSeen: now,
165
+ };
166
+ mkdirSync(dirname(file), { recursive: true });
167
+ appendFileSync(file, `${JSON.stringify(rec)}\n`);
168
+ return { incident: { ...rec, resolution: null }, deduped: false };
169
+ }
170
+
171
+ /**
172
+ * Records the plan that fixes an incident: refused unless the file exists, is listed in its repo
173
+ * INDEX.md, and contains `INCIDENT <id>` (the spawn gates look for that text). Returns the
174
+ * refusal reason, or null when recorded.
175
+ */
176
+ export function planIncident(cfg: Config, id: string, planPath: string): string | null {
177
+ const file = incidentsFile(cfg);
178
+ const store = readStore(file);
179
+ if (!store.incidents.some(i => i.id === id)) return `unknown incident ${id}`;
180
+ const res = store.resolutions.filter(r => r.id === id).at(-1);
181
+ if (res) return `incident ${id} already has a ${res.type} record`;
182
+ const abs = resolve(q.expandHome(planPath));
183
+ if (!existsSync(abs)) return `plan file not found: ${abs}`;
184
+ const repo = dirname(dirname(dirname(abs)));
185
+ if (!q.readRepoIndex(repo).includes(abs)) return `${abs} is not listed in ${join(repo, q.REPO_INDEX)}`;
186
+ let text: string;
187
+ try {
188
+ text = readFileSync(abs, "utf8");
189
+ } catch {
190
+ return `cannot read ${abs}`;
191
+ }
192
+ if (!text.includes(`INCIDENT ${id}`)) return `${abs} must contain "INCIDENT ${id}" so the guards can see the fix names the incident`;
193
+ mkdirSync(dirname(file), { recursive: true });
194
+ appendFileSync(file, `${JSON.stringify({ type: "plan", id, plan: abs })}\n`);
195
+ return null;
196
+ }
197
+
198
+ /** Records why an incident is not a bug (or not worth fixing); an empty why is refused. */
199
+ export function dismissIncident(cfg: Config, id: string, why: string): string | null {
200
+ const file = incidentsFile(cfg);
201
+ const store = readStore(file);
202
+ if (!store.incidents.some(i => i.id === id)) return `unknown incident ${id}`;
203
+ const res = store.resolutions.filter(r => r.id === id).at(-1);
204
+ if (res) return `incident ${id} already has a ${res.type} record`;
205
+ if (!why.trim()) return "refused: an empty --why would hide the incident without a recorded reason";
206
+ mkdirSync(dirname(file), { recursive: true });
207
+ appendFileSync(file, `${JSON.stringify({ type: "dismiss", id, why })}\n`);
208
+ return null;
209
+ }
210
+
211
+ /**
212
+ * Records that an incident's fix shipped: the queue writes this when it closes a plan citing
213
+ * `INCIDENT <id>` (plan P5), so the guards stop pushing a bug whose fix just landed. Refusals
214
+ * mirror `incident plan`; the caller logs them and closes anyway.
215
+ */
216
+ export function fixedIncident(cfg: Config, id: string, plan: string, now = nowSec()): string | null {
217
+ const file = incidentsFile(cfg);
218
+ const store = readStore(file);
219
+ if (!store.incidents.some(i => i.id === id)) return `unknown incident ${id}`;
220
+ const res = store.resolutions.filter(r => r.id === id).at(-1);
221
+ if (res) return `incident ${id} already has a ${res.type} record`;
222
+ mkdirSync(dirname(file), { recursive: true });
223
+ appendFileSync(file, `${JSON.stringify({ type: "fixed", id, plan, ts: now })}\n`);
224
+ return null;
225
+ }
@@ -1,8 +1,16 @@
1
- import { existsSync, readFileSync, statSync } from "node:fs";
1
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
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";
6
+ import { readEvents } from "./agent-score.ts";
5
7
  import type { Config } from "./config.ts";
8
+ import { nowSec, strftime } from "./clock.ts";
9
+ import { runDetectors, type TaskResult } from "./incident-detectors.ts";
10
+ import { addIncident, type IncidentView } from "./incidents.ts";
11
+ import { log as logGuard } from "./guards.ts";
12
+ import { dailyChecks, readBlocks, readMetricEvents, worseThanMean } from "./metrics.ts";
13
+ import { buildReport } from "./report.ts";
6
14
 
7
15
  function bin(name: string, cfg: Config): string {
8
16
  return join(cfg.paths.home, ".local/bin", name);
@@ -53,15 +61,52 @@ function run(file: string, args: string[], opts: RunOpts = {}): Promise<RunResul
53
61
  // an agent host passes false, because its stdin is the session's input.
54
62
  // stderr: the CLI lets a child's stderr reach the terminal. An agent host captures it and appends it
55
63
  // after that child's stdout, because a write to the terminal would draw over the session's UI.
56
- export async function mainStartText(args: string[], cfg: Config, opts: { inheritStdin: boolean }): Promise<string> {
64
+ /** What the caller supplies for the detector run and (later phases) the daily/weekly checks. */
65
+ export interface MainStartDeps {
66
+ /** Runs for the ledger-contradiction detector; null/absent skips what needs one. */
67
+ source?: RunSource | null;
68
+ /** Finished task results parsed from Main's session file (the adapter's format knowledge). */
69
+ results?: TaskResult[];
70
+ }
71
+
72
+ // Real-time detectors at main-start (plan 20261022_2330 P3): best effort, logged, never thrown.
73
+ function runMainStartDetectors(cfg: Config, deps: MainStartDeps): void {
74
+ if (!deps.source && !deps.results) return;
75
+ try {
76
+ runDetectors(cfg, { results: deps.results, runs: deps.source ? deps.source.listRuns(nowSec() - 2 * 86400) : undefined });
77
+ } catch (err) {
78
+ logGuard(cfg.paths.guard_log, `main-start detectors failed: ${err instanceof Error ? err.message : String(err)}`);
79
+ }
80
+ }
81
+
82
+ export async function mainStartText(args: string[], cfg: Config, opts: { inheritStdin: boolean }, deps: MainStartDeps = {}): Promise<string> {
57
83
  const out: string[] = [];
58
84
  const say = (line: string) => out.push(`${line}\n`);
85
+ runMainStartDetectors(cfg, deps);
59
86
  const h = args[0] ?? String(cfg.health.default_hours);
60
87
  const childStdin = opts.inheritStdin ? "inherit" : "ignore";
61
88
  const childStderr = opts.inheritStdin ? "inherit" : "pipe";
62
- // Weekly self-metrics: nudge the owner's report when notes/metrics.md is missing or older than the window.
63
- const due = metricsDueLine(cfg, Date.now());
64
- if (due) say(due);
89
+ // Daily metrics check and the forced weekly report (plan 20261022_2330 P4): best effort, each
90
+ // failure logged, never thrown — the preflight must print even when a check fails.
91
+ if (deps.source) {
92
+ try {
93
+ for (const i of runDailyCheck(cfg, deps.source, nowSec())) say(`incident ${i.id} [daily/${i.kind}]: ${i.summary}`);
94
+ } catch (err) {
95
+ logGuard(cfg.paths.guard_log, `daily check failed: ${err instanceof Error ? err.message : String(err)}`);
96
+ }
97
+ try {
98
+ const weekly = runWeeklyCheck(cfg, deps.source, nowSec());
99
+ if (weekly) say(weekly);
100
+ } catch (err) {
101
+ logGuard(cfg.paths.guard_log, `weekly check failed: ${err instanceof Error ? err.message : String(err)}`);
102
+ const due = metricsDueLine(cfg, Date.now());
103
+ if (due) say(due);
104
+ }
105
+ } else {
106
+ // Weekly self-metrics: nudge the owner's report when notes/metrics.md is missing or older than the window.
107
+ const due = metricsDueLine(cfg, Date.now());
108
+ if (due) say(due);
109
+ }
65
110
  say("=== machine");
66
111
  const mg = await run(bin("machine-guard", cfg), [], { stderr: "ignore" });
67
112
  const mgLines = mg.stdout.trim().split("\n");
@@ -106,8 +151,8 @@ export async function mainStartText(args: string[], cfg: Config, opts: { inherit
106
151
  return out.join("");
107
152
  }
108
153
 
109
- export async function mainStart(args: string[], cfg: Config): Promise<number> {
110
- process.stdout.write(await mainStartText(args, cfg, { inheritStdin: true }));
154
+ export async function mainStart(args: string[], cfg: Config, deps: MainStartDeps = {}): Promise<number> {
155
+ process.stdout.write(await mainStartText(args, cfg, { inheritStdin: true }, deps));
111
156
  return 0;
112
157
  }
113
158
 
@@ -117,5 +162,97 @@ export function metricsDueLine(cfg: Config, nowMs: number): string | null {
117
162
  const stamp = existsSync(reportFile) ? statSync(reportFile).mtime : null;
118
163
  if (stamp && nowMs - stamp.getTime() <= cfg.metrics.report_days * 86400 * 1000) return null;
119
164
  const last = stamp ? stamp.toISOString().slice(0, 10) : "never";
120
- return `metrics: report due (last: ${last}) — run neurastream metrics report, then propose ONE rule change to the owner`;
165
+ return `metrics: report due (last: ${last}) — neurastream writes the report itself and the worst metric becomes an incident; plan or dismiss that incident`;
166
+ }
167
+
168
+ // ---- daily and weekly, forced (plan 20261022_2330 P4) ----
169
+
170
+ const DAY = 86400;
171
+
172
+ function dailyStateFile(cfg: Config): string {
173
+ return join(cfg.paths.queue_state, "incidents-daily.json");
174
+ }
175
+
176
+ function fmtMetric(v: number | null): string {
177
+ return v === null ? "n/a" : v >= 10 ? String(Math.round(v)) : v.toFixed(2);
178
+ }
179
+
180
+ /**
181
+ * Once per calendar day (state file in queue_state), at the first main-start or Main
182
+ * before_agent_start: M1-M5 for the last 24h against the mean of the 7 days before; each metric
183
+ * worse by ≥ incidents.daily_worse_pct and above its floor opens a daily incident. Returns the
184
+ * incidents opened; [] when today is already checked. The day is marked only after the check
185
+ * ran, so a failed check is retried at the next event.
186
+ */
187
+ export function runDailyCheck(cfg: Config, source: RunSource, now: number): IncidentView[] {
188
+ const today = strftime(now, "%Y-%m-%d");
189
+ const file = dailyStateFile(cfg);
190
+ try {
191
+ const st = JSON.parse(readFileSync(file, "utf8")) as { date?: string };
192
+ if (st.date === today) return [];
193
+ } catch {}
194
+ const inp = {
195
+ runs: source.listRuns(now - 8 * DAY),
196
+ events: [...readEvents(cfg), ...readMetricEvents(cfg)],
197
+ };
198
+ const out: IncidentView[] = [];
199
+ for (const c of dailyChecks(cfg, inp, readBlocks(cfg), now)) {
200
+ if (!worseThanMean(c, cfg.incidents.daily_worse_pct)) continue;
201
+ const { incident } = addIncident(
202
+ cfg,
203
+ {
204
+ source: "daily",
205
+ kind: "daily-regression",
206
+ summary: `${c.label} regressed: ${fmtMetric(c.cur)} last 24h vs ${fmtMetric(c.mean)}/day over the 7 days before (floor ${fmtMetric(c.floor)})`,
207
+ evidence: `${c.label}: last 24h ${fmtMetric(c.cur)} vs 7-day daily mean ${fmtMetric(c.mean)}`,
208
+ fingerprint: `daily:${c.key}:${today}`,
209
+ },
210
+ now,
211
+ );
212
+ logGuard(cfg.paths.guard_log, `incident ${incident.id} [daily/${incident.kind}] opened: ${incident.summary}`);
213
+ out.push(incident);
214
+ }
215
+ mkdirSync(dirname(file), { recursive: true });
216
+ writeFileSync(file, `${JSON.stringify({ date: today })}\n`);
217
+ return out;
218
+ }
219
+
220
+ /**
221
+ * When the weekly report is due, the code writes notes/metrics.md itself (as `metrics report`
222
+ * does) and the worst ranked metric becomes an incident (source "weekly"). Returns the due line
223
+ * for the main-start text — the incident id where "propose ONE rule change" used to be — and ""
224
+ * while the report is fresh. Best effort: a failed write returns the plain due line.
225
+ */
226
+ export function runWeeklyCheck(cfg: Config, source: RunSource, now: number): string {
227
+ const due = metricsDueLine(cfg, now * 1000);
228
+ if (!due) return "";
229
+ const last = /\(last: ([^)]+)\)/.exec(due)?.[1] ?? "never";
230
+ try {
231
+ const rep = buildReport(cfg, source, cfg.metrics.report_days, now);
232
+ mkdirSync(cfg.paths.notes, { recursive: true });
233
+ writeFileSync(join(cfg.paths.notes, "metrics.md"), rep.md);
234
+ const w = rep.worst;
235
+ if (!w || w.change === null) {
236
+ return `metrics: report due (last: ${last}) — wrote ${join(cfg.paths.notes, "metrics.md")}; no ranked metric moved this window`;
237
+ }
238
+ const pct = `${w.change >= 0 ? "+" : ""}${w.change.toFixed(1)}%`;
239
+ const { incident } = addIncident(
240
+ cfg,
241
+ {
242
+ source: "weekly",
243
+ kind: "weekly-regression",
244
+ summary: `${w.name} is the worst mover this report: ${pct} (${fmtMetric(w.cur)} vs ${fmtMetric(w.prev)})`,
245
+ evidence: `${w.name}: ${fmtMetric(w.cur)} this window vs ${fmtMetric(w.prev)} the window before (${pct})`,
246
+ fingerprint: `weekly:${w.key}:${strftime(now, "%Y%m%d")}`,
247
+ },
248
+ now,
249
+ );
250
+ logGuard(cfg.paths.guard_log, `incident ${incident.id} [weekly/${incident.kind}] opened: ${incident.summary}`);
251
+ return (
252
+ `metrics: report due (last: ${last}) — wrote ${join(cfg.paths.notes, "metrics.md")}; worst metric ${w.name} is incident ${incident.id}: ` +
253
+ `plan it (\`neurastream incident plan ${incident.id} <plan.md>\`) or dismiss it (\`neurastream incident dismiss ${incident.id} --why "<text>"\`)`
254
+ );
255
+ } catch (err) {
256
+ return `metrics: report due (last: ${last}) — the report write failed: ${err instanceof Error ? err.message : String(err)}`;
257
+ }
121
258
  }