neurastream 0.2.62 → 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.
@@ -188,6 +188,10 @@ export function lintText(text: string, cfg: Config): { errs: string[]; warns: st
188
188
 
189
189
  export function briefLint(args: string[], cfg: Config): number {
190
190
  if (args.length === 0) return exitText(helpDoc("brief-lint"));
191
+ if (args[0] === "-h" || args[0] === "--help") {
192
+ printText(helpDoc("brief-lint"));
193
+ return 0;
194
+ }
191
195
  let rc = 0;
192
196
  for (const path of args) {
193
197
  const { errs, warns } = lint(path, cfg);
package/src/core/ci.ts ADDED
@@ -0,0 +1,271 @@
1
+ // CI in the loop (plan 20261027_1430 P6b): the watcher's forge checks, plus the M3 `ci` recording
2
+ // that used to live only in the CLI. Every forge call goes through an injected CommandRunner
3
+ // (mr-sweep's), so tests run a fake glab/gh/git and never touch a real forge.
4
+ // Only finished pipelines (success|failed) count: a running or pending one neither opens nor
5
+ // closes an incident, so a run in flight cannot flap one.
6
+
7
+ import type { Config } from "./config.ts";
8
+ import { appendMetric, readMetricEvents } from "./metrics.ts";
9
+ import { defaultRunner, listOpenMrs, mentioned, parseList, repoForge, type CommandRunner, type Forge } from "./mr-sweep.ts";
10
+
11
+ /** One pipeline. `other` = running, pending, canceled or skipped. */
12
+ export interface Pipeline {
13
+ ref: string;
14
+ sha: string;
15
+ status: "success" | "failed" | "other";
16
+ /** Unix seconds the pipeline was created. */
17
+ at: number;
18
+ }
19
+
20
+ /** One CI problem, shaped like the watcher's WatchProblem (watch.ts keeps its own copy). */
21
+ export interface CiProblem {
22
+ fingerprint: string;
23
+ kind: string;
24
+ job: string;
25
+ at: string;
26
+ line: string;
27
+ summary: string;
28
+ evidence: string;
29
+ }
30
+
31
+ export interface CiInputs {
32
+ run: CommandRunner;
33
+ now: number;
34
+ /** The plans whose repos are scanned, and the text an MR is matched against. */
35
+ plans: { file: string; repo: string; text: string }[];
36
+ /** Plan files with a running agent: an MR they name never opens ci-red-mr. */
37
+ staffed: string[];
38
+ }
39
+
40
+ export interface CiScan {
41
+ problems: CiProblem[];
42
+ /** M3 `ci` records this run wrote. */
43
+ recorded: number;
44
+ /** `ci-flaky` records this run wrote. */
45
+ flaky: number;
46
+ /** Repos or steps the check could not read, with the reason. */
47
+ skipped: string[];
48
+ /** ci-red-mr fingerprints a staffed plan held back this run: still red, so their incidents stay open. */
49
+ held: string[];
50
+ }
51
+
52
+ export type CiRecord = { ok: true; tries: number; skipped: string[] } | { ok: false; code: number; error: string };
53
+
54
+ /** Newest merged MRs one run reads per repo. The ledger marks what is recorded, so an MR is never recorded twice; this only bounds the first backfill. */
55
+ const MERGED_LIST = 20;
56
+ /** Newest pipelines one run reads per repo. */
57
+ const PIPELINE_LIST = 100;
58
+
59
+ const iso = (sec: number): string => new Date(sec * 1000).toISOString();
60
+ const str = (v: unknown): string => (typeof v === "string" ? v : "");
61
+
62
+ /** Runs the configured CI command for one MR and records how many pipelines it needed (M3), then the repo's product numbers. The CLI and the watcher show the error their own way. */
63
+ export function recordCiMr(cfg: Config, repoDir: string, mr: string, now: number, run: CommandRunner = defaultRunner): CiRecord {
64
+ const template = cfg.metrics.ci_pipelines_cmd;
65
+ if (!template) return { ok: false, code: 2, error: "metrics.ci_pipelines_cmd not set" };
66
+ const r = run(["sh", "-c", template.replaceAll("{mr}", `'${mr.replaceAll("'", "'\\''")}'`)], { cwd: repoDir });
67
+ if (r.code !== 0) return { ok: false, code: 1, error: `ci command exited ${r.code}: ${r.stderr.trim()}` };
68
+ let pipelines: unknown;
69
+ try {
70
+ pipelines = JSON.parse(r.stdout);
71
+ } catch {
72
+ pipelines = undefined;
73
+ }
74
+ if (!Array.isArray(pipelines)) return { ok: false, code: 1, error: "ci command must print a JSON array on stdout" };
75
+ appendMetric(cfg, { type: "ci", mr, repo: repoDir, tries: pipelines.length, ts: now });
76
+ return { ok: true, tries: pipelines.length, skipped: recordProducts(cfg, repoDir, now) };
77
+ }
78
+
79
+ const PRODUCT_TIMEOUT_MS = 10_000;
80
+
81
+ /**
82
+ * Runs the repo's configured product numbers once each (metrics.product_cmds) and appends one
83
+ * product record per number. A command that fails, times out or prints anything but one finite
84
+ * number is skipped and returned as a message; the ci record itself never fails on a product number.
85
+ */
86
+ function recordProducts(cfg: Config, repoDir: string, now: number): string[] {
87
+ const skipped: string[] = [];
88
+ for (const [name, cmd] of Object.entries(cfg.metrics.product_cmds[repoDir] ?? {})) {
89
+ const proc = Bun.spawnSync(["sh", "-c", cmd], { cwd: repoDir, stdout: "pipe", stderr: "pipe", timeout: PRODUCT_TIMEOUT_MS });
90
+ const out = proc.stdout.toString().trim();
91
+ const value = Number(out);
92
+ if (proc.exitCode !== 0 || out === "" || !Number.isFinite(value)) {
93
+ const why = proc.exitCode !== 0 ? `exit ${proc.exitCode ?? "signal"}` : `not one number: "${out.slice(0, 40)}"`;
94
+ skipped.push(`product_cmds.${name}: skipped (${why})`);
95
+ continue;
96
+ }
97
+ appendMetric(cfg, { type: "product", repo: repoDir, name, value, ts: now });
98
+ }
99
+ return skipped;
100
+ }
101
+
102
+ /** The default branch from origin's HEAD; null when origin has no HEAD ref. */
103
+ function defaultBranch(repo: string, run: CommandRunner): string | null {
104
+ const r = run(["git", "-C", repo, "symbolic-ref", "--short", "refs/remotes/origin/HEAD"], {});
105
+ const name = r.code === 0 ? r.stdout.trim().replace(/^origin\//, "") : "";
106
+ return name || null;
107
+ }
108
+
109
+ /** Newest pipelines of a repo; null when the forge CLI cannot answer (never "no pipelines"). */
110
+ export function pipelinesOf(repo: string, forge: Forge, run: CommandRunner): Pipeline[] | null {
111
+ const r =
112
+ forge === "gitlab"
113
+ ? run(["glab", "api", `projects/:id/pipelines?per_page=${PIPELINE_LIST}`], { cwd: repo })
114
+ : run(["gh", "run", "list", "--limit", String(PIPELINE_LIST), "--json", "headBranch,headSha,conclusion,status,createdAt"], { cwd: repo });
115
+ const rows = r.code === 0 ? parseList(r.stdout) : null;
116
+ if (!rows) return null;
117
+ const pipes = rows.map((row): Pipeline => {
118
+ if (forge === "gitlab") {
119
+ const s = str(row.status);
120
+ return { ref: str(row.ref), sha: str(row.sha), status: s === "success" || s === "failed" ? s : "other", at: Date.parse(str(row.created_at)) / 1000 };
121
+ }
122
+ // A gh run is finished when its status is completed; the conclusion then says how it ended.
123
+ const c = str(row.conclusion);
124
+ const status = str(row.status) !== "completed" ? "other" : c === "success" ? "success" : c === "failure" ? "failed" : "other";
125
+ return { ref: str(row.headBranch), sha: str(row.headSha), status, at: Date.parse(str(row.createdAt)) / 1000 };
126
+ });
127
+ return pipes.filter(p => Number.isFinite(p.at));
128
+ }
129
+
130
+ /** Newest merged MR numbers of a repo; null when the forge CLI cannot answer. */
131
+ function mergedMrs(repo: string, forge: Forge, run: CommandRunner): number[] | null {
132
+ const r =
133
+ forge === "gitlab"
134
+ ? run(["glab", "mr", "list", "--merged", "-F", "json", "-P", String(MERGED_LIST)], { cwd: repo })
135
+ : run(["gh", "pr", "list", "--state", "merged", "--limit", String(MERGED_LIST), "--json", "number"], { cwd: repo });
136
+ const rows = r.code === 0 ? parseList(r.stdout) : null;
137
+ if (!rows) return null;
138
+ // The cap holds here too: the forge's own limit flag is only a hint, and the first backfill must stay bounded.
139
+ return rows.map(row => (typeof row.iid === "number" ? row.iid : row.number)).filter((n): n is number => typeof n === "number" && n > 0).slice(0, MERGED_LIST);
140
+ }
141
+
142
+ /** When the newest finished run of a ref started failing: the oldest failure of the unbroken red streak at the head. Null when the newest passed. */
143
+ function redSince(runs: Pipeline[]): number | null {
144
+ if (runs[0]?.status !== "failed") return null;
145
+ let since = runs[0].at;
146
+ for (const p of runs) {
147
+ if (p.status !== "failed") break;
148
+ since = p.at;
149
+ }
150
+ return since;
151
+ }
152
+
153
+ /** Shas that went red and then green: a passing run newer than a failed run of the same commit. */
154
+ function flakyShas(pipes: Pipeline[]): string[] {
155
+ const out = new Set<string>();
156
+ pipes.forEach((ok, i) => {
157
+ if (ok.status === "success" && pipes.slice(i + 1).some(p => p.status === "failed" && p.sha === ok.sha)) out.add(ok.sha);
158
+ });
159
+ return [...out];
160
+ }
161
+
162
+ function redProblems(cfg: Config, repo: string, pipes: Pipeline[], inp: CiInputs, scan: CiScan): CiProblem[] {
163
+ const out: CiProblem[] = [];
164
+ const finished = pipes.filter(p => p.status !== "other");
165
+ const branch = defaultBranch(repo, inp.run);
166
+ const main = finished.find(p => p.ref === branch);
167
+ if (main?.status === "failed") {
168
+ out.push({
169
+ fingerprint: `watch:ci-red-main:${repo}`,
170
+ kind: "ci-red-main",
171
+ job: repo,
172
+ at: iso(main.at),
173
+ line: `pipeline on ${branch} failed (sha ${main.sha.slice(0, 8)})`,
174
+ summary: `${branch} pipeline failed in ${repo}`,
175
+ evidence: `ci: newest finished pipeline on ${branch} is failed`,
176
+ });
177
+ }
178
+ const open = listOpenMrs(repo, inp.run);
179
+ if (!open.ok) {
180
+ scan.skipped.push(`${repo} (open MRs: ${open.why})`);
181
+ return out;
182
+ }
183
+ for (const mr of open.mrs) {
184
+ const since = redSince(finished.filter(p => p.ref === mr.branch));
185
+ if (since === null) continue;
186
+ const hours = (inp.now - since) / 3600;
187
+ if (hours <= cfg.watch.ci_red_hours) continue;
188
+ const staffed = inp.plans.some(p => p.repo === repo && inp.staffed.includes(p.file) && mentioned(mr.token, mr.branch, [p.text]));
189
+ const fingerprint = `watch:ci-red-mr:${repo}#${mr.number}`;
190
+ if (staffed) {
191
+ // Held back, not recovered: the MR is still red, so its incident stays open.
192
+ scan.held.push(fingerprint);
193
+ continue;
194
+ }
195
+ const h = hours.toFixed(1);
196
+ out.push({
197
+ fingerprint,
198
+ kind: "ci-red-mr",
199
+ job: `${repo} ${mr.token}`,
200
+ at: iso(since),
201
+ line: `pipeline on ${mr.branch} red for ${h}h (limit ${cfg.watch.ci_red_hours}h)`,
202
+ summary: `${mr.token} pipeline red for ${h}h on ${mr.branch} in ${repo}`,
203
+ evidence: `ci: newest finished pipelines on ${mr.branch} failed since ${iso(since)}`,
204
+ });
205
+ }
206
+ return out;
207
+ }
208
+
209
+ /**
210
+ * Records M3 `ci` for merged MRs with no ledger row. A CI error skips only that MR, so the rest still
211
+ * record. Its skip is logged once (a ci-skip record) and the MR is retried on the next run.
212
+ */
213
+ function recordMerged(cfg: Config, repo: string, forge: Forge, done: Set<string>, skipLogged: Set<string>, inp: CiInputs, scan: CiScan): void {
214
+ if (!cfg.metrics.ci_pipelines_cmd) return;
215
+ const merged = mergedMrs(repo, forge, inp.run);
216
+ if (!merged) {
217
+ scan.skipped.push(`${repo} (merged MRs unreachable)`);
218
+ return;
219
+ }
220
+ for (const mr of merged) {
221
+ const key = `${repo}#${mr}`;
222
+ if (done.has(key)) continue;
223
+ const rec = recordCiMr(cfg, repo, String(mr), inp.now, inp.run);
224
+ if (!rec.ok) {
225
+ if (!skipLogged.has(key)) {
226
+ scan.skipped.push(`${repo} (ci command for !${mr}: ${rec.error})`);
227
+ appendMetric(cfg, { type: "ci-skip", repo, mr: String(mr), ts: inp.now });
228
+ skipLogged.add(key);
229
+ }
230
+ continue;
231
+ }
232
+ done.add(key);
233
+ scan.recorded++;
234
+ for (const s of rec.skipped) scan.skipped.push(`${repo} (${s})`);
235
+ }
236
+ }
237
+
238
+ function recordFlaky(cfg: Config, repo: string, pipes: Pipeline[], flagged: Set<string>, inp: CiInputs, scan: CiScan): void {
239
+ for (const sha of flakyShas(pipes)) {
240
+ const key = `${repo}@${sha}`;
241
+ if (flagged.has(key)) continue;
242
+ appendMetric(cfg, { type: "ci-flaky", repo, sha, ts: inp.now });
243
+ flagged.add(key);
244
+ scan.flaky++;
245
+ }
246
+ }
247
+
248
+ /** One watcher pass over CI: red default branch, red open MRs, M3 for merged MRs, flaky commits. Repos come from the active plans, as mr-sweep does. */
249
+ export function ciScan(cfg: Config, inp: CiInputs): CiScan {
250
+ const scan: CiScan = { problems: [], recorded: 0, flaky: 0, skipped: [], held: [] };
251
+ const events = readMetricEvents(cfg);
252
+ const ciDone = new Set(events.filter(e => e.type === "ci").map(e => `${e.repo}#${e.mr}`));
253
+ const flagged = new Set(events.filter(e => e.type === "ci-flaky").map(e => `${e.repo}@${e.sha}`));
254
+ const skipLogged = new Set(events.filter(e => e.type === "ci-skip").map(e => `${e.repo}#${e.mr}`));
255
+ for (const repo of new Set(inp.plans.map(p => p.repo))) {
256
+ const found = repoForge(repo, inp.run);
257
+ if ("why" in found) {
258
+ scan.skipped.push(`${repo} (${found.why})`);
259
+ continue;
260
+ }
261
+ const pipes = pipelinesOf(repo, found.forge, inp.run);
262
+ if (!pipes) {
263
+ scan.skipped.push(`${repo} (pipelines unreachable)`);
264
+ continue;
265
+ }
266
+ scan.problems.push(...redProblems(cfg, repo, pipes, inp, scan));
267
+ recordMerged(cfg, repo, found.forge, ciDone, skipLogged, inp, scan);
268
+ recordFlaky(cfg, repo, pipes, flagged, inp, scan);
269
+ }
270
+ return scan;
271
+ }
@@ -107,6 +107,10 @@ export interface Config {
107
107
  auto_close_min: number;
108
108
  repo_index: string;
109
109
  cancelled_rel: string;
110
+ /** How long a hold's `still true if` result is reused (src/core/waiting-check.ts). */
111
+ waiting_check_ttl_sec: number;
112
+ /** One hold check may run this long; a timeout is "unknown", never "stale". */
113
+ waiting_check_timeout_sec: number;
110
114
  };
111
115
  guards: {
112
116
  sub_warn_calls: number;
@@ -198,6 +202,31 @@ export interface Config {
198
202
  daily_worse_pct: number;
199
203
  /** Per-metric daily floors (keys: m1, m2, m3, m4_corrections, m4_questions, m5): a regression below the floor is noise. */
200
204
  daily_floor: Record<string, number>;
205
+ /** D8: seconds after a guard block within which a similar call of the same tool counts as a bypass. */
206
+ bypass_window_sec: number;
207
+ /** D8: token-set Jaccard similarity in (0, 1] between a blocked call's args and the bypass. */
208
+ bypass_similarity: number;
209
+ };
210
+ /** The watcher (src/core/watch.ts, plan 20261027_1430 P2): job heartbeats, failed units, detectors. */
211
+ watch: {
212
+ /** Per job: hours after which its last heartbeat is stale. Only listed jobs are expected to beat at all. */
213
+ expect: Record<string, number>;
214
+ /** Globs of the user units the watcher reports when failed. */
215
+ units: string[];
216
+ /** Per watcher run: at most this many new-incident posts; the rest fold into one "+N more" line. */
217
+ max_posts_per_run: number;
218
+ /** Minutes between watcher runs; `neurastream watch on` writes this into the timer (plan 20261027_1430 P4). */
219
+ interval_min: number;
220
+ /** Weekly report: a detector kind with at least this many incidents in the window and a dismiss rate >= noisy_ratio opens one "noisy detector" incident (plan 20261027_1430 P6). */
221
+ noisy_min: number;
222
+ /** Dismiss-rate threshold (0 < ratio <= 1) for the noisy-detector rule (plan 20261027_1430 P6). */
223
+ noisy_ratio: number;
224
+ /** Hours an open MR's pipeline may stay failed before incident "ci-red-mr" opens (plan 20261027_1430 P6b). */
225
+ ci_red_hours: number;
226
+ /** Release verdict (P11): any group but owner pain reads WORSE when its number grows by at least this percent over the before window. */
227
+ release_regress_pct: number;
228
+ /** Release verdict: fewer Main tool calls than this on either side reads "not enough data yet" — no verdict. */
229
+ release_min_calls: number;
201
230
  };
202
231
  machine: {
203
232
  load_over_cores: number;
@@ -562,6 +591,33 @@ function check(cfg: Config): void {
562
591
  if (typeof r !== "string" || r.length === 0) throw new ConfigError("knowledge.roots entries must be non-empty paths");
563
592
  }
564
593
  if (!Number.isInteger(cfg.knowledge.max_age_s) || cfg.knowledge.max_age_s < 1) throw new ConfigError("knowledge.max_age_s must be an integer >= 1");
594
+ for (const [job, hours] of Object.entries(cfg.watch.expect)) {
595
+ if (typeof hours !== "number" || !(hours > 0)) throw new ConfigError(`watch.expect.${job} must be a positive number of hours`);
596
+ }
597
+ if (!Array.isArray(cfg.watch.units) || cfg.watch.units.some(u => typeof u !== "string" || u === "")) {
598
+ throw new ConfigError("watch.units must be a list of non-empty glob strings");
599
+ }
600
+ if (!Number.isInteger(cfg.watch.max_posts_per_run) || cfg.watch.max_posts_per_run < 1) {
601
+ throw new ConfigError("watch.max_posts_per_run must be an integer >= 1");
602
+ }
603
+ if (!Number.isInteger(cfg.watch.interval_min) || cfg.watch.interval_min < 1) {
604
+ throw new ConfigError("watch.interval_min must be an integer >= 1");
605
+ }
606
+ if (!Number.isInteger(cfg.watch.noisy_min) || cfg.watch.noisy_min < 1) {
607
+ throw new ConfigError("watch.noisy_min must be an integer >= 1");
608
+ }
609
+ if (typeof cfg.watch.noisy_ratio !== "number" || !(cfg.watch.noisy_ratio > 0 && cfg.watch.noisy_ratio <= 1)) {
610
+ throw new ConfigError("watch.noisy_ratio must be a number in (0, 1]");
611
+ }
612
+ if (typeof cfg.watch.ci_red_hours !== "number" || !(cfg.watch.ci_red_hours > 0)) {
613
+ throw new ConfigError("watch.ci_red_hours must be a number > 0");
614
+ }
615
+ if (typeof cfg.watch.release_regress_pct !== "number" || !(cfg.watch.release_regress_pct > 0)) {
616
+ throw new ConfigError("watch.release_regress_pct must be a number > 0");
617
+ }
618
+ if (!Number.isInteger(cfg.watch.release_min_calls) || cfg.watch.release_min_calls < 1) {
619
+ throw new ConfigError("watch.release_min_calls must be an integer >= 1");
620
+ }
565
621
  for (const p of cfg.metrics.correction_patterns) {
566
622
  try {
567
623
  new RegExp(p, "i");
@@ -615,6 +671,12 @@ function check(cfg: Config): void {
615
671
  } catch {
616
672
  throw new ConfigError(`traces.bloat.tool_group: not a valid regex: ${cfg.traces.bloat.tool_group}`);
617
673
  }
674
+ if (!Number.isInteger(cfg.incidents.bypass_window_sec) || cfg.incidents.bypass_window_sec < 1) {
675
+ throw new ConfigError("incidents.bypass_window_sec must be an integer >= 1");
676
+ }
677
+ if (typeof cfg.incidents.bypass_similarity !== "number" || !(cfg.incidents.bypass_similarity > 0) || cfg.incidents.bypass_similarity > 1) {
678
+ throw new ConfigError("incidents.bypass_similarity must be a number in (0, 1]");
679
+ }
618
680
  for (const rule of cfg.brief.repo_rules) {
619
681
  for (const key of ["match", "require", "first", "unless"] as const) {
620
682
  const pattern = rule[key];
@@ -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
 
@@ -406,37 +408,50 @@ function staffingFile(): string {
406
408
  // The owner-message store (owner-messages.jsonl) and its matcher live in src/core/incidents.ts
407
409
  // (20261028_0900 P3): dismissIncident needs them too, and guards already imports incidents.
408
410
 
409
- /** 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. */
410
412
  function isOwnerProse(text: string): boolean {
411
- return !(text.trimStart().startsWith("main-guard:") || text.trimStart().startsWith("<system-notice>") || text.includes("<task-result"));
413
+ const t = text.trimStart();
414
+ return !(t.startsWith("main-guard:") || t.startsWith(UNANSWERED_PREFIX) || t.startsWith("<system-notice>") || text.includes("<task-result"));
412
415
  }
413
416
 
414
417
  function recordOwnerMessage(text: string, cfg: Config): void {
415
418
  if (!isOwnerProse(text)) return;
416
- const file = ownerMessagesFile();
417
419
  try {
418
- mkdirSync(q.STATE_DIR, { recursive: true });
419
- const messages = readOwnerMessages();
420
- messages.push({ at: nowSec(), text });
421
- writeFileSync(file, `${messages.slice(-50).map(m => JSON.stringify(m)).join("\n")}\n`);
420
+ writeOwnerStore([...readOwnerMessages(), { at: nowSec(), text }], readOwnerAnswers());
422
421
  } catch (err) {
423
- log(cfg.paths.guard_log, `cannot write ${file}: ${err}`);
422
+ log(cfg.paths.guard_log, `cannot write ${ownerMessagesFile()}: ${err}`);
424
423
  }
425
424
  }
426
425
 
427
- /** plan → the task names of its newest spawn (staffing.json); read for the staffed check. */
428
- export function readStaffing(): Record<string, string[]> {
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> {
429
434
  try {
430
435
  const raw: unknown = JSON.parse(readFileSync(staffingFile(), "utf8"));
431
436
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
432
- const out: Record<string, string[]> = {};
433
- for (const [k, v] of Object.entries(raw)) if (Array.isArray(v)) out[k] = v.map(String);
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
+ }
434
444
  return out;
435
445
  } catch {
436
446
  return {};
437
447
  }
438
448
  }
439
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
+
440
455
  function readSpawns(): Record<string, string> {
441
456
  try {
442
457
  const raw: unknown = JSON.parse(readFileSync(spawnsFile(), "utf8"));
@@ -464,8 +479,9 @@ export function recordSpawns(files: string[], staffing: Record<string, string[]>
464
479
  log(`${q.STATE_DIR}/../main-guard.log`, `cannot write ${spawnsFile()}: ${err}`);
465
480
  }
466
481
  if (!Object.keys(staffing).length) return;
467
- const st = readStaffing();
468
- for (const [f, names] of Object.entries(staffing)) if (names.length) st[f] = [...names];
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 };
469
485
  try {
470
486
  mkdirSync(q.STATE_DIR, { recursive: true });
471
487
  writeFileSync(staffingFile(), JSON.stringify(st, null, 1));
@@ -1661,7 +1677,7 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
1661
1677
  recordOwnerMessage(e.inject, cfg);
1662
1678
  let summary: string;
1663
1679
  try {
1664
- summary = q.queueSummary(undefined, cfg.review.agents);
1680
+ summary = q.queueSummary(undefined, cfg.review.agents, staleFiles(recheckHolds(cfg, q.activePlans())));
1665
1681
  } catch (err) {
1666
1682
  summary = `Queue unreadable (${q.INDEX}): ${err}`;
1667
1683
  }
@@ -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
+ }