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.
@@ -0,0 +1,74 @@
1
+ // `neurastream watch on|off` (plan 20261027_1430 P4): installs or removes the watcher's timer —
2
+ // a systemd user timer on Linux, a LaunchAgent on macOS — through the same Runner seam as
3
+ // `pages on|off` (src/core/pages-setup.ts). The service manager is probed first: a failed probe
4
+ // writes nothing. The period is watch.interval_min. Core stays free of service-manager calls
5
+ // (watch.ts only reports the unit files); this file is the CLI side that writes them.
6
+
7
+ import { spawnSync } from "node:child_process";
8
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
+ import { dirname, join } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ import { loadConfig } from "../core/config.ts";
13
+ import { systemRunner, type Runner, type Setup } from "../core/pages-setup.ts";
14
+ import { watchUnitPaths } from "../core/watch.ts";
15
+
16
+ const TEMPLATES = join(dirname(fileURLToPath(import.meta.url)), "../../templates");
17
+
18
+ /** launchctl: the macOS counterpart of systemRunner. */
19
+ export const launchRunner: Runner = args => {
20
+ const r = spawnSync("launchctl", args, { encoding: "utf8" });
21
+ return { status: r.status, stderr: r.stderr ?? "" };
22
+ };
23
+
24
+ export interface WatchSetup extends Setup {
25
+ /** Defaults to process.platform; tests inject it to pick the unit set. */
26
+ platform?: NodeJS.Platform;
27
+ }
28
+
29
+ export function watchOn(opts: WatchSetup = {}): number {
30
+ const home = opts.home ?? homedir(), platform = opts.platform ?? process.platform;
31
+ const runner = opts.runner ?? (platform === "darwin" ? launchRunner : systemRunner);
32
+ const probe = runner(platform === "darwin" ? ["list"] : ["--user", "show-environment"]);
33
+ if (probe.status !== 0) { console.error(probe.stderr); return 1; }
34
+ const cfg = loadConfig({ home });
35
+ const paths = watchUnitPaths(home, platform);
36
+ // Templates in the same order as watchUnitPaths returns their targets.
37
+ const templates = platform === "darwin" ? ["launchd/neurastream-watch.plist"] : ["systemd/neurastream-watch.service", "systemd/neurastream-watch.timer"];
38
+ paths.forEach((path, i) => {
39
+ const text = readFileSync(join(TEMPLATES, templates[i]!), "utf8")
40
+ .replaceAll("__INTERVAL_MIN__", String(cfg.watch.interval_min))
41
+ .replaceAll("__INTERVAL_SEC__", String(cfg.watch.interval_min * 60))
42
+ .replaceAll("__HOME__", home);
43
+ mkdirSync(dirname(path), { recursive: true });
44
+ writeFileSync(path, text);
45
+ });
46
+ if (platform === "darwin") {
47
+ // Unloading first makes a re-run with a new interval take effect; "not loaded yet" is fine.
48
+ runner(["unload", "-w", paths[0]!]);
49
+ const r = runner(["load", "-w", paths[0]!]);
50
+ if (r.status !== 0) { console.error(r.stderr); return 1; }
51
+ } else {
52
+ for (const args of [["--user", "daemon-reload"], ["--user", "enable", "--now", "neurastream-watch.timer"]]) {
53
+ const r = runner(args);
54
+ if (r.status !== 0) { console.error(r.stderr); return 1; }
55
+ }
56
+ }
57
+ console.log(`watch: on, every ${cfg.watch.interval_min} min`);
58
+ return 0;
59
+ }
60
+
61
+ export function watchOff(opts: WatchSetup = {}): number {
62
+ const home = opts.home ?? homedir(), platform = opts.platform ?? process.platform;
63
+ const runner = opts.runner ?? (platform === "darwin" ? launchRunner : systemRunner);
64
+ const paths = watchUnitPaths(home, platform);
65
+ const stop = runner(platform === "darwin" ? ["unload", "-w", paths[0]!] : ["--user", "disable", "--now", "neurastream-watch.timer"]);
66
+ if (stop.status !== 0) { console.error(stop.stderr); return 1; }
67
+ for (const path of paths) rmSync(path, { force: true });
68
+ if (platform !== "darwin") {
69
+ const reload = runner(["--user", "daemon-reload"]);
70
+ if (reload.status !== 0) { console.error(reload.stderr); return 1; }
71
+ }
72
+ console.log("watch: off");
73
+ return 0;
74
+ }
@@ -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;
@@ -214,7 +243,7 @@ export interface Config {
214
243
  quota: { reset_tz: string; reset_pattern: string; label: string };
215
244
  /** Chat notify (src/core/notify.ts): Main's final reply goes to these webhooks at session_stop.
216
245
  * The values are paths to secret files holding the webhook URLs — never the URLs themselves. */
217
- notify: { discord_webhook_file: string; slack_webhook_file: string; prefix: string };
246
+ notify: { discord_webhook_file: string; slack_webhook_file: string; prefix: string; /** Minutes a phone-page owner message may wait before the answer steer (P9; 0 = off). */ answer_within_min: number };
218
247
  /** Content redaction (src/core/secret-redact.ts, plan 20261025_2204): every tool result, every
219
248
  * notify post and `neurastream redact` go through it. Detection is by content, not file name. */
220
249
  secrets: {
@@ -496,6 +525,8 @@ function check(cfg: Config): void {
496
525
  }
497
526
  const wc = cfg.write_check;
498
527
  if (wc.applies_to !== "sub" && wc.applies_to !== "all") throw new ConfigError('write_check.applies_to must be "sub" or "all"');
528
+ if (!(Number.isFinite(cfg.notify.answer_within_min) && cfg.notify.answer_within_min >= 0))
529
+ throw new ConfigError("notify.answer_within_min must be a number >= 0 (minutes an owner message may wait; 0 = off)");
499
530
  if (!(wc.timeout_ms > 0)) throw new ConfigError("write_check.timeout_ms must be > 0");
500
531
  if (!Array.isArray(wc.linters)) throw new ConfigError("write_check.linters must be a list");
501
532
  if (!Array.isArray(wc.defer_rules) || wc.defer_rules.some((r) => typeof r !== "string" || r === ""))
@@ -562,6 +593,33 @@ function check(cfg: Config): void {
562
593
  if (typeof r !== "string" || r.length === 0) throw new ConfigError("knowledge.roots entries must be non-empty paths");
563
594
  }
564
595
  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");
596
+ for (const [job, hours] of Object.entries(cfg.watch.expect)) {
597
+ if (typeof hours !== "number" || !(hours > 0)) throw new ConfigError(`watch.expect.${job} must be a positive number of hours`);
598
+ }
599
+ if (!Array.isArray(cfg.watch.units) || cfg.watch.units.some(u => typeof u !== "string" || u === "")) {
600
+ throw new ConfigError("watch.units must be a list of non-empty glob strings");
601
+ }
602
+ if (!Number.isInteger(cfg.watch.max_posts_per_run) || cfg.watch.max_posts_per_run < 1) {
603
+ throw new ConfigError("watch.max_posts_per_run must be an integer >= 1");
604
+ }
605
+ if (!Number.isInteger(cfg.watch.interval_min) || cfg.watch.interval_min < 1) {
606
+ throw new ConfigError("watch.interval_min must be an integer >= 1");
607
+ }
608
+ if (!Number.isInteger(cfg.watch.noisy_min) || cfg.watch.noisy_min < 1) {
609
+ throw new ConfigError("watch.noisy_min must be an integer >= 1");
610
+ }
611
+ if (typeof cfg.watch.noisy_ratio !== "number" || !(cfg.watch.noisy_ratio > 0 && cfg.watch.noisy_ratio <= 1)) {
612
+ throw new ConfigError("watch.noisy_ratio must be a number in (0, 1]");
613
+ }
614
+ if (typeof cfg.watch.ci_red_hours !== "number" || !(cfg.watch.ci_red_hours > 0)) {
615
+ throw new ConfigError("watch.ci_red_hours must be a number > 0");
616
+ }
617
+ if (typeof cfg.watch.release_regress_pct !== "number" || !(cfg.watch.release_regress_pct > 0)) {
618
+ throw new ConfigError("watch.release_regress_pct must be a number > 0");
619
+ }
620
+ if (!Number.isInteger(cfg.watch.release_min_calls) || cfg.watch.release_min_calls < 1) {
621
+ throw new ConfigError("watch.release_min_calls must be an integer >= 1");
622
+ }
565
623
  for (const p of cfg.metrics.correction_patterns) {
566
624
  try {
567
625
  new RegExp(p, "i");
@@ -615,6 +673,12 @@ function check(cfg: Config): void {
615
673
  } catch {
616
674
  throw new ConfigError(`traces.bloat.tool_group: not a valid regex: ${cfg.traces.bloat.tool_group}`);
617
675
  }
676
+ if (!Number.isInteger(cfg.incidents.bypass_window_sec) || cfg.incidents.bypass_window_sec < 1) {
677
+ throw new ConfigError("incidents.bypass_window_sec must be an integer >= 1");
678
+ }
679
+ if (typeof cfg.incidents.bypass_similarity !== "number" || !(cfg.incidents.bypass_similarity > 0) || cfg.incidents.bypass_similarity > 1) {
680
+ throw new ConfigError("incidents.bypass_similarity must be a number in (0, 1]");
681
+ }
618
682
  for (const rule of cfg.brief.repo_rules) {
619
683
  for (const key of ["match", "require", "first", "unless"] as const) {
620
684
  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));
@@ -1059,12 +1075,33 @@ function runsCloser(input: Record<string, unknown>): boolean {
1059
1075
 
1060
1076
  const bin = (w: string | undefined) => (w ?? "").replace(/^["']+|["']+$/g, "").split("/").pop() ?? "";
1061
1077
 
1078
+ // P5g (plan 20261027_0915): the shell text a call would really run — bash's command line, eval's
1079
+ // !cmd shell-escape lines and the Bun.$/spawn arguments inside its code. Everything else in an
1080
+ // input is prose or string data (a task brief, plan text, an eval cell that only names the page's
1081
+ // words), and prose runs nothing.
1082
+ function shellText(input: Record<string, unknown>): string {
1083
+ if (typeof input.command === "string") return input.command;
1084
+ const code = input.code;
1085
+ if (typeof code !== "string") return "";
1086
+ const out: string[] = [];
1087
+ for (const m of code.matchAll(/^[ \t]*!(.+)$/gm)) out.push(m[1] ?? "");
1088
+ for (const m of code.matchAll(/(?<!\w)(?:Bun\.)?\$[ \t]*`((?:[^`\\]|\\.)*)`/g)) out.push(m[1] ?? "");
1089
+ for (const m of code.matchAll(/\b(?:Bun\.)?spawn(?:Sync)?[ \t]*\(([^)]*)/g))
1090
+ out.push(
1091
+ [...(m[1] ?? "").matchAll(/[`"']([^`"']*)[`"']/g)]
1092
+ .map(s => s[1] ?? "")
1093
+ .join(" "),
1094
+ );
1095
+ return out.join("\n");
1096
+ }
1097
+
1062
1098
  // True when a command segment starts the owner page (plan 20261024_2230 P3c): `neurastream ui`
1063
1099
  // serves it and `systemctl --user start/restart/enable` of neurastream-ui relaunches it — the
1064
- // owner's systemd moves, never an agent's, unlocked or not. Segment splitting and launcher
1065
- // skipping match runsCloser, so `sh -c "neurastream ui"` and `sudo systemctl --user ...` are seen.
1100
+ // owner's systemd moves, never an agent's, unlocked or not. P5g: the text is shellText's — only
1101
+ // real shell commands, never prose. Segment splitting and launcher skipping match runsCloser, so
1102
+ // `sh -c "neurastream ui"` and `sudo systemctl --user ...` are seen.
1066
1103
  function startsOwnerUi(input: Record<string, unknown>): boolean {
1067
- const text = Object.values(input).filter((v): v is string => typeof v === "string").join("\n");
1104
+ const text = shellText(input);
1068
1105
  return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
1069
1106
  const words = seg.trim().split(/\s+/).filter(Boolean).map(w => w.replace(/^["'(]+|["')]+$/g, ""));
1070
1107
  let i = 0;
@@ -1123,6 +1160,17 @@ function addedText(input: Record<string, unknown>): string {
1123
1160
  .join("\n");
1124
1161
  }
1125
1162
 
1163
+ // P5g: tools whose string fields are content — a task brief, the text a write or edit adds — are
1164
+ // prose, never reads; the notify-secret check scans only their path argument.
1165
+ const PROSE_TOOLS: Record<string, true> = { task: true, write: true, edit: true, ast_edit: true };
1166
+
1167
+ // Only a tool call's path arguments — the paths it names as targets, not its prose fields.
1168
+ function pathArgs(input: Record<string, unknown>): Record<string, unknown> {
1169
+ const out: Record<string, unknown> = {};
1170
+ for (const key of ["path", "file"]) if (typeof input[key] === "string") out[key] = input[key];
1171
+ return out;
1172
+ }
1173
+
1126
1174
  // Subagent half of a tool call (the original plan-guard checkCall without the main return).
1127
1175
  // `cap` is the sub's hard call cap: its recorded per-spawn budget, else the global sub_max_calls.
1128
1176
  function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[], writes: string[], cfg: Config, cap: number): string | null {
@@ -1422,8 +1470,14 @@ export function checkTool(e: ToolEvent, cfg: Config): Decision {
1422
1470
  }
1423
1471
  // Notify secrets: no agent, main or sub, reads a webhook URL — with or without the unlock.
1424
1472
  // A call that changes a secret is not a read: its target goes through the protected-write
1425
- // rule above, so the owner's unlock covers it like any guard file.
1426
- const secretHit = notifySecretReadHit(paths.filter(p => !writes.includes(p)), cfg);
1473
+ // rule above, so the owner's unlock covers it like any guard file. P5g: the scan reads real
1474
+ // read targets only — naming a secret-shaped glob in a task brief or in plan text is prose,
1475
+ // not a read — so prose tools (task, write/edit) scan just their path argument, while every
1476
+ // other tool keeps the whole-input scan (glob/grep patterns arrive through it).
1477
+ const secretPaths: string[] = [];
1478
+ for (const p of [...(e.paths ?? []), ...q.touchedPaths(e.tool, PROSE_TOOLS[e.tool] === true ? pathArgs(input) : input, e.cwd)])
1479
+ if (!secretPaths.includes(p)) secretPaths.push(p);
1480
+ const secretHit = notifySecretReadHit(secretPaths.filter(p => !writes.includes(p)), cfg);
1427
1481
  if (secretHit) {
1428
1482
  log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} notify secret: ${secretHit}`);
1429
1483
  return deny(`plan-guard: ${secretHit} is a notify secret path. Only the owner touches the webhook files, in a terminal.`);
@@ -1661,7 +1715,7 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
1661
1715
  recordOwnerMessage(e.inject, cfg);
1662
1716
  let summary: string;
1663
1717
  try {
1664
- summary = q.queueSummary(undefined, cfg.review.agents);
1718
+ summary = q.queueSummary(undefined, cfg.review.agents, staleFiles(recheckHolds(cfg, q.activePlans())));
1665
1719
  } catch (err) {
1666
1720
  summary = `Queue unreadable (${q.INDEX}): ${err}`;
1667
1721
  }