neurastream 0.2.61 → 0.2.63
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -0
- package/package.json +1 -1
- package/src/adapters/omp/index.ts +36 -30
- package/src/adapters/omp/launch.ts +6 -1
- package/src/cli/commands.ts +3 -2
- package/src/cli/dispatch.ts +76 -1
- package/src/cli/init.ts +8 -0
- package/src/cli/metrics.ts +15 -55
- package/src/cli/pages.ts +10 -3
- package/src/cli/ui.ts +8 -1
- package/src/cli/watch-setup.ts +74 -0
- package/src/core/brief-lint.ts +4 -0
- package/src/core/ci.ts +271 -0
- package/src/core/config.ts +73 -1
- package/src/core/guards.ts +146 -42
- package/src/core/heartbeat.ts +79 -0
- package/src/core/incident-detectors.ts +104 -17
- package/src/core/incidents.ts +31 -4
- package/src/core/main-start.ts +83 -2
- package/src/core/metrics.ts +3 -2
- package/src/core/mr-sweep.ts +14 -7
- package/src/core/owner-ui.ts +4 -2
- package/src/core/plan-approval.ts +1 -1
- package/src/core/queue/lib.ts +85 -10
- package/src/core/queue-cancel.ts +1 -1
- package/src/core/queue-check.ts +8 -2
- package/src/core/queue-close.ts +19 -2
- package/src/core/queue-trim.ts +4 -0
- package/src/core/report.ts +88 -6
- package/src/core/rollover.ts +47 -5
- package/src/core/ui-setup.ts +5 -3
- package/src/core/waiting-check.ts +131 -0
- package/src/core/watch.ts +509 -0
- package/templates/config.yml +27 -4
- package/templates/help/watch.txt +45 -0
- package/templates/launchd/neurastream-watch.plist +17 -0
- package/templates/queue/TEMPLATE.md +5 -1
- package/templates/systemd/neurastream-watch.service +6 -0
- package/templates/systemd/neurastream-watch.timer +10 -0
package/src/core/report.ts
CHANGED
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
m3,
|
|
12
12
|
m4,
|
|
13
13
|
m5,
|
|
14
|
+
inWindow,
|
|
14
15
|
readBlocks,
|
|
15
16
|
readMetricEvents,
|
|
16
17
|
windows,
|
|
@@ -43,7 +44,8 @@ function day(t: number): string {
|
|
|
43
44
|
return new Date(t * 1000).toISOString().slice(0, 10);
|
|
44
45
|
}
|
|
45
46
|
|
|
46
|
-
|
|
47
|
+
/** One window's raw metric values: the inputs every before/after view (weekly report, release verdict) compares. */
|
|
48
|
+
export function snap(cfg: Config, source: RunSource, events: Ev[], blocks: GuardBlock[], incidents: IncidentView[], w: Window): Snap {
|
|
47
49
|
const runs = source.listRuns(w.from);
|
|
48
50
|
const patterns = cfg.metrics.correction_patterns.map((p) => new RegExp(p, "i"));
|
|
49
51
|
return {
|
|
@@ -83,12 +85,77 @@ export function m6(incidents: IncidentView[], w: Window): M6 {
|
|
|
83
85
|
.map((i) => ({ opened: i.ts, at: fixedAt(i) }))
|
|
84
86
|
.filter((x): x is { opened: number; at: number } => x.at !== null)
|
|
85
87
|
.map((x) => (x.at - x.opened) / 3600)
|
|
86
|
-
.
|
|
88
|
+
.toSorted((a, b) => a - b);
|
|
87
89
|
const mid = Math.floor(hours.length / 2);
|
|
88
90
|
const median = hours.length === 0 ? null : hours.length % 2 ? hours[mid]! : (hours[mid - 1]! + hours[mid]!) / 2;
|
|
89
91
|
return { opened: inW.length, planned: byType("plan"), dismissed: byType("dismiss"), fixed: byType("fixed"), medianHours: median };
|
|
90
92
|
}
|
|
91
93
|
|
|
94
|
+
/** Silent failures (P6): watch-source incidents opened in the window, i.e. failures the watcher found without anyone asking. */
|
|
95
|
+
export function silentFailures(incidents: IncidentView[], w: Window): number {
|
|
96
|
+
return incidents.filter((i) => i.source === "watch" && inWindow(i.ts, w)).length;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** M7 (P6): suspected false blocks in one window: D8 block-then-bypass incidents plus false-alarm events. */
|
|
100
|
+
export function m7(incidents: IncidentView[], falseAlarms: number, w: Window): number {
|
|
101
|
+
return incidents.filter((i) => i.kind === "block-then-bypass" && inWindow(i.ts, w)).length + falseAlarms;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** One kind's outcomes for incidents opened in the window; dismissRate is dismissed / opened. */
|
|
105
|
+
export interface KindStat {
|
|
106
|
+
kind: string;
|
|
107
|
+
opened: number;
|
|
108
|
+
planned: number;
|
|
109
|
+
dismissed: number;
|
|
110
|
+
dismissRate: number;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Per-kind outcomes, busiest kind first. */
|
|
114
|
+
export function kindStats(incidents: IncidentView[], w: Window): KindStat[] {
|
|
115
|
+
const byKind = new Map<string, IncidentView[]>();
|
|
116
|
+
for (const i of incidents) {
|
|
117
|
+
if (!inWindow(i.ts, w)) continue;
|
|
118
|
+
byKind.set(i.kind, [...(byKind.get(i.kind) ?? []), i]);
|
|
119
|
+
}
|
|
120
|
+
return [...byKind]
|
|
121
|
+
.map(([kind, list]): KindStat => {
|
|
122
|
+
const dismissed = list.filter((i) => i.resolution?.type === "dismiss").length;
|
|
123
|
+
return {
|
|
124
|
+
kind,
|
|
125
|
+
opened: list.length,
|
|
126
|
+
planned: list.filter((i) => i.resolution?.type === "plan").length,
|
|
127
|
+
dismissed,
|
|
128
|
+
dismissRate: dismissed / list.length,
|
|
129
|
+
};
|
|
130
|
+
})
|
|
131
|
+
.toSorted((a, b) => b.opened - a.opened || (a.kind < b.kind ? -1 : a.kind > b.kind ? 1 : 0));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** A noisy detector (P6): the finding the weekly check turns into one "noisy-detector" incident. */
|
|
135
|
+
export interface NoisyFinding {
|
|
136
|
+
kind: "noisy-detector";
|
|
137
|
+
/** The incident kind that is noisy. */
|
|
138
|
+
detector: string;
|
|
139
|
+
summary: string;
|
|
140
|
+
/** The three latest dismiss reasons, joined with "; ". */
|
|
141
|
+
evidence: string;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** A kind is noisy when this window opened at least noisy_min incidents of it and at least
|
|
145
|
+
* noisy_ratio of them were dismissed. */
|
|
146
|
+
export function noisyDetectors(incidents: IncidentView[], w: Window, t: { noisy_min: number; noisy_ratio: number }): NoisyFinding[] {
|
|
147
|
+
return kindStats(incidents, w)
|
|
148
|
+
.filter((s) => s.opened >= t.noisy_min && s.dismissRate >= t.noisy_ratio)
|
|
149
|
+
.map((s): NoisyFinding => {
|
|
150
|
+
const why = incidents
|
|
151
|
+
.filter((i) => i.kind === s.kind && inWindow(i.ts, w) && i.resolution?.type === "dismiss")
|
|
152
|
+
.toSorted((a, b) => b.ts - a.ts)
|
|
153
|
+
.slice(0, 3)
|
|
154
|
+
.map((i) => (i.resolution?.type === "dismiss" ? i.resolution.why : ""));
|
|
155
|
+
return { kind: "noisy-detector", detector: s.kind, summary: `noisy detector: ${s.kind} (${s.dismissed}/${s.opened} dismissed)`, evidence: why.join("; ") };
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
92
159
|
interface Row {
|
|
93
160
|
/** Stable metric key (m1, m2, m3, m4_corrections, m4_questions, m4_users, m5). */
|
|
94
161
|
key: string;
|
|
@@ -100,10 +167,12 @@ interface Row {
|
|
|
100
167
|
rank: boolean;
|
|
101
168
|
}
|
|
102
169
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
170
|
+
const usd = (v: number | null) => (v === null ? "n/a (0 merged)" : `$${v.toFixed(2)}`);
|
|
171
|
+
const num = (v: number | null) => (v === null ? "n/a" : String(v));
|
|
172
|
+
const mean = (v: number | null) => (v === null ? "n/a" : v.toFixed(2));
|
|
173
|
+
|
|
174
|
+
/** The report's ranked rows: the release verdict reads the same numbers the owner sees (P11). */
|
|
175
|
+
export function rowsOf(c: Snap, p: Snap): Row[] {
|
|
107
176
|
return [
|
|
108
177
|
{ key: "m1", name: "M1 cost per merge", cur: c.m1.perMerge, prev: p.m1.perMerge, fmt: usd, rank: true },
|
|
109
178
|
{ key: "m2", name: "M2 idle calls", cur: c.m2.calls, prev: p.m2.calls, fmt: num, rank: true },
|
|
@@ -170,6 +239,8 @@ export interface Report {
|
|
|
170
239
|
text: string;
|
|
171
240
|
/** The ranked row with the biggest percent increase; null when nothing ranked moved. */
|
|
172
241
|
worst: { key: string; name: string; cur: number | null; prev: number | null; change: number | null } | null;
|
|
242
|
+
/** Noisy-detector findings for this window; runWeeklyCheck opens one incident for each. */
|
|
243
|
+
noisy: NoisyFinding[];
|
|
173
244
|
}
|
|
174
245
|
|
|
175
246
|
/** Weekly provider-honesty counts the report appends; the CLI caller builds them from the
|
|
@@ -220,6 +291,14 @@ export function buildReport(cfg: Config, source: RunSource, days: number, now: n
|
|
|
220
291
|
return `| ${r.name} | ${r.fmt(r.cur)} | ${r.fmt(r.prev)} | ${signed(change(r))}${mark} |`;
|
|
221
292
|
}),
|
|
222
293
|
];
|
|
294
|
+
const falseAlarms = events.filter((e) => e.type === "false-alarm" && inWindow(Number(e.ts), cur)).length;
|
|
295
|
+
const noisy = noisyDetectors(incidents, cur, cfg.watch);
|
|
296
|
+
const quality = [
|
|
297
|
+
`Silent failures: ${silentFailures(incidents, cur)} watch incidents; suspected false blocks: ${m7(incidents, falseAlarms, cur)}`,
|
|
298
|
+
`Flaky jobs: ${events.filter((e) => e.type === "ci-flaky" && inWindow(Number(e.ts), cur)).length} same-commit red→green re-runs`,
|
|
299
|
+
"Dismiss rate by kind (opened, planned, dismissed):",
|
|
300
|
+
...kindStats(incidents, cur).map((k) => `- ${k.kind}: ${k.opened}, ${k.planned}, ${k.dismissed} (${Math.round(k.dismissRate * 100)}% dismissed)`),
|
|
301
|
+
];
|
|
223
302
|
const body = [
|
|
224
303
|
`Self-metrics: last ${days} days [${day(cur.from)} to ${day(cur.to)}) vs previous ${days} days.`,
|
|
225
304
|
"",
|
|
@@ -227,6 +306,8 @@ export function buildReport(cfg: Config, source: RunSource, days: number, now: n
|
|
|
227
306
|
"",
|
|
228
307
|
...detail(c),
|
|
229
308
|
"",
|
|
309
|
+
...quality,
|
|
310
|
+
"",
|
|
230
311
|
"Approved rules, before vs after:",
|
|
231
312
|
...ruleLines(cfg, source, events, blocks, incidents, days, now),
|
|
232
313
|
...(provider
|
|
@@ -260,5 +341,6 @@ export function buildReport(cfg: Config, source: RunSource, days: number, now: n
|
|
|
260
341
|
md,
|
|
261
342
|
text: body,
|
|
262
343
|
worst: worst ? { key: worst.key, name: worst.name, cur: worst.cur, prev: worst.prev, change: change(worst) } : null,
|
|
344
|
+
noisy,
|
|
263
345
|
};
|
|
264
346
|
}
|
package/src/core/rollover.ts
CHANGED
|
@@ -5,7 +5,9 @@
|
|
|
5
5
|
// the jobs and the note mtime, and performs the switch. No harness names here.
|
|
6
6
|
|
|
7
7
|
import { join } from "node:path";
|
|
8
|
+
import { strftime } from "./clock.ts";
|
|
8
9
|
import { stateDirPath } from "./queue/lib.ts";
|
|
10
|
+
import type { OwnerAnswer, OwnerMessage } from "./incidents.ts";
|
|
9
11
|
|
|
10
12
|
export type RolloverState = "below" | "need-note" | "wait-jobs" | "ready";
|
|
11
13
|
|
|
@@ -62,6 +64,8 @@ export interface HandoffInput {
|
|
|
62
64
|
previousSessionFile: string;
|
|
63
65
|
/** The owner's message exactly as typed; it is the last thing in the handoff. */
|
|
64
66
|
ownerMessage: string;
|
|
67
|
+
/** Owner messages no turn has ended after (P5b); the handoff starts with their block. */
|
|
68
|
+
unanswered?: readonly OwnerMessage[];
|
|
65
69
|
}
|
|
66
70
|
|
|
67
71
|
/** Prefixes of the machine-written messages: the builders write them, ownerText reads them. */
|
|
@@ -69,13 +73,50 @@ const NOTE_REQUEST_PREFIX = "Session rollover:";
|
|
|
69
73
|
const HANDOFF_PREFIX = "Previous session file:";
|
|
70
74
|
const OWNER_MARK = "Owner's message:";
|
|
71
75
|
|
|
72
|
-
/** The
|
|
76
|
+
/** The prefix both machine prompts start with while owner messages sit unanswered (P5b). */
|
|
77
|
+
export const UNANSWERED_PREFIX =
|
|
78
|
+
"UNANSWERED OWNER MESSAGES — answer these first, then end the turn so the reply reaches Discord:";
|
|
79
|
+
|
|
80
|
+
/** Owner messages no real turn end has followed: an answer record ({at, answer}, the page's lastAnswerFor shape) rides the message store, and a message with one after it is answered. */
|
|
81
|
+
export function unansweredOwnerMessages(messages: readonly OwnerMessage[], answers: readonly OwnerAnswer[]): OwnerMessage[] {
|
|
82
|
+
const answeredAt = Math.max(-1, ...answers.map(a => a.at));
|
|
83
|
+
return messages.filter(m => m.at > answeredAt);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** The unanswered block proper: the prefix line, then each message's arrival time and first 300 characters. */
|
|
87
|
+
export function unansweredPrompt(unanswered: readonly OwnerMessage[]): string {
|
|
88
|
+
return [
|
|
89
|
+
UNANSWERED_PREFIX,
|
|
90
|
+
...unanswered.map(m => {
|
|
91
|
+
const quote = m.text.replace(/\s+/g, " ").trim();
|
|
92
|
+
return `- ${strftime(m.at, "%Y-%m-%d %H:%M")}: ${quote.length > 300 ? `${quote.slice(0, 300)}…` : quote}`;
|
|
93
|
+
}),
|
|
94
|
+
].join("\n");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The one wrapper for machine prompts — the resume text may be swapped (plan 20261027_1500_limit_probe), the prefix rides either way. Unchanged when nothing is unanswered. */
|
|
98
|
+
export function withUnanswered(resume: string, messages: readonly OwnerMessage[], answers: readonly OwnerAnswer[]): string {
|
|
99
|
+
const un = unansweredOwnerMessages(messages, answers);
|
|
100
|
+
return un.length === 0 ? resume : `${unansweredPrompt(un)}\n\n${resume}`;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The first user message of the new session: header, Main's note, generated state, owner message.
|
|
105
|
+
* Every `(from: \`cmd\`)` in the note is listed under "## Numbers to re-run" right after it — re-run
|
|
106
|
+
* these before repeating any number. No numbers, no section.
|
|
107
|
+
*/
|
|
73
108
|
export function buildHandoff(p: HandoffInput): string {
|
|
109
|
+
const note = p.note.trimEnd();
|
|
110
|
+
const numbers = [...note.matchAll(/\(from: `([^`]+)`\)/g)].map((m) => m[1]);
|
|
74
111
|
return [
|
|
112
|
+
...(p.unanswered && p.unanswered.length > 0 ? [unansweredPrompt(p.unanswered), ""] : []),
|
|
75
113
|
`${HANDOFF_PREFIX} ${p.previousSessionFile}. Its full history stays there; this session continues from the handoff below.`,
|
|
76
114
|
"",
|
|
77
115
|
"## Main's handoff note (verbatim)",
|
|
78
|
-
|
|
116
|
+
note,
|
|
117
|
+
...(numbers.length > 0
|
|
118
|
+
? ["", "## Numbers to re-run", "re-run these before repeating any number", ...numbers.map((c) => `- \`${c}\``)]
|
|
119
|
+
: []),
|
|
79
120
|
"",
|
|
80
121
|
"## Generated state (main-start)",
|
|
81
122
|
p.generated.trimEnd(),
|
|
@@ -87,15 +128,16 @@ export function buildHandoff(p: HandoffInput): string {
|
|
|
87
128
|
|
|
88
129
|
/**
|
|
89
130
|
* The owner's own words in a user prompt, or undefined for a machine prompt: a guard continuation, the
|
|
90
|
-
* rollover note request, or a handoff without its owner marker. A handoff yields only its owner message
|
|
131
|
+
* rollover note request, or a handoff without its owner marker. A handoff yields only its owner message;
|
|
132
|
+
* since P5b the handoff may start with the unanswered block, which is machine text either way.
|
|
91
133
|
*/
|
|
92
134
|
export function ownerText(prompt: string): string | undefined {
|
|
93
135
|
const t = prompt.trimStart();
|
|
94
|
-
if (t.startsWith(
|
|
95
|
-
if (t.startsWith(HANDOFF_PREFIX)) {
|
|
136
|
+
if (t.startsWith(HANDOFF_PREFIX) || t.startsWith(UNANSWERED_PREFIX)) {
|
|
96
137
|
const at = prompt.lastIndexOf(OWNER_MARK);
|
|
97
138
|
return at < 0 ? undefined : prompt.slice(at + OWNER_MARK.length).trim();
|
|
98
139
|
}
|
|
140
|
+
if (t.startsWith("main-guard:") || t.startsWith(NOTE_REQUEST_PREFIX)) return undefined;
|
|
99
141
|
return prompt;
|
|
100
142
|
}
|
|
101
143
|
|
package/src/core/ui-setup.ts
CHANGED
|
@@ -127,8 +127,6 @@ export function uiOn(opts: UiOnOptions): number {
|
|
|
127
127
|
const original = existsSync(file) ? readFileSync(file, "utf8") : null;
|
|
128
128
|
const edited = editUiBlock(original, { enabled: true, owner_login: opts.login, port: opts.port ?? null });
|
|
129
129
|
if (!checkEdited(edited, home, "on", error)) return 1;
|
|
130
|
-
mkdirSync(dirname(file), { recursive: true });
|
|
131
|
-
writeFileSync(file, edited);
|
|
132
130
|
const unitPath = join(home, ".config", "systemd", "user", "neurastream-ui.service");
|
|
133
131
|
mkdirSync(dirname(unitPath), { recursive: true });
|
|
134
132
|
copyFileSync(UI_UNIT_TEMPLATE, unitPath);
|
|
@@ -140,10 +138,14 @@ export function uiOn(opts: UiOnOptions): number {
|
|
|
140
138
|
const r = runner(args);
|
|
141
139
|
if (r.status !== 0) {
|
|
142
140
|
if (r.stderr.trim()) error(r.stderr.trimEnd());
|
|
143
|
-
error("neurastream ui: systemctl failed — the config was
|
|
141
|
+
error("neurastream ui: systemctl failed — the config was not changed; fix the unit and run `neurastream ui` (or this command again).");
|
|
144
142
|
return 1;
|
|
145
143
|
}
|
|
146
144
|
}
|
|
145
|
+
// The config only turns on once the unit is up: a systemctl failure leaves the config
|
|
146
|
+
// exactly as it was (a leftover unit file is fine).
|
|
147
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
148
|
+
writeFileSync(file, edited);
|
|
147
149
|
const name = tailscale.dnsName() ?? tailscale.ip4();
|
|
148
150
|
const port = opts.port ?? cfg.ui.port;
|
|
149
151
|
if (name) print(`http://${name}:${port}`);
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// Live recheck: a `WAITING on owner:` line may carry `— still true if: `<cmd>``, the command that
|
|
2
|
+
// proves the hold is still real. Exit 0 keeps the owner card up; any other exit code hides it and
|
|
3
|
+
// opens a "stale-hold" incident naming the plan and the command; a timeout or a spawn error is
|
|
4
|
+
// "unknown" (the card stays, no incident) — a check that cannot run never counts as proof.
|
|
5
|
+
// Results are cached per (plan file mtime, command, HEAD) for queue.waiting_check_ttl_sec, so the
|
|
6
|
+
// same cheap command costs one spawn per real change, not one per turn. The runner is injected:
|
|
7
|
+
// tests never run a plan's command.
|
|
8
|
+
|
|
9
|
+
import { spawnSync } from "node:child_process";
|
|
10
|
+
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
11
|
+
import { dirname, join } from "node:path";
|
|
12
|
+
import { nowSec } from "./clock.ts";
|
|
13
|
+
import type { Config } from "./config.ts";
|
|
14
|
+
import { addIncident } from "./incidents.ts";
|
|
15
|
+
import * as q from "./queue/lib.ts";
|
|
16
|
+
|
|
17
|
+
export type HoldState = "holds" | "stale" | "unknown";
|
|
18
|
+
|
|
19
|
+
export interface HoldResult {
|
|
20
|
+
/** The plan file that carries the hold. */
|
|
21
|
+
plan: string;
|
|
22
|
+
state: HoldState;
|
|
23
|
+
/** The command's exit code; null when it did not finish (timeout, spawn error). */
|
|
24
|
+
code: number | null;
|
|
25
|
+
/** Milliseconds the command took; the original measurement for a cached result. */
|
|
26
|
+
ms: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Runs one check command in a directory. `code` null means it did not finish. */
|
|
30
|
+
export type HoldRunner = (cmd: string, cwd: string) => { code: number | null };
|
|
31
|
+
|
|
32
|
+
interface CacheRec {
|
|
33
|
+
key: string;
|
|
34
|
+
state: HoldState;
|
|
35
|
+
code: number | null;
|
|
36
|
+
ms: number;
|
|
37
|
+
at: number;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** bash -lc with the configured timeout: only whether the command still passes matters, not its output. */
|
|
41
|
+
export function spawnHoldRunner(timeoutSec: number): HoldRunner {
|
|
42
|
+
return (cmd, cwd) => {
|
|
43
|
+
const res = spawnSync("bash", ["-lc", cmd], { cwd, timeout: timeoutSec * 1000, stdio: "ignore" });
|
|
44
|
+
return { code: typeof res.status === "number" ? res.status : null };
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function gitHead(dir: string): string {
|
|
49
|
+
const res = spawnSync("git", ["rev-parse", "HEAD"], { cwd: dir, encoding: "utf8" });
|
|
50
|
+
return res.status === 0 ? res.stdout.trim() : "";
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function readCache(file: string): Record<string, CacheRec> {
|
|
54
|
+
try {
|
|
55
|
+
const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
|
|
56
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, CacheRec>) : {};
|
|
57
|
+
} catch {
|
|
58
|
+
return {};
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Runs the `still true if` command of every open, waiting plan that has one. `now` is epoch seconds
|
|
64
|
+
* (the TTL and the incident stamps are seconds); a plan whose cached key still matches and is inside
|
|
65
|
+
* queue.waiting_check_ttl_sec is returned without running the command. `fresh` skips that cache read
|
|
66
|
+
* (metrics ci re-checks after a new CI record) but still writes the result back.
|
|
67
|
+
*/
|
|
68
|
+
export function recheckHolds(
|
|
69
|
+
cfg: Config,
|
|
70
|
+
plans: q.Plan[],
|
|
71
|
+
run: HoldRunner = spawnHoldRunner(cfg.queue.waiting_check_timeout_sec),
|
|
72
|
+
now = nowSec(),
|
|
73
|
+
fresh = false,
|
|
74
|
+
): HoldResult[] {
|
|
75
|
+
const file = join(cfg.paths.queue_state, "waiting-check.json");
|
|
76
|
+
const cache = readCache(file);
|
|
77
|
+
const ttl = cfg.queue.waiting_check_ttl_sec;
|
|
78
|
+
const out: HoldResult[] = [];
|
|
79
|
+
for (const p of plans) {
|
|
80
|
+
const cmd = p.waitingCheck;
|
|
81
|
+
if (!p.waiting || p.status !== "open" || !cmd) continue;
|
|
82
|
+
const cwd = p.worktree && existsSync(p.worktree) ? p.worktree : p.repo;
|
|
83
|
+
let mtime = 0;
|
|
84
|
+
try {
|
|
85
|
+
mtime = statSync(p.file).mtimeMs;
|
|
86
|
+
} catch {}
|
|
87
|
+
const key = q.sha(`${mtime}\n${cmd}\n${gitHead(cwd)}`);
|
|
88
|
+
const hit = cache[p.file];
|
|
89
|
+
let rec = !fresh && hit && hit.key === key && now - hit.at < ttl ? hit : undefined;
|
|
90
|
+
if (!rec) {
|
|
91
|
+
const started = Date.now();
|
|
92
|
+
const code = run(cmd, cwd).code;
|
|
93
|
+
const state: HoldState = code === 0 ? "holds" : code === null ? "unknown" : "stale";
|
|
94
|
+
rec = { key, state, code, ms: Date.now() - started, at: now };
|
|
95
|
+
if (state === "stale") {
|
|
96
|
+
addIncident(
|
|
97
|
+
cfg,
|
|
98
|
+
{
|
|
99
|
+
source: "realtime",
|
|
100
|
+
kind: "stale-hold",
|
|
101
|
+
summary: `stale hold: ${p.file} — \`${cmd}\` exited ${code}`,
|
|
102
|
+
evidence: `WAITING on owner: ${p.waitingAsk ?? ""} — still true if: \`${cmd}\` (exit ${code}) ran in ${cwd}`,
|
|
103
|
+
fingerprint: q.sha(`stale-hold|${p.file}|${cmd}`),
|
|
104
|
+
},
|
|
105
|
+
now,
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
cache[p.file] = rec;
|
|
110
|
+
out.push({ plan: p.file, state: rec.state, code: rec.code, ms: rec.ms });
|
|
111
|
+
}
|
|
112
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
113
|
+
writeFileSync(file, `${JSON.stringify(cache)}\n`);
|
|
114
|
+
return out;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The plan files whose hold is stale: the queue summary and the owner page hide their owner line. */
|
|
118
|
+
export function staleFiles(holds: HoldResult[]): Set<string> {
|
|
119
|
+
return new Set(holds.filter(h => h.state === "stale").map(h => h.plan));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** One line per stale hold for queue-check and metrics ci: the ask, the check, and its exit code. */
|
|
123
|
+
export function staleHoldLines(holds: HoldResult[], plans: q.Plan[]): string[] {
|
|
124
|
+
const byFile = new Map(plans.map(p => [p.file, p]));
|
|
125
|
+
return holds
|
|
126
|
+
.filter(h => h.state === "stale")
|
|
127
|
+
.map(h => {
|
|
128
|
+
const p = byFile.get(h.plan);
|
|
129
|
+
return `STALE HOLD: ${h.plan}: ${p?.waitingAsk ?? ""} — check \`${p?.waitingCheck ?? ""}\` exited ${h.code}`;
|
|
130
|
+
});
|
|
131
|
+
}
|