reevesagents 2.1.0 → 2.2.1

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,1246 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ FLOW_ID_PATTERN,
4
+ FLOW_LOG_LIMIT,
5
+ FlowStateError,
6
+ RUN_SESSION_PATTERN,
7
+ VIEWER_SESSION_PATTERN,
8
+ appendLog,
9
+ emitNotification,
10
+ findAgent,
11
+ flowPath,
12
+ flowsDir,
13
+ killAgent,
14
+ killSession,
15
+ listAgents,
16
+ listFlowFiles,
17
+ listRuns,
18
+ loadConfig,
19
+ logDiagnostic,
20
+ moveItemByEngine,
21
+ mutatePlan,
22
+ nowIso,
23
+ nowMs,
24
+ planExists,
25
+ readFlow,
26
+ readPlan,
27
+ readRun,
28
+ redactSecrets,
29
+ runDir,
30
+ saveFlow,
31
+ sessionAttached,
32
+ sessionInGroup,
33
+ shortHomePath,
34
+ stateRoot,
35
+ tmuxAvailable,
36
+ tryAllWindowIds,
37
+ tryListSessions,
38
+ tryTargetExists,
39
+ withRunsLock
40
+ } from "./chunk-CJKEBBUI.js";
41
+
42
+ // src/version.ts
43
+ import { readFileSync } from "fs";
44
+ import { URL } from "url";
45
+ function readVersion() {
46
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
47
+ if (typeof pkg.version !== "string") throw new Error("package.json version must be a string");
48
+ return pkg.version;
49
+ }
50
+ var REEVESAGENTS_VERSION = readVersion();
51
+
52
+ // src/core/reaper.ts
53
+ function sweepAgents(options = {}) {
54
+ const haveTmux = options.targetExists ? true : (options.tmuxAvailable ?? tmuxAvailable)();
55
+ if (!haveTmux) return { reaped: [] };
56
+ const targetExists = options.targetExists ?? tryTargetExists;
57
+ const now = options.now ?? nowMs;
58
+ const maxLifetimeMs = options.maxLifetimeMs ?? loadConfig().global.max_lifetime_ms;
59
+ const candidates = listAgents().filter((agent) => !agent.ended_at && !agent.headless);
60
+ const needsBatch = candidates.some((agent) => agent.tmux_window_id) && (options.targetExists === void 0 || options.windowIds !== void 0);
61
+ const batchWindows = needsBatch ? (options.windowIds ?? tryAllWindowIds)() : null;
62
+ if (needsBatch && batchWindows === null) {
63
+ logDiagnostic("sweep-agents-skipped", {
64
+ reason: "tmux-enumeration-failed",
65
+ candidates: candidates.length
66
+ });
67
+ return { reaped: [] };
68
+ }
69
+ const probe = batchWindows ? (id, session) => batchWindows.has(`${session}\0${id}`) || targetExists(id, session) : targetExists;
70
+ const reaped = [];
71
+ for (const agent of candidates) {
72
+ const ageMs = now() - new Date(agent.started_at).getTime();
73
+ let reason = null;
74
+ if (agent.tmux_window_id) {
75
+ const exists = probe(agent.tmux_window_id, agent.tmux_session);
76
+ if (exists === null) {
77
+ logDiagnostic("sweep-agent-skipped", {
78
+ reason: "tmux-target-probe-failed",
79
+ run_id: agent.run_id,
80
+ agent_id: agent.id,
81
+ session: agent.tmux_session,
82
+ target: agent.tmux_window_id
83
+ });
84
+ continue;
85
+ }
86
+ if (!exists) reason = "window-gone";
87
+ }
88
+ if (!reason && maxLifetimeMs > 0 && ageMs > maxLifetimeMs) {
89
+ reason = "lifetime-exceeded";
90
+ }
91
+ if (!reason) continue;
92
+ try {
93
+ killAgent(agent.id, options.driver ? { driver: options.driver } : {});
94
+ reaped.push({
95
+ agent_id: agent.id,
96
+ run_id: agent.run_id,
97
+ nickname: agent.nickname,
98
+ reason,
99
+ age_ms: Math.max(0, Math.round(ageMs))
100
+ });
101
+ } catch {
102
+ }
103
+ }
104
+ if (reaped.length > 0) {
105
+ logDiagnostic("agents-reaped", {
106
+ count: reaped.length,
107
+ agents: reaped.map((item) => `${item.nickname}:${item.reason}`)
108
+ });
109
+ }
110
+ return { reaped };
111
+ }
112
+ var ORPHAN_MIN_AGE_SEC = 60;
113
+ function isReevesOwnedName(name) {
114
+ return RUN_SESSION_PATTERN.test(name) || VIEWER_SESSION_PATTERN.test(name);
115
+ }
116
+ function sweepOrphanSessions(options = {}) {
117
+ const haveTmux = options.listSessions ? true : (options.tmuxAvailable ?? tmuxAvailable)();
118
+ if (!haveTmux) return { killed: [] };
119
+ const sessions = (options.listSessions ?? tryListSessions)();
120
+ if (sessions === null) {
121
+ logDiagnostic("orphan-sweep-skipped", { reason: "tmux-enumeration-failed" });
122
+ return { killed: [] };
123
+ }
124
+ const killSession2 = options.killSession ?? killSession;
125
+ const sessionAttached2 = options.sessionAttached ?? sessionAttached;
126
+ const nowSec = (options.now ?? nowMs)() / 1e3;
127
+ const runs = (options.runs ?? listRuns)();
128
+ const liveRunSessions = new Set(runs.map((run) => run.tmux_session));
129
+ if (runs.length === 0 && sessions.some((session) => isReevesOwnedName(session.name))) {
130
+ return { killed: [], skipped: "foreign-registry" };
131
+ }
132
+ const killed = [];
133
+ for (const info of sessions) {
134
+ if (info.attached) continue;
135
+ if (!options.ignoreGrace && info.createdSec > 0 && nowSec - info.createdSec < ORPHAN_MIN_AGE_SEC) continue;
136
+ let orphan = false;
137
+ if (RUN_SESSION_PATTERN.test(info.name)) {
138
+ orphan = !liveRunSessions.has(info.name);
139
+ } else if (VIEWER_SESSION_PATTERN.test(info.name)) {
140
+ orphan = ![...liveRunSessions].some((s) => sessionInGroup(info, s));
141
+ }
142
+ if (!orphan) continue;
143
+ if (sessionAttached2(info.name)) continue;
144
+ try {
145
+ killSession2(info.name);
146
+ killed.push(info.name);
147
+ } catch {
148
+ }
149
+ }
150
+ if (killed.length > 0) {
151
+ logDiagnostic("orphan-sessions-killed", { sessions: killed });
152
+ }
153
+ return { killed };
154
+ }
155
+ var lastOrphanSweepAt = 0;
156
+ function sweepOrphanSessionsThrottled(minIntervalMs = 15e3, options = {}) {
157
+ const now = nowMs();
158
+ if (lastOrphanSweepAt !== 0 && now - lastOrphanSweepAt < minIntervalMs) return { killed: [], swept: false };
159
+ lastOrphanSweepAt = now;
160
+ return { ...sweepOrphanSessions(options), swept: true };
161
+ }
162
+ var lastSweepAt = 0;
163
+ function sweepAgentsThrottled(minIntervalMs = 15e3, options = {}) {
164
+ const now = (options.now ?? nowMs)();
165
+ if (lastSweepAt !== 0 && now - lastSweepAt < minIntervalMs) return { reaped: [], swept: false };
166
+ lastSweepAt = now;
167
+ return { ...sweepAgents(options), swept: true };
168
+ }
169
+
170
+ // src/core/approvals.ts
171
+ import { unlinkSync } from "fs";
172
+ import {
173
+ chmodSync,
174
+ mkdirSync,
175
+ readdirSync,
176
+ readFileSync as readFileSync2,
177
+ renameSync,
178
+ writeFileSync
179
+ } from "fs";
180
+ import { randomUUID } from "crypto";
181
+
182
+ // src/core/flow-escalation.ts
183
+ var FLOW_ESCALATION_ACTION = "flow_escalation";
184
+ function applyEscalationDecision(approval, note = "") {
185
+ if (approval.action !== FLOW_ESCALATION_ACTION) return null;
186
+ const runId = typeof approval.details?.run_id === "string" ? approval.details.run_id : approval.run_id;
187
+ const itemId = typeof approval.details?.item_id === "string" ? approval.details.item_id : null;
188
+ const reason = typeof approval.details?.reason === "string" ? approval.details.reason : "escalated";
189
+ const episode = typeof approval.details?.episode === "number" ? approval.details.episode : null;
190
+ const outcome = withRunsLock(() => {
191
+ const state = readFlow(runId);
192
+ if (state.state !== "escalated" || episode !== null && state.notify_episode !== episode) {
193
+ return { run_id: runId, decision: "approved", flow_state: state.state, item_id: null };
194
+ }
195
+ if (approval.status === "approved") {
196
+ const resumed = {
197
+ ...state,
198
+ state: "idle",
199
+ rounds: 0,
200
+ claim: { ...state.claim, verdict: null, verdict_count: state.claim.verdict_count },
201
+ review_started_at: null,
202
+ log: [
203
+ ...state.log,
204
+ { at: (/* @__PURE__ */ new Date()).toISOString(), event: "escalation_approved", detail: `${reason}${note ? ` \xB7 ${note}` : ""}` }
205
+ ].slice(-50)
206
+ };
207
+ saveFlow(resumed, { root: void 0 });
208
+ return { run_id: runId, decision: "approved", flow_state: resumed.state, item_id: itemId };
209
+ }
210
+ const closed = {
211
+ ...state,
212
+ state: "done",
213
+ review_started_at: null,
214
+ close_reason: `escalation denied: ${reason}${note ? ` \xB7 ${note}` : ""}`,
215
+ log: [
216
+ ...state.log,
217
+ { at: (/* @__PURE__ */ new Date()).toISOString(), event: "escalation_denied", detail: closedDetail(reason, note) }
218
+ ].slice(-50)
219
+ };
220
+ saveFlow(closed, { root: void 0 });
221
+ return { run_id: runId, decision: "denied", flow_state: closed.state, item_id: itemId };
222
+ });
223
+ if (itemId && planExists(runId)) {
224
+ try {
225
+ mutatePlan(runId, (current) => {
226
+ if (!current) return { plan: null, value: null };
227
+ if (outcome.decision === "approved") {
228
+ return { plan: moveItemByEngine(current, { id: itemId, status: "queued", now: Date.now() }), value: null };
229
+ }
230
+ const requeued = moveItemByEngine(current, { id: itemId, status: "queued", now: Date.now() });
231
+ return { plan: moveItemByEngine(requeued, { id: itemId, status: "skipped", block_reason: "escalation_denied", now: Date.now() }), value: null };
232
+ });
233
+ } catch {
234
+ }
235
+ }
236
+ return outcome;
237
+ }
238
+ function closedDetail(reason, note) {
239
+ return `escalation denied: ${reason}${note ? ` \xB7 ${note}` : ""}`;
240
+ }
241
+
242
+ // src/core/approvals.ts
243
+ import { dirname, join } from "path";
244
+ function runApprovalsDir(runId) {
245
+ return join(runDir(runId), "approvals");
246
+ }
247
+ function runApprovalPath(runId, approvalId) {
248
+ return join(runApprovalsDir(runId), `${approvalId}.json`);
249
+ }
250
+ function atomicWriteJson(path, data) {
251
+ mkdirSync(dirname(path), { recursive: true });
252
+ const tmpPath = `${path}.tmp`;
253
+ writeFileSync(tmpPath, JSON.stringify(data, null, 2), "utf-8");
254
+ chmodSync(tmpPath, 384);
255
+ renameSync(tmpPath, path);
256
+ }
257
+ function asString(value, fallback = "") {
258
+ return typeof value === "string" ? value : fallback;
259
+ }
260
+ function asNullableString(value) {
261
+ return typeof value === "string" ? value : null;
262
+ }
263
+ function normalizeApprovalStatus(value) {
264
+ if (value === "pending" || value === "approved" || value === "denied" || value === "expired") return value;
265
+ return "pending";
266
+ }
267
+ function normalizeRisk(value) {
268
+ if (value === "low" || value === "medium" || value === "high") return value;
269
+ return "medium";
270
+ }
271
+ function redactValue(value) {
272
+ if (typeof value === "string") return redactSecrets(value);
273
+ if (Array.isArray(value)) return value.map(redactValue);
274
+ if (typeof value === "object" && value !== null) {
275
+ return Object.fromEntries(
276
+ Object.entries(value).map(([key, item]) => [key, redactValue(item)])
277
+ );
278
+ }
279
+ return value;
280
+ }
281
+ function normalizeApproval(raw) {
282
+ return {
283
+ id: asString(raw.id),
284
+ run_id: asString(raw.run_id),
285
+ agent_id: asString(raw.agent_id),
286
+ action: asString(raw.action),
287
+ summary: asString(raw.summary),
288
+ details: typeof raw.details === "object" && raw.details !== null ? raw.details : {},
289
+ risk: normalizeRisk(raw.risk),
290
+ status: normalizeApprovalStatus(raw.status),
291
+ decision_note: asString(raw.decision_note),
292
+ requested_at: asString(raw.requested_at, nowIso()),
293
+ resolved_at: asNullableString(raw.resolved_at)
294
+ };
295
+ }
296
+ function redactApproval(approval) {
297
+ return {
298
+ ...approval,
299
+ action: redactSecrets(approval.action),
300
+ summary: redactSecrets(approval.summary),
301
+ details: redactValue(approval.details),
302
+ decision_note: redactSecrets(approval.decision_note)
303
+ };
304
+ }
305
+ function writeApprovalUnlocked(approval) {
306
+ const path = runApprovalPath(approval.run_id, approval.id);
307
+ atomicWriteJson(path, redactApproval(approval));
308
+ return path;
309
+ }
310
+ function readApprovalUnlocked(runId, approvalId) {
311
+ try {
312
+ return normalizeApproval(JSON.parse(readFileSync2(runApprovalPath(runId, approvalId), "utf-8")));
313
+ } catch {
314
+ throw new Error(`Approval not found: ${approvalId}`);
315
+ }
316
+ }
317
+ function runNameOf(runId) {
318
+ try {
319
+ const run = listRuns().find((entry) => entry.id === runId);
320
+ return run?.name.slice(0, 80) ?? "";
321
+ } catch {
322
+ return "";
323
+ }
324
+ }
325
+ function projectOf(dir) {
326
+ const parts = dir.split(/[\\/]+/).filter(Boolean);
327
+ return parts.length > 0 ? parts[parts.length - 1].slice(0, 64) : "";
328
+ }
329
+ function createRunApproval(input) {
330
+ return withRunsLock(() => {
331
+ const agent = findAgent(input.agent_id);
332
+ const approval = {
333
+ id: randomUUID(),
334
+ run_id: agent.run_id,
335
+ agent_id: agent.id,
336
+ action: input.action,
337
+ summary: input.summary,
338
+ details: input.details ?? {},
339
+ risk: input.risk ?? "medium",
340
+ status: "pending",
341
+ decision_note: "",
342
+ requested_at: nowIso(),
343
+ resolved_at: null
344
+ };
345
+ writeApprovalUnlocked(approval);
346
+ emitNotification({
347
+ kind: "agent.needs_human",
348
+ title: `approval needed: ${agent.nickname}`,
349
+ detail: approval.summary,
350
+ run_id: agent.run_id,
351
+ run_name: runNameOf(agent.run_id),
352
+ project: projectOf(agent.working_dir),
353
+ agent_id: agent.id,
354
+ agent_nickname: agent.nickname,
355
+ source: "product"
356
+ });
357
+ return redactApproval(approval);
358
+ });
359
+ }
360
+ function readRunApproval(runId, approvalId) {
361
+ return readApprovalUnlocked(runId, approvalId);
362
+ }
363
+ function listRunApprovals(runId, status) {
364
+ const runIds = runId ? [runId] : listRuns().map((run) => run.id);
365
+ const approvals = [];
366
+ for (const id of runIds) {
367
+ let files;
368
+ try {
369
+ files = readdirSync(runApprovalsDir(id));
370
+ } catch {
371
+ continue;
372
+ }
373
+ for (const file of files) {
374
+ if (!file.endsWith(".json")) continue;
375
+ try {
376
+ approvals.push(readApprovalUnlocked(id, file.slice(0, -5)));
377
+ } catch {
378
+ }
379
+ }
380
+ }
381
+ return approvals.filter((approval) => !status || approval.status === status).sort((a, b) => new Date(b.requested_at).getTime() - new Date(a.requested_at).getTime());
382
+ }
383
+ function resolveRunApproval(approvalId, decision, note = "") {
384
+ const { approval: resolved, transitioned } = resolveRunApprovalUnlocked(approvalId, decision, note);
385
+ if (transitioned) applyEscalationDecision(resolved, note);
386
+ return resolved;
387
+ }
388
+ function resolveRunApprovalUnlocked(approvalId, decision, note) {
389
+ return withRunsLock(() => {
390
+ const approval = listRunApprovals().find((item) => item.id === approvalId);
391
+ if (!approval) throw new Error(`Approval not found: ${approvalId}`);
392
+ if (approval.status !== "pending") return { approval, transitioned: false };
393
+ const updated = {
394
+ ...approval,
395
+ status: decision,
396
+ decision_note: note,
397
+ resolved_at: nowIso()
398
+ };
399
+ writeApprovalUnlocked(updated);
400
+ return { approval: redactApproval(updated), transitioned: true };
401
+ });
402
+ }
403
+
404
+ // src/core/tick-status.ts
405
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync as renameSync2, writeFileSync as writeFileSync2 } from "fs";
406
+ import { dirname as dirname2, join as join2 } from "path";
407
+ import { execFileSync } from "child_process";
408
+ function tickStatusPath(root = stateRoot()) {
409
+ return join2(root, "tick-status.json");
410
+ }
411
+ function tickDriver(env = process.env) {
412
+ const named = env.REEVES_TICK_DRIVER?.trim();
413
+ return named ? named : "external";
414
+ }
415
+ function writeTickStatus(mode, counts, options = {}) {
416
+ const status = {
417
+ at: options.at ?? (/* @__PURE__ */ new Date()).toISOString(),
418
+ mode,
419
+ driver: options.driver ?? tickDriver(),
420
+ pid: options.pid ?? process.pid,
421
+ advanced: counts.advanced,
422
+ held: counts.held,
423
+ skipped: counts.skipped
424
+ };
425
+ try {
426
+ const path = tickStatusPath(options.root);
427
+ mkdirSync2(dirname2(path), { recursive: true });
428
+ const text = JSON.stringify(status, null, 2);
429
+ const tmp = `${path}.tmp`;
430
+ writeFileSync2(tmp, text, "utf-8");
431
+ try {
432
+ renameSync2(tmp, path);
433
+ } catch {
434
+ writeFileSync2(path, text, "utf-8");
435
+ }
436
+ return status;
437
+ } catch {
438
+ return null;
439
+ }
440
+ }
441
+ function count(value) {
442
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
443
+ }
444
+ function readTickStatus(root = stateRoot()) {
445
+ try {
446
+ const raw = JSON.parse(readFileSync3(tickStatusPath(root), "utf-8"));
447
+ if (typeof raw !== "object" || raw === null) return null;
448
+ const record = raw;
449
+ const at = typeof record.at === "string" ? record.at : "";
450
+ if (!at || Number.isNaN(Date.parse(at))) return null;
451
+ return {
452
+ at,
453
+ mode: record.mode === "run" ? "run" : "all",
454
+ driver: typeof record.driver === "string" && record.driver.trim() ? record.driver.trim() : "external",
455
+ pid: count(record.pid),
456
+ advanced: count(record.advanced),
457
+ held: count(record.held),
458
+ skipped: count(record.skipped)
459
+ };
460
+ } catch {
461
+ return null;
462
+ }
463
+ }
464
+ function tickAgeSeconds(status, now = Date.now()) {
465
+ const at = Date.parse(status.at);
466
+ return Number.isNaN(at) ? 0 : Math.max(0, Math.round((now - at) / 1e3));
467
+ }
468
+ function tickStateText(status, now = Date.now()) {
469
+ if (!status) return "none recorded \u2014 `flow tick --all` or install reeves-flow-tick.timer";
470
+ return `last ${tickAgeSeconds(status, now)}s ago \xB7 driver ${status.driver}`;
471
+ }
472
+ function systemctlRun(command, args) {
473
+ return String(execFileSync(command, args, {
474
+ encoding: "utf-8",
475
+ stdio: ["ignore", "pipe", "ignore"],
476
+ timeout: 1500,
477
+ windowsHide: true
478
+ }));
479
+ }
480
+ function parseSystemdTimestamp(raw) {
481
+ const text = raw.trim();
482
+ if (!text || text === "n/a") return null;
483
+ if (/^\d+$/.test(text)) {
484
+ const micros = Number(text);
485
+ return Number.isFinite(micros) ? micros / 1e3 : null;
486
+ }
487
+ const match = /^(?:[A-Za-z]{3,9},?\s+)?(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?\s*([A-Za-z]{1,5}|[+-]\d{2}:?\d{2})?$/.exec(text);
488
+ if (!match) return null;
489
+ const [, year, month, day, hour, minute, second, fraction, zone] = match;
490
+ const millis = fraction ? Number(fraction.padEnd(3, "0").slice(0, 3)) : 0;
491
+ const parts = [Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute), Number(second), millis];
492
+ let stamp;
493
+ if (zone !== void 0 && /^(?:utc|gmt|ut|z)$/i.test(zone)) {
494
+ stamp = Date.UTC(...parts);
495
+ } else {
496
+ const offset = zone === void 0 ? null : /^([+-])(\d{2}):?(\d{2})$/.exec(zone);
497
+ if (offset) {
498
+ const minutes = (Number(offset[2]) * 60 + Number(offset[3])) * (offset[1] === "-" ? -1 : 1);
499
+ stamp = Date.UTC(...parts) - minutes * 6e4;
500
+ } else {
501
+ stamp = new Date(...parts).getTime();
502
+ }
503
+ }
504
+ return Number.isNaN(stamp) ? null : stamp;
505
+ }
506
+ var TIMESPAN_UNITS = {
507
+ month: 2629800,
508
+ months: 2629800,
509
+ mo: 2629800,
510
+ week: 604800,
511
+ weeks: 604800,
512
+ w: 604800,
513
+ wk: 604800,
514
+ day: 86400,
515
+ days: 86400,
516
+ d: 86400,
517
+ hour: 3600,
518
+ hours: 3600,
519
+ hr: 3600,
520
+ h: 3600,
521
+ minute: 60,
522
+ minutes: 60,
523
+ min: 60,
524
+ second: 1,
525
+ seconds: 1,
526
+ sec: 1,
527
+ s: 1,
528
+ ms: 1e-3,
529
+ msec: 1e-3,
530
+ us: 1e-6,
531
+ usec: 1e-6,
532
+ "\xB5s": 1e-6
533
+ };
534
+ function parseSystemdTimespan(raw) {
535
+ const text = raw.trim();
536
+ if (!text || text === "n/a" || text === "infinity") return null;
537
+ let total = 0;
538
+ for (const token of text.split(/\s+/)) {
539
+ const match = /^(\d+(?:\.\d+)?)([a-zµ]+)$/i.exec(token);
540
+ if (!match) return null;
541
+ const scale = TIMESPAN_UNITS[match[2].toLowerCase()];
542
+ if (scale === void 0) return null;
543
+ total += Number(match[1]) * scale;
544
+ }
545
+ return total;
546
+ }
547
+ function monotonicSeconds() {
548
+ try {
549
+ const first = readFileSync3("/proc/uptime", "utf-8").trim().split(/\s+/)[0];
550
+ const seconds = Number(first);
551
+ return Number.isFinite(seconds) ? seconds : null;
552
+ } catch {
553
+ return null;
554
+ }
555
+ }
556
+ function systemdTimerState(options = {}) {
557
+ const now = options.now ?? Date.now();
558
+ let text;
559
+ try {
560
+ text = (options.run ?? systemctlRun)("systemctl", [
561
+ "--user",
562
+ "show",
563
+ "reeves-flow-tick.timer",
564
+ "-p",
565
+ "ActiveState",
566
+ "-p",
567
+ "NextElapseUSecRealtime",
568
+ "-p",
569
+ "NextElapseUSecMonotonic"
570
+ ]);
571
+ } catch {
572
+ return null;
573
+ }
574
+ const fields = /* @__PURE__ */ new Map();
575
+ for (const line of text.split("\n")) {
576
+ const index = line.indexOf("=");
577
+ if (index <= 0) continue;
578
+ fields.set(line.slice(0, index).trim(), line.slice(index + 1).trim());
579
+ }
580
+ const activeState = fields.get("ActiveState");
581
+ if (!activeState) return null;
582
+ const state = { active: activeState === "active" };
583
+ const realtime = parseSystemdTimestamp(fields.get("NextElapseUSecRealtime") ?? "");
584
+ if (realtime !== null) {
585
+ state.next_at = realtime;
586
+ return state;
587
+ }
588
+ const elapse = parseSystemdTimespan(fields.get("NextElapseUSecMonotonic") ?? "");
589
+ if (elapse !== null) {
590
+ const current = (options.monotonicNow ?? monotonicSeconds)();
591
+ if (current !== null) state.next_at = now + Math.round((elapse - current) * 1e3);
592
+ }
593
+ return state;
594
+ }
595
+
596
+ // src/core/flow-incidents.ts
597
+ import { randomUUID as randomUUID2 } from "crypto";
598
+ import { chmodSync as chmodSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync4, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "fs";
599
+ import { join as join3 } from "path";
600
+ var DEFAULT_INCIDENT_ACK_TIMEOUT_MS = 10 * 6e4;
601
+ var DEFAULT_PANE_UNKNOWN_GRACE_MS = 12e4;
602
+ function incidentPath(runId, root) {
603
+ if (!FLOW_ID_PATTERN.test(runId)) throw new Error(`not a valid flow id: ${runId}`);
604
+ return join3(flowsDir(root), runId, "incidents.json");
605
+ }
606
+ function emptyStore(runId) {
607
+ return { schema_version: 1, run_id: runId, incidents: [], watches: {} };
608
+ }
609
+ function normalizeIncident(raw, runId) {
610
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
611
+ const row = raw;
612
+ if (typeof row.id !== "string" || typeof row.kind !== "string") return null;
613
+ const evidence = typeof row.evidence === "object" && row.evidence !== null ? row.evidence : {};
614
+ const lastLog = typeof evidence.last_log === "object" && evidence.last_log !== null ? evidence.last_log : null;
615
+ const severity = row.severity === "blocker" || row.severity === "warn" ? row.severity : "info";
616
+ const status = row.status === "acked" || row.status === "resolved" ? row.status : "open";
617
+ const owner = row.owner === "human" ? "human" : "orchestrator";
618
+ return {
619
+ id: row.id,
620
+ run_id: runId,
621
+ spec_id: typeof row.spec_id === "string" ? row.spec_id : null,
622
+ kind: row.kind,
623
+ severity,
624
+ evidence: {
625
+ state: typeof evidence.state === "string" ? evidence.state : "",
626
+ head: typeof evidence.head === "string" ? evidence.head : "",
627
+ dev_pane: typeof evidence.dev_pane === "string" ? evidence.dev_pane : "unknown",
628
+ review_pane: typeof evidence.review_pane === "string" ? evidence.review_pane : "unknown",
629
+ tree_clean: typeof evidence.tree_clean === "boolean" ? evidence.tree_clean : null,
630
+ reason: typeof evidence.reason === "string" ? redactSecrets(evidence.reason) : "",
631
+ last_log: lastLog && typeof lastLog.at === "string" && typeof lastLog.event === "string" ? { at: lastLog.at, event: lastLog.event, detail: redactSecrets(typeof lastLog.detail === "string" ? lastLog.detail : "") } : null
632
+ },
633
+ first_seen: typeof row.first_seen === "string" ? row.first_seen : (/* @__PURE__ */ new Date(0)).toISOString(),
634
+ last_seen: typeof row.last_seen === "string" ? row.last_seen : (/* @__PURE__ */ new Date(0)).toISOString(),
635
+ count: typeof row.count === "number" && Number.isFinite(row.count) ? Math.max(1, Math.floor(row.count)) : 1,
636
+ episode: typeof row.episode === "string" ? row.episode : "",
637
+ owner,
638
+ status,
639
+ note: typeof row.note === "string" ? redactSecrets(row.note) : null,
640
+ ack_deadline: typeof row.ack_deadline === "string" ? row.ack_deadline : null,
641
+ approval_id: typeof row.approval_id === "string" ? row.approval_id : null,
642
+ resolved_at: typeof row.resolved_at === "string" ? row.resolved_at : null
643
+ };
644
+ }
645
+ function readStore(runId, root) {
646
+ try {
647
+ const parsed = JSON.parse(readFileSync4(incidentPath(runId, root), "utf8"));
648
+ if (parsed.schema_version !== 1 || parsed.run_id !== runId || !Array.isArray(parsed.incidents)) {
649
+ throw new Error(`flow incidents file for ${runId} has an unsupported shape`);
650
+ }
651
+ const watches = typeof parsed.watches === "object" && parsed.watches !== null && !Array.isArray(parsed.watches) ? Object.fromEntries(Object.entries(parsed.watches).filter((entry) => typeof entry[1] === "number" && Number.isFinite(entry[1]))) : {};
652
+ return {
653
+ schema_version: 1,
654
+ run_id: runId,
655
+ incidents: parsed.incidents.map((row) => normalizeIncident(row, runId)).filter((row) => row !== null),
656
+ watches
657
+ };
658
+ } catch (error) {
659
+ if (error.code === "ENOENT") return emptyStore(runId);
660
+ throw error;
661
+ }
662
+ }
663
+ function writeStore(store, root) {
664
+ const path = incidentPath(store.run_id, root);
665
+ mkdirSync3(join3(flowsDir(root), store.run_id), { recursive: true });
666
+ const tmp = `${path}.tmp`;
667
+ writeFileSync3(tmp, JSON.stringify(store, null, 2), "utf8");
668
+ chmodSync2(tmp, 384);
669
+ renameSync3(tmp, path);
670
+ }
671
+ function itemFor(state, observations, decision) {
672
+ return decision?.spec_id ?? state.claim.spec_id ?? state.active_plan_item ?? observations?.plan?.items.find((item) => item.status === "in_work" || item.status === "reviewing")?.id ?? null;
673
+ }
674
+ function episodeFor(state, item) {
675
+ return `${state.claim.head || "no-head"}:${item ?? "-"}`;
676
+ }
677
+ function signalsFor(state, observations, decision, now, paneGrace, previousWatches) {
678
+ const item = itemFor(state, observations, decision);
679
+ const signals = [];
680
+ const watches = {};
681
+ const watchActive = /* @__PURE__ */ new Set();
682
+ const reason = decision?.reason ?? state.hold?.reason ?? "";
683
+ const evidenceReason = decision?.log_detail ?? state.hold?.detail ?? reason;
684
+ const paneUnknown = reason === "dev_pane_unknown" || reason === "review_pane_unknown";
685
+ if (paneUnknown && observations) {
686
+ const since = state.hold?.reason === reason ? Date.parse(state.hold.since) : now;
687
+ if (Number.isFinite(since) && now - since >= paneGrace) {
688
+ const pane = reason.startsWith("dev_") ? "dev" : "review";
689
+ const diagnosis = observations?.pane_diagnostics?.[pane] ?? "pane classification signal was unavailable";
690
+ signals.push({ kind: "pane_unknown", severity: "warn", spec_id: item, reason: `${pane}: ${diagnosis}` });
691
+ }
692
+ }
693
+ if (observations?.tree_clean === false) {
694
+ if (observations.dev_pane === "idle") {
695
+ const key = `dev_stalled|${episodeFor(state, item)}`;
696
+ const since = Number.isFinite(state.stalled_since) && state.stalled_since !== null ? state.stalled_since : void 0;
697
+ const watchAt = since ?? previousWatches[key] ?? now;
698
+ watchActive.add(key);
699
+ watches[key] = watchAt;
700
+ const elapsed = now - watchAt;
701
+ if (elapsed >= state.dev_timeout_sec * 1e3) {
702
+ signals.push({ kind: "dev_stalled", severity: "warn", spec_id: item, reason: `tree is dirty and dev pane is idle for ${Math.floor(elapsed / 1e3)}s` });
703
+ }
704
+ }
705
+ }
706
+ let dispatch = false;
707
+ let dispatchLog;
708
+ for (const entry of [...state.log].reverse()) {
709
+ if (entry.event === "dispatch_unconfirmed" || entry.event === "dispatch_retry_enter") {
710
+ dispatch = true;
711
+ dispatchLog = entry;
712
+ break;
713
+ }
714
+ if (/^(?:request_review|dispatch_fix|dispatch_spec|dispatch_stall_retry|plan_item_dispatched|dispatch_refused)$/.test(entry.event)) break;
715
+ }
716
+ if (dispatch) signals.push({ kind: "dispatch_unconfirmed", severity: "blocker", spec_id: item, reason: dispatchLog?.detail ?? "dispatch submit could not be confirmed" });
717
+ const latest = [...state.log].reverse().find((entry) => entry.event !== "incident_opened" && entry.event !== "incident_resolved") ?? null;
718
+ const latestDetail = latest?.detail ?? "";
719
+ const escalationCause = [...state.log].reverse().find((entry) => entry.event === "escalate")?.detail;
720
+ const escalatedReason = state.state === "escalated" ? (decision?.kind === "escalate" ? decision.reason : void 0) ?? escalationCause ?? (decision?.reason === "flow_closed" ? void 0 : decision?.reason) ?? latestDetail : decision?.reason ?? reason;
721
+ if (escalatedReason.includes("dispatch_unresolved") || escalatedReason.includes("review_dispatch_unconfirmed") || latest?.event === "dispatch_unresolved") {
722
+ signals.push({ kind: "dispatch_unconfirmed", severity: "blocker", spec_id: item, reason: escalatedReason || latestDetail });
723
+ } else if (escalatedReason.includes("plan_item_stale_in_flight")) {
724
+ const staleReason = decision?.log_detail ?? escalatedReason;
725
+ const staleItem = /plan_item_stale_in_flight:\s*(\S+)\s+is reviewing/.exec(staleReason)?.[1];
726
+ signals.push({ kind: "plan_item_stale_in_flight", severity: "blocker", spec_id: staleItem ?? item, reason: staleReason });
727
+ } else if (escalatedReason.includes("review_timeout")) {
728
+ signals.push({ kind: "review_timeout", severity: "blocker", spec_id: item, reason: escalatedReason });
729
+ } else if (/rounds_exhausted|total_rounds_exhausted|rounds spent/.test(escalatedReason)) {
730
+ signals.push({ kind: "rounds_exhausted", severity: "blocker", spec_id: item, reason: escalatedReason });
731
+ } else if (escalatedReason.includes("dev_stalled") && !observations) {
732
+ signals.push({ kind: "dev_stalled", severity: "warn", spec_id: item, reason: escalatedReason });
733
+ } else if (state.state === "escalated" && escalatedReason) {
734
+ signals.push({ kind: "unknown_hold", severity: "blocker", spec_id: item, reason: escalatedReason });
735
+ }
736
+ const planBlocked = observations?.plan?.items.find((entry) => entry.id === item && entry.status === "blocked_owner");
737
+ if (planBlocked?.block_reason === "rounds_exhausted") {
738
+ signals.push({ kind: "rounds_exhausted", severity: "blocker", spec_id: item, reason: "plan item exhausted its review rounds" });
739
+ }
740
+ if (reason === "agent_question" || state.agent_question) {
741
+ signals.push({ kind: "agent_question", severity: "warn", spec_id: item, reason: state.agent_question?.text ?? evidenceReason });
742
+ }
743
+ const normal = /* @__PURE__ */ new Set([
744
+ "",
745
+ "head_unchanged",
746
+ "tree_dirty",
747
+ "dev_busy",
748
+ "review_busy",
749
+ "dev_pane_unknown",
750
+ "review_pane_unknown",
751
+ "awaiting_verdict",
752
+ "review_timer_started",
753
+ "dispatch_pending",
754
+ "dispatch_unresolved",
755
+ "plan_incomplete",
756
+ "plan_in_flight",
757
+ "plan_item_requeued",
758
+ "fix_refused",
759
+ "flow_closed",
760
+ "flow_done",
761
+ "spec_pending",
762
+ "agent_question",
763
+ "agent_question_answered"
764
+ ]);
765
+ if (decision?.kind === "none" && !normal.has(decision.reason) && decision.reason !== "dev_stalled" && decision.reason !== "review_timeout" && decision.reason !== "rounds_exhausted") {
766
+ signals.push({ kind: "unknown_hold", severity: "warn", spec_id: item, reason: decision.log_detail ?? decision.reason });
767
+ }
768
+ if (decision?.reason === "dev_stalled" || state.stalled_since !== null && observations?.dev_pane === "idle" && now - state.stalled_since >= state.dev_timeout_sec * 1e3) {
769
+ signals.push({ kind: "dev_stalled", severity: "warn", spec_id: item, reason: decision?.log_detail ?? "dev remained idle beyond the configured timeout" });
770
+ }
771
+ return { signals, watches, watchActive };
772
+ }
773
+ function evidenceOf(state, observations, reason) {
774
+ const last = state.log.at(-1);
775
+ return {
776
+ state: state.state,
777
+ head: state.claim.head,
778
+ dev_pane: observations?.dev_pane ?? "unknown",
779
+ review_pane: observations?.review_pane ?? "unknown",
780
+ tree_clean: observations?.tree_clean ?? null,
781
+ reason: redactSecrets(reason),
782
+ last_log: last ? { at: last.at, event: last.event, detail: redactSecrets(last.detail) } : null
783
+ };
784
+ }
785
+ function keyFor(episode, kind, item) {
786
+ return `${episode}|${kind}|${item ?? "-"}`;
787
+ }
788
+ function activeKey(row) {
789
+ return keyFor(row.episode, row.kind, row.spec_id);
790
+ }
791
+ function withIncidentJournal(state, events, at, root, preserveTickTail = false) {
792
+ if (events.length === 0) return state;
793
+ let log = state.log;
794
+ const tickTail = preserveTickTail && log.at(-1)?.at === at ? log.at(-1) : void 0;
795
+ if (tickTail) log = log.slice(0, -1);
796
+ for (const event of events) {
797
+ if (log.some((entry) => entry.event === event.event && entry.detail === event.detail)) continue;
798
+ log = [...appendLog({ ...state, log }, { at, event: event.event, detail: event.detail })].slice(-FLOW_LOG_LIMIT);
799
+ }
800
+ if (tickTail) log = appendLog({ ...state, log }, tickTail);
801
+ const updated = { ...state, log, updated_at: at };
802
+ saveFlow(updated, { root });
803
+ return updated;
804
+ }
805
+ function reconcileFlowIncidents(state, observations, decision, options = {}) {
806
+ const now = options.now ?? Date.now();
807
+ const at = options.at ?? new Date(now).toISOString();
808
+ const ackTimeout = options.ack_timeout_ms ?? DEFAULT_INCIDENT_ACK_TIMEOUT_MS;
809
+ const paneGrace = options.pane_unknown_grace_ms ?? DEFAULT_PANE_UNKNOWN_GRACE_MS;
810
+ const approvalsToCreate = [];
811
+ const events = [];
812
+ withRunsLock(() => {
813
+ const store = readStore(state.run_id, options.root);
814
+ const detected = signalsFor(state, observations, decision, now, paneGrace, store.watches);
815
+ store.watches = Object.fromEntries(Object.entries(store.watches).filter(([key]) => detected.watchActive.has(key)));
816
+ Object.assign(store.watches, detected.watches);
817
+ const signalByKey = /* @__PURE__ */ new Map();
818
+ for (const signal of detected.signals) {
819
+ const key = keyFor(episodeFor(state, signal.spec_id), signal.kind, signal.spec_id);
820
+ signalByKey.set(key, signal);
821
+ }
822
+ for (const row of store.incidents) {
823
+ if (row.status === "resolved") continue;
824
+ const key = activeKey(row);
825
+ const signal = signalByKey.get(key);
826
+ if (signal) {
827
+ row.last_seen = at;
828
+ row.count += 1;
829
+ row.evidence = evidenceOf(state, observations, signal.reason);
830
+ continue;
831
+ }
832
+ if (!observations) continue;
833
+ row.status = "resolved";
834
+ row.resolved_at = at;
835
+ row.last_seen = at;
836
+ row.note = "condition cleared";
837
+ events.push({ event: "incident_resolved", detail: `${row.id} ${row.kind}: condition cleared` });
838
+ }
839
+ for (const [key, signal] of signalByKey) {
840
+ const episode = episodeFor(state, signal.spec_id);
841
+ const prior = store.incidents.find((row) => activeKey(row) === key);
842
+ if (prior) continue;
843
+ const resolvedBefore = store.incidents.some((row) => row.status === "resolved" && activeKey(row) === key);
844
+ if (resolvedBefore) continue;
845
+ const incident = {
846
+ id: randomUUID2(),
847
+ run_id: state.run_id,
848
+ spec_id: signal.spec_id,
849
+ kind: signal.kind,
850
+ severity: signal.severity,
851
+ evidence: evidenceOf(state, observations, signal.reason),
852
+ first_seen: at,
853
+ last_seen: at,
854
+ count: 1,
855
+ episode,
856
+ owner: "orchestrator",
857
+ status: "open",
858
+ note: null,
859
+ ack_deadline: signal.severity === "blocker" ? new Date(now + ackTimeout).toISOString() : null,
860
+ approval_id: null,
861
+ resolved_at: null
862
+ };
863
+ store.incidents.push(incident);
864
+ events.push({ event: "incident_opened", detail: `${incident.id} ${incident.severity} ${incident.kind}${incident.spec_id ? ` ${incident.spec_id}` : ""}` });
865
+ }
866
+ for (const row of store.incidents) {
867
+ if (row.status !== "open" || row.severity !== "blocker" || !row.ack_deadline || Date.parse(row.ack_deadline) > now) continue;
868
+ if (row.owner === "orchestrator") {
869
+ row.owner = "human";
870
+ row.note = row.note ?? "orchestrator ACK timeout; escalated to human";
871
+ }
872
+ if (row.owner === "human" && !row.approval_id) approvalsToCreate.push(row.id);
873
+ }
874
+ writeStore(store, options.root);
875
+ const current = readFlow(state.run_id, { root: options.root });
876
+ const updated = withIncidentJournal(current, events, at, options.root, decision !== void 0);
877
+ state = updated;
878
+ });
879
+ for (const incidentId of approvalsToCreate) {
880
+ let incident = listFlowIncidents(state.run_id, { root: options.root }).find((row) => row.id === incidentId);
881
+ if (!incident || incident.approval_id) continue;
882
+ try {
883
+ const existing = listRunApprovals(state.run_id).find((approval) => approval.details.incident_id === incidentId && approval.status === "pending");
884
+ let approvalId = existing?.id;
885
+ if (!approvalId) {
886
+ const run = readRun(state.run_id);
887
+ const approval = createRunApproval({
888
+ agent_id: run.root_agent_id,
889
+ action: "flow_incident",
890
+ summary: `Flow incident needs attention: ${incident.kind}${incident.spec_id ? ` (${incident.spec_id})` : ""}`,
891
+ details: { incident_id: incident.id, kind: incident.kind, evidence: incident.evidence.reason },
892
+ risk: "high"
893
+ });
894
+ approvalId = approval.id;
895
+ }
896
+ withRunsLock(() => {
897
+ const store = readStore(state.run_id, options.root);
898
+ const row = store.incidents.find((item) => item.id === incidentId);
899
+ if (!row || row.status === "resolved" || row.approval_id) return;
900
+ row.approval_id = approvalId ?? null;
901
+ writeStore(store, options.root);
902
+ });
903
+ } catch {
904
+ }
905
+ }
906
+ return state;
907
+ }
908
+ function listFlowIncidents(runId, options = {}) {
909
+ const rows = readStore(runId, options.root).incidents;
910
+ return rows.filter((row) => options.open_only !== true || row.status !== "resolved").map((row) => ({ ...row, evidence: { ...row.evidence } })).sort((a, b) => a.first_seen.localeCompare(b.first_seen));
911
+ }
912
+ function findIncident(store, id) {
913
+ const matches = store.incidents.filter((row) => row.id === id || row.id.startsWith(id));
914
+ if (matches.length !== 1) throw new Error(matches.length > 1 ? `ambiguous incident id ${id}` : `no incident ${id}`);
915
+ return matches[0];
916
+ }
917
+ function claimFlowIncident(runId, id, options = {}) {
918
+ return withRunsLock(() => {
919
+ const store = readStore(runId, options.root);
920
+ const row = findIncident(store, id);
921
+ if (row.status === "resolved") throw new Error(`incident ${row.id} is already resolved`);
922
+ row.owner = "orchestrator";
923
+ writeStore(store, options.root);
924
+ return row;
925
+ });
926
+ }
927
+ function ackFlowIncident(runId, id, options = {}) {
928
+ return withRunsLock(() => {
929
+ const at = options.at ?? (/* @__PURE__ */ new Date()).toISOString();
930
+ const store = readStore(runId, options.root);
931
+ const row = findIncident(store, id);
932
+ if (row.status === "resolved") throw new Error(`incident ${row.id} is already resolved`);
933
+ row.owner = "orchestrator";
934
+ row.status = "acked";
935
+ row.note = row.note ?? "acknowledged by orchestrator";
936
+ row.last_seen = at;
937
+ writeStore(store, options.root);
938
+ return row;
939
+ });
940
+ }
941
+ function resolveFlowIncident(runId, id, note, options = {}) {
942
+ const cleanNote = note.trim();
943
+ if (!cleanNote) throw new Error("resolving an incident requires a note");
944
+ return withRunsLock(() => {
945
+ const at = options.at ?? (/* @__PURE__ */ new Date()).toISOString();
946
+ const store = readStore(runId, options.root);
947
+ const row = findIncident(store, id);
948
+ if (row.status === "resolved") return row;
949
+ row.status = "resolved";
950
+ row.resolved_at = at;
951
+ row.last_seen = at;
952
+ row.note = redactSecrets(cleanNote);
953
+ writeStore(store, options.root);
954
+ const current = readFlow(runId, { root: options.root });
955
+ const detail = `${row.id} ${row.kind}: ${row.note}`;
956
+ if (!current.log.some((entry) => entry.event === "incident_resolved" && entry.detail.startsWith(`${row.id} `))) {
957
+ const updated = { ...current, log: appendLog(current, { at, event: "incident_resolved", detail }), updated_at: at };
958
+ saveFlow(updated, { root: options.root });
959
+ }
960
+ return row;
961
+ });
962
+ }
963
+ function flowIncidentAgeMs(row, now = Date.now()) {
964
+ return Math.max(0, now - Date.parse(row.first_seen));
965
+ }
966
+
967
+ // src/core/flow-view.ts
968
+ function resolveFlowRunId(input, root) {
969
+ const wanted = input.trim();
970
+ if (!wanted) throw new FlowStateError("a run id is required");
971
+ const files = listFlowFiles(root);
972
+ const exact = files.find((file) => file.run_id === wanted);
973
+ if (exact) return exact.run_id;
974
+ const matches = files.filter((file) => file.run_id.startsWith(wanted));
975
+ if (matches.length === 1) return matches[0].run_id;
976
+ if (matches.length > 1) throw new FlowStateError(`ambiguous run id: ${matches.map((file) => file.run_id).join(", ")}`);
977
+ const known = files.slice(0, 5).map((file) => file.run_id).join(", ");
978
+ throw new FlowStateError(known ? `no flow for run ${wanted} (flow not started; flows exist for: ${known}${files.length > 5 ? ", ..." : ""})` : `no flow for run ${wanted} (flow not started; no flows exist yet)`);
979
+ }
980
+ var SETTLED_DISPATCH_EVENTS = /^(?:request_review|dispatch_fix|dispatch_spec|dispatch_stall_retry|plan_item_dispatched)$/;
981
+ function flowDispatchNote(state) {
982
+ for (let index = state.log.length - 1; index >= 0; index -= 1) {
983
+ const entry = state.log[index];
984
+ if (entry.event === "dispatch_unconfirmed" || entry.event === "dispatch_retry_enter") {
985
+ return { state: "unconfirmed", reason: redactSecrets(entry.detail), at: entry.at };
986
+ }
987
+ if (entry.event === "dispatch_claimed" || entry.event === "dispatch_refused") continue;
988
+ if (SETTLED_DISPATCH_EVENTS.test(entry.event)) return null;
989
+ }
990
+ return null;
991
+ }
992
+ function flowQueueSummary(state) {
993
+ return state.specs.filter((spec) => !state.dispatched_specs.includes(spec.id)).map((spec) => ({
994
+ id: spec.id,
995
+ title: redactSecrets(spec.title),
996
+ source_path: spec.source_path ? shortHomePath(spec.source_path) : null
997
+ }));
998
+ }
999
+ function parseEvidence(detail) {
1000
+ const match = /elapsed=(\d+)s notes=(\d+)\/(\d+)b tool=(\d+)/.exec(detail);
1001
+ if (!match) return null;
1002
+ return {
1003
+ elapsed_ms: Number(match[1]) * 1e3,
1004
+ notes_findings: Number(match[2]),
1005
+ notes_bytes: Number(match[3]),
1006
+ pane_tool_lines: Number(match[4])
1007
+ };
1008
+ }
1009
+ function flowStatusPayload(state, path = flowPath(state.run_id)) {
1010
+ const queue = flowQueueSummary(state);
1011
+ const log = state.log.slice(-5).map((entry) => ({
1012
+ at: entry.at,
1013
+ event: entry.event,
1014
+ detail: redactSecrets(entry.detail)
1015
+ }));
1016
+ return {
1017
+ schema_version: state.schema_version,
1018
+ run_id: state.run_id,
1019
+ state: state.state,
1020
+ rounds: state.rounds,
1021
+ max_rounds: state.max_rounds,
1022
+ review_started_at: state.review_started_at,
1023
+ review_timeout_sec: state.review_timeout_sec,
1024
+ dev_timeout_sec: state.dev_timeout_sec,
1025
+ dev_stall_attempts: state.dev_stall_attempts,
1026
+ dev_stall_max_attempts: state.dev_stall_max_attempts,
1027
+ stalled_since: state.stalled_since,
1028
+ head: state.claim.head,
1029
+ claim: {
1030
+ head: state.claim.head,
1031
+ verdict: state.claim.verdict,
1032
+ verdict_count: state.claim.verdict_count,
1033
+ verdict_applied: state.claim.verdict_applied,
1034
+ spec_id: state.claim.spec_id
1035
+ },
1036
+ pending: state.pending ? { kind: state.pending.kind, target: state.pending.target, at: state.pending.at } : null,
1037
+ // The reason the flow is standing still, so a host does not have to run a `--dry-run` tick to find out. The field is
1038
+ // passed through, never derived: `since` is when the hold started, not when this payload was built.
1039
+ hold: state.hold ? { reason: state.hold.reason, since: state.hold.since, ...state.hold.detail ? { detail: state.hold.detail } : {} } : null,
1040
+ agent_question: state.agent_question ? {
1041
+ agent: state.agent_question.agent,
1042
+ item: state.agent_question.item,
1043
+ text: redactSecrets(state.agent_question.text),
1044
+ since: state.agent_question.since
1045
+ } : null,
1046
+ incidents: listFlowIncidents(state.run_id, { open_only: true }).map((row) => ({
1047
+ id: row.id,
1048
+ spec_id: row.spec_id,
1049
+ kind: row.kind,
1050
+ severity: row.severity,
1051
+ owner: row.owner,
1052
+ status: row.status,
1053
+ first_seen: row.first_seen,
1054
+ last_seen: row.last_seen,
1055
+ count: row.count,
1056
+ note: row.note,
1057
+ evidence: row.evidence,
1058
+ age_ms: flowIncidentAgeMs(row)
1059
+ })),
1060
+ // The last decision that saw a verdict carries the numbers the evidence rule used; a state written
1061
+ // before this field existed simply has none.
1062
+ last_evidence: (() => {
1063
+ for (let index = state.log.length - 1; index >= 0; index -= 1) {
1064
+ const entry = state.log[index];
1065
+ if (entry.event === "review_unsubstantiated") return parseEvidence(entry.detail);
1066
+ }
1067
+ return null;
1068
+ })(),
1069
+ // The newest log entry that consumed a notes file. The text stays in the file.
1070
+ last_notes: (() => {
1071
+ for (let index = state.log.length - 1; index >= 0; index -= 1) {
1072
+ const entry = state.log[index];
1073
+ if (entry.notes_ref) {
1074
+ return { ref: entry.notes_ref, counts: entry.notes_counts ?? { blocker: 0, major: 0, minor: 0 } };
1075
+ }
1076
+ }
1077
+ return null;
1078
+ })(),
1079
+ paused_from: state.paused_from,
1080
+ paused_at: state.paused_at,
1081
+ // Both reasons are text a human wrote or a short engine string; the redactor still runs so a
1082
+ // pasted token cannot ride out through them.
1083
+ orphan_reason: state.orphan_reason ? redactSecrets(state.orphan_reason) : null,
1084
+ close_reason: state.close_reason ? redactSecrets(state.close_reason) : null,
1085
+ queue,
1086
+ dispatched_specs: state.dispatched_specs,
1087
+ dispatch: flowDispatchNote(state),
1088
+ repo: shortHomePath(state.repo),
1089
+ updated_at: state.updated_at,
1090
+ // `flow status` and an MCP host both want "why is it sitting there" in one field.
1091
+ last_decision: log.at(-1) ?? null,
1092
+ log,
1093
+ path: shortHomePath(path)
1094
+ };
1095
+ }
1096
+ function flowBadge(state, now = Date.now(), plan = null, planProgress = null, incidentSummary = null) {
1097
+ const queueDepth = state.specs.filter((spec) => !state.dispatched_specs.includes(spec.id)).length;
1098
+ const lostSpec = lostQueuedSpec(state);
1099
+ const overdue = state.state === "reviewing" && state.review_started_at !== null && now - state.review_started_at >= state.review_timeout_sec * 1e3;
1100
+ const escalation = state.state === "escalated" ? "escalated" : overdue ? "review_timeout" : null;
1101
+ const stalled = escalation === null && state.state !== "done" && state.state !== "orphaned" && state.state !== "paused" && flowDispatchNote(state) !== null ? "dispatch_unconfirmed" : null;
1102
+ const devStalled = escalation === null && stalled === null && state.stalled_since !== null && (state.dev_stall_attempts > 0 || now - state.stalled_since >= state.dev_timeout_sec * 1e3) && state.state !== "done" && state.state !== "orphaned" && state.state !== "paused" ? "dev_stalled" : null;
1103
+ const planAttention = escalation === null && stalled === null && devStalled === null && plan !== null && (state.state === "idle" || state.state === "reviewing" || state.state === "fixing") ? "plan_waiting" : null;
1104
+ const incidentAttention = incidentSummary && incidentSummary.open > 0 ? "incident" : null;
1105
+ const specLost = lostSpec ? "spec_lost" : null;
1106
+ return {
1107
+ status: state.state,
1108
+ rounds: state.rounds,
1109
+ max_rounds: state.max_rounds,
1110
+ review_overdue: overdue,
1111
+ attention: incidentAttention ?? escalation ?? stalled ?? devStalled ?? specLost ?? planAttention,
1112
+ attention_detail: lostSpec ? `queued spec ${lostSpec} is missing from both the queue and dispatch history` : null,
1113
+ queue_depth: queueDepth,
1114
+ plan: incidentAttention !== null ? null : planAttention === null ? null : plan,
1115
+ plan_progress: planProgress,
1116
+ incident_summary: incidentSummary,
1117
+ close_reason: state.close_reason ?? null,
1118
+ updated_at: Date.parse(state.updated_at) || 0
1119
+ };
1120
+ }
1121
+ function lostQueuedSpec(state) {
1122
+ const seen = /* @__PURE__ */ new Set();
1123
+ for (const entry of [...state.log].reverse()) {
1124
+ if (entry.event === "spec_queued") {
1125
+ for (const id of entry.detail.split(",").map((value) => value.trim()).filter(Boolean)) {
1126
+ if (seen.has(id)) continue;
1127
+ seen.add(id);
1128
+ if (!state.specs.some((spec) => spec.id === id) && !state.dispatched_specs.includes(id)) return id;
1129
+ }
1130
+ } else if (entry.event === "spec_dropped") {
1131
+ const id = entry.detail.split(":", 1)[0]?.trim();
1132
+ if (id) seen.add(id);
1133
+ }
1134
+ }
1135
+ return null;
1136
+ }
1137
+ function planAttentionOf(runId, root) {
1138
+ try {
1139
+ const plan = readPlan(runId, { root });
1140
+ for (const item of plan.items) {
1141
+ if (item.missing_since !== null) continue;
1142
+ if (item.status === "blocked_owner") return { reason: "blocked_owner", item: item.id };
1143
+ if (item.spec === null && item.status !== "done" && item.status !== "skipped") return { reason: "needs_brief", item: item.id };
1144
+ }
1145
+ return null;
1146
+ } catch {
1147
+ return null;
1148
+ }
1149
+ }
1150
+ function planProgressOf(runId, root) {
1151
+ try {
1152
+ const plan = readPlan(runId, { root });
1153
+ const total = plan.items.length;
1154
+ if (total === 0) return null;
1155
+ const done = plan.items.filter((item) => item.status === "done" || item.status === "skipped").length;
1156
+ return { done, total };
1157
+ } catch {
1158
+ return null;
1159
+ }
1160
+ }
1161
+ function flowSectionLines(state, options = {}) {
1162
+ const now = options.now ?? Date.now();
1163
+ const badge = flowBadge(state, now, options.plan ?? null);
1164
+ const lines = [];
1165
+ const budget = badge.status === "escalated" || badge.status === "done" || badge.status === "orphaned" ? `round ${badge.rounds}` : `round ${badge.rounds}/${badge.max_rounds}`;
1166
+ lines.push(`state ${badge.status} \xB7 ${budget}`);
1167
+ if (state.agent_question) lines.push(`question ${state.agent_question.agent}: ${state.agent_question.text}`);
1168
+ if (options.active_plan_item) {
1169
+ const suffix = options.plan && options.plan.item === options.active_plan_item ? "" : "";
1170
+ lines.push(`item ${options.active_plan_item}${suffix}`);
1171
+ }
1172
+ if (typeof options.queue_depth === "number") lines.push(`queue ${options.queue_depth} pending`);
1173
+ if (options.plan) {
1174
+ const why = options.plan.reason === "needs_brief" ? "needs a brief" : "blocked_owner";
1175
+ lines.push(`waiting ${options.plan.item} (${why})`);
1176
+ }
1177
+ if (badge.attention === "review_timeout") lines.push("attention review timed out");
1178
+ else if (badge.attention === "escalated") lines.push("attention rounds spent \u2014 approve or deny in Approvals");
1179
+ else if (badge.attention === "dev_stalled") lines.push(`attention dev stalled \xB7 retry ${state.dev_stall_attempts}/${state.dev_stall_max_attempts}`);
1180
+ else if (badge.attention === "plan_waiting") lines.push("attention waiting for you");
1181
+ lines.push(`tick ${tickStateText(options.tick ?? null, now)}`);
1182
+ return lines.map((line) => line.length > 78 ? `${line.slice(0, 77)}\u2026` : line);
1183
+ }
1184
+ function readFlowBadge(runId, now = Date.now(), root) {
1185
+ try {
1186
+ const incidents = listFlowIncidents(runId, { root, open_only: true });
1187
+ const incidentSummary = incidents.length > 0 ? {
1188
+ open: incidents.length,
1189
+ blockers: incidents.filter((row) => row.severity === "blocker").length,
1190
+ owner: incidents.some((row) => row.owner === "human") ? "human" : "orchestrator"
1191
+ } : null;
1192
+ return flowBadge(readFlow(runId, { root }), now, planAttentionOf(runId, root), planProgressOf(runId, root), incidentSummary);
1193
+ } catch {
1194
+ return null;
1195
+ }
1196
+ }
1197
+ function listFlowBadges(runIds, now = Date.now(), root) {
1198
+ const badges = /* @__PURE__ */ new Map();
1199
+ for (const runId of runIds) {
1200
+ const badge = readFlowBadge(runId, now, root);
1201
+ if (badge) badges.set(runId, badge);
1202
+ }
1203
+ return badges;
1204
+ }
1205
+ function sameFlowBadges(a, b) {
1206
+ if (a.size !== b.size) return false;
1207
+ for (const [runId, badge] of a) {
1208
+ const other = b.get(runId);
1209
+ if (!other) return false;
1210
+ if (other.status !== badge.status || other.rounds !== badge.rounds || other.max_rounds !== badge.max_rounds) return false;
1211
+ if (other.attention !== badge.attention || other.review_overdue !== badge.review_overdue) return false;
1212
+ }
1213
+ return true;
1214
+ }
1215
+
1216
+ export {
1217
+ REEVESAGENTS_VERSION,
1218
+ sweepAgents,
1219
+ sweepOrphanSessions,
1220
+ sweepOrphanSessionsThrottled,
1221
+ sweepAgentsThrottled,
1222
+ createRunApproval,
1223
+ readRunApproval,
1224
+ listRunApprovals,
1225
+ resolveRunApproval,
1226
+ writeTickStatus,
1227
+ readTickStatus,
1228
+ tickStateText,
1229
+ systemdTimerState,
1230
+ reconcileFlowIncidents,
1231
+ listFlowIncidents,
1232
+ claimFlowIncident,
1233
+ ackFlowIncident,
1234
+ resolveFlowIncident,
1235
+ flowIncidentAgeMs,
1236
+ resolveFlowRunId,
1237
+ flowDispatchNote,
1238
+ flowQueueSummary,
1239
+ flowStatusPayload,
1240
+ planAttentionOf,
1241
+ flowSectionLines,
1242
+ readFlowBadge,
1243
+ listFlowBadges,
1244
+ sameFlowBadges
1245
+ };
1246
+ //# sourceMappingURL=chunk-XEOWHTRQ.js.map