@rasensio/aidlc 2.22.0 → 2.24.0

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.
Files changed (90) hide show
  1. package/dist/autopilot/answers.d.ts +2 -0
  2. package/dist/autopilot/answers.d.ts.map +1 -1
  3. package/dist/autopilot/answers.js +11 -5
  4. package/dist/autopilot/answers.js.map +1 -1
  5. package/dist/autopilot/check.d.ts +135 -0
  6. package/dist/autopilot/check.d.ts.map +1 -0
  7. package/dist/autopilot/check.js +220 -0
  8. package/dist/autopilot/check.js.map +1 -0
  9. package/dist/autopilot/decisions.d.ts +10 -1
  10. package/dist/autopilot/decisions.d.ts.map +1 -1
  11. package/dist/autopilot/decisions.js +16 -2
  12. package/dist/autopilot/decisions.js.map +1 -1
  13. package/dist/autopilot/driver.d.ts +20 -1
  14. package/dist/autopilot/driver.d.ts.map +1 -1
  15. package/dist/autopilot/driver.js +754 -42
  16. package/dist/autopilot/driver.js.map +1 -1
  17. package/dist/autopilot/gitlab.d.ts +6 -0
  18. package/dist/autopilot/gitlab.d.ts.map +1 -1
  19. package/dist/autopilot/gitlab.js +8 -0
  20. package/dist/autopilot/gitlab.js.map +1 -1
  21. package/dist/autopilot/main-home.d.ts +23 -0
  22. package/dist/autopilot/main-home.d.ts.map +1 -0
  23. package/dist/autopilot/main-home.js +45 -0
  24. package/dist/autopilot/main-home.js.map +1 -0
  25. package/dist/autopilot/open-decisions.d.ts +7 -0
  26. package/dist/autopilot/open-decisions.d.ts.map +1 -1
  27. package/dist/autopilot/open-decisions.js +101 -1
  28. package/dist/autopilot/open-decisions.js.map +1 -1
  29. package/dist/autopilot/pause.d.ts.map +1 -1
  30. package/dist/autopilot/pause.js +3 -4
  31. package/dist/autopilot/pause.js.map +1 -1
  32. package/dist/autopilot/pending.d.ts +14 -0
  33. package/dist/autopilot/pending.d.ts.map +1 -1
  34. package/dist/autopilot/pending.js +57 -7
  35. package/dist/autopilot/pending.js.map +1 -1
  36. package/dist/autopilot/presets.d.ts +4 -0
  37. package/dist/autopilot/presets.d.ts.map +1 -1
  38. package/dist/autopilot/presets.js +5 -0
  39. package/dist/autopilot/presets.js.map +1 -1
  40. package/dist/autopilot/proposal.d.ts +4 -2
  41. package/dist/autopilot/proposal.d.ts.map +1 -1
  42. package/dist/autopilot/proposal.js +9 -4
  43. package/dist/autopilot/proposal.js.map +1 -1
  44. package/dist/autopilot/result.d.ts +12 -3
  45. package/dist/autopilot/result.d.ts.map +1 -1
  46. package/dist/autopilot/result.js +11 -4
  47. package/dist/autopilot/result.js.map +1 -1
  48. package/dist/autopilot/retro.d.ts +79 -0
  49. package/dist/autopilot/retro.d.ts.map +1 -0
  50. package/dist/autopilot/retro.js +93 -0
  51. package/dist/autopilot/retro.js.map +1 -0
  52. package/dist/autopilot/review.d.ts +7 -0
  53. package/dist/autopilot/review.d.ts.map +1 -1
  54. package/dist/autopilot/review.js +46 -11
  55. package/dist/autopilot/review.js.map +1 -1
  56. package/dist/autopilot/run.d.ts.map +1 -1
  57. package/dist/autopilot/run.js +28 -0
  58. package/dist/autopilot/run.js.map +1 -1
  59. package/dist/autopilot/state.d.ts +62 -2
  60. package/dist/autopilot/state.d.ts.map +1 -1
  61. package/dist/autopilot/state.js +20 -0
  62. package/dist/autopilot/state.js.map +1 -1
  63. package/dist/autopilot/stops.d.ts +4 -3
  64. package/dist/autopilot/stops.d.ts.map +1 -1
  65. package/dist/autopilot/stops.js +5 -3
  66. package/dist/autopilot/stops.js.map +1 -1
  67. package/dist/autopilot/typed.d.ts +10 -0
  68. package/dist/autopilot/typed.d.ts.map +1 -1
  69. package/dist/autopilot/typed.js +3 -1
  70. package/dist/autopilot/typed.js.map +1 -1
  71. package/dist/autopilot/watch-view.d.ts.map +1 -1
  72. package/dist/autopilot/watch-view.js +5 -2
  73. package/dist/autopilot/watch-view.js.map +1 -1
  74. package/dist/commands/autopilot.d.ts.map +1 -1
  75. package/dist/commands/autopilot.js +4 -2
  76. package/dist/commands/autopilot.js.map +1 -1
  77. package/dist/commands/cost.d.ts.map +1 -1
  78. package/dist/commands/cost.js +4 -0
  79. package/dist/commands/cost.js.map +1 -1
  80. package/dist/console/operator/panels.js +1 -1
  81. package/dist/console/operator/panels.js.map +1 -1
  82. package/dist/cost/recorder.d.ts +15 -0
  83. package/dist/cost/recorder.d.ts.map +1 -1
  84. package/dist/cost/recorder.js +27 -1
  85. package/dist/cost/recorder.js.map +1 -1
  86. package/dist/cost/sync.d.ts +5 -0
  87. package/dist/cost/sync.d.ts.map +1 -1
  88. package/dist/cost/sync.js +5 -2
  89. package/dist/cost/sync.js.map +1 -1
  90. package/package.json +2 -2
@@ -20,9 +20,12 @@ import { mapUnits } from '../cost/providers/codex.js';
20
20
  import { microToUsd, priceUnits } from '../cost/rates.js';
21
21
  import { MODEL_ID_RE } from '../cost/types.js';
22
22
  import { hostFromConfigText } from '../core/host.js';
23
+ import { DIFF_MAX, DIFF_PATHSPEC, VERDICT_SCHEMA, changedSince, checkerPrompt, fingerprint, parseVerdict, readCriteria, rejectPrompt, renderVerdict, } from './check.js';
23
24
  import { classify, jobRef, parseRunJobs } from './ci-jobs.js';
24
- import { GLAB_READ_RE, TAG_PIPELINES_ARGS, classifyJobs, jobsArgs, mergeArgs, mergedAnswer, mrCreateArgs, mrNumber, mrViewArgs, parseJobs, parseMr, releaseInFlight, retryArgs, } from './gitlab.js';
25
- import { REASON_MAX, RESET_WAIT_MAX_MS, codexEnd, emptyCodexProgress, firstLine, readClaudeResult, readCodexEvents, refusalSuffix, resetAt, stoppedBy, summaryLines, } from './result.js';
25
+ import { GLAB_READ_RE, TAG_PIPELINES_ARGS, classifyJobs, jobsArgs, mergeArgs, mergedAnswer, mrCreateArgs, mrNumber, mrViewArgs, noteArgs, parseJobs, parseMr, releaseInFlight, retryArgs, } from './gitlab.js';
26
+ import { REASON_MAX, RESET_WAIT_MAX_MS, codexEnd, emptyCodexProgress, firstLine, lastClaudeResult, readClaudeResult, readCodexEvents, refusalSuffix, resetAt, stoppedBy, summaryLines, } from './result.js';
27
+ import { retroMarker, retroSnapshotPath } from './state.js';
28
+ import { RETRO_LIMIT_MS, retroAllowed, retroChanges, retroPrompt } from './retro.js';
26
29
  import { capInForce, tokensLeft } from './cap.js';
27
30
  import { fmtTokens } from '../commands/cost.js';
28
31
  import { LEGACY_STOPS, pauseEnv, pendingReview, stopsInForce } from './stops.js';
@@ -77,8 +80,9 @@ function isReadOnly(cmd, args) {
77
80
  // The retry and the merge carry `--method`, so a dry run prints them (autopilot-gitlab-merge-requests/AC-16).
78
81
  if (cmd === 'glab')
79
82
  return a === '--version' || GLAB_READ_RE.test(a);
83
+ // `diff` and `ls-remote` read what the pull request check is given (pr-checker-earns-merge/AC-2, AC-5).
80
84
  if (cmd === 'git')
81
- return /^(rev-parse|status|merge-base)\b/.test(a);
85
+ return /^(rev-parse|status|merge-base|diff|ls-remote)\b/.test(a);
82
86
  return /\broadmap next\b/.test(a) || (/\bcost\b/.test(a) && /--json/.test(a));
83
87
  }
84
88
  /** `args` past `cli`'s own, when `cmd args` is an `aidlc` invocation; else undefined. */
@@ -245,8 +249,12 @@ function dequeue(state, item) {
245
249
  }
