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,1697 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ reconcileFlowIncidents
4
+ } from "./chunk-XEOWHTRQ.js";
5
+ import {
6
+ DEFAULT_EVIDENCE_POLICY,
7
+ FLOW_LOG_LIMIT,
8
+ FlowStateError,
9
+ MAX_ENTER_RETRIES,
10
+ PLAN_LIMITS,
11
+ addItemRound,
12
+ appendLog,
13
+ appendLogEntries,
14
+ applyDecisionToState,
15
+ applyOperatorTransition,
16
+ applyUnconfirmedDispatch,
17
+ canTransition,
18
+ claimPendingDispatch,
19
+ closeItemOnAccept,
20
+ composerText,
21
+ countFindings,
22
+ decisionChangesState,
23
+ devStallRetryMessage,
24
+ displayPath,
25
+ emitNotification,
26
+ ensureNotesInbox,
27
+ escalateOnDirtyComposer,
28
+ escalateUnconfirmedDispatch,
29
+ findingsText,
30
+ flowTick,
31
+ formatSpecIssues,
32
+ isCommitId,
33
+ isComposerPlaceholder,
34
+ isRunsLockTimeout,
35
+ loadConfig,
36
+ moveItemByEngine,
37
+ mutatePlan,
38
+ notesRef,
39
+ paneBusy,
40
+ paneDiagnosis,
41
+ paneReadyForNudge,
42
+ parsePlanDocument,
43
+ parseSpecJson,
44
+ peekAgentRaw,
45
+ planExists,
46
+ planTickSummary,
47
+ planTickView,
48
+ pruneClosedFlowNotes,
49
+ pruneNotes,
50
+ publishNotesIfChanged,
51
+ readDurable,
52
+ readFlow,
53
+ readNewestNotes,
54
+ readPlan,
55
+ readRun,
56
+ readStaging,
57
+ redactSecrets,
58
+ releaseDispatch,
59
+ resolveRepositoryPath,
60
+ retryEnterDispatch,
61
+ retrySpecDispatch,
62
+ runPath,
63
+ saveFlow,
64
+ sendWhenIdle,
65
+ setItemStatus,
66
+ specFromMarkdown,
67
+ stagingPath,
68
+ stateRoot,
69
+ tryListAgents,
70
+ withRunsLock,
71
+ writePaneCapture
72
+ } from "./chunk-CJKEBBUI.js";
73
+
74
+ // src/core/flow-queue.ts
75
+ import { readFileSync, realpathSync, statSync } from "fs";
76
+ import { isAbsolute, extname, relative, resolve, sep } from "path";
77
+ var SPEC_FILE_MAX_BYTES = 64 * 1024;
78
+ var FlowSpecError = class extends Error {
79
+ constructor(message) {
80
+ super(message);
81
+ this.name = "FlowSpecError";
82
+ }
83
+ };
84
+ function escapesProject(target, base) {
85
+ const inside = relative(base, target);
86
+ return inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside);
87
+ }
88
+ function realPath(path) {
89
+ try {
90
+ return realpathSync(path);
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+ function readSpecFile(path, options) {
96
+ const raw = path.trim();
97
+ if (!raw) throw new FlowSpecError("a spec file path is required");
98
+ const fromProject = !isAbsolute(raw);
99
+ let absolute;
100
+ if (!fromProject) {
101
+ absolute = raw;
102
+ } else if (options.repo) {
103
+ absolute = resolve(options.repo, raw);
104
+ if (escapesProject(absolute, options.repo)) {
105
+ throw new FlowSpecError(`spec path ${raw} is outside the project directory; pass an absolute path`);
106
+ }
107
+ } else {
108
+ throw new FlowSpecError(`spec path ${raw} is relative and the flow has no project directory`);
109
+ }
110
+ const real = realPath(absolute);
111
+ if (!real) throw new FlowSpecError(`spec file not found: ${displayPath(absolute)}`);
112
+ if (fromProject && escapesProject(real, realPath(options.repo) ?? resolve(options.repo))) {
113
+ throw new FlowSpecError(`spec path ${raw} resolves outside the project directory; pass an absolute path`);
114
+ }
115
+ let size;
116
+ try {
117
+ const stats = statSync(real);
118
+ if (!stats.isFile()) throw new FlowSpecError(`spec path is not a file: ${displayPath(absolute)}`);
119
+ size = stats.size;
120
+ } catch (err) {
121
+ if (err instanceof FlowSpecError) throw err;
122
+ throw new FlowSpecError(`spec file not found: ${displayPath(absolute)}`);
123
+ }
124
+ if (size > SPEC_FILE_MAX_BYTES) {
125
+ throw new FlowSpecError(`spec file is larger than ${SPEC_FILE_MAX_BYTES} bytes: ${displayPath(absolute)}`);
126
+ }
127
+ let text;
128
+ try {
129
+ text = readFileSync(real, "utf-8");
130
+ } catch {
131
+ throw new FlowSpecError(`spec file could not be read: ${displayPath(absolute)}`);
132
+ }
133
+ if (!text.trim()) throw new FlowSpecError(`spec file is empty: ${displayPath(absolute)}`);
134
+ const asMarkdown = options.asMarkdown === true || extname(absolute).toLowerCase() !== ".json";
135
+ const validation = asMarkdown ? specFromMarkdown(text, absolute, { existingIds: options.existingIds }) : parseSpecJson(text, { existingIds: options.existingIds });
136
+ if (!validation.spec) throw new FlowSpecError(formatSpecIssues(validation.issues));
137
+ return { ...validation.spec, source_path: absolute };
138
+ }
139
+ function queueSpecFile(state, path, at) {
140
+ if (state.state === "escalated" || state.state === "done") {
141
+ throw new FlowSpecError(`flow for run ${state.run_id} is ${state.state}; resume or start a new flow before queueing a block`);
142
+ }
143
+ const spec = readSpecFile(path, {
144
+ repo: state.repo,
145
+ existingIds: [...state.specs.map((entry) => entry.id), ...state.dispatched_specs]
146
+ });
147
+ return {
148
+ state: {
149
+ ...state,
150
+ specs: [...state.specs, spec],
151
+ updated_at: at ?? (/* @__PURE__ */ new Date()).toISOString()
152
+ },
153
+ spec
154
+ };
155
+ }
156
+
157
+ // src/core/flow-runner.ts
158
+ import { randomUUID as randomUUID2 } from "crypto";
159
+ import { readFileSync as readFileSync4, statSync as statSync3 } from "fs";
160
+ import { execFileSync as execFileSync3 } from "child_process";
161
+
162
+ // src/core/flow-dispatch-gate.ts
163
+ import { mkdirSync, readFileSync as readFileSync2, readdirSync, renameSync, unlinkSync, writeFileSync } from "fs";
164
+ import { execFileSync } from "child_process";
165
+ import { randomUUID } from "crypto";
166
+ import { basename, dirname, join } from "path";
167
+ var DISPATCH_GATE_TIMEOUT_MS = 15e3;
168
+ var GATE_POLL_MS = 25;
169
+ var PREFIX = ".flow-dispatch";
170
+ function gateCandidatesPath(root = stateRoot()) {
171
+ return join(root, PREFIX);
172
+ }
173
+ function sleepSync(ms) {
174
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
175
+ }
176
+ function pidAlive(pid) {
177
+ try {
178
+ process.kill(pid, 0);
179
+ return true;
180
+ } catch (err) {
181
+ return err.code !== "ESRCH";
182
+ }
183
+ }
184
+ var instanceCache = /* @__PURE__ */ new Map();
185
+ var defaultProbe = (pid) => {
186
+ let found = null;
187
+ try {
188
+ const stat = readFileSync2(`/proc/${pid}/stat`, "utf-8");
189
+ const start = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
190
+ if (start && /^\d+$/.test(start)) found = `linux:${start}`;
191
+ } catch {
192
+ }
193
+ if (found === null) {
194
+ try {
195
+ const out = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
196
+ encoding: "utf-8",
197
+ stdio: ["ignore", "pipe", "ignore"],
198
+ timeout: 2e3
199
+ }).trim();
200
+ if (out) found = `ps:${out}`;
201
+ } catch {
202
+ }
203
+ }
204
+ return found;
205
+ };
206
+ function probeInstance(pid, probe) {
207
+ if (instanceCache.has(pid)) return instanceCache.get(pid) ?? null;
208
+ const found = probe(pid);
209
+ instanceCache.set(pid, found);
210
+ return found;
211
+ }
212
+ function participantAlive(record, path, probe) {
213
+ if (!pidAlive(record.pid)) return false;
214
+ if (!record.instance) {
215
+ throw new Error(
216
+ `gate file ${basename(path)} records no process instance (written by an older reevesagents); check that no dispatch is running, then remove ${displayPath(path)}`
217
+ );
218
+ }
219
+ const current = probeInstance(record.pid, probe);
220
+ if (current === null) return true;
221
+ const sameProbe = current.split(":")[0] === record.instance.split(":")[0];
222
+ if (!sameProbe) return true;
223
+ return current === record.instance;
224
+ }
225
+ function publish(path, data) {
226
+ const temp = `${path}.tmp.${randomUUID()}`;
227
+ writeFileSync(temp, JSON.stringify(data), { encoding: "utf-8", mode: 384 });
228
+ try {
229
+ renameSync(temp, path);
230
+ } catch (err) {
231
+ try {
232
+ unlinkSync(temp);
233
+ } catch {
234
+ }
235
+ throw err;
236
+ }
237
+ }
238
+ function pathFor(root, kind, pid, token) {
239
+ return join(root, `${PREFIX}.${kind}.${pid}.${token}`);
240
+ }
241
+ function entries(root, kind, probe) {
242
+ let names;
243
+ try {
244
+ names = readdirSync(root);
245
+ } catch (err) {
246
+ const code = err.code ?? "unknown";
247
+ throw new Error(
248
+ `cannot read the state directory ${displayPath(root)} (${code}); the dispatch gate needs read access to it`,
249
+ { cause: err }
250
+ );
251
+ }
252
+ const found = [];
253
+ for (const name of names) {
254
+ if (!name.startsWith(`${PREFIX}.${kind}.`)) continue;
255
+ const path = join(root, name);
256
+ let record;
257
+ try {
258
+ record = JSON.parse(readFileSync2(path, "utf-8"));
259
+ } catch {
260
+ continue;
261
+ }
262
+ if (typeof record.pid !== "number" || !Number.isFinite(record.pid)) continue;
263
+ const token = typeof record.token === "string" ? record.token : "";
264
+ const ts = typeof record.ts === "number" && Number.isFinite(record.ts) ? record.ts : 0;
265
+ const instance = typeof record.instance === "string" ? record.instance : "";
266
+ if (!participantAlive({ pid: record.pid, instance }, path, probe)) {
267
+ try {
268
+ unlinkSync(path);
269
+ } catch {
270
+ }
271
+ continue;
272
+ }
273
+ found.push({ path, pid: record.pid, token, ts, instance });
274
+ }
275
+ return found;
276
+ }
277
+ function liveTickets(root, probe) {
278
+ return entries(root, "cand", probe).sort((a, b) => a.ts - b.ts || a.pid - b.pid || a.token.localeCompare(b.token));
279
+ }
280
+ function acquire(root, token, timeoutMs, probe) {
281
+ const deadline = Date.now() + timeoutMs;
282
+ const choosing = pathFor(root, "choosing", process.pid, token);
283
+ const ticket = pathFor(root, "cand", process.pid, token);
284
+ entries(root, "cand", probe);
285
+ const instance = probeInstance(process.pid, probe);
286
+ if (!instance) {
287
+ throw new Error(
288
+ "cannot identify this process instance (no /proc and no working ps), so the dispatch gate cannot tell a dead contender from a live one; nothing was dispatched"
289
+ );
290
+ }
291
+ let held = false;
292
+ try {
293
+ publish(choosing, { pid: process.pid, token, instance });
294
+ const maxTs = liveTickets(root, probe).reduce((max, entry) => Math.max(max, entry.ts), 0);
295
+ publish(ticket, { pid: process.pid, token, ts: maxTs + 1, instance });
296
+ try {
297
+ unlinkSync(choosing);
298
+ } catch {
299
+ }
300
+ while (true) {
301
+ if (entries(root, "choosing", probe).length > 0) {
302
+ if (Date.now() > deadline) return withdraw(ticket);
303
+ sleepSync(GATE_POLL_MS);
304
+ continue;
305
+ }
306
+ const tickets = liveTickets(root, probe);
307
+ if (tickets.length === 0 || tickets[0].token === token) {
308
+ held = true;
309
+ return true;
310
+ }
311
+ if (Date.now() > deadline) return withdraw(ticket);
312
+ sleepSync(GATE_POLL_MS);
313
+ }
314
+ } catch (err) {
315
+ if (!held) {
316
+ try {
317
+ unlinkSync(choosing);
318
+ } catch {
319
+ }
320
+ try {
321
+ unlinkSync(ticket);
322
+ } catch {
323
+ }
324
+ }
325
+ throw err;
326
+ }
327
+ }
328
+ function withdraw(ticket) {
329
+ try {
330
+ unlinkSync(ticket);
331
+ } catch {
332
+ }
333
+ return false;
334
+ }
335
+ function withDispatchGate(fn, options = {}) {
336
+ const root = options.root ?? stateRoot();
337
+ mkdirSync(dirname(gateCandidatesPath(root)), { recursive: true });
338
+ const token = randomUUID();
339
+ const probe = options.instanceProbe ?? defaultProbe;
340
+ instanceCache.clear();
341
+ if (!acquire(root, token, options.timeoutMs ?? DISPATCH_GATE_TIMEOUT_MS, probe)) return { acquired: false };
342
+ try {
343
+ return { acquired: true, value: fn() };
344
+ } finally {
345
+ try {
346
+ unlinkSync(pathFor(root, "cand", process.pid, token));
347
+ } catch {
348
+ }
349
+ }
350
+ }
351
+
352
+ // src/core/plan-mark.ts
353
+ import { readFileSync as readFileSync3, statSync as statSync2, writeFileSync as writeFileSync2 } from "fs";
354
+ import { execFileSync as execFileSync2 } from "child_process";
355
+ import { join as join2, relative as relative2, isAbsolute as isAbsolute2 } from "path";
356
+ var PLAN_MARK_MESSAGE = "chore(flow): mark";
357
+ function emptyMarkOutcome() {
358
+ return { marked: [], already: [], deferred: false, failures: [], sha: null };
359
+ }
360
+ function rowFor(parsed, line, id) {
361
+ if (line === null || line < 1) return null;
362
+ const row = parsed.items.find((item) => item.line === line);
363
+ return row && row.id === id ? row : null;
364
+ }
365
+ function tickLine(line) {
366
+ const index = line.indexOf("[ ]");
367
+ return `${line.slice(0, index)}[x]${line.slice(index + 3)}`;
368
+ }
369
+ function git(repo, args) {
370
+ return String(execFileSync2("git", ["-C", repo, ...args], { encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] }));
371
+ }
372
+ function probeDocument(repo, sourcePath) {
373
+ const wanted = sourcePath.trim();
374
+ if (!wanted || isAbsolute2(wanted)) return { ok: false, reason: `the plan document ${displayPath(sourcePath)} is not inside the project` };
375
+ const target = join2(repo, wanted);
376
+ const inside = relative2(repo, target);
377
+ if (inside === "" || inside.startsWith("..") || isAbsolute2(inside)) {
378
+ return { ok: false, reason: `the plan document ${displayPath(sourcePath)} is not inside the project` };
379
+ }
380
+ try {
381
+ if (!statSync2(target).isFile()) return { ok: false, reason: `the plan document ${displayPath(sourcePath)} is not a file` };
382
+ } catch (err) {
383
+ return {
384
+ ok: false,
385
+ reason: err.code === "ENOENT" ? `the plan document ${displayPath(sourcePath)} was not found` : `the plan document ${displayPath(sourcePath)} could not be read`
386
+ };
387
+ }
388
+ const text = readDocument(target);
389
+ if (text === null) return { ok: false, reason: `the plan document ${displayPath(sourcePath)} could not be read` };
390
+ return { ok: true, path: target, text };
391
+ }
392
+ function readDocument(path) {
393
+ try {
394
+ return readFileSync3(path, "utf-8");
395
+ } catch {
396
+ return null;
397
+ }
398
+ }
399
+ function markPlanItems(options) {
400
+ const outcome = emptyMarkOutcome();
401
+ if (options.ids.length === 0) return outcome;
402
+ if (!options.tree_clean) return { ...outcome, deferred: true };
403
+ const document = probeDocument(options.repo, options.source_path);
404
+ if (!document.ok) {
405
+ return { ...outcome, failures: options.ids.map((id) => ({ id, reason: document.reason })) };
406
+ }
407
+ const target = document.path;
408
+ const raw = document.text;
409
+ let parsed;
410
+ try {
411
+ parsed = parsePlanDocument(raw);
412
+ } catch (err) {
413
+ const reason = `the plan document does not parse: ${err instanceof Error ? err.message : String(err)}`;
414
+ return { ...outcome, failures: options.ids.map((id) => ({ id, reason })) };
415
+ }
416
+ const lines = raw.split("\n");
417
+ const alreadyMarked = existingMarkIds(options.repo);
418
+ const marked = [];
419
+ for (const id of options.ids) {
420
+ if (alreadyMarked.has(id)) {
421
+ outcome.already.push(id);
422
+ continue;
423
+ }
424
+ const item = options.plan.items.find((entry) => entry.id === id);
425
+ const line = item?.line ?? null;
426
+ if (line === null || line < 1 || line > lines.length) {
427
+ outcome.failures.push({ id, reason: "no line in the document for this item" });
428
+ continue;
429
+ }
430
+ const row = rowFor(parsed, line, id);
431
+ if (!row) {
432
+ const actual = parsed.items.find((entry) => entry.line === line);
433
+ outcome.failures.push({
434
+ id,
435
+ reason: actual ? `line ${line} belongs to ${actual.id}, not to ${id}` : `line ${line} is not a plan item any more`
436
+ });
437
+ continue;
438
+ }
439
+ if (row.checked) {
440
+ outcome.already.push(id);
441
+ continue;
442
+ }
443
+ lines[line - 1] = tickLine(lines[line - 1]);
444
+ marked.push({ id, line });
445
+ }
446
+ if (marked.length === 0) return { ...outcome, marked, failures: outcome.failures };
447
+ const updated = lines.join("\n");
448
+ try {
449
+ writeFileSync2(target, updated, "utf-8");
450
+ } catch {
451
+ return { ...outcome, marked: [], failures: [...outcome.failures, ...marked.map((entry) => ({ id: entry.id, reason: "the plan document could not be written" }))] };
452
+ }
453
+ const ids = marked.map((entry) => entry.id);
454
+ const message = `${PLAN_MARK_MESSAGE} ${ids.join(", ")} done in the plan`;
455
+ try {
456
+ git(options.repo, ["add", "--", target]);
457
+ git(options.repo, ["commit", "-q", "-m", message]);
458
+ const sha = git(options.repo, ["rev-parse", "HEAD"]).trim();
459
+ return { ...outcome, marked, sha, failures: outcome.failures };
460
+ } catch (err) {
461
+ try {
462
+ writeFileSync2(target, raw, "utf-8");
463
+ } catch {
464
+ }
465
+ const reason = err instanceof Error ? err.message.split("\n")[0].trim() : String(err);
466
+ return {
467
+ ...outcome,
468
+ marked: [],
469
+ failures: [...outcome.failures, ...marked.map((entry) => ({ id: entry.id, reason: `git commit failed: ${reason}` }))]
470
+ };
471
+ }
472
+ }
473
+ function existingMarkIds(repo) {
474
+ const ids = /* @__PURE__ */ new Set();
475
+ try {
476
+ const log = git(repo, ["log", "--format=%s"]).trim();
477
+ for (const subject of log.split("\n")) {
478
+ const match = subject.match(/^chore\(flow\): mark (.+) done in the plan$/);
479
+ if (!match) continue;
480
+ for (const id of match[1].split(",")) ids.add(id.trim());
481
+ }
482
+ } catch {
483
+ }
484
+ return ids;
485
+ }
486
+ function pendingPlanMarks(plan, parsed) {
487
+ const result = { pending: [], failures: [] };
488
+ for (const item of plan.items) {
489
+ if (item.status !== "done") continue;
490
+ const row = rowFor(parsed, item.line, item.id);
491
+ if (!row) {
492
+ const actual = parsed.items.find((entry) => entry.line === item.line);
493
+ result.failures.push({
494
+ id: item.id,
495
+ reason: item.line === null ? "the document no longer lists this item" : actual ? `line ${item.line} belongs to ${actual.id}, not to ${item.id}` : `line ${item.line} is not a plan item any more`
496
+ });
497
+ continue;
498
+ }
499
+ if (!row.checked) result.pending.push(item.id);
500
+ }
501
+ return result;
502
+ }
503
+ function applyPlanMarks(runId, options) {
504
+ const attempt = options.attempt ?? "close";
505
+ let plan;
506
+ try {
507
+ if (!planExists(runId, { root: options.root })) return emptyMarkOutcome();
508
+ plan = readPlan(runId, { root: options.root });
509
+ } catch {
510
+ return emptyMarkOutcome();
511
+ }
512
+ const requested = options.ids ?? (options.closed ? [options.closed] : []);
513
+ const document = probeDocument(options.repo, plan.source_path);
514
+ let pending = { pending: [], failures: [] };
515
+ if (document.ok) {
516
+ let parsed;
517
+ try {
518
+ parsed = parsePlanDocument(document.text);
519
+ } catch (err) {
520
+ const outcome2 = {
521
+ ...emptyMarkOutcome(),
522
+ failures: [{ id: "", reason: `the plan document does not parse: ${err instanceof Error ? err.message : String(err)}` }]
523
+ };
524
+ journalPlanMarks(runId, outcome2, { root: options.root, at: options.at, attempt });
525
+ return outcome2;
526
+ }
527
+ pending = pendingPlanMarks(plan, parsed);
528
+ }
529
+ const ids = [.../* @__PURE__ */ new Set([...requested, ...pending.pending])];
530
+ if (ids.length === 0 && pending.failures.length === 0) return emptyMarkOutcome();
531
+ const marked = ids.length === 0 ? emptyMarkOutcome() : markPlanItems({ repo: options.repo, source_path: plan.source_path, ids, plan, tree_clean: options.tree_clean });
532
+ const outcome = { ...marked, failures: [...marked.failures, ...pending.failures] };
533
+ journalPlanMarks(runId, outcome, { root: options.root, at: options.at, attempt });
534
+ return outcome;
535
+ }
536
+ function journalPlanMarks(runId, outcome, options = {}) {
537
+ const at = options.at ?? (/* @__PURE__ */ new Date()).toISOString();
538
+ const attempt = options.attempt ?? "close";
539
+ const lines = [];
540
+ if (outcome.deferred && attempt === "close") lines.push({ event: "plan_mark_deferred", detail: "tree_dirty" });
541
+ for (const entry of outcome.marked) lines.push({ event: "plan_item_marked", detail: `${entry.id} ${outcome.sha ?? ""}`.trim() });
542
+ for (const failure of outcome.failures) {
543
+ lines.push({ event: "plan_mark_failed", detail: failure.id ? `${failure.id}: ${failure.reason}` : failure.reason });
544
+ }
545
+ if (lines.length === 0) return;
546
+ if (outcome.marked.length === 0 && attempt === "reconcile" && outcome.failures.length === 0) return;
547
+ let flow;
548
+ try {
549
+ flow = readFlow(runId, { root: options.root });
550
+ } catch {
551
+ return;
552
+ }
553
+ try {
554
+ withRunsLock(() => {
555
+ const current = readFlow(runId, { root: options.root });
556
+ const recorded = new Set(current.log.filter((entry) => entry.event === "plan_mark_failed").map((entry) => entry.detail));
557
+ const fresh = lines.filter((line) => !(line.event === "plan_mark_failed" && recorded.has(line.detail)));
558
+ if (fresh.length === 0) return;
559
+ const log = fresh.reduce((entries2, line) => appendLogEntries(entries2, { at, event: line.event, detail: line.detail }), current.log);
560
+ saveFlow({ ...current, log }, { root: options.root });
561
+ });
562
+ } catch {
563
+ }
564
+ for (const entry of outcome.marked) {
565
+ emitNotification({
566
+ kind: "plan.item_marked",
567
+ title: `plan item ${entry.id} marked in the document`,
568
+ detail: `${flow.repo} \xB7 ${outcome.sha ?? ""}`.trim(),
569
+ run_id: runId,
570
+ project: flow.repo.split(/[\\/]+/).filter(Boolean).at(-1)?.slice(0, 64) ?? "",
571
+ source: "product",
572
+ dedupe_key: `${flow.flow_id}:plan.item_marked:${entry.id}:${outcome.sha ?? ""}`
573
+ });
574
+ }
575
+ }
576
+
577
+ // src/core/verdict.ts
578
+ var VERDICT_SCAN_LINES = 400;
579
+ var NOTES_LIMIT = 20;
580
+ var VERDICT_PATTERN = /(?:VERDICT|ВЕРДИКТ)\s*[:\-—]?\s*(ACCEPT|CHANGES_REQUESTED)/gi;
581
+ var NOTES_PATTERN = /^(BLOCKER|MAJOR|MINOR)\b/;
582
+ function scanWindow(paneText, lines = VERDICT_SCAN_LINES) {
583
+ const all = paneText.split("\n").map((line) => line.trimEnd());
584
+ return lines > 0 ? all.slice(-lines) : all;
585
+ }
586
+ function countVerdicts(paneText, lines = VERDICT_SCAN_LINES) {
587
+ const text = scanWindow(paneText, lines).join("\n");
588
+ return text.match(VERDICT_PATTERN)?.length ?? 0;
589
+ }
590
+ function lastVerdict(paneText, lines = VERDICT_SCAN_LINES) {
591
+ const text = scanWindow(paneText, lines).join("\n");
592
+ const matches = [...text.matchAll(VERDICT_PATTERN)];
593
+ const last = matches.at(-1);
594
+ if (!last) return null;
595
+ return last[1]?.toUpperCase() === "ACCEPT" ? "ACCEPT" : "CHANGES_REQUESTED";
596
+ }
597
+ function verdictNotes(paneText, lines = VERDICT_SCAN_LINES, limit = NOTES_LIMIT) {
598
+ const notes = scanWindow(paneText, lines).map((line) => line.trim()).filter((line) => NOTES_PATTERN.test(line)).slice(-limit).join("\n");
599
+ return redactSecrets(notes);
600
+ }
601
+ function scanVerdict(paneText, lines = VERDICT_SCAN_LINES) {
602
+ return {
603
+ count: countVerdicts(paneText, lines),
604
+ last: lastVerdict(paneText, lines),
605
+ notes: verdictNotes(paneText, lines),
606
+ truncated: lines > 0 && paneText.split("\n").length > lines
607
+ };
608
+ }
609
+
610
+ // src/core/flow-runner.ts
611
+ import stripAnsi from "strip-ansi";
612
+ function withEnterRetries(state, decision, retries, at) {
613
+ if (retries === void 0 || retries <= 0) return state;
614
+ const head = decision.head ?? state.claim.head;
615
+ const spec = decision.spec_id === void 0 || decision.spec_id === null ? "" : ` \xB7 spec ${decision.spec_id}`;
616
+ let next = state;
617
+ for (let attempt = 1; attempt <= retries; attempt += 1) {
618
+ next = { ...next, log: appendLog(next, { at, event: "submit_retry", detail: `enter ${attempt} \xB7 ${head}${spec}` }) };
619
+ }
620
+ return next;
621
+ }
622
+ function ownerDecisionBlockFromPane(text) {
623
+ const ignoredTail = /^(?:\s*|›\s*|›\s*Ask Codex to do anything\s*|❯\s*|←\s*for agents\s*·\s*\?\s*for shortcuts\s*|\?\s*for shortcuts\s*|esc(?:ape)?\s+to interrupt\b.*|ctrl\+c\s+to\b.*)$/i;
624
+ const providerMeta = /^[\w.-]+(?:\s+[\w.-]+){0,3}\s+·\s+(?:~[/\\]|[/\\]|[a-z]:[/\\])/i;
625
+ const lines = stripAnsi(text).split(/\r?\n/).map((line) => line.trim());
626
+ while (lines.length > 0 && (ignoredTail.test(lines.at(-1)) || providerMeta.test(lines.at(-1)))) lines.pop();
627
+ const match = /^FLOW-BLOCKED:\s*(\S(?:.*\S)?)\s*$/i.exec(lines.at(-1) ?? "");
628
+ return match?.[1]?.slice(0, 500) ?? null;
629
+ }
630
+ var defaultFlowPorts = {
631
+ paneBusy: (agentId) => paneBusy(agentId),
632
+ peek: (agentId, lines) => peekAgentRaw(agentId, lines),
633
+ send: (agentId, text, options) => sendWhenIdle(agentId, text, {
634
+ pasted: options?.pasted ?? null,
635
+ ...options?.maxEnters === void 0 ? {} : { maxEnters: options.maxEnters },
636
+ ...options?.stallRetry ? { maxEnters: 1, refuseCopyMode: true } : {},
637
+ ...options?.maxEnters === 1 ? { refuseCopyMode: true } : {}
638
+ }),
639
+ paneDiagnosis: (agentId) => paneDiagnosis(agentId),
640
+ devNudgeReady: (agentId, text, pasted) => paneReadyForNudge(agentId, text, pasted)
641
+ };
642
+ function readGitHead(repo) {
643
+ if (!repo) return "";
644
+ try {
645
+ return execFileSync3("git", ["-C", repo, "rev-parse", "HEAD"], {
646
+ encoding: "utf-8",
647
+ stdio: ["ignore", "pipe", "ignore"]
648
+ }).trim();
649
+ } catch {
650
+ return "";
651
+ }
652
+ }
653
+ function commitTimestamp(repo, head) {
654
+ if (!repo || !isCommitId(head)) return void 0;
655
+ try {
656
+ const seconds = Number(execFileSync3("git", ["-C", repo, "show", "-s", "--format=%ct", head], {
657
+ encoding: "utf-8",
658
+ stdio: ["ignore", "pipe", "ignore"]
659
+ }).trim());
660
+ return Number.isFinite(seconds) && seconds > 0 ? seconds * 1e3 : void 0;
661
+ } catch {
662
+ return void 0;
663
+ }
664
+ }
665
+ function changedPathsBetween(repo, from, to) {
666
+ if (!repo || !isCommitId(from) || !isCommitId(to) || from === to) return [];
667
+ try {
668
+ return execFileSync3("git", ["-C", repo, "diff", "--name-only", `${from}..${to}`], {
669
+ encoding: "utf-8",
670
+ stdio: ["ignore", "pipe", "ignore"]
671
+ }).split("\n").map((line) => line.trim()).filter(Boolean);
672
+ } catch {
673
+ return null;
674
+ }
675
+ }
676
+ function documentationPaths(state) {
677
+ const paths = ["docs/briefs/"];
678
+ try {
679
+ const plan = readPlan(state.run_id);
680
+ if (plan) paths.push(plan.source_path);
681
+ } catch {
682
+ }
683
+ return paths;
684
+ }
685
+ function docsOnlySince(state, head) {
686
+ if (state.state === "done") return null;
687
+ const changed = changedPathsBetween(state.repo, state.claim.head, head);
688
+ if (changed === null) return null;
689
+ if (changed.length === 0) return false;
690
+ const docs = documentationPaths(state);
691
+ return changed.every((path) => docs.some((prefix) => path === prefix || path.startsWith(prefix)));
692
+ }
693
+ function headIsMarkCommit(state, head) {
694
+ if (headIsDocsOnly(state, head) !== true) return false;
695
+ try {
696
+ const subject = String(execFileSync3("git", ["-C", state.repo, "log", "-1", "--format=%s", head], {
697
+ encoding: "utf-8",
698
+ stdio: ["ignore", "pipe", "ignore"]
699
+ })).trim();
700
+ return subject.startsWith("chore(flow): mark ");
701
+ } catch {
702
+ return false;
703
+ }
704
+ }
705
+ function headIsDocsOnly(state, head) {
706
+ if (!head || !isCommitId(head)) return null;
707
+ try {
708
+ const listing = String(execFileSync3("git", ["-C", state.repo, "show", "--pretty=format:", "--name-only", head], {
709
+ encoding: "utf-8",
710
+ stdio: ["ignore", "pipe", "ignore"]
711
+ }));
712
+ const changed = listing.split("\n").map((line) => line.trim()).filter(Boolean);
713
+ if (changed.length === 0) return false;
714
+ const docs = documentationPaths(state);
715
+ return changed.every((path) => docs.some((prefix) => path === prefix || path.startsWith(prefix)));
716
+ } catch {
717
+ return null;
718
+ }
719
+ }
720
+ function isGitTreeClean(repo) {
721
+ if (!repo) return false;
722
+ try {
723
+ const status = execFileSync3("git", ["-C", repo, "status", "--porcelain"], {
724
+ encoding: "utf-8",
725
+ stdio: ["ignore", "pipe", "ignore"]
726
+ }).trim();
727
+ return status === "";
728
+ } catch {
729
+ return false;
730
+ }
731
+ }
732
+ function registryPresence(state) {
733
+ const presence = probeRunFile(runPath(state.run_id));
734
+ if (presence === "missing") return { run_present: false, agents_present: false };
735
+ if (presence === "unreadable") return {};
736
+ let run;
737
+ try {
738
+ run = readRun(state.run_id);
739
+ } catch {
740
+ return {};
741
+ }
742
+ if (run.status === "ended" || run.ended_at !== null) return { run_present: false, agents_present: false };
743
+ const agents = tryListAgents(run.id);
744
+ if (agents === null) return { run_present: true };
745
+ return { run_present: true, agents_present: everyAgentPresent(state, agents) };
746
+ }
747
+ function probeRunFile(path) {
748
+ try {
749
+ statSync3(path);
750
+ return "present";
751
+ } catch (err) {
752
+ return err.code === "ENOENT" ? "missing" : "unreadable";
753
+ }
754
+ }
755
+ function everyAgentPresent(state, agents) {
756
+ const live = new Set(agents.filter((agent) => agent.ended_at === null).map((agent) => agent.id));
757
+ return [state.roles.dev, state.roles.review].every((id) => id !== "" && live.has(id));
758
+ }
759
+ function unobservedFlow(now) {
760
+ return {
761
+ now,
762
+ head: "",
763
+ tree_clean: false,
764
+ dev_pane: "unknown",
765
+ review_pane: "unknown",
766
+ verdict: null,
767
+ verdict_count: 0
768
+ };
769
+ }
770
+ function reviewRound(state) {
771
+ return state.rounds + 1;
772
+ }
773
+ function readRoundNotes(state, options, observedHead) {
774
+ if (options.notes) return options.notes;
775
+ const round = reviewRound(state);
776
+ const requestHead = isCommitId(observedHead) ? observedHead.trim() : isCommitId(state.claim.head) ? state.claim.head : "";
777
+ const staging = requestHead ? stagingPath(state.run_id, requestHead, round, options.root) : void 0;
778
+ if (requestHead) ensureNotesInbox(state.run_id, options.root);
779
+ const pendingReview = state.pending?.kind === "request_review" ? state.pending : null;
780
+ const head = [pendingReview?.head, observedHead, state.claim.head].map((candidate) => typeof candidate === "string" ? candidate.trim() : "").find((candidate) => isCommitId(candidate)) ?? "";
781
+ if (!isCommitId(head)) return { source: "pane", staging_path: staging };
782
+ const stagingRead = readStaging(state.run_id, head, round, { root: options.root });
783
+ const durableRead = stagingRead.ok ? null : readDurable(state.run_id, head, round, { root: options.root });
784
+ const exact = stagingRead.ok ? stagingRead : durableRead && durableRead.ok ? durableRead : stagingRead;
785
+ const newest = exact.ok || exact.reason !== "missing" ? null : readNewestNotes(state.run_id, head, { root: options.root });
786
+ const found = stagingRead.ok ? { text: stagingRead.text, verdict: stagingRead.verdict, counts: stagingRead.counts, round, publishable: true } : durableRead?.ok ? { text: durableRead.text, verdict: durableRead.verdict, counts: durableRead.counts, round, publishable: false } : newest?.ok && newest.round !== void 0 ? {
787
+ text: newest.text ?? "",
788
+ verdict: newest.verdict,
789
+ counts: newest.counts ?? countFindings(newest.text ?? ""),
790
+ round: newest.round,
791
+ publishable: newest.source === "staging"
792
+ } : null;
793
+ if (found) {
794
+ return {
795
+ source: "file",
796
+ verdict: found.verdict,
797
+ text: findingsText(found.text),
798
+ ref: notesRef(head, found.round),
799
+ counts: found.counts,
800
+ staging_path: staging,
801
+ head,
802
+ evidence_text: found.text,
803
+ // Only a staging text is published later; a durable one is already the record.
804
+ raw: found.publishable ? found.text : void 0,
805
+ round: found.round
806
+ };
807
+ }
808
+ const exactReason = "reason" in exact ? exact.reason : void 0;
809
+ const invalid = exactReason === void 0 || exactReason === "missing" ? newest !== null && !newest.ok && newest.reason !== "missing" ? newest.reason : void 0 : exactReason;
810
+ return {
811
+ source: "pane",
812
+ staging_path: staging,
813
+ ...invalid === void 0 ? {} : { invalid }
814
+ };
815
+ }
816
+ var TOOL_LINE_PATTERN = /^(?:\s*[│|]?\s*[●◦•·]\s|\s*[│|]\s*(?:run|exec|shell|read|write|edit|grep|search)\b)|\bexec_command\b|\brun_shell\b/i;
817
+ function measureEvidence(state, observations) {
818
+ const elapsed = state.review_started_at === null ? 0 : Math.max(0, observations.now - state.review_started_at);
819
+ const findingsSource = observations.notes_text ?? observations.verdict_notes ?? "";
820
+ const paneText = observations.pane_text ?? "";
821
+ return {
822
+ elapsed_ms: elapsed,
823
+ notes_bytes: Buffer.byteLength(findingsSource, "utf-8"),
824
+ notes_findings: findingsSource ? findingsSource.split("\n").filter((line) => /^(BLOCKER|MAJOR|MINOR)\b/.test(line.trim())).length : 0,
825
+ pane_tool_lines: paneText.split("\n").filter((line) => TOOL_LINE_PATTERN.test(line)).length
826
+ };
827
+ }
828
+ function evidencePolicy() {
829
+ try {
830
+ const global = loadConfig().global;
831
+ return {
832
+ min_seconds: global.review_min_seconds ?? DEFAULT_EVIDENCE_POLICY.min_seconds,
833
+ retries: global.review_evidence_retries ?? DEFAULT_EVIDENCE_POLICY.retries
834
+ };
835
+ } catch {
836
+ return DEFAULT_EVIDENCE_POLICY;
837
+ }
838
+ }
839
+ function readPlanConflicts(state) {
840
+ try {
841
+ return planExists(state.run_id) ? readPlan(state.run_id).conflicts : [];
842
+ } catch {
843
+ return [];
844
+ }
845
+ }
846
+ function readPlanView(state) {
847
+ if (!planExists(state.run_id)) return null;
848
+ const plan = readPlan(state.run_id);
849
+ return planTickView(plan, { perItem: state.max_rounds, total: state.max_total_rounds });
850
+ }
851
+ function readCheckedPlanDocument(state) {
852
+ try {
853
+ const plan = readPlan(state.run_id);
854
+ const source = resolveRepositoryPath(plan.source_path, state.repo);
855
+ return parsePlanDocument(readFileSync4(source.absolute, "utf-8")).items.filter((item) => item.checked).map((item) => item.id);
856
+ } catch {
857
+ return void 0;
858
+ }
859
+ }
860
+ function markPlanDocument(before, observations, decision, options) {
861
+ if (!observations.plan) return;
862
+ try {
863
+ applyPlanMarks(before.run_id, {
864
+ root: options.root,
865
+ repo: before.repo,
866
+ tree_clean: observations.tree_clean,
867
+ closed: decision.next_plan_close?.id ?? null,
868
+ attempt: decision.next_plan_close ? "close" : "reconcile",
869
+ at: options.at
870
+ });
871
+ } catch {
872
+ }
873
+ }
874
+ function applyPlanDecision(before, observations, decision) {
875
+ if (!observations.plan) return;
876
+ const ownerId = before.claim.spec_id ?? before.active_plan_item;
877
+ const activeId = ownerId;
878
+ const close = decision.next_plan_close;
879
+ const status = decision.next_plan_status;
880
+ const fixRound = decision.kind === "dispatch_fix" && activeId !== null;
881
+ const started = decision.reason === "plan_item_dispatched" || decision.kind === "dispatch_spec";
882
+ const reviewStarted = decision.kind === "request_review" && activeId !== null;
883
+ const refusedClose = decision.reason === "plan_item_double_close";
884
+ if (!close && !status && !fixRound && !started && !reviewStarted && !refusedClose) return;
885
+ try {
886
+ mutatePlan(before.run_id, (current) => {
887
+ if (!current) return { plan: null, value: null };
888
+ let next = current;
889
+ if (close) {
890
+ emitNotification({
891
+ kind: "plan.item_done",
892
+ title: `plan item ${close.id} done`,
893
+ detail: `closed by ${close.head} after ${close.rounds} round${close.rounds === 1 ? "" : "s"}${close.notes_ref ? ` \xB7 notes ${close.notes_ref}` : ""}`,
894
+ run_id: before.run_id,
895
+ project: projectOfRepo(before.repo),
896
+ source: "product",
897
+ dedupe_key: `${before.flow_id}:plan.item_done:${close.id}:${close.head}`
898
+ });
899
+ next = closeItemOnAccept(next, {
900
+ id: close.id,
901
+ head: close.head,
902
+ rounds: close.rounds,
903
+ notes_ref: close.notes_ref,
904
+ now: Date.now()
905
+ });
906
+ }
907
+ if (status) {
908
+ if (status.status === "blocked_owner") {
909
+ emitNotification({
910
+ kind: "plan.item_blocked",
911
+ title: `plan item ${status.id} blocked`,
912
+ detail: status.block_reason ?? "blocked_owner",
913
+ run_id: before.run_id,
914
+ project: projectOfRepo(before.repo),
915
+ source: "product",
916
+ dedupe_key: `${before.flow_id}:plan.item_blocked:${status.id}`
917
+ });
918
+ }
919
+ next = moveItemByEngine(next, {
920
+ id: status.id,
921
+ status: status.status,
922
+ block_reason: status.block_reason ?? null,
923
+ now: Date.now()
924
+ });
925
+ }
926
+ if (decision.reason === "plan_item_double_close" && decision.log_detail) {
927
+ next = {
928
+ ...next,
929
+ conflicts: [...next.conflicts, {
930
+ kind: "plan_item_double_close",
931
+ item_id: ownerId ?? "",
932
+ detail: decision.log_detail,
933
+ at: (/* @__PURE__ */ new Date()).toISOString()
934
+ }].slice(-PLAN_LIMITS.conflicts)
935
+ };
936
+ }
937
+ if (fixRound) next = addItemRound(next, activeId, Date.now());
938
+ if (started && decision.next_active_plan_item) {
939
+ next = moveItemByEngine(next, { id: decision.next_active_plan_item, status: "in_work", now: Date.now() });
940
+ }
941
+ if (reviewStarted) {
942
+ next = moveItemByEngine(next, { id: activeId, status: "reviewing", now: Date.now() });
943
+ }
944
+ return { plan: next === current ? null : next, value: null };
945
+ });
946
+ } catch {
947
+ }
948
+ }
949
+ function emitPlanAttention(state, observations, decision) {
950
+ const plan = observations.plan;
951
+ if (!plan || decision.reason !== "plan_incomplete") return;
952
+ const detail = decision.log_detail ?? "";
953
+ const briefItem = /needs a brief for ([\w.@:-]+)/.exec(detail)?.[1];
954
+ const blockedItem = /([\w.@:-]+) is blocked_owner/.exec(detail)?.[1];
955
+ if (!briefItem && !blockedItem) return;
956
+ const item = briefItem ?? blockedItem;
957
+ const kind = briefItem ? "plan.item_needs_brief" : "plan.item_blocked";
958
+ emitNotification({
959
+ kind,
960
+ title: briefItem ? `plan item ${item} needs a brief` : `plan item ${item} is blocked`,
961
+ detail: briefItem ? "attach one with `flow plan attach`; the engine does not invent scope" : detail,
962
+ run_id: state.run_id,
963
+ project: projectOfRepo(state.repo),
964
+ source: "product",
965
+ dedupe_key: `${state.flow_id}:${kind}:${item}`
966
+ });
967
+ }
968
+ function emitFlowAttention(state, decision) {
969
+ const escalated = decision.kind === "escalate" || state.state === "escalated";
970
+ if (!escalated) return;
971
+ const reason = decision.kind === "escalate" ? decision.reason : state.log.at(-1)?.detail ?? "escalated";
972
+ const kind = reason.startsWith("review_timeout") ? "flow.review_timeout" : "flow.escalated";
973
+ const parts = state.repo.split(/[\\/]+/).filter(Boolean);
974
+ emitNotification({
975
+ kind,
976
+ title: kind === "flow.review_timeout" ? `review timed out on ${state.run_id}` : `flow escalated on ${state.run_id}`,
977
+ detail: `reason ${reason} \xB7 round ${state.rounds}/${state.max_rounds} \xB7 ${planTickSummaryOf(state)}`,
978
+ run_id: state.run_id,
979
+ project: parts.length > 0 ? parts[parts.length - 1].slice(0, 64) : "",
980
+ source: "product",
981
+ dedupe_key: `${state.flow_id}:${kind}:${state.notify_episode}`
982
+ });
983
+ }
984
+ function projectOfRepo(repo) {
985
+ const parts = repo.split(/[\\/]+/).filter(Boolean);
986
+ return parts.length > 0 ? parts[parts.length - 1].slice(0, 64) : "";
987
+ }
988
+ function planTickSummaryOf(state) {
989
+ try {
990
+ const view = readPlanView(state);
991
+ return view ? planTickSummary(view) : "no plan";
992
+ } catch {
993
+ return "plan unreadable";
994
+ }
995
+ }
996
+ var EXPLICIT_CLEAN_PATTERN = /(?:no findings|nothing to report|nothing found|замечаний нет|нет замечаний)/i;
997
+ function observations_explicit_clean(text) {
998
+ return EXPLICIT_CLEAN_PATTERN.test(text);
999
+ }
1000
+ function observeFlow(state, options = {}) {
1001
+ const ports = options.ports ?? defaultFlowPorts;
1002
+ const observedNow = options.now ?? Date.now();
1003
+ const head = options.head ?? readGitHead(state.repo);
1004
+ const headCommittedAt = options.head_committed_at ?? (state.pending && state.pending.head !== head ? commitTimestamp(state.repo, head) : void 0);
1005
+ const treeClean = options.tree_clean ?? isGitTreeClean(state.repo);
1006
+ const plan = options.plan === null ? void 0 : options.plan ?? readPlanView(state) ?? void 0;
1007
+ const planDocumentChecked = readCheckedPlanDocument(state);
1008
+ const itemId = state.claim.spec_id ?? state.active_plan_item;
1009
+ const item = itemId ? plan?.items.find((entry) => entry.id === itemId) : void 0;
1010
+ const nudgeText = itemId && item ? devStallRetryMessage(itemId, state.claim.brief_path ?? item.spec_path ?? `docs/briefs/${itemId}.md`) : void 0;
1011
+ const recordedStallPaste = state.dispatch_paste?.agent === state.roles.dev && state.dispatch_paste.head === state.claim.head && state.dispatch_paste.purpose === "dev_stall_retry" ? { at: state.dispatch_paste.at } : null;
1012
+ const devNudgeReady = state.roles.dev ? ports.devNudgeReady?.(state.roles.dev, nudgeText, recordedStallPaste) ?? false : false;
1013
+ const devPane = state.roles.dev ? ports.paneBusy(state.roles.dev) : "unknown";
1014
+ const reviewPane = state.roles.review ? ports.paneBusy(state.roles.review) : "unknown";
1015
+ const devText = devPane === "idle" ? ports.peek(state.roles.dev, VERDICT_SCAN_LINES) : "";
1016
+ const paneText = reviewPane === "unknown" ? "" : ports.peek(state.roles.review, VERDICT_SCAN_LINES);
1017
+ const scan = reviewPane === "unknown" ? { count: 0, last: null, notes: "" } : scanVerdict(paneText);
1018
+ const presence = options.run_present === void 0 || options.agents_present === void 0 ? registryPresence(state) : { run_present: options.run_present, agents_present: options.agents_present };
1019
+ const notes = readRoundNotes(state, options, head);
1020
+ let pendingDispatchDelivery;
1021
+ let pendingDispatchComposer;
1022
+ if (state.pending) {
1023
+ const agentId = state.roles[state.pending.target];
1024
+ const paneState = state.pending.target === "dev" ? devPane : reviewPane;
1025
+ if (agentId && paneState === "idle") {
1026
+ const pane = ports.peek(agentId, VERDICT_SCAN_LINES);
1027
+ const agents = tryListAgents(state.run_id);
1028
+ const provider = agents?.find((agent) => agent.id === agentId)?.provider;
1029
+ const composer = provider ? composerText(pane, provider) : null;
1030
+ if (composer !== null && provider !== void 0) {
1031
+ pendingDispatchComposer = composer;
1032
+ if (composer.trim() === "" || isComposerPlaceholder(composer, provider)) pendingDispatchDelivery = "empty";
1033
+ else {
1034
+ const paste = state.dispatch_paste;
1035
+ const isCollapsedPaste = /^\[Pasted (?:Content|text) \d+ (?:chars|lines)\]/i.test(composer.trim());
1036
+ const freshOwnedPaste = paste?.agent === agentId && paste.head === (state.pending.head ?? state.claim.head) && observedNow >= paste.at;
1037
+ pendingDispatchDelivery = isCollapsedPaste && freshOwnedPaste ? "ours" : "ambiguous";
1038
+ }
1039
+ } else pendingDispatchDelivery = "ambiguous";
1040
+ } else pendingDispatchDelivery = "ambiguous";
1041
+ }
1042
+ const devDiagnosis = devPane === "unknown" ? ports.paneDiagnosis?.(state.roles.dev) ?? null : null;
1043
+ const fromFile = notes.source === "file" && notes.text !== void 0;
1044
+ const observations = {
1045
+ now: observedNow,
1046
+ head,
1047
+ head_committed_at: headCommittedAt,
1048
+ tree_clean: treeClean,
1049
+ dev_pane: devPane,
1050
+ dev_nudge_ready: devNudgeReady,
1051
+ review_pane: reviewPane,
1052
+ // A pane the detector could not classify says why, in its own words: the hold is explained rather than merely named
1053
+ // (block 73).
1054
+ pane_diagnostics: {
1055
+ dev: devDiagnosis,
1056
+ review: reviewPane === "unknown" ? ports.paneDiagnosis?.(state.roles.review) ?? null : null
1057
+ },
1058
+ agent_question: devDiagnosis?.startsWith("agent_question:") ? devDiagnosis.slice("agent_question:".length).trim() : null,
1059
+ owner_blocked: devPane === "idle" ? ownerDecisionBlockFromPane(devText) : null,
1060
+ verdict: fromFile ? notes.verdict ?? null : scan.last,
1061
+ verdict_count: scan.count,
1062
+ verdict_notes: fromFile ? notes.text : scan.notes,
1063
+ run_present: options.run_present ?? presence.run_present,
1064
+ agents_present: options.agents_present ?? presence.agents_present,
1065
+ verdict_source: fromFile ? "file" : "pane",
1066
+ // "Nothing to report" is evidence only when the reviewer chose to say it in the record: a bare
1067
+ // ACCEPT in a pane is exactly the one-second stamp the evidence rule rejects.
1068
+ // The phrase lives in the file body, not in the finding lines: `notes.raw` is the whole staging text.
1069
+ verdict_explicit_clean: fromFile && observations_explicit_clean(notes.raw ?? notes.text ?? ""),
1070
+ // Evidence wants the file, not the filtered findings; the prompt and the journal keep the findings.
1071
+ notes_text: fromFile ? notes.evidence_text ?? notes.text : void 0,
1072
+ notes_ref: fromFile ? notes.ref : void 0,
1073
+ notes_counts: fromFile ? notes.counts : void 0,
1074
+ notes_invalid: fromFile ? void 0 : notes.invalid,
1075
+ notes_raw: fromFile ? notes.raw : void 0,
1076
+ notes_staging_path: notes.staging_path,
1077
+ notes_head: notes.head,
1078
+ notes_round: notes.round,
1079
+ pane_text: reviewPane === "unknown" ? void 0 : paneText,
1080
+ evidence_policy: options.evidence_policy ?? evidencePolicy(),
1081
+ // The plan owns the queue only when it exists: a flow without one keeps `state.specs`, which is what
1082
+ // schema-v1 flows have always used.
1083
+ plan,
1084
+ plan_conflicts: readPlanConflicts(state),
1085
+ ...planDocumentChecked === void 0 ? {} : { plan_document_checked: planDocumentChecked },
1086
+ docs_only_since_claim: options.docs_only_since_claim ?? docsOnlySince(state, head) ?? false,
1087
+ head_docs_only: options.head_docs_only ?? headIsDocsOnly(state, head) ?? false,
1088
+ head_mark_commit: options.head_mark_commit ?? headIsMarkCommit(state, head),
1089
+ ...pendingDispatchDelivery === void 0 ? {} : { pending_dispatch_delivery: pendingDispatchDelivery },
1090
+ ...pendingDispatchComposer === void 0 ? {} : { pending_dispatch_composer: pendingDispatchComposer }
1091
+ };
1092
+ if (observations.head_mark_commit === true && observations.verdict_source !== "file" && observations.verdict !== null) {
1093
+ observations.verdict = null;
1094
+ observations.verdict_notes = void 0;
1095
+ observations.verdict_count = state.claim.verdict_count;
1096
+ observations.docs_verdict_ignored = head;
1097
+ }
1098
+ observations.verdict_evidence = options.verdict_evidence ?? measureEvidence(state, observations);
1099
+ return observations;
1100
+ }
1101
+ function withStateLock(fn) {
1102
+ try {
1103
+ return { locked: false, value: withRunsLock(fn) };
1104
+ } catch (err) {
1105
+ if (isRunsLockTimeout(err)) return { locked: true };
1106
+ throw err;
1107
+ }
1108
+ }
1109
+ function isParked(state) {
1110
+ return state.state === "paused" || state.state === "orphaned";
1111
+ }
1112
+ function writeRoundCapture(state, observations, options) {
1113
+ if (state.state !== "reviewing") return;
1114
+ const head = state.claim.head;
1115
+ if (!head || !isCommitId(head) || observations.pane_text === void 0) return;
1116
+ try {
1117
+ writePaneCapture(state.run_id, head, reviewRound(state), observations.pane_text, { root: options.root });
1118
+ } catch {
1119
+ }
1120
+ }
1121
+ function publishRoundNotes(state, observations, decision, options) {
1122
+ if (state.state !== "reviewing") return;
1123
+ const head = state.claim.head;
1124
+ if (!head || !isCommitId(head)) return;
1125
+ if (observations.notes_raw === void 0) return;
1126
+ if (decision.reason === "review_unsubstantiated") return;
1127
+ try {
1128
+ publishNotesIfChanged(state.run_id, head, observations.notes_round ?? reviewRound(state), observations.notes_raw, { root: options.root });
1129
+ pruneNotes(state.run_id, { root: options.root });
1130
+ } catch {
1131
+ }
1132
+ }
1133
+ function journalDocsVerdictIgnored(runId, sha, at, options) {
1134
+ const detail = sha.slice(0, 7);
1135
+ try {
1136
+ withRunsLock(() => {
1137
+ const current = readFlow(runId, { root: options.root });
1138
+ if (current.log.some((entry) => entry.event === "docs_commit_verdict_ignored" && entry.detail === detail)) return;
1139
+ const log = appendLogEntries(current.log, { at, event: "docs_commit_verdict_ignored", detail });
1140
+ saveFlow({ ...current, log }, { root: options.root });
1141
+ });
1142
+ } catch {
1143
+ }
1144
+ }
1145
+ function pruneClosedNotes(state, options) {
1146
+ if (state.state !== "done" && state.state !== "escalated" && state.state !== "orphaned") return;
1147
+ try {
1148
+ pruneClosedFlowNotes(state.run_id, { root: options.root });
1149
+ } catch {
1150
+ }
1151
+ }
1152
+ var PANE_UNKNOWN_HOLD_MS = 12e4;
1153
+ function paneStateUnknownNote(state, decision, observations, at) {
1154
+ const pane = decision.reason === "dev_pane_unknown" ? "dev" : decision.reason === "review_pane_unknown" ? "review" : null;
1155
+ if (!pane) return null;
1156
+ const reason = observations.pane_diagnostics?.[pane];
1157
+ if (!reason) return null;
1158
+ const since = state.hold !== null && state.hold.reason === decision.reason ? Date.parse(state.hold.since) : Date.parse(at);
1159
+ const now = Date.parse(at);
1160
+ if (!Number.isFinite(since) || !Number.isFinite(now) || now - since < PANE_UNKNOWN_HOLD_MS) return null;
1161
+ const detail = `${pane}: ${reason}`;
1162
+ if (state.log.some((entry) => entry.event === "pane_state_unknown" && entry.detail === detail)) return null;
1163
+ return { at, event: "pane_state_unknown", detail };
1164
+ }
1165
+ function holdOfDecision(state, decision, at) {
1166
+ if (decision.kind !== "none") return null;
1167
+ const same = state.hold !== null && state.hold.reason === decision.reason && (state.hold.detail ?? null) === (decision.log_detail ?? null);
1168
+ return {
1169
+ reason: decision.reason,
1170
+ since: same && state.hold ? state.hold.since : at,
1171
+ ...decision.log_detail ? { detail: decision.log_detail } : {}
1172
+ };
1173
+ }
1174
+ function sameHold(current, next) {
1175
+ if (current === null || next === null) return current === next;
1176
+ return current.reason === next.reason && (current.detail ?? null) === (next.detail ?? null);
1177
+ }
1178
+ function stepFlow(runId, options = {}) {
1179
+ const ports = options.ports ?? defaultFlowPorts;
1180
+ const at = options.at ?? (/* @__PURE__ */ new Date()).toISOString();
1181
+ const now = options.now ?? Date.now();
1182
+ if (options.dryRun === true) {
1183
+ const state = readFlow(runId, { root: options.root });
1184
+ const observations2 = isParked(state) ? unobservedFlow(now) : observeFlow(state, options);
1185
+ return { observations: observations2, decision: flowTick(state, observations2), status: "skipped", state };
1186
+ }
1187
+ const before = readFlow(runId, { root: options.root });
1188
+ const observations = isParked(before) ? unobservedFlow(now) : observeFlow(before, options);
1189
+ if (!isParked(before)) {
1190
+ if (observations.docs_verdict_ignored !== void 0) journalDocsVerdictIgnored(runId, observations.docs_verdict_ignored, at, options);
1191
+ writeRoundCapture(before, observations, options);
1192
+ pruneClosedNotes(before, options);
1193
+ }
1194
+ const claim = withStateLock(() => {
1195
+ const state = readFlow(runId, { root: options.root });
1196
+ const decision = flowTick(state, observations);
1197
+ if (!decisionChangesState(state, decision)) {
1198
+ const nextHold = holdOfDecision(state, decision, at);
1199
+ const lastHold = [...state.log].reverse().find((entry) => entry.event === "hold");
1200
+ const journalled = lastHold?.detail === decision.reason;
1201
+ const repeated = sameHold(state.hold, nextHold);
1202
+ const paneNote = paneStateUnknownNote(state, decision, observations, at);
1203
+ if (repeated && journalled && !paneNote) {
1204
+ return { state, decision, dispatch: null, settled: null };
1205
+ }
1206
+ const noted = decision.log_detail && !repeated ? applyDecisionToState(state, decision, at) : state;
1207
+ const withHold = !repeated || !journalled ? appendLog(noted, { at, event: "hold", detail: decision.reason }) : noted.log;
1208
+ const log = paneNote === null ? withHold : [...withHold, paneNote].slice(-FLOW_LOG_LIMIT);
1209
+ const held = { ...noted, hold: nextHold, log, updated_at: state.updated_at };
1210
+ return {
1211
+ state,
1212
+ decision,
1213
+ dispatch: null,
1214
+ // A detailed hold has always been applied (it writes the sentence into the journal); a silent one only becomes
1215
+ // visible now, and stays a hold the driver does not count as a move.
1216
+ settled: {
1217
+ state: held,
1218
+ path: saveFlow(held, { root: options.root }),
1219
+ status: decision.log_detail ? "applied" : "skipped"
1220
+ }
1221
+ };
1222
+ }
1223
+ const { message, target } = decision;
1224
+ if (!message || !target) {
1225
+ const next = applyDecisionToState(state, decision, at);
1226
+ applyPlanDecision(state, observations, decision);
1227
+ const path = saveFlow(next, { root: options.root });
1228
+ return { state, decision, dispatch: null, settled: { state: next, path } };
1229
+ }
1230
+ const opId = randomUUID2();
1231
+ const claimed = claimPendingDispatch(state, decision, { op_id: opId, now, at });
1232
+ return {
1233
+ state,
1234
+ decision,
1235
+ dispatch: {
1236
+ op_id: opId,
1237
+ agent: state.roles[target],
1238
+ message,
1239
+ state: claimed,
1240
+ path: saveFlow(claimed, { root: options.root })
1241
+ },
1242
+ settled: null
1243
+ };
1244
+ });
1245
+ if (claim.locked) {
1246
+ return { observations, decision: flowTick(before, observations), status: "locked", state: before };
1247
+ }
1248
+ const phase = claim.value;
1249
+ const { dispatch } = phase;
1250
+ if (!dispatch) {
1251
+ applyPlanDecision(before, observations, phase.decision);
1252
+ markPlanDocument(before, observations, phase.decision, options);
1253
+ emitFlowAttention(phase.settled?.state ?? before, phase.decision);
1254
+ emitPlanAttention(before, observations, phase.decision);
1255
+ if (phase.settled && phase.settled.status !== "skipped") {
1256
+ publishRoundNotes(before, observations, phase.decision, options);
1257
+ pruneClosedNotes(phase.settled.state, options);
1258
+ }
1259
+ const settledState = phase.settled?.state ?? phase.state;
1260
+ const incidentState2 = reconcileFlowIncidents(
1261
+ settledState,
1262
+ isParked(before) ? void 0 : observations,
1263
+ isParked(before) ? void 0 : phase.decision,
1264
+ { root: options.root, now, at }
1265
+ );
1266
+ return {
1267
+ observations,
1268
+ decision: phase.decision,
1269
+ status: phase.settled?.status ?? (phase.settled ? "applied" : "skipped"),
1270
+ state: incidentState2,
1271
+ path: phase.settled?.path
1272
+ };
1273
+ }
1274
+ options.onClaimed?.(dispatch.state);
1275
+ const act = withDispatchGate(() => {
1276
+ const current = readFlow(runId, { root: options.root });
1277
+ if (current.pending?.op_id !== dispatch.op_id) return { kind: "cancelled", state: current };
1278
+ if (current.state === "paused" || current.state === "orphaned" || current.state === "done") {
1279
+ const released = releaseDispatch(current, `flow is ${current.state}`, at);
1280
+ return { kind: "cancelled", state: released, path: saveFlow(released, { root: options.root }) };
1281
+ }
1282
+ const paste = dispatch.state.dispatch_paste;
1283
+ const send = ports.send(dispatch.agent, dispatch.message, {
1284
+ pasted: paste !== null && paste.agent === dispatch.agent && paste.head === (phase.decision.head ?? dispatch.state.claim.head) ? { at: paste.at } : null,
1285
+ ...phase.decision.kind === "dispatch_stall_retry" ? { stallRetry: true } : {},
1286
+ ...phase.decision.log_event === "dispatch_retry_enter" ? { maxEnters: 1 } : {}
1287
+ });
1288
+ const settle = withStateLock(() => {
1289
+ const settledState = readFlow(runId, { root: options.root });
1290
+ if (settledState.pending?.op_id !== dispatch.op_id) return { state: settledState, status: "skipped" };
1291
+ const after = withEnterRetries(settledState, phase.decision, send.enter_retries, at);
1292
+ if (send.sent) {
1293
+ const next = applyDecisionToState(after, phase.decision, at);
1294
+ const path = saveFlow(next, { root: options.root });
1295
+ return { state: next, status: "applied", path };
1296
+ }
1297
+ if (phase.decision.kind === "dispatch_spec" && phase.decision.spec_id && after.specs.some((spec) => spec.id === phase.decision.spec_id)) {
1298
+ const pasted = send.pastedAt === void 0 ? null : {
1299
+ agent: dispatch.agent,
1300
+ head: phase.decision.head ?? dispatch.state.claim.head,
1301
+ at: send.pastedAt
1302
+ };
1303
+ const retry = retrySpecDispatch(after, phase.decision, send.reason, pasted, at);
1304
+ return {
1305
+ state: retry.state,
1306
+ status: retry.escalated ? "unconfirmed" : "refused",
1307
+ path: saveFlow(retry.state, { root: options.root })
1308
+ };
1309
+ }
1310
+ if (send.reason === "composer_dirty") {
1311
+ const escalated = escalateOnDirtyComposer(after, {
1312
+ ...phase.decision,
1313
+ // A raced dirty composer means no retry was submitted; preserve the old timer and count.
1314
+ next_dev_stall_attempts: void 0,
1315
+ next_stalled_since: void 0
1316
+ }, at);
1317
+ return { state: escalated, status: "unconfirmed", path: saveFlow(escalated, { root: options.root }) };
1318
+ }
1319
+ if (send.reason === "pane_changed") {
1320
+ const released2 = releaseDispatch(after, send.reason, at);
1321
+ return { state: released2, status: "refused", path: saveFlow(released2, { root: options.root }) };
1322
+ }
1323
+ if (send.reason === "unconfirmed_paste") {
1324
+ const pasted = send.pastedAt === void 0 ? null : {
1325
+ agent: dispatch.agent,
1326
+ head: phase.decision.head ?? dispatch.state.claim.head,
1327
+ at: send.pastedAt,
1328
+ ...phase.decision.kind === "dispatch_stall_retry" ? { purpose: "dev_stall_retry" } : {}
1329
+ };
1330
+ if (after.enter_retries >= MAX_ENTER_RETRIES) {
1331
+ const escalated = escalateUnconfirmedDispatch(after, phase.decision, at);
1332
+ return { state: escalated, status: "unconfirmed", path: saveFlow(escalated, { root: options.root }) };
1333
+ }
1334
+ const retried = retryEnterDispatch(after, send.reason, pasted, at);
1335
+ return { state: retried, status: "refused", path: saveFlow(retried, { root: options.root }) };
1336
+ }
1337
+ if (send.reason === "unconfirmed") {
1338
+ const stuck = applyUnconfirmedDispatch(after, phase.decision, send.reason, at);
1339
+ return { state: stuck, status: "unconfirmed", path: saveFlow(stuck, { root: options.root }) };
1340
+ }
1341
+ const released = releaseDispatch(after, send.reason, at);
1342
+ return { state: released, status: "refused", path: saveFlow(released, { root: options.root }) };
1343
+ });
1344
+ if (settle.locked) return { kind: "settle-locked", send, state: dispatch.state, path: dispatch.path };
1345
+ return {
1346
+ kind: "settled",
1347
+ send,
1348
+ status: settle.value.status,
1349
+ state: settle.value.state,
1350
+ path: settle.value.path ?? dispatch.path
1351
+ };
1352
+ }, { root: options.root, timeoutMs: options.gate_timeout_ms });
1353
+ if (!act.acquired) {
1354
+ const freed = withStateLock(() => {
1355
+ const current = readFlow(runId, { root: options.root });
1356
+ if (current.pending?.op_id !== dispatch.op_id) return { state: current, status: "locked" };
1357
+ const released = releaseDispatch(current, "dispatch gate busy", at);
1358
+ return { state: released, status: "locked", path: saveFlow(released, { root: options.root }) };
1359
+ });
1360
+ return {
1361
+ observations,
1362
+ decision: phase.decision,
1363
+ status: "locked",
1364
+ state: freed.locked ? dispatch.state : freed.value.state,
1365
+ path: freed.locked ? dispatch.path : freed.value.path
1366
+ };
1367
+ }
1368
+ const done = act.value;
1369
+ if (done.kind === "cancelled") {
1370
+ return { observations, decision: phase.decision, status: "cancelled", state: done.state, path: done.path };
1371
+ }
1372
+ if (done.kind === "settle-locked") {
1373
+ return {
1374
+ observations,
1375
+ decision: phase.decision,
1376
+ status: "unconfirmed",
1377
+ send: done.send,
1378
+ state: done.state,
1379
+ path: done.path
1380
+ };
1381
+ }
1382
+ if (done.status === "applied") {
1383
+ applyPlanDecision(before, observations, phase.decision);
1384
+ markPlanDocument(before, observations, phase.decision, options);
1385
+ }
1386
+ emitFlowAttention(done.state, phase.decision);
1387
+ emitPlanAttention(before, observations, phase.decision);
1388
+ if (done.status === "applied") publishRoundNotes(before, observations, phase.decision, options);
1389
+ pruneClosedNotes(done.state, options);
1390
+ const incidentState = reconcileFlowIncidents(done.state, observations, phase.decision, { root: options.root, now, at });
1391
+ return {
1392
+ observations,
1393
+ decision: phase.decision,
1394
+ status: done.status,
1395
+ send: done.send,
1396
+ state: incidentState,
1397
+ path: done.path
1398
+ };
1399
+ }
1400
+
1401
+ // src/core/flow-control.ts
1402
+ var FlowRefusalError = class extends FlowStateError {
1403
+ code;
1404
+ constructor(code, message) {
1405
+ super(`${code}: ${message}`);
1406
+ this.name = "FlowRefusalError";
1407
+ this.code = code;
1408
+ }
1409
+ };
1410
+ function transition(runId, options, fn) {
1411
+ try {
1412
+ const gated = withDispatchGate(
1413
+ () => withRunsLock(() => {
1414
+ const next = fn(readFlow(runId, { root: options.root }));
1415
+ return { state: next, path: saveFlow(next, { root: options.root }) };
1416
+ }),
1417
+ { root: options.root, timeoutMs: options.gate_timeout_ms }
1418
+ );
1419
+ if (!gated.acquired) {
1420
+ throw new FlowStateError("a dispatch is in flight; nothing was changed \u2014 try again in a moment");
1421
+ }
1422
+ return gated.value;
1423
+ } catch (err) {
1424
+ if (isRunsLockTimeout(err)) {
1425
+ throw new FlowStateError("another reevesagents process is writing the state directory; try again");
1426
+ }
1427
+ throw err;
1428
+ }
1429
+ }
1430
+ function pauseFlow(runId, options = {}) {
1431
+ const at = options.at ?? (/* @__PURE__ */ new Date()).toISOString();
1432
+ const now = options.now ?? Date.now();
1433
+ return transition(runId, options, (state) => {
1434
+ if (state.state === "paused") {
1435
+ throw new FlowStateError(`flow for run ${state.run_id} is already paused; \`flow resume\` puts it back to work`);
1436
+ }
1437
+ return applyOperatorTransition(state, {
1438
+ to: "paused",
1439
+ action: "pause",
1440
+ event: "flow_paused",
1441
+ detail: `from ${state.state}${state.pending ? ", dropped an unsettled dispatch" : ""}`,
1442
+ at,
1443
+ patch: { paused_from: state.state, paused_at: Math.floor(now) }
1444
+ });
1445
+ });
1446
+ }
1447
+ function resumeFlow(runId, options = {}) {
1448
+ const at = options.at ?? (/* @__PURE__ */ new Date()).toISOString();
1449
+ return transition(runId, options, (state) => {
1450
+ if (state.state === "paused") {
1451
+ const target = state.paused_from ?? "idle";
1452
+ if (!canTransition("paused", target)) {
1453
+ throw new FlowStateError(`flow for run ${state.run_id} cannot resume into state ${target}`);
1454
+ }
1455
+ return applyOperatorTransition(state, {
1456
+ to: target,
1457
+ action: "resume",
1458
+ event: "flow_resumed",
1459
+ detail: `from paused to ${target}`,
1460
+ at,
1461
+ patch: { paused_from: null, paused_at: null, ...anchorOnHead(state) }
1462
+ });
1463
+ }
1464
+ if (state.state === "escalated") {
1465
+ return applyOperatorTransition(state, {
1466
+ to: "idle",
1467
+ action: "resume",
1468
+ event: "flow_resumed",
1469
+ detail: `from escalated to idle, rounds reset from ${state.rounds}`,
1470
+ at,
1471
+ patch: { rounds: 0, ...anchorOnHead(state) }
1472
+ });
1473
+ }
1474
+ throw new FlowStateError(
1475
+ `cannot resume a flow in state ${state.state} (only a paused or escalated flow can be resumed)`
1476
+ );
1477
+ });
1478
+ }
1479
+ function releaseRound(runId, options = {}) {
1480
+ const reason = options.reason?.trim();
1481
+ if (!reason) throw new FlowStateError('a release needs a reason: pass --reason "<why the round was lost>"');
1482
+ const before = readFlow(runId, { root: options.root });
1483
+ const item = before.active_plan_item ?? before.claim.spec_id;
1484
+ if (!item) throw new FlowStateError(`flow for run ${before.run_id} has no plan item in flight; there is no round to release`);
1485
+ if (roundIsLive(before)) {
1486
+ throw new FlowStateError(
1487
+ `flow for run ${before.run_id} has a live round on ${item} (a review was requested); wait for the verdict, or stop the flow`
1488
+ );
1489
+ }
1490
+ if (before.state !== "paused") {
1491
+ throw new FlowStateError(`flow for run ${before.run_id} is ${before.state}; pause it first, then release the round`);
1492
+ }
1493
+ try {
1494
+ mutatePlan(runId, (plan) => {
1495
+ const row = plan?.items.find((entry) => entry.id === item);
1496
+ if (!plan || !row || row.status !== "in_work" && row.status !== "reviewing") return { plan: null, value: null };
1497
+ const moved = setItemStatus(plan, {
1498
+ id: item,
1499
+ status: "queued",
1500
+ now: options.now ?? Date.now(),
1501
+ at: options.at,
1502
+ intervention: { paused: true, round_live: false }
1503
+ });
1504
+ return { plan: moved.plan, value: null };
1505
+ }, { root: options.root });
1506
+ } catch {
1507
+ }
1508
+ const result = transition(runId, options, (state) => {
1509
+ if (state.active_plan_item !== item && state.claim.spec_id !== item) {
1510
+ throw new FlowStateError(`the round on ${item} changed while it was being released; run it again`);
1511
+ }
1512
+ const at = options.at ?? (/* @__PURE__ */ new Date()).toISOString();
1513
+ return {
1514
+ ...state,
1515
+ active_plan_item: null,
1516
+ review_started_at: null,
1517
+ pending: null,
1518
+ updated_at: at,
1519
+ log: [...state.log, {
1520
+ at,
1521
+ event: "round_released",
1522
+ detail: `${item}: ${reason}`
1523
+ }].slice(-FLOW_LOG_LIMIT)
1524
+ };
1525
+ });
1526
+ return { ...result, item };
1527
+ }
1528
+ function roundIsLive(state) {
1529
+ return state.review_started_at !== null || state.pending !== null;
1530
+ }
1531
+ function stopFlow(runId, options = {}) {
1532
+ const at = options.at ?? (/* @__PURE__ */ new Date()).toISOString();
1533
+ return transition(runId, options, (state) => {
1534
+ if (state.state === "done") {
1535
+ throw new FlowStateError(`flow for run ${state.run_id} is already closed (${state.close_reason ?? "done"})`);
1536
+ }
1537
+ const stopped = applyOperatorTransition(state, {
1538
+ to: "done",
1539
+ action: "stop",
1540
+ event: "flow_stopped",
1541
+ detail: `from ${state.state}${state.pending ? ", dropped an unsettled dispatch" : ""}`,
1542
+ at,
1543
+ patch: { close_reason: "stopped by the operator" }
1544
+ });
1545
+ try {
1546
+ pruneClosedFlowNotes(state.run_id, { root: options.root });
1547
+ } catch {
1548
+ }
1549
+ return stopped;
1550
+ });
1551
+ }
1552
+ function planItemIds(runId) {
1553
+ try {
1554
+ if (!planExists(runId)) return null;
1555
+ return readPlan(runId).items.map((item) => item.id);
1556
+ } catch {
1557
+ return null;
1558
+ }
1559
+ }
1560
+ function addFlowSpecs(input, options = {}) {
1561
+ const at = options.at ?? (/* @__PURE__ */ new Date()).toISOString();
1562
+ const files = input.files ?? [];
1563
+ const markdown = input.markdown ?? [];
1564
+ if (files.length === 0 && markdown.length === 0) {
1565
+ throw new FlowStateError("pass at least one --file or --markdown");
1566
+ }
1567
+ const before = readFlow(input.run_id, { root: options.root });
1568
+ refuseClosed(before);
1569
+ const queued = [];
1570
+ const ids = [...before.specs.map((spec) => spec.id), ...before.dispatched_specs];
1571
+ for (const [paths, asMarkdown] of [[files, false], [markdown, true]]) {
1572
+ for (const path of paths) {
1573
+ const spec = readSpecFile(path, { repo: before.repo, existingIds: ids, asMarkdown });
1574
+ queued.push(spec);
1575
+ ids.push(spec.id);
1576
+ }
1577
+ }
1578
+ return {
1579
+ ...transition(input.run_id, options, (state) => {
1580
+ refuseClosed(state);
1581
+ const taken = queued.filter((spec) => state.specs.some((entry) => entry.id === spec.id) || state.dispatched_specs.includes(spec.id));
1582
+ if (taken.length > 0) {
1583
+ throw new FlowStateError(`block ${taken.map((spec) => spec.id).join(", ")} was queued by another call meanwhile`);
1584
+ }
1585
+ const offPlan = planItemIds(state.run_id);
1586
+ const strays = offPlan === null ? [] : queued.map((spec) => spec.id).filter((id) => !offPlan.includes(id));
1587
+ return {
1588
+ ...state,
1589
+ specs: [...state.specs, ...queued],
1590
+ log: [
1591
+ ...state.log,
1592
+ { at, event: "spec_queued", detail: queued.map((spec) => spec.id).join(", ") },
1593
+ ...strays.length > 0 ? [{ at, event: "off_plan_spec", detail: `${strays.join(", ")} \u2014 queued outside the plan` }] : []
1594
+ ].slice(-FLOW_LOG_LIMIT),
1595
+ updated_at: at
1596
+ };
1597
+ }),
1598
+ queued
1599
+ };
1600
+ }
1601
+ function mayDropUnconfirmedSpec(state, id) {
1602
+ if (!state.specs.some((spec) => spec.id === id) || state.pending !== null || state.claim.spec_id !== id || state.state !== "idle" || state.review_started_at !== null) return false;
1603
+ let unconfirmed = false;
1604
+ for (const entry of [...state.log].reverse()) {
1605
+ if (entry.event === "dispatch_unconfirmed" && entry.detail.includes(`spec_dispatched ${id}`)) {
1606
+ unconfirmed = true;
1607
+ break;
1608
+ }
1609
+ if ((entry.event === "dispatch_spec" || entry.event === "plan_item_dispatched") && entry.detail.includes(id)) return false;
1610
+ if (entry.event === "request_review" || entry.event === "dispatch_fix") return false;
1611
+ }
1612
+ return unconfirmed;
1613
+ }
1614
+ function dropFlowSpec(input, options = {}) {
1615
+ const at = options.at ?? (/* @__PURE__ */ new Date()).toISOString();
1616
+ const id = input.id.trim();
1617
+ const reason = input.reason?.trim();
1618
+ const removed = { spec: null };
1619
+ const result = transition(input.run_id, options, (state) => {
1620
+ if (state.state === "done") {
1621
+ throw new FlowRefusalError("flow_closed", `flow for run ${state.run_id} is closed (${state.close_reason ?? "done"}); its queue cannot be changed`);
1622
+ }
1623
+ const unconfirmed = mayDropUnconfirmedSpec(state, id);
1624
+ if (state.dispatched_specs.includes(id) && !unconfirmed) {
1625
+ throw new FlowRefusalError("already_dispatched", `block ${id} was already sent to the dev; a dispatched block cannot be dropped`);
1626
+ }
1627
+ const queued = state.specs.find((spec) => spec.id === id);
1628
+ if (!id || !queued) {
1629
+ const waiting = state.specs.filter((spec) => !state.dispatched_specs.includes(spec.id)).map((spec) => spec.id);
1630
+ throw new FlowRefusalError("not_found", `no block ${id || "(none)"} queued on flow for run ${state.run_id}${waiting.length > 0 ? `; waiting: ${waiting.join(", ")}` : "; its queue is empty"}`);
1631
+ }
1632
+ if (state.pending) {
1633
+ throw new FlowRefusalError("dispatch_pending", `a ${state.pending.kind} dispatch to ${state.pending.target} is in flight; nothing was dropped \u2014 try again in a moment`);
1634
+ }
1635
+ removed.spec = queued;
1636
+ return {
1637
+ ...state,
1638
+ specs: state.specs.filter((spec) => spec.id !== id),
1639
+ ...unconfirmed ? { dispatched_specs: state.dispatched_specs.filter((specId) => specId !== id) } : {},
1640
+ log: [
1641
+ ...state.log,
1642
+ // The id, plus the reason when a human gave one: never a brief body (§11.3).
1643
+ { at, event: "spec_dropped", detail: reason ? `${id}: ${reason}` : id }
1644
+ ].slice(-FLOW_LOG_LIMIT),
1645
+ updated_at: at
1646
+ };
1647
+ });
1648
+ return { ...result, spec: removed.spec };
1649
+ }
1650
+ function anchorHead(state) {
1651
+ const current = readGitHead(state.repo) || state.claim.head;
1652
+ if (!state.claim.head) return current;
1653
+ return docsOnlySince(state, current) === true ? current : state.claim.head;
1654
+ }
1655
+ function boundItemOpen(state) {
1656
+ const id = state.claim.spec_id;
1657
+ if (!id) return false;
1658
+ try {
1659
+ const plan = readPlan(state.run_id);
1660
+ return plan.items.some((item) => item.id === id && item.status !== "done" && item.status !== "skipped");
1661
+ } catch {
1662
+ return true;
1663
+ }
1664
+ }
1665
+ function anchorOnHead(state) {
1666
+ const owed = state.claim.verdict !== null && (!state.claim.verdict_applied || boundItemOpen(state));
1667
+ const head = owed ? state.claim.head : anchorHead(state);
1668
+ return {
1669
+ claim: owed ? { ...state.claim, head } : { head, verdict: null, verdict_count: state.claim.verdict_count, verdict_applied: false, spec_id: null },
1670
+ verdict_handled_for: null
1671
+ };
1672
+ }
1673
+ function refuseClosed(state) {
1674
+ if (state.state !== "done" && state.state !== "escalated" && state.state !== "orphaned") return;
1675
+ const why = state.close_reason ?? state.orphan_reason ?? "closed";
1676
+ throw new FlowStateError(
1677
+ `flow for run ${state.run_id} is ${state.state}; a block queued there would never be dispatched (${why})`
1678
+ );
1679
+ }
1680
+
1681
+ export {
1682
+ readSpecFile,
1683
+ queueSpecFile,
1684
+ applyPlanMarks,
1685
+ readGitHead,
1686
+ headIsDocsOnly,
1687
+ isGitTreeClean,
1688
+ stepFlow,
1689
+ pauseFlow,
1690
+ resumeFlow,
1691
+ releaseRound,
1692
+ roundIsLive,
1693
+ stopFlow,
1694
+ addFlowSpecs,
1695
+ dropFlowSpec
1696
+ };
1697
+ //# sourceMappingURL=chunk-PVYM35RS.js.map