246
250
  /** At most two at once, whatever the config says. */
247
251
  const buildSlots = (ctx) => Math.min(2, Math.max(1, ctx.config?.max_parallel ?? 2));
248
- /** Only a building item holds a slot; one waiting for a person does not (autopilot-stop-controls/AC-15). */
249
- const building = (state) => state.items.filter((i) => i.step === 'building').length;
252
+ /**
253
+ * Only an item running an agent holds a slot; one waiting for a person does not
254
+ * (autopilot-stop-controls/AC-15). A pull request checker runs the project's tests, so it
255
+ * holds one like a build (pr-checker-earns-merge, design D3).
256
+ */
257
+ const building = (state) => state.items.filter((i) => i.step === 'building' || i.step === 'checking').length;
250
258
  /** The stops an item is held to: those recorded when it started (autopilot-stop-controls/AC-6). */
251
259
  export function itemStops(item) {
252
260
  return item.stops ?? LEGACY_STOPS;
@@ -309,6 +317,21 @@ export function launchBlocked(state, now) {
309
317
  const capReached = (cap, spentMicro) => `cost cap ${cap} USD reached — spent ${microToUsd(spentMicro)}`;
310
318
  /** The park reason when the item's tokens have used up its token cap (cost-in-tokens/AC-14, AC-15). */
311
319
  const tokenCapReached = (cap, used) => `token cap ${fmtTokens(cap)} reached — used ${fmtTokens(used)} tokens`;
320
+ /**
321
+ * Why the item's recorded spend leaves no room for another session, or null. In dollars: a
322
+ * budget under a cent. In tokens: none left — checked between sessions, since Claude has a
323
+ * dollar budget flag and no token one (cost-in-tokens/AC-14, AC-17).
324
+ */
325
+ function capUsedUp(ctx, item) {
326
+ const capSet = capInForce(ctx.config);
327
+ const spent = item.spent_micro_usd ?? 0;
328
+ if (capSet?.unit === 'usd' && budgetCents(capSet.usd, spent) < 1)
329
+ return capReached(capSet.usd, spent);
330
+ if (capSet?.unit === 'tokens' && tokensLeft(capSet.tokens, item.spent_tokens ?? 0) < 1) {
331
+ return tokenCapReached(capSet.tokens, item.spent_tokens ?? 0);
332
+ }
333
+ return null;
334
+ }
312
335
  const logFile = (ctx, item) => `${ctx.paths.logs}/${item.name}.log`;
313
336
  /**
314
337
  * Launch the item's agent. False when nothing was launched: a session-limit wait is in
@@ -323,21 +346,19 @@ const logFile = (ctx, item) => `${ctx.paths.logs}/${item.name}.log`;
323
346
  *
324
347
  * @param budget - the run's item budget, which a park here must reach.
325
348
  */
326
- function launchAgent(ctx, io, state, item, prompt, budget, resume) {
349
+ function launchAgent(ctx, io, state, item, prompt, budget, resume, kind = 'build') {
327
350
  if (launchBlocked(state, ctx.now()) !== null)
328
351
  return false;
329
352
  const capSet = capInForce(ctx.config);
330
353
  const cap = capSet?.unit === 'usd' ? capSet.usd : undefined;
331
354
  const spent = item.spent_micro_usd ?? 0;
332
355
  const cents = typeof cap === 'number' ? budgetCents(cap, spent) : null;
333
- if (typeof cap === 'number' && (cents ?? 0) < 1) {
334
- park(ctx, io, state, item, capReached(cap, spent), budget);
335
- return false;
336
- }
337
- // A token cap is checked between sessions: Claude has a dollar budget flag and no
338
- // token one, so `cents` stays null and none is passed (cost-in-tokens/AC-14, AC-17).
339
- if (capSet?.unit === 'tokens' && tokensLeft(capSet.tokens, item.spent_tokens ?? 0) < 1) {
340
- park(ctx, io, state, item, tokenCapReached(capSet.tokens, item.spent_tokens ?? 0), budget);
356
+ const used = capUsedUp(ctx, item);
357
+ if (used !== null) {
358
+ // A retrospective never parks: `afterClose` checked the cap before it got here, and
359
+ // this is only the net under that check (autopilot-runs-retrospective/AC-5, AC-13).
360
+ if (kind !== 'retro')
361
+ park(ctx, io, state, item, used, budget);
341
362
  return false;
342
363
  }
343
364
  const command = ctx.config?.agent_command ?? [];
@@ -349,18 +370,24 @@ function launchAgent(ctx, io, state, item, prompt, budget, resume) {
349
370
  argv = command.map((a) => (a === '{prompt}' ? prompt : a));
350
371
  }
351
372
  else {
352
- const outcomeFile = `${ctx.paths.dir}/outcomes/${item.name}.json`;
353
- const schemaFile = `${ctx.paths.dir}/outcome-schema.json`;
373
+ // A checker ends with its verdict, not the build's outcome, and cannot use the edit
374
+ // tools; it never resumes (pr-checker-earns-merge/AC-1, AC-4, AC-6, design D5).
375
+ const check = kind === 'check';
376
+ // Its own file, so a build's outcome is never read as the retrospective's (autopilot-runs-retrospective, design D2).
377
+ const outcomeFile = `${ctx.paths.dir}/outcomes/${item.name}${check ? '.check' : kind === 'retro' ? '.retro' : ''}.json`;
378
+ const schemaFile = `${ctx.paths.dir}/${check ? 'check' : 'outcome'}-schema.json`;
354
379
  const typed = typedArgv(command, {
355
380
  harness,
356
- prompt: withOutcomeContract(prompt),
381
+ prompt: check ? prompt : withOutcomeContract(prompt),
357
382
  schemaFile,
358
383
  outcomeFile,
359
384
  maxBudgetCents: harness === 'claude' ? cents : null,
360
- resume: resume?.session ?? null,
385
+ resume: check ? null : resume?.session ?? null,
386
+ ...(check ? { schema: VERDICT_SCHEMA, disallowedTools: ['Edit', 'Write', 'NotebookEdit'] } : {}),
361
387
  });
362
388
  if (typed === null) {
363
- park(ctx, io, state, item, `${resume?.label ?? 'session'} — no usable session id`, budget);
389
+ if (kind !== 'retro')
390
+ park(ctx, io, state, item, `${resume?.label ?? 'session'} — no usable session id`, budget);
364
391
  return false;
365
392
  }
366
393
  argv = typed;
@@ -381,18 +408,26 @@ function launchAgent(ctx, io, state, item, prompt, budget, resume) {
381
408
  launch.rollout_at = resume.from.rollout_at ?? resume.from.at;
382
409
  }
383
410
  if (harness === 'codex' && !ctx.dryRun) {
384
- ctx.fs.write(schemaFile, `${JSON.stringify(OUTCOME_SCHEMA, null, 2)}\n`);
411
+ ctx.fs.write(schemaFile, `${JSON.stringify(check ? VERDICT_SCHEMA : OUTCOME_SCHEMA, null, 2)}\n`);
385
412
  ctx.fs.write(outcomeFile, '');
386
413
  }
387
414
  }
415
+ const retro = kind === 'retro';
388
416
  const env = {
389
417
  AIDLC_UNATTENDED: '1',
390
418
  AIDLC_AGENT: ctx.config?.agent_platform ?? 'claude-code',
391
419
  // Where the unattended rule's review boundaries are (autopilot-stop-controls/AC-11).
392
- AIDLC_PAUSE_AFTER: itemPauses(item),
420
+ // A retrospective has no phases to pause after (autopilot-runs-retrospective, design D2).
421
+ AIDLC_PAUSE_AFTER: retro ? '' : itemPauses(item),
422
+ // Its session is after the completion moment, which no claim interval covers: the
423
+ // recorder files it under the instance by this name (AC-16, design D5).
424
+ ...(retro ? { AIDLC_COST_INSTANCE: item.name } : {}),
393
425
  };
426
+ const who = kind === 'check' ? 'checker' : retro ? 'retrospective agent' : 'agent';
427
+ // The primary checkout: the item's worktree no longer holds anything to merge (AC-1).
428
+ const cwd = retro ? ctx.repo : item.worktree;
394
429
  if (ctx.dryRun) {
395
- ctx.say(`[dry-run] (in ${item.worktree}) launch agent: ${argv[0]} … (${argv.length} args${harness === null ? '' : `, typed ${harness}`})`);
430
+ ctx.say(`[dry-run] (in ${cwd}) launch ${who}: ${argv[0]} … (${argv.length} args${harness === null ? '' : `, typed ${harness}`})`);
396
431
  return true;
397
432
  }
398
433
  if (launch === undefined) {
@@ -406,11 +441,11 @@ function launchAgent(ctx, io, state, item, prompt, budget, resume) {
406
441
  launch.read_offset = launch.log_offset;
407
442
  item.launch = launch;
408
443
  }
409
- item.pid = ctx.spawnDetached(argv, { cwd: item.worktree, env, logFile: log });
444
+ item.pid = ctx.spawnDetached(argv, { cwd, env, logFile: log });
410
445
  item.pid_started_at = new Date(ctx.now()).toISOString();
411
446
  if (!isPid(item.pid)) {
412
447
  // Its error arrives after this pass; the next one parks it (agent-binary-missing-crashes-loop/AC-3).
413
- tell(ctx, item, 'agent did not start');
448
+ tell(ctx, item, `${who} did not start`);
414
449
  return true;
415
450
  }
416
451
  const id = ctx.identify?.(item.pid);
@@ -419,7 +454,7 @@ function launchAgent(ctx, io, state, item, prompt, budget, resume) {
419
454
  item.pid_boot = id.boot;
420
455
  item.pid_ns = id.ns;
421
456
  }
422
- tell(ctx, item, `agent started (pid ${item.pid})`);
457
+ tell(ctx, item, `${who} started (pid ${item.pid})`);
423
458
  return true;
424
459
  }
425
460
  function drop(state, item, budget) {
@@ -642,7 +677,7 @@ const onRecord = (record, key) => key === null ? 0 : record?.[key] ?? 0;
642
677
  *
643
678
  * @returns whether it stopped and parked the item.
644
679
  */
645
- function stoppedAtCap(ctx, io, state, item, launch, capSet, budget) {
680
+ function stoppedAtCap(ctx, io, state, item, launch, capSet, budget, onCap = (reason) => park(ctx, io, state, item, reason, budget)) {
646
681
  if ((launch.progress?.turns ?? 0) === 0)
647
682
  return false;
648
683
  const thread = launch.progress?.thread_id ?? null;
@@ -657,7 +692,7 @@ function stoppedAtCap(ctx, io, state, item, launch, capSet, budget) {
657
692
  if (!ctx.dryRun && item.pid !== null)
658
693
  ctx.kill(item.pid);
659
694
  appendSummary(ctx, item, summaryLines(sessionSoFar(launch, launchUsageMicro(ctx, launch)), 'stopped by autopilot at the token cap'));
660
- park(ctx, io, state, item, tokenCapReached(capSet.tokens, used), budget);
695
+ onCap(tokenCapReached(capSet.tokens, used));
661
696
  return true;
662
697
  }
663
698
  const cap = capSet.usd;
@@ -672,7 +707,7 @@ function stoppedAtCap(ctx, io, state, item, launch, capSet, budget) {
672
707
  if (!ctx.dryRun && item.pid !== null)
673
708
  ctx.kill(item.pid);
674
709
  appendSummary(ctx, item, summaryLines(sessionSoFar(launch, priced), 'stopped by autopilot at the cost cap'));
675
- park(ctx, io, state, item, capReached(cap, spent), budget);
710
+ onCap(capReached(cap, spent));
676
711
  return true;
677
712
  }
678
713
  /**
@@ -766,15 +801,21 @@ function appendSummary(ctx, item, lines) {
766
801
  const lead = last !== undefined && last.length === 1 && last[0] !== 0x0a ? '\n' : '';
767
802
  append(log, `${lead}${lines.join('\n')}\n`);
768
803
  }
769
- function advanceBuilding(ctx, io, state, item, budget) {
804
+ /**
805
+ * While the item's agent — a build, a pull request checker or a retrospective — is alive:
806
+ * fold a Codex log and hold it to the cap, calling `onCap` when it is past: a park, except
807
+ * for a retrospective, which fails instead (pr-checker-earns-merge/AC-18,
808
+ * autopilot-runs-retrospective/AC-11). True while it runs.
809
+ */
810
+ function agentRunning(ctx, io, state, item, budget, onCap = (reason) => park(ctx, io, state, item, reason, budget)) {
770
811
  if (isPid(item.pid) && ctx.isAlive(item.pid)) {
771
812
  const launch = item.launch;
772
813
  if (launch?.harness === 'codex')
773
814
  followCodex(ctx, item, launch, false);
774
815
  const capSet = capInForce(ctx.config);
775
816
  if (capSet !== null) {
776
- if (launch?.harness === 'codex' && stoppedAtCap(ctx, io, state, item, launch, capSet, budget))
777
- return;
817
+ if (launch?.harness === 'codex' && stoppedAtCap(ctx, io, state, item, launch, capSet, budget, onCap))
818
+ return true;
778
819
  // Every agent, typed or not: the ledger's view of the cap stands (autopilot-reads-agent-result/AC-22),
779
820
  // in the unit the cap is set in (cost-in-tokens/AC-16).
780
821
  const r = io.cli(['cost', item.name, '--json']);
@@ -798,11 +839,16 @@ function advanceBuilding(ctx, io, state, item, budget) {
798
839
  const reason = capSet.unit === 'usd'
799
840
  ? `cost cap ${capSet.usd} USD exceeded`
800
841
  : `token cap ${fmtTokens(capSet.tokens)} exceeded — aidlc cost reports ${fmtTokens(tokens)} tokens`;
801
- park(ctx, io, state, item, reason, budget);
842
+ onCap(reason);
802
843
  }
803
844
  }
804
- return;
845
+ return true;
805
846
  }
847
+ return false;
848
+ }
849
+ function advanceBuilding(ctx, io, state, item, budget) {
850
+ if (agentRunning(ctx, io, state, item, budget))
851
+ return;
806
852
  // A launch that never started had no session to read: unmarked, its log would gain the
807
853
  // summary of a session that "ended with no readable result" (agent-binary-missing-crashes-loop/AC-4).
808
854
  if (neverStarted(item) && item.launch !== undefined && item.launch.end === undefined)
@@ -1146,6 +1192,14 @@ function droppedIfMerged(ctx, state, item, view, budget) {
1146
1192
  */
1147
1193
  function answeredByPerson(ctx, io, state, item, view, budget) {
1148
1194
  if (view?.state === 'MERGED') {
1195
+ // Its close-out waits for the running retrospective, and runs on the first pass after it.
1196
+ // Checked here, not in a caller, so every step a person can merge from waits
1197
+ // (autopilot-runs-retrospective/AC-3, design D1).
1198
+ const retro = retroRunning(state);
1199
+ if (retro !== null) {
1200
+ record(ctx, item, `merged — closing it out waits for ${retro.name}'s retrospective`);
1201
+ return true;
1202
+ }
1149
1203
  closeOut(ctx, io, state, item, budget);
1150
1204
  return true;
1151
1205
  }
@@ -1196,7 +1250,7 @@ function closeOut(ctx, io, state, item, budget) {
1196
1250
  const closed = `${ref(hostOf(ctx), item.pr)} merged by you, and closed${closeNote(report)}`;
1197
1251
  tell(ctx, item, closed);
1198
1252
  notice(ctx, 'item closed', `${item.name}: ${closed}`);
1199
- drop(state, item, budget);
1253
+ afterClose(ctx, io, state, item, budget);
1200
1254
  }
1201
1255
  const emptyReport = () => ({ paths: [], leftOut: [], earlier: [], notCopied: [] });
1202
1256
  /** Shown by a dry run in place of the pathspec, which is only known once the transition has written (design D6). */
@@ -1207,8 +1261,8 @@ const DRY_PATHS = '<the paths the close-out changed>';
1207
1261
  * new file; porcelain paths are relative to the repository's top, so the project's `prefix`
1208
1262
  * is removed (closeout-carries-worktree-state/AC-4, design D1).
1209
1263
  */
1210
- function dirtyPaths(ctx, io, prefix) {
1211
- const r = io.call('git', ['status', '--porcelain=v1', '-z', '--no-renames', '--untracked-files=all', '--', '.aidlc'], { cwd: ctx.repo });
1264
+ function dirtyPaths(ctx, io, prefix, pathspec = '.aidlc') {
1265
+ const r = io.call('git', ['status', '--porcelain=v1', '-z', '--no-renames', '--untracked-files=all', '--', pathspec], { cwd: ctx.repo });
1212
1266
  if (r.status !== 0)
1213
1267
  return r;
1214
1268
  return r.stdout
@@ -1217,7 +1271,8 @@ function dirtyPaths(ctx, io, prefix) {
1217
1271
  .map((rec) => rec.slice(3))
1218
1272
  .map((p) => (p.startsWith(prefix) ? p.slice(prefix.length) : p));
1219
1273
  }
1220
- const LATE_FILES = ['costs.ndjson', 'unattended-stops.md'];
1274
+ /** Written in the worktree after its last commit; `pr-check.md` by the pull request check (pr-checker-earns-merge/AC-17). */
1275
+ const LATE_FILES = ['costs.ndjson', 'unattended-stops.md', 'pr-check.md'];
1221
1276
  /** `t` without its `**Review:**` lines — the line `withVerdict` inserts or replaces. */
1222
1277
  const withoutVerdicts = (t) => t
1223
1278
  .split('\n')
@@ -1342,10 +1397,281 @@ function closeSteps(ctx, io, item, report) {
1342
1397
  ['push-close', () => io.call('git', ['push', 'origin', 'main'], { cwd: ctx.repo })],
1343
1398
  ];
1344
1399
  }
1400
+ // ---------------------------------------------------------------------------
1401
+ // The retrospective after a close-out (autopilot-runs-retrospective)
1402
+ // ---------------------------------------------------------------------------
1403
+ /** The item whose retrospective is running, or null. At most one is (AC-3). */
1404
+ function retroRunning(state) {
1405
+ return state.items.find((i) => i.step === 'retrospective') ?? null;
1406
+ }
1407
+ const MARKER_STAYS = 'the marker stays for aidlc autopilot pending';
1408
+ /** `; left as they are: a, b` — the paths it changed outside the allowed set (AC-7). */
1409
+ const leftAloneNote = (paths) => (paths.length === 0 ? '' : `; left as they are: ${paths.join(', ')}`);
1410
+ function readSnapshot(ctx, item) {
1411
+ const text = ctx.fs.read(retroSnapshotPath(ctx.paths, item.name));
1412
+ if (text === null)
1413
+ return null;
1414
+ try {
1415
+ return JSON.parse(text);
1416
+ }
1417
+ catch {
1418
+ return null;
1419
+ }
1420
+ }
1421
+ /** The fixed allowed paths' text and every uncommitted path's fingerprint, now; or git's failure (design D3). */
1422
+ function readRetroNow(ctx, io, prefix, name) {
1423
+ const dirty = dirtyPaths(ctx, io, prefix, '.');
1424
+ if (!Array.isArray(dirty))
1425
+ return { failed: `git status: ${fail(dirty)}` };
1426
+ const allowed = Object.fromEntries(Object.values(retroAllowed(name)).map((p) => [p, ctx.fs.read(`${ctx.repo}/${p}`)]));
1427
+ return { allowed, dirty: fingerprint(ctx.fs.read, ctx.repo, dirty) };
1428
+ }
1429
+ /** Stop tracking the item, and delete its snapshot. */
1430
+ function finishRetro(ctx, state, item, budget) {
1431
+ ctx.fs.remove?.(retroSnapshotPath(ctx.paths, item.name));
1432
+ drop(state, item, budget);
1433
+ }
1434
+ /**
1435
+ * Push main; a rate limit is a failed push like any other here, because the commit is made
1436
+ * and a back-off that left the item where it is would read the committed paths as changed
1437
+ * on the next pass (AC-14).
1438
+ */
1439
+ function pushMain(ctx, io) {
1440
+ try {
1441
+ return io.call('git', ['push', 'origin', 'main'], { cwd: ctx.repo });
1442
+ }
1443
+ catch (err) {
1444
+ if (!(err instanceof RateLimited))
1445
+ throw err;
1446
+ return { status: 1, stdout: '', stderr: err.message };
1447
+ }
1448
+ }
1449
+ /**
1450
+ * After a close-out has committed on main: run the item's retrospective, or stop tracking it
1451
+ * as before (AC-1, AC-2, AC-5, AC-13, design D1, D2). With no marker there is nothing to run.
1452
+ * A session-limit wait or a used-up cap launches nothing and keeps the marker. Otherwise the
1453
+ * snapshot is taken and the agent launched in the primary checkout; the item moves to
1454
+ * `retrospective`, which holds the merge lane until it ends.
1455
+ */
1456
+ function afterClose(ctx, io, state, item, budget) {
1457
+ const markerText = ctx.fs.read(retroMarker(ctx.paths, item.name));
1458
+ // A dry run ran no transition, so it cannot know whether one would leave a marker: it
1459
+ // says the launch either way (AC-5).
1460
+ if (markerText === null && !ctx.dryRun) {
1461
+ drop(state, item, budget);
1462
+ return;
1463
+ }
1464
+ const skip = (why) => {
1465
+ tell(ctx, item, `retrospective not run — ${why}; ${MARKER_STAYS}`);
1466
+ drop(state, item, budget);
1467
+ };
1468
+ const blocked = launchBlocked(state, ctx.now());
1469
+ if (blocked !== null)
1470
+ return skip(`waiting for the session limit to reset at ${blocked}`);
1471
+ const used = capUsedUp(ctx, item);
1472
+ if (used !== null)
1473
+ return skip(used);
1474
+ if (ctx.dryRun) {
1475
+ launchAgent(ctx, io, state, item, retroPrompt(item), budget, undefined, 'retro');
1476
+ drop(state, item, budget);
1477
+ return;
1478
+ }
1479
+ const head = io.call('git', ['rev-parse', 'HEAD'], { cwd: ctx.repo });
1480
+ if (head.status !== 0)
1481
+ return skip(`main cannot be read (git rev-parse: ${fail(head)})`);
1482
+ const top = io.call('git', ['rev-parse', '--show-prefix'], { cwd: ctx.repo });
1483
+ if (top.status !== 0)
1484
+ return skip(`main cannot be read (git rev-parse: ${fail(top)})`);
1485
+ const prefix = top.stdout.trim();
1486
+ const now = readRetroNow(ctx, io, prefix, item.name);
1487
+ if ('failed' in now)
1488
+ return skip(`main cannot be read (${now.failed})`);
1489
+ const at = new Date(ctx.now()).toISOString();
1490
+ const snapshot = {
1491
+ name: item.name,
1492
+ at,
1493
+ head: head.stdout.trim(),
1494
+ prefix,
1495
+ marker: markerText ?? '',
1496
+ allowed: now.allowed,
1497
+ dirty: now.dirty,
1498
+ };
1499
+ ctx.fs.write(retroSnapshotPath(ctx.paths, item.name), `${JSON.stringify(snapshot)}\n`);
1500
+ dequeue(state, item);
1501
+ item.step = 'retrospective';
1502
+ item.retro = { at };
1503
+ if (!launchAgent(ctx, io, state, item, retroPrompt(item), budget, undefined, 'retro')) {
1504
+ // Unreachable past the two checks above; the net keeps the item from waiting on nothing.
1505
+ ctx.fs.remove?.(retroSnapshotPath(ctx.paths, item.name));
1506
+ skip('it could not be launched');
1507
+ }
1508
+ }
1509
+ /**
1510
+ * Why the ended retrospective is not a success, or null (AC-12). Success is a known exit
1511
+ * of 0, the marker gone, and for a typed launch the outcome `shipped`. An exit the pass
1512
+ * cannot read — the run restarted while the agent ran — is a failure: the marker is put
1513
+ * back, and a person can still run it from `aidlc autopilot pending`.
1514
+ */
1515
+ function retroFailure(ctx, item) {
1516
+ const launch = item.launch;
1517
+ const end = launch?.end ?? null;
1518
+ if (end?.limit === 'budget') {
1519
+ const spent = item.spent_micro_usd ?? 0;
1520
+ return `stopped at the cost cap — ${launch?.cap_usd === undefined ? `budget reached, spent ${microToUsd(spent)}` : capReached(launch.cap_usd, spent)}`;
1521
+ }
1522
+ if (neverStarted(item))
1523
+ return launchFailure(ctx, item) ?? 'its agent did not start';
1524
+ const exit = isPid(item.pid) ? ctx.exited?.(item.pid) ?? null : null;
1525
+ if (exit === null)
1526
+ return 'how its agent ended cannot be read';
1527
+ if (exit.code !== 0)
1528
+ return exit.code === null ? `its agent ended on signal ${exit.signal ?? 'unknown'}` : `its agent exited ${exit.code}`;
1529
+ if (ctx.fs.exists(retroMarker(ctx.paths, item.name)))
1530
+ return 'it left the retro-pending marker in place';
1531
+ if (launch === undefined)
1532
+ return null;
1533
+ if (end?.outcome == null)
1534
+ return 'it ended with no readable result';
1535
+ if (end.outcome.outcome !== 'shipped') {
1536
+ const reason = firstLine(end.outcome.reason, REASON_MAX);
1537
+ return `it reported ${end.outcome.outcome}${reason === null ? '' : `: ${reason}`}`;
1538
+ }
1539
+ return null;
1540
+ }
1541
+ /**
1542
+ * The retrospective step, each pass (AC-6..AC-16, design D4..D6). While its agent runs it is
1543
+ * held to the 30-minute limit and the cap; once it has ended: its spend, one capture of its
1544
+ * cost, the success check, the limits, then the commit by pathspec and the push.
1545
+ */
1546
+ function advanceRetrospective(ctx, io, state, item, budget) {
1547
+ if (ctx.dryRun) {
1548
+ // A dry run reads nothing back and writes nothing: restoring or committing is a write.
1549
+ ctx.say(`[dry-run] ${item.name}: its retrospective is running — nothing is read or written`);
1550
+ return;
1551
+ }
1552
+ const snap = readSnapshot(ctx, item);
1553
+ const at = item.retro?.at;
1554
+ if (snap === null || at === undefined) {
1555
+ if (isPid(item.pid) && ctx.isAlive(item.pid))
1556
+ return;
1557
+ tell(ctx, item, `retrospective ended, but its launch record is gone — nothing committed or restored; check main with git status`);
1558
+ finishRetro(ctx, state, item, budget);
1559
+ return;
1560
+ }
1561
+ const failed = (why, now) => failRetro(ctx, io, state, item, snap, why, budget, now);
1562
+ if (isPid(item.pid) && ctx.isAlive(item.pid) && ctx.now() - Date.parse(at) >= RETRO_LIMIT_MS) {
1563
+ ctx.kill(item.pid);
1564
+ failed(`still running after ${RETRO_LIMIT_MS / 60_000} minutes`);
1565
+ return;
1566
+ }
1567
+ if (agentRunning(ctx, io, state, item, budget, (reason) => failed(`stopped at the cost cap — ${reason}`)))
1568
+ return;
1569
+ const launch = item.launch;
1570
+ if (neverStarted(item) && launch !== undefined && launch.end === undefined)
1571
+ launch.end = null;
1572
+ // Its tokens and price on the item, so the cap sees them (AC-16).
1573
+ if (launch !== undefined && launch.end === undefined && !endSession(ctx, item, launch))
1574
+ return;
1575
+ const sessionId = launch?.end?.session_id ?? null;
1576
+ if (launch !== undefined && sessionId !== null && item.retro?.captured !== true && ctx.captureSession !== undefined) {
1577
+ // The hook runs detached and may finish after the commit; one capture now leaves it
1578
+ // nothing to append, so the ledger is final before the diff is read (design D5).
1579
+ const r = ctx.captureSession({ provider: launch.harness === 'codex' ? 'codex' : 'claude-code', sessionId, instance: item.name });
1580
+ if (r === 'busy') {
1581
+ record(ctx, item, 'retrospective ended — waiting for its cost to be recorded');
1582
+ return;
1583
+ }
1584
+ item.retro = { at, captured: true };
1585
+ }
1586
+ const why = retroFailure(ctx, item);
1587
+ if (why !== null)
1588
+ return failed(why);
1589
+ const now = readRetroNow(ctx, io, snap.prefix, item.name);
1590
+ if ('failed' in now)
1591
+ return failed(`main cannot be read (${now.failed})`);
1592
+ const changes = retroChanges(snap, now);
1593
+ if (!changes.ok)
1594
+ return failed(changes.why, now);
1595
+ let line = 'retrospective ran and wrote nothing to commit';
1596
+ if (changes.commit.length > 0) {
1597
+ const repo = { cwd: ctx.repo };
1598
+ // `add` first: a pathspec commit of an untracked file fails (design D4).
1599
+ const add = io.call('git', ['add', '--', ...changes.commit], repo);
1600
+ const commit = add.status !== 0 ? add : io.call('git', ['commit', '-q', '-m', `chore(aidlc): retrospective for ${item.name} (autopilot)`, '--', ...changes.commit], repo);
1601
+ if (commit.status !== 0) {
1602
+ io.call('git', ['reset', '-q', '--', ...changes.commit], repo);
1603
+ return failed(`its commit failed: ${fail(commit)}`, now);
1604
+ }
1605
+ const counts = `${changes.lessons} ${changes.lessons === 1 ? 'lesson' : 'lessons'}, ${changes.followUps} ${changes.followUps === 1 ? 'follow-up' : 'follow-ups'}`;
1606
+ const push = pushMain(ctx, io);
1607
+ line =
1608
+ push.status === 0
1609
+ ? `retrospective committed on main and pushed — ${counts}`
1610
+ : `retrospective committed on main (${counts}); the push failed (${fail(push)}) — the next push of main carries it`;
1611
+ }
1612
+ tell(ctx, item, `${line}${leftAloneNote(changes.leftAlone)}`);
1613
+ finishRetro(ctx, state, item, budget);
1614
+ }
1615
+ /**
1616
+ * A failed retrospective (AC-10, design D6): each allowed path it changed goes back to its
1617
+ * text at launch and each inbox file it created is deleted; its cost lines are kept and
1618
+ * committed alone (Q1); the marker is put back; one line says why; the item is dropped.
1619
+ * Never `park` and never `error`, so the merge lane is never halted.
1620
+ */
1621
+ function failRetro(ctx, io, state, item, snap, why, budget, known) {
1622
+ const now = known ?? readRetroNow(ctx, io, snap.prefix, item.name);
1623
+ const { retro, lessons, costs } = retroAllowed(item.name);
1624
+ for (const p of [retro, lessons]) {
1625
+ const before = snap.allowed[p] ?? null;
1626
+ const file = `${ctx.repo}/${p}`;
1627
+ if (ctx.fs.read(file) === before)
1628
+ continue;
1629
+ if (before === null)
1630
+ ctx.fs.remove?.(file);
1631
+ else
1632
+ ctx.fs.write(file, before);
1633
+ }
1634
+ // Unreadable git: the fixed paths are back, but its new inbox files cannot be told apart.
1635
+ const seen = 'failed' in now ? null : retroChanges(snap, now);
1636
+ for (const p of seen?.created ?? [])
1637
+ ctx.fs.remove?.(`${ctx.repo}/${p}`);
1638
+ const leftAlone = [...(seen?.leftAlone ?? [])];
1639
+ let costNote = '';
1640
+ if (ctx.fs.read(`${ctx.repo}/${costs}`) !== (snap.allowed[costs] ?? null)) {
1641
+ if (costs in snap.dirty)
1642
+ leftAlone.push(costs);
1643
+ else
1644
+ costNote = commitRetroCost(ctx, io, item, costs);
1645
+ }
1646
+ const marker = retroMarker(ctx.paths, item.name);
1647
+ if (!ctx.fs.exists(marker))
1648
+ ctx.fs.write(marker, snap.marker);
1649
+ const unread = 'failed' in now ? `; its new inbox files cannot be told apart (${now.failed})` : '';
1650
+ tell(ctx, item, `retrospective failed — ${why}; ${MARKER_STAYS}${costNote}${unread}${leftAloneNote([...new Set(leftAlone)].sort())}`);
1651
+ notice(ctx, 'retrospective failed', `${item.name}: ${why}`);
1652
+ finishRetro(ctx, state, item, budget);
1653
+ }
1654
+ /**
1655
+ * Commit the failed retrospective's cost lines alone and push them: a deleted ledger line
1656
+ * cannot be recovered, a commit can be reverted (design-questions Q1). A failure is named
1657
+ * and changes nothing else.
1658
+ */
1659
+ function commitRetroCost(ctx, io, item, costs) {
1660
+ const repo = { cwd: ctx.repo };
1661
+ const add = io.call('git', ['add', '--', costs], repo);
1662
+ const commit = add.status !== 0
1663
+ ? add
1664
+ : io.call('git', ['commit', '-q', '-m', `chore(aidlc): record the failed retrospective's cost for ${item.name} (autopilot)`, '--', costs], repo);
1665
+ if (commit.status !== 0)
1666
+ return `; its cost lines are not committed (${fail(commit)})`;
1667
+ const push = pushMain(ctx, io);
1668
+ return push.status === 0 ? '; its cost lines are committed on main' : `; its cost lines are committed on main, the push failed (${fail(push)})`;
1669
+ }
1345
1670
  /** Waiting for a person to merge: only their answer moves it (autopilot-stop-controls/AC-19). */
1346
1671
  function advanceAwaitingMerge(ctx, io, state, item, budget) {
1672
+ const view = prView(ctx, io, item);
1347
1673
  // Silent otherwise: a "still waiting" line would repeat every pass.
1348
- answeredByPerson(ctx, io, state, item, prView(ctx, io, item), budget);
1674
+ answeredByPerson(ctx, io, state, item, view, budget);
1349
1675
  }
1350
1676
  /**
1351
1677
  * The branch conflicts with main: hand it back to the agent, twice at most,
@@ -1370,7 +1696,7 @@ function handleConflict(ctx, io, state, item, budget) {
1370
1696
  dequeue(state, item);
1371
1697
  item.step = 'building';
1372
1698
  tell(ctx, item, `conflicts with main — relaunching the agent to resolve it (attempt ${tries + 1} of ${CONFLICT_FIX_LIMIT})`);
1373
- launchAgent(ctx, io, state, item, conflictPrompt(item, hostOf(ctx)), budget);
1699
+ relaunchBuild(ctx, io, state, item, conflictPrompt(item, hostOf(ctx)), budget);
1374
1700
  }
1375
1701
  /**
1376
1702
  * The two `merge=union` cost ledgers a worktree collects between commits. `name` is
@@ -1500,6 +1826,348 @@ function pushed(ctx, io, state, item) {
1500
1826
  function openQuestions(ctx, item) {
1501
1827
  return unreviewedOpenQuestions(ctx.fs.read(stopsLogPath(item.worktree, item.name)));
1502
1828
  }
1829
+ /**
1830
+ * Relaunch the build agent on an open pull request — a CI fix, a conflict, a REJECT — and
1831
+ * discard the check, so the head autopilot merges is one a check passed. Autopilot's own
1832
+ * update from main does not come here, and keeps it (pr-checker-earns-merge/AC-12).
1833
+ */
1834
+ function relaunchBuild(ctx, io, state, item, prompt, budget) {
1835
+ delete item.check;
1836
+ return launchAgent(ctx, io, state, item, prompt, budget);
1837
+ }
1838
+ const short = (sha) => sha.slice(0, 12) || 'none';
1839
+ /**
1840
+ * The tracked files that differ from the head, by content hash, keyed by their path from
1841
+ * the repository's top — what porcelain prints, for a project below the root as well — or
1842
+ * git's failure (pr-checker-earns-merge/AC-5, design D4).
1843
+ */
1844
+ function trackedSnapshot(ctx, io, item, also = []) {
1845
+ const wt = { cwd: item.worktree };
1846
+ const top = io.call('git', ['rev-parse', '--show-toplevel'], wt);
1847
+ if (top.status !== 0)
1848
+ return { failed: `git rev-parse: ${fail(top)}` };
1849
+ const prefix = io.call('git', ['rev-parse', '--show-prefix'], wt);
1850
+ if (prefix.status !== 0)
1851
+ return { failed: `git rev-parse: ${fail(prefix)}` };
1852
+ const status = io.call('git', ['status', '--porcelain=v1', '-z', '--no-renames', '--untracked-files=no'], wt);
1853
+ if (status.status !== 0)
1854
+ return { failed: `git status: ${fail(status)}` };
1855
+ const dirty = status.stdout
1856
+ .split('\0')
1857
+ .filter((rec) => rec.length > 3)
1858
+ .map((rec) => rec.slice(3));
1859
+ const paths = [...new Set([...dirty, ...also])];
1860
+ return { snap: fingerprint(ctx.fs.read, top.stdout.trim(), paths), prefix: prefix.stdout.trim() };
1861
+ }
1862
+ /** The remote branch's head, '' when it has none, or git's failure. */
1863
+ function remoteHead(io, item) {
1864
+ const r = io.call('git', ['ls-remote', 'origin', `refs/heads/${item.branch}`], { cwd: item.worktree });
1865
+ if (r.status !== 0)
1866
+ return { failed: `git ls-remote: ${fail(r)}` };
1867
+ return r.stdout.trim().split(/\s+/)[0] ?? '';
1868
+ }
1869
+ /**
1870
+ * Launch the pull request check of the head CI just passed on (pr-checker-earns-merge/AC-1..AC-4).
1871
+ * In order, each failing step deciding the pass: no preset or no criteria leaves a blocked
1872
+ * check for the person (AC-3, AC-7); no free agent slot or a session-limit wait leaves the
1873
+ * item where it is, saying so (design D3); then the change is read and the checker
1874
+ * launched as one more launch, under the cap like any other (AC-18, design D1).
1875
+ */
1876
+ function launchCheck(ctx, io, state, item, budget) {
1877
+ const n = (item.checks_run ?? 0) + 1;
1878
+ const blocked = (why) => {
1879
+ item.check = { n, head: '', remote: '', baseline: {}, given: [], blocked: why };
1880
+ };
1881
+ if (typedHarness(ctx.config?.agent_command ?? []) === null) {
1882
+ blocked('the agent command is not a preset autopilot reads a result from');
1883
+ return;
1884
+ }
1885
+ const stateDir = `${item.worktree}/.aidlc/state/${item.name}`;
1886
+ const { criteria } = readCriteria(ctx.fs.read, stateDir);
1887
+ if (criteria.length === 0) {
1888
+ blocked('no acceptance criteria found in requirements.md or roadmap-item.md');
1889
+ return;
1890
+ }
1891
+ if (building(state) >= buildSlots(ctx)) {
1892
+ tell(ctx, item, 'CI green — the pull request check waits for a free agent slot');
1893
+ return;
1894
+ }
1895
+ const limit = launchBlocked(state, ctx.now());
1896
+ if (limit !== null) {
1897
+ tell(ctx, item, `CI green — the pull request check waits for the session limit to reset at ${limit}`);
1898
+ return;
1899
+ }
1900
+ const wt = { cwd: item.worktree };
1901
+ const fetch = io.call('git', ['fetch', 'origin', 'main'], wt);
1902
+ if (fetch.status !== 0) {
1903
+ blocked(`could not read the change: git fetch: ${fail(fetch)}`);
1904
+ return;
1905
+ }
1906
+ const range = 'origin/main...HEAD';
1907
+ let diff = io.call('git', ['diff', '--no-color', '--no-ext-diff', range, ...DIFF_PATHSPEC], wt);
1908
+ let truncated = false;
1909
+ if (diff.status === 0 && diff.stdout.length > DIFF_MAX) {
1910
+ diff = io.call('git', ['diff', '--stat', '--no-color', range, ...DIFF_PATHSPEC], wt);
1911
+ truncated = true;
1912
+ }
1913
+ if (diff.status !== 0) {
1914
+ blocked(`could not read the change: git diff: ${fail(diff)}`);
1915
+ return;
1916
+ }
1917
+ const head = io.call('git', ['rev-parse', 'HEAD'], wt);
1918
+ if (head.status !== 0) {
1919
+ blocked(`could not read the change: git rev-parse: ${fail(head)}`);
1920
+ return;
1921
+ }
1922
+ const remote = remoteHead(io, item);
1923
+ if (typeof remote !== 'string') {
1924
+ blocked(`could not read the change: ${remote.failed}`);
1925
+ return;
1926
+ }
1927
+ const snapshot = trackedSnapshot(ctx, io, item);
1928
+ if ('failed' in snapshot) {
1929
+ blocked(`could not read the change: ${snapshot.failed}`);
1930
+ return;
1931
+ }
1932
+ const prRef = ref(hostOf(ctx), item.pr);
1933
+ const prompt = checkerPrompt({
1934
+ name: item.name,
1935
+ prRef,
1936
+ criteria,
1937
+ tasks: ctx.fs.read(`${stateDir}/tasks.md`),
1938
+ diff: { text: diff.stdout, base: 'origin/main', head: head.stdout.trim(), truncated },
1939
+ });
1940
+ const check = { n, head: head.stdout.trim(), remote, baseline: snapshot.snap, given: criteria.map((c) => c.id) };
1941
+ const step = item.step;
1942
+ item.check = check;
1943
+ item.checks_run = n;
1944
+ item.step = 'checking';
1945
+ tell(ctx, item, `CI green — checking ${prRef} against its ${criteria.length} criteria with an agent that did not build it`);
1946
+ if (!launchAgent(ctx, io, state, item, prompt, budget, undefined, 'check') && state.items.includes(item)) {
1947
+ // Not launched and not parked: nothing ran, so nothing is counted.
1948
+ delete item.check;
1949
+ item.checks_run = n - 1;
1950
+ item.step = step;
1951
+ }
1952
+ }
1953
+ /**
1954
+ * What the checker changed during its session, in words, or null: the branch head, the
1955
+ * remote branch, or a tracked file other than the two cost ledgers, measured against the
1956
+ * snapshot taken at launch (pr-checker-earns-merge/AC-5, design D4).
1957
+ */
1958
+ function checkerChanged(ctx, io, item, check) {
1959
+ const head = io.call('git', ['rev-parse', 'HEAD'], { cwd: item.worktree });
1960
+ if (head.status !== 0)
1961
+ return `the branch head cannot be read (${fail(head)})`;
1962
+ if (head.stdout.trim() !== check.head)
1963
+ return `the branch head (${short(check.head)} → ${short(head.stdout.trim())})`;
1964
+ const remote = remoteHead(io, item);
1965
+ if (typeof remote !== 'string')
1966
+ return `the remote branch cannot be read (${remote.failed})`;
1967
+ if (remote !== check.remote)
1968
+ return `the remote branch (${short(check.remote)} → ${short(remote)})`;
1969
+ const now = trackedSnapshot(ctx, io, item, Object.keys(check.baseline));
1970
+ if ('failed' in now)
1971
+ return `the tracked files cannot be read (${now.failed})`;
1972
+ const changed = changedSince(check.baseline, now.snap, ledgerPaths(item.name).map((p) => `${now.prefix}${p}`));
1973
+ return changed.length === 0 ? null : `tracked files: ${changed.slice(0, 5).join(', ')}${changed.length > 5 ? ` and ${changed.length - 5} more` : ''}`;
1974
+ }
1975
+ /** The checker's structured output, or undefined when it wrote none (pr-checker-earns-merge/AC-6). */
1976
+ function checkerOutput(ctx, item) {
1977
+ const launch = item.launch;
1978
+ const { readRange, size } = ctx.fs;
1979
+ if (launch === undefined || readRange === undefined || size === undefined)
1980
+ return undefined;
1981
+ if (launch.harness === 'claude') {
1982
+ const log = logFile(ctx, item);
1983
+ const total = size(log);
1984
+ const start = Math.max(launch.log_offset, total - RESULT_TAIL_BYTES);
1985
+ return lastClaudeResult(readRange(log, start, Math.max(0, total - start)).toString('utf8')).found?.structured_output;
1986
+ }
1987
+ if (launch.outcome_file === undefined)
1988
+ return undefined;
1989
+ const text = readRange(launch.outcome_file, 0, OUTCOME_FILE_BYTES).toString('utf8').trim();
1990
+ try {
1991
+ return text === '' ? undefined : JSON.parse(text);
1992
+ }
1993
+ catch {
1994
+ return undefined;
1995
+ }
1996
+ }
1997
+ /**
1998
+ * The checker has exited: record its spend, then decide what its session counts for — first
1999
+ * match wins (pr-checker-earns-merge/AC-5..AC-7, AC-18, design D9). Every ending that could
2000
+ * not judge goes to the person, never to the builder. The integrity check comes before the
2001
+ * verdict, so a checker that edited and then said PASS is never read.
2002
+ */
2003
+ function advanceChecking(ctx, io, state, item, budget) {
2004
+ if (agentRunning(ctx, io, state, item, budget))
2005
+ return;
2006
+ const check = item.check;
2007
+ if (check === undefined) {
2008
+ // Hand-edited state: CI is read again and a check launched.
2009
+ item.step = 'pr-open';
2010
+ return;
2011
+ }
2012
+ if (neverStarted(item) && item.launch !== undefined && item.launch.end === undefined)
2013
+ item.launch.end = null;
2014
+ if (item.launch !== undefined && item.launch.end === undefined && !endSession(ctx, item, item.launch))
2015
+ return;
2016
+ const end = item.launch?.end ?? null;
2017
+ const spent = item.spent_micro_usd ?? 0;
2018
+ item.step = 'pr-open';
2019
+ check.at = new Date(ctx.now()).toISOString();
2020
+ if (end?.limit === 'budget') {
2021
+ const cap = item.launch?.cap_usd;
2022
+ park(ctx, io, state, item, cap === undefined ? `budget reached — spent ${microToUsd(spent)}` : capReached(cap, spent), budget);
2023
+ return;
2024
+ }
2025
+ if (end === null) {
2026
+ check.blocked = launchFailure(ctx, item)?.replace(/^agent/, 'checker') ?? 'the checker ended with no readable result';
2027
+ return;
2028
+ }
2029
+ if (end.error !== null) {
2030
+ check.blocked = `checker session failed: ${firstLine(end.error, REASON_MAX) ?? 'error'}`;
2031
+ return;
2032
+ }
2033
+ const changed = checkerChanged(ctx, io, item, check);
2034
+ if (changed !== null) {
2035
+ check.blocked = `the checker changed ${changed} — verdict discarded`;
2036
+ return;
2037
+ }
2038
+ const output = checkerOutput(ctx, item);
2039
+ const read = output === undefined ? { ok: false, reason: 'the checker gave no verdict' } : parseVerdict(output, check.given);
2040
+ if (!read.ok) {
2041
+ check.blocked = `the verdict cannot be read: ${read.reason}`;
2042
+ return;
2043
+ }
2044
+ check.verdict = read.verdict;
2045
+ tell(ctx, item, `check ${check.n}: ${read.verdict.verdict}${notMetText(check)}`);
2046
+ recordCheck(ctx, item, check);
2047
+ postCheck(ctx, io, item, check);
2048
+ }
2049
+ /** ` (not met: AC-2, AC-5)`, or '' when every criterion is met. */
2050
+ function notMetText(check) {
2051
+ const ids = (check.verdict?.criteria ?? []).filter((c) => !c.met).map((c) => c.id);
2052
+ return ids.length === 0 ? '' : ` (not met: ${ids.join(', ')})`;
2053
+ }
2054
+ const checkText = (check) => renderVerdict(check.verdict, { n: check.n, head: check.head, at: check.at ?? '' });
2055
+ /**
2056
+ * Append the verdict to `pr-check.md` in the worktree, a later verdict below the earlier,
2057
+ * in the text the comment carries (pr-checker-earns-merge/AC-17).
2058
+ */
2059
+ function recordCheck(ctx, item, check) {
2060
+ if (check.recorded === true || check.verdict === undefined || ctx.dryRun)
2061
+ return;
2062
+ const path = `${item.worktree}/.aidlc/state/${item.name}/pr-check.md`;
2063
+ const before = ctx.fs.read(path);
2064
+ const head = before === null ? `# Pull request check — ${item.name}\n` : before.endsWith('\n') ? '' : '\n';
2065
+ const text = `${head}\n${checkText(check)}`;
2066
+ if (before !== null && ctx.fs.append !== undefined)
2067
+ ctx.fs.append(path, text);
2068
+ else
2069
+ ctx.fs.write(path, `${before ?? ''}${text}`);
2070
+ check.recorded = true;
2071
+ }
2072
+ /**
2073
+ * Post the verdict as one comment on the pull request — `gh` from the primary checkout,
2074
+ * with the body in a file under the autopilot directory, never through a shell; a note
2075
+ * through `glab api` on GitLab. A failure is said and tried again on the next pass
2076
+ * (pr-checker-earns-merge/AC-15, AC-16).
2077
+ */
2078
+ function postCheck(ctx, io, item, check) {
2079
+ if (check.posted === true)
2080
+ return true;
2081
+ if (check.verdict === undefined)
2082
+ return false;
2083
+ const host = hostOf(ctx);
2084
+ const text = checkText(check);
2085
+ let r;
2086
+ if (host === 'gitlab') {
2087
+ r = io.call('glab', noteArgs(item.pr ?? 0, text), { cwd: ctx.repo });
2088
+ }
2089
+ else {
2090
+ const body = `${ctx.paths.dir}/checks/${item.name}.md`;
2091
+ if (!ctx.dryRun)
2092
+ ctx.fs.write(body, text);
2093
+ r = io.call('gh', ['pr', 'comment', String(item.pr), '--body-file', body], { cwd: ctx.repo });
2094
+ }
2095
+ if (r.status !== 0) {
2096
+ tell(ctx, item, `could not post check ${check.n} on ${ref(host, item.pr)}: ${fail(r)} — trying again next pass; nothing merges until it is posted`);
2097
+ return false;
2098
+ }
2099
+ check.posted = true;
2100
+ return true;
2101
+ }
2102
+ /**
2103
+ * Act on the check of the head CI passed on (pr-checker-earns-merge/AC-8..AC-11, design D7).
2104
+ * A check that could not decide waits for a person under either stop. Nothing is acted on
2105
+ * before its verdict is posted. Under `pr` the item then waits whatever the verdict; under
2106
+ * `checked-merge` a first REJECT relaunches the build once, a second parks the item, and a
2107
+ * PASS joins the merge queue unless an open question waits for a person.
2108
+ */
2109
+ function actOnCheck(ctx, io, state, item, check, budget) {
2110
+ const host = hostOf(ctx);
2111
+ const prRef = ref(host, item.pr);
2112
+ if (check.blocked !== undefined) {
2113
+ item.step = 'awaiting-merge';
2114
+ const text = `CI green — the pull request check could not decide: ${check.blocked}; ${prRef} waits for you to merge it`;
2115
+ tell(ctx, item, text);
2116
+ if (check.told !== true)
2117
+ notice(ctx, 'merge needed', `${item.name}: ${text}`);
2118
+ check.told = true;
2119
+ return;
2120
+ }
2121
+ const verdict = check.verdict;
2122
+ if (verdict === undefined) {
2123
+ // A check with neither verdict nor reason outside `checking`: hand-edited state. Check again.
2124
+ delete item.check;
2125
+ return;
2126
+ }
2127
+ recordCheck(ctx, item, check);
2128
+ if (!postCheck(ctx, io, item, check))
2129
+ return;
2130
+ const said = `check ${check.n}: ${verdict.verdict}${notMetText(check)}`;
2131
+ if (itemStops(item).stop_at === 'pr') {
2132
+ item.step = 'awaiting-merge';
2133
+ tell(ctx, item, `CI green, ${said} — ${prRef} waits for you to merge it`);
2134
+ notice(ctx, 'merge needed', `${item.name}: ${said} — ${prRef} waits for you to merge it`);
2135
+ return;
2136
+ }
2137
+ if (verdict.verdict === 'REJECT') {
2138
+ const notMet = verdict.criteria.filter((c) => !c.met);
2139
+ const rejects = item.check_rejects ?? 0;
2140
+ if (rejects >= 1) {
2141
+ item.check_rejects = rejects + 1;
2142
+ const ids = notMet.length > 0 ? notMet.map((c) => c.id).join(', ') : 'no criterion marked';
2143
+ park(ctx, io, state, item, `pull request check rejected twice: ${ids} not met — evidence in .aidlc/state/${item.name}/pr-check.md in its worktree and on ${prRef}`, budget);
2144
+ return;
2145
+ }
2146
+ const limit = launchBlocked(state, ctx.now());
2147
+ if (limit !== null) {
2148
+ tell(ctx, item, `${said} — the fix waits for the session limit to reset at ${limit}`);
2149
+ return;
2150
+ }
2151
+ item.check_rejects = 1;
2152
+ item.step = 'building';
2153
+ tell(ctx, item, `${said} — relaunching the agent once with the findings`);
2154
+ // A REJECT that marks nothing not met still carries the evidence of each criterion.
2155
+ relaunchBuild(ctx, io, state, item, rejectPrompt(item, prRef, notMet.length > 0 ? notMet : verdict.criteria), budget);
2156
+ return;
2157
+ }
2158
+ const open = openQuestions(ctx, item);
2159
+ if (open > 0) {
2160
+ item.step = 'awaiting-merge';
2161
+ const questions = `${open} open question${open === 1 ? '' : 's'}`;
2162
+ tell(ctx, item, `CI green, ${said} — ${questions} wait${open === 1 ? 's' : ''} for you: run aidlc autopilot review ${item.name}, then merge ${prRef}`);
2163
+ notice(ctx, 'open questions', `${item.name}: ${questions} — ${prRef} waits for you to merge it`);
2164
+ return;
2165
+ }
2166
+ item.step = 'queued';
2167
+ if (!state.queue.includes(item.name))
2168
+ state.queue.push(item.name);
2169
+ tell(ctx, item, `CI green, ${said}, queued for merge`);
2170
+ }
1503
2171
  function advancePr(ctx, io, state, item, budget) {
1504
2172
  const view = prView(ctx, io, item);
1505
2173
  // An open question makes this pass a stop at the pull request: opened and watched, closed
@@ -1535,6 +2203,17 @@ function advancePr(ctx, io, state, item, budget) {
1535
2203
  const failing = failed.map((c) => c.name);
1536
2204
  if (failing.length === 0) {
1537
2205
  item.ci = 'passed';
2206
+ // Before the open questions: under `checked-merge` they are read once the check passed,
2207
+ // and under `pr` the item waits whatever (pr-checker-earns-merge/AC-1, AC-8, AC-11, AC-13).
2208
+ const stop = itemStops(item).stop_at;
2209
+ if (stop === 'pr' || stop === 'checked-merge') {
2210
+ if (item.check === undefined)
2211
+ launchCheck(ctx, io, state, item, budget);
2212
+ // A check that could not start is acted on in the same pass; a launched one waits for its verdict.
2213
+ if (item.check !== undefined && item.step === 'pr-open')
2214
+ actOnCheck(ctx, io, state, item, item.check, budget);
2215
+ return;
2216
+ }
1538
2217
  if (open > 0) {
1539
2218
  item.step = 'awaiting-merge';
1540
2219
  const questions = `${open} open question${open === 1 ? '' : 's'}`;
@@ -1573,7 +2252,7 @@ function advancePr(ctx, io, state, item, budget) {
1573
2252
  item.ci_failures = failures;
1574
2253
  tell(ctx, item, `CI failed (${failing.join(', ')}), relaunching the agent once`);
1575
2254
  item.step = 'building';
1576
- launchAgent(ctx, io, state, item, fixPrompt(item, failing, hostOf(ctx)), budget);
2255
+ relaunchBuild(ctx, io, state, item, fixPrompt(item, failing, hostOf(ctx)), budget);
1577
2256
  }
1578
2257
  /**
1579
2258
  * The item's checks, or null to do nothing with it this pass. On GitLab, the jobs of the
@@ -1712,6 +2391,13 @@ function serveQueue(ctx, io, state, budget) {
1712
2391
  state.queue.shift();
1713
2392
  return;
1714
2393
  }
2394
+ // The merge lane is one lane: a retrospective writes on main, so nothing merges or closes
2395
+ // out under it (autopilot-runs-retrospective/AC-3). Recorded, not said: it would repeat every pass.
2396
+ const retro = retroRunning(state);
2397
+ if (retro !== null) {
2398
+ record(ctx, item, `waiting — ${retro.name}'s retrospective is running on main`);
2399
+ return;
2400
+ }
1715
2401
  if (item.step === 'error') {
1716
2402
  // An observation repeated every pass: the failure that halted the queue already notified.
1717
2403
  ctx.say(`queue halted: ${item.name} — ${item.error}`);
@@ -1719,6 +2405,14 @@ function serveQueue(ctx, io, state, budget) {
1719
2405
  }
1720
2406
  if (droppedIfMerged(ctx, state, item, prView(ctx, io, item), budget))
1721
2407
  return;
2408
+ // The net under the verdict's discard: only a head a posted check passed is merged
2409
+ // (pr-checker-earns-merge/AC-12, AC-16, design D7).
2410
+ if (itemStops(item).stop_at === 'checked-merge' && !(item.check?.verdict?.verdict === 'PASS' && item.check.posted === true)) {
2411
+ dequeue(state, item);
2412
+ item.step = 'pr-open';
2413
+ tell(ctx, item, 'no posted PASS from the pull request check for this head — back to CI and the check');
2414
+ return;
2415
+ }
1722
2416
  const host = hostOf(ctx);
1723
2417
  if (host === 'gitlab' ? gitlabReleaseInFlight(ctx, io) : githubReleaseInFlight(ctx, io)) {
1724
2418
  tell(ctx, item, 'waiting — a release is already in flight');
@@ -1785,7 +2479,7 @@ function serveQueue(ctx, io, state, budget) {
1785
2479
  const closed = `merged${releases ? ', released' : ''} and closed${closeNote(report)}`;
1786
2480
  tell(ctx, item, closed);
1787
2481
  notice(ctx, releases ? 'item released' : 'item merged', `${item.name}: ${closed}`);
1788
- drop(state, item, budget);
2482
+ afterClose(ctx, io, state, item, budget);
1789
2483
  }
1790
2484
  /**
1791
2485
  * Park an item `aidlc start` failed on. By file, not by instance: a start that failed
@@ -1997,12 +2691,16 @@ export function tick(ctx, state, budget) {
1997
2691
  // `awaiting-review` is passed over: nothing to read until a person approves.
1998
2692
  if (item.step === 'building')
1999
2693
  advanceBuilding(ctx, io, state, item, budget);
2694
+ else if (item.step === 'checking')
2695
+ advanceChecking(ctx, io, state, item, budget);
2000
2696
  else if (item.step === 'approved')
2001
2697
  advanceApproved(ctx, io, state, item, budget);
2002
2698
  else if (item.step === 'pr-open')
2003
2699
  advancePr(ctx, io, state, item, budget);
2004
2700
  else if (item.step === 'awaiting-merge')
2005
2701
  advanceAwaitingMerge(ctx, io, state, item, budget);
2702
+ else if (item.step === 'retrospective')
2703
+ advanceRetrospective(ctx, io, state, item, budget);
2006
2704
  }
2007
2705
  serveQueue(ctx, io, state, budget);
2008
2706
  startBuilds(ctx, io, state, budget);
@@ -2048,8 +2746,22 @@ function waitingFor(i, host) {
2048
2746
  }
2049
2747
  if (i.step === 'awaiting-merge')
2050
2748
  return ` — waiting for you to merge ${ref(host, i.pr)}`;
2749
+ if (i.step === 'retrospective')
2750
+ return ` — running its retrospective on main since ${i.retro?.at ?? 'its close-out'}; nothing merges meanwhile`;
2051
2751
  return '';
2052
2752
  }
2753
+ /** The item's pull request check in words, or '' when it has none (pr-checker-earns-merge/AC-8). */
2754
+ export function checkNote(i) {
2755
+ const c = i.check;
2756
+ if (c === undefined)
2757
+ return '';
2758
+ if (c.blocked !== undefined)
2759
+ return ` — check could not decide: ${c.blocked}`;
2760
+ if (c.verdict === undefined)
2761
+ return i.step === 'checking' ? ` — check ${c.n} running` : '';
2762
+ const notMet = c.verdict.criteria.filter((x) => !x.met).map((x) => x.id);
2763
+ return ` — check ${c.n}: ${c.verdict.verdict}${notMet.length > 0 ? ` (not met: ${notMet.join(', ')})` : ''}${c.posted ? '' : ', not posted yet'}`;
2764
+ }
2053
2765
  /**
2054
2766
  * The driver's line, shared by `status` and the watch view.
2055
2767
  *
@@ -2082,7 +2794,7 @@ export function statusLines(ctx, state, host = 'github') {
2082
2794
  lines.push('no items in flight');
2083
2795
  for (const i of state.items) {
2084
2796
  lines.push(`${i.name}: ${i.step}${i.pr ? ` PR #${i.pr}` : ''} — CI failures ${i.ci_failures ?? 0}` +
2085
- `${waitingFor(i, host)}${i.error ? ` — last error: ${i.error}` : ''}`);
2797
+ `${checkNote(i)}${waitingFor(i, host)}${i.error ? ` — last error: ${i.error}` : ''}`);
2086
2798
  lines.push(...decisionCards(ctx, i));
2087
2799
  }
2088
2800
  const queue = queueLine(state);