@rasensio/aidlc 2.27.0 → 2.30.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 (189) hide show
  1. package/README.md +7 -1
  2. package/dist/autopilot/driver.d.ts +69 -7
  3. package/dist/autopilot/driver.d.ts.map +1 -1
  4. package/dist/autopilot/driver.js +371 -118
  5. package/dist/autopilot/driver.js.map +1 -1
  6. package/dist/autopilot/gitlab.d.ts +9 -0
  7. package/dist/autopilot/gitlab.d.ts.map +1 -1
  8. package/dist/autopilot/gitlab.js +21 -0
  9. package/dist/autopilot/gitlab.js.map +1 -1
  10. package/dist/autopilot/outcome.d.ts +72 -0
  11. package/dist/autopilot/outcome.d.ts.map +1 -0
  12. package/dist/autopilot/outcome.js +107 -0
  13. package/dist/autopilot/outcome.js.map +1 -0
  14. package/dist/autopilot/result.d.ts.map +1 -1
  15. package/dist/autopilot/result.js +8 -1
  16. package/dist/autopilot/result.js.map +1 -1
  17. package/dist/autopilot/retro.d.ts +7 -3
  18. package/dist/autopilot/retro.d.ts.map +1 -1
  19. package/dist/autopilot/retro.js +6 -2
  20. package/dist/autopilot/retro.js.map +1 -1
  21. package/dist/autopilot/state.d.ts +16 -1
  22. package/dist/autopilot/state.d.ts.map +1 -1
  23. package/dist/autopilot/state.js.map +1 -1
  24. package/dist/autopilot/team.d.ts +21 -1
  25. package/dist/autopilot/team.d.ts.map +1 -1
  26. package/dist/autopilot/team.js +27 -2
  27. package/dist/autopilot/team.js.map +1 -1
  28. package/dist/autopilot/typed.d.ts +10 -0
  29. package/dist/autopilot/typed.d.ts.map +1 -1
  30. package/dist/autopilot/typed.js +21 -0
  31. package/dist/autopilot/typed.js.map +1 -1
  32. package/dist/cli.d.ts.map +1 -1
  33. package/dist/cli.js +9 -0
  34. package/dist/cli.js.map +1 -1
  35. package/dist/closeout/gate-criterion.d.ts +33 -0
  36. package/dist/closeout/gate-criterion.d.ts.map +1 -0
  37. package/dist/closeout/gate-criterion.js +61 -0
  38. package/dist/closeout/gate-criterion.js.map +1 -0
  39. package/dist/closeout/hand-closeout.d.ts +43 -0
  40. package/dist/closeout/hand-closeout.d.ts.map +1 -0
  41. package/dist/closeout/hand-closeout.js +139 -0
  42. package/dist/closeout/hand-closeout.js.map +1 -0
  43. package/dist/closeout/outcome.d.ts +38 -0
  44. package/dist/closeout/outcome.d.ts.map +1 -0
  45. package/dist/closeout/outcome.js +141 -0
  46. package/dist/closeout/outcome.js.map +1 -0
  47. package/dist/commands/autopilot.d.ts +11 -1
  48. package/dist/commands/autopilot.d.ts.map +1 -1
  49. package/dist/commands/autopilot.js +97 -4
  50. package/dist/commands/autopilot.js.map +1 -1
  51. package/dist/commands/init.d.ts +3 -0
  52. package/dist/commands/init.d.ts.map +1 -1
  53. package/dist/commands/init.js +51 -3
  54. package/dist/commands/init.js.map +1 -1
  55. package/dist/commands/status.d.ts.map +1 -1
  56. package/dist/commands/status.js +5 -0
  57. package/dist/commands/status.js.map +1 -1
  58. package/dist/commands/transition.d.ts.map +1 -1
  59. package/dist/commands/transition.js +70 -1
  60. package/dist/commands/transition.js.map +1 -1
  61. package/dist/commands/update.d.ts.map +1 -1
  62. package/dist/commands/update.js +23 -4
  63. package/dist/commands/update.js.map +1 -1
  64. package/dist/compile/register-template.d.ts +12 -9
  65. package/dist/compile/register-template.d.ts.map +1 -1
  66. package/dist/compile/register-template.js +14 -31
  67. package/dist/compile/register-template.js.map +1 -1
  68. package/dist/compile/resource-template.d.ts +45 -0
  69. package/dist/compile/resource-template.d.ts.map +1 -0
  70. package/dist/compile/resource-template.js +53 -0
  71. package/dist/compile/resource-template.js.map +1 -0
  72. package/dist/compile/skill-metadata.d.ts +22 -1
  73. package/dist/compile/skill-metadata.d.ts.map +1 -1
  74. package/dist/compile/skill-metadata.js +55 -8
  75. package/dist/compile/skill-metadata.js.map +1 -1
  76. package/dist/compile/system-template.d.ts +38 -0
  77. package/dist/compile/system-template.d.ts.map +1 -0
  78. package/dist/compile/system-template.js +40 -0
  79. package/dist/compile/system-template.js.map +1 -0
  80. package/dist/concurrency/common-dir.d.ts +13 -0
  81. package/dist/concurrency/common-dir.d.ts.map +1 -1
  82. package/dist/concurrency/common-dir.js +9 -8
  83. package/dist/concurrency/common-dir.js.map +1 -1
  84. package/dist/concurrency/gitattributes.d.ts +2 -2
  85. package/dist/concurrency/gitattributes.d.ts.map +1 -1
  86. package/dist/concurrency/gitattributes.js +5 -14
  87. package/dist/concurrency/gitattributes.js.map +1 -1
  88. package/dist/console/operator/read.d.ts.map +1 -1
  89. package/dist/console/operator/read.js +2 -1
  90. package/dist/console/operator/read.js.map +1 -1
  91. package/dist/core/next-steps.d.ts.map +1 -1
  92. package/dist/core/next-steps.js +8 -0
  93. package/dist/core/next-steps.js.map +1 -1
  94. package/dist/core/project-version.d.ts +52 -0
  95. package/dist/core/project-version.d.ts.map +1 -0
  96. package/dist/core/project-version.js +188 -0
  97. package/dist/core/project-version.js.map +1 -0
  98. package/dist/core/template-resolver.d.ts.map +1 -1
  99. package/dist/core/template-resolver.js +90 -8
  100. package/dist/core/template-resolver.js.map +1 -1
  101. package/dist/core/types.d.ts +4 -1
  102. package/dist/core/types.d.ts.map +1 -1
  103. package/dist/cost/dedupe-history.d.ts.map +1 -1
  104. package/dist/cost/dedupe-history.js +3 -2
  105. package/dist/cost/dedupe-history.js.map +1 -1
  106. package/dist/cost/gitignore.d.ts +9 -4
  107. package/dist/cost/gitignore.d.ts.map +1 -1
  108. package/dist/cost/gitignore.js +16 -5
  109. package/dist/cost/gitignore.js.map +1 -1
  110. package/dist/cost/ledger.d.ts +1 -4
  111. package/dist/cost/ledger.d.ts.map +1 -1
  112. package/dist/cost/ledger.js +25 -21
  113. package/dist/cost/ledger.js.map +1 -1
  114. package/dist/cost/purge.d.ts.map +1 -1
  115. package/dist/cost/purge.js +3 -2
  116. package/dist/cost/purge.js.map +1 -1
  117. package/dist/cost/record-paths.d.ts +42 -0
  118. package/dist/cost/record-paths.d.ts.map +1 -0
  119. package/dist/cost/record-paths.js +119 -0
  120. package/dist/cost/record-paths.js.map +1 -0
  121. package/dist/cost/rederive.d.ts.map +1 -1
  122. package/dist/cost/rederive.js +4 -3
  123. package/dist/cost/rederive.js.map +1 -1
  124. package/dist/cost/sessions.d.ts +1 -1
  125. package/dist/cost/sessions.d.ts.map +1 -1
  126. package/dist/cost/sessions.js +22 -12
  127. package/dist/cost/sessions.js.map +1 -1
  128. package/dist/discover/scanner.d.ts +11 -1
  129. package/dist/discover/scanner.d.ts.map +1 -1
  130. package/dist/discover/scanner.js +23 -2
  131. package/dist/discover/scanner.js.map +1 -1
  132. package/dist/doctor/migrations/cost-gitignore.d.ts.map +1 -1
  133. package/dist/doctor/migrations/cost-gitignore.js +18 -8
  134. package/dist/doctor/migrations/cost-gitignore.js.map +1 -1
  135. package/dist/doctor/migrations/cost-records-out-of-git.d.ts +39 -0
  136. package/dist/doctor/migrations/cost-records-out-of-git.d.ts.map +1 -0
  137. package/dist/doctor/migrations/cost-records-out-of-git.js +158 -0
  138. package/dist/doctor/migrations/cost-records-out-of-git.js.map +1 -0
  139. package/dist/doctor/migrations/decision-register-location.d.ts +59 -0
  140. package/dist/doctor/migrations/decision-register-location.d.ts.map +1 -0
  141. package/dist/doctor/migrations/decision-register-location.js +226 -0
  142. package/dist/doctor/migrations/decision-register-location.js.map +1 -0
  143. package/dist/doctor/migrations/deployment-outcome.d.ts +29 -0
  144. package/dist/doctor/migrations/deployment-outcome.d.ts.map +1 -0
  145. package/dist/doctor/migrations/deployment-outcome.js +89 -0
  146. package/dist/doctor/migrations/deployment-outcome.js.map +1 -0
  147. package/dist/doctor/migrations/index.d.ts.map +1 -1
  148. package/dist/doctor/migrations/index.js +16 -0
  149. package/dist/doctor/migrations/index.js.map +1 -1
  150. package/dist/doctor/migrations/nested-gitignore.d.ts +2 -2
  151. package/dist/doctor/migrations/nested-gitignore.js +2 -2
  152. package/dist/doctor/migrations/tracked-nested-ignored.d.ts.map +1 -1
  153. package/dist/doctor/migrations/tracked-nested-ignored.js +4 -1
  154. package/dist/doctor/migrations/tracked-nested-ignored.js.map +1 -1
  155. package/dist/doctor/migrations/untrack-cost-ephemera.d.ts +3 -1
  156. package/dist/doctor/migrations/untrack-cost-ephemera.d.ts.map +1 -1
  157. package/dist/doctor/migrations/untrack-cost-ephemera.js +3 -1
  158. package/dist/doctor/migrations/untrack-cost-ephemera.js.map +1 -1
  159. package/dist/knowledge/index/sqlite-index.d.ts.map +1 -1
  160. package/dist/knowledge/index/sqlite-index.js +13 -0
  161. package/dist/knowledge/index/sqlite-index.js.map +1 -1
  162. package/dist/knowledge/storable.d.ts +6 -3
  163. package/dist/knowledge/storable.d.ts.map +1 -1
  164. package/dist/knowledge/storable.js +10 -6
  165. package/dist/knowledge/storable.js.map +1 -1
  166. package/dist/metrics/report.d.ts.map +1 -1
  167. package/dist/metrics/report.js +2 -1
  168. package/dist/metrics/report.js.map +1 -1
  169. package/dist/roadmap/view-assets.d.ts +7 -0
  170. package/dist/roadmap/view-assets.d.ts.map +1 -1
  171. package/dist/roadmap/view-assets.js +10 -0
  172. package/dist/roadmap/view-assets.js.map +1 -1
  173. package/dist/roadmap/view-html.d.ts +6 -0
  174. package/dist/roadmap/view-html.d.ts.map +1 -1
  175. package/dist/roadmap/view-html.js +35 -4
  176. package/dist/roadmap/view-html.js.map +1 -1
  177. package/dist/roadmap/view-model.d.ts +26 -0
  178. package/dist/roadmap/view-model.d.ts.map +1 -1
  179. package/dist/roadmap/view-model.js +27 -1
  180. package/dist/roadmap/view-model.js.map +1 -1
  181. package/dist/setup/setup-compute.d.ts +5 -0
  182. package/dist/setup/setup-compute.d.ts.map +1 -1
  183. package/dist/setup/setup-compute.js +1 -0
  184. package/dist/setup/setup-compute.js.map +1 -1
  185. package/dist/setup/tier-models.d.ts +51 -0
  186. package/dist/setup/tier-models.d.ts.map +1 -0
  187. package/dist/setup/tier-models.js +175 -0
  188. package/dist/setup/tier-models.js.map +1 -0
  189. package/package.json +2 -2
@@ -16,15 +16,20 @@
16
16
  * @module
17
17
  */
18
18
  import { join, resolve } from 'node:path';
19
+ import { parse as parseYaml } from 'yaml';
19
20
  import { mapUnits } from '../cost/providers/codex.js';
20
21
  import { microToUsd, priceUnits } from '../cost/rates.js';
21
22
  import { MODEL_ID_RE } from '../cost/types.js';
22
23
  import { hostFromConfigText } from '../core/host.js';
24
+ import { PHASE_TIERS, resolveSkillTiers } from '../compile/skill-metadata.js';
23
25
  import { DIFF_MAX, DIFF_PATHSPEC, VERDICT_SCHEMA, changedSince, checkerPrompt, fingerprint, parseVerdict, readCriteria, rejectPrompt, renderVerdict, } from './check.js';
24
26
  import { classify, jobRef, parseRunJobs } from './ci-jobs.js';
25
- import { GLAB_READ_RE, TAG_PIPELINES_ARGS, classifyJobs, jobsArgs, mergeArgs, mergedAnswer, mrCreateArgs, mrNumber, mrViewArgs, noteArgs, parseJobs, parseMr, releaseInFlight, retryArgs, } from './gitlab.js';
27
+ import { GLAB_READ_RE, TAG_PIPELINES_ARGS, classifyJobs, jobsArgs, mergeArgs, mergedAnswer, mrCreateArgs, mrNumber, mrViewArgs, noteArgs, parseJobs, parseMergeCommit, parseMr, releaseInFlight, retryArgs, } from './gitlab.js';
28
+ import { deployRunArgs, ghMergeCommitArgs, outcomeStop, parseDeployRun, parseGhMergeCommit, renderOutcome, } from './outcome.js';
29
+ import { recordPath } from '../closeout/gate-criterion.js';
30
+ import { readOutcome, withOutcome } from '../closeout/outcome.js';
26
31
  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';
32
+ import { emptyState, retroMarker, retroSnapshotPath } from './state.js';
28
33
  import { RETRO_LIMIT_MS, retroAllowed, retroChanges, retroPrompt } from './retro.js';
29
34
  import { capInForce, tokensLeft } from './cap.js';
30
35
  import { fmtTokens } from '../commands/cost.js';
@@ -67,6 +72,19 @@ const BACKOFF_MAX_MS = 2 * 60 * 60 * 1000;
67
72
  const CI_FAILURE_LIMIT = 2;
68
73
  /** Agent relaunches to resolve conflicts with main before an item is parked (autopilot-merge-lane-stalls-on-conflicts/AC-11). */
69
74
  export const CONFLICT_FIX_LIMIT = 2;
75
+ /**
76
+ * Templates whose instances ship a release post. A copy of POST_TEMPLATES in
77
+ * packages/website/scripts/blog/bookkeeping.mjs, which the CLI cannot import; a test keeps
78
+ * the two equal (autopilot-checks-post-files-before-pr/AC-1, design D5).
79
+ */
80
+ export const POST_TEMPLATES = ['quick-feature', 'full-feature', 'bugfix'];
81
+ /**
82
+ * Where the post files live, from the project root. This repository's convention, not the
83
+ * framework's: a project without the directory owes no post (autopilot-checks-post-files-before-pr/AC-3).
84
+ */
85
+ export const POST_DIR = 'packages/website/content/blog/overrides';
86
+ /** Agent relaunches to write missing post files before the item is parked (autopilot-checks-post-files-before-pr/AC-2). */
87
+ export const POST_FILE_FIX_LIMIT = 1;
70
88
  export class RateLimited extends Error {
71
89
  }
72
90
  const JOBS_READ_RE = /^api repos\/\{owner\}\/\{repo\}\/actions\/runs\/\d+\/jobs$/;
@@ -174,26 +192,45 @@ const Ref = (host, n) => {
174
192
  const r = ref(host, n);
175
193
  return r[0].toUpperCase() + r.slice(1);
176
194
  };
177
- /**
195
+ /** The phases whose launch stops at the release boundary rather than at the phase's end (design D5). */
196
+ const RELEASE_PHASES = new Set(['testing', 'deployment']);
197
+ /** Whether `name` is a lifecycle phase: it reaches a prompt and a file path (design, Non-functional). */
198
+ const isPhaseName = (name) => typeof name === 'string' && Object.hasOwn(PHASE_TIERS, name);
199
+ /**
200
+ * The build prompt for one phase: complete it, commit and stop, so autopilot starts a
201
+ * fresh agent for the next (phase-agents-on-tier-models/AC-1). Testing and deployment
202
+ * stop at the release boundary, as the one whole-lifecycle prompt did (AC-2).
203
+ *
178
204
  * @param pauses - `AIDLC_PAUSE_AFTER` as the agent will see it. Empty is said in words,
179
205
  * because the rule reads a prompt silent on the list as "nobody told me" and pauses
180
206
  * everywhere (scoped-preset-cannot-read-unattended-env/AC-2).
181
207
  */
182
- export function agentPrompt(item, pauses = '') {
208
+ export function phasePrompt(item, phase, pauses = '') {
183
209
  return (`You are running unattended (AIDLC_UNATTENDED=1). Follow .aidlc/resources/rules/unattended.md. ` +
184
- `Continue the AIDLC instance "${item.name}" in this worktree with the aidlc-continue skill, through ` +
185
- `every phase up to the release boundary: complete testing, write the deployment record's release ` +
186
- `plan, commit on this branch, and stop. Do not push, open a pull request, merge or release.` +
210
+ `Continue the AIDLC instance "${item.name}" in this worktree with the aidlc-continue skill. ` +
211
+ (RELEASE_PHASES.has(phase)
212
+ ? `Complete the ${phase} phase up to the release boundary: complete testing, write the deployment ` +
213
+ `record's release plan and the release's blog post files, commit on this branch, and stop.`
214
+ : `Complete the ${phase} phase only, commit on this branch, and stop. Do not start the next phase; ` +
215
+ `autopilot starts a fresh agent for it.`) +
216
+ ` Do not push, open a pull request, merge or release.` +
187
217
  (pauses
188
218
  ? ` AIDLC_PAUSE_AFTER=${pauses}: when one of those phases completes, stop there instead — that is ` +
189
219
  `the rule's review boundary: commit, release your claim, and stop.`
190
- : ` AIDLC_PAUSE_AFTER is empty: no phase is a review boundary, so carry on through every phase.`));
220
+ : ` AIDLC_PAUSE_AFTER is empty: no phase is a review boundary.`));
191
221
  }
192
222
  export function fixPrompt(item, failing, host = 'github') {
193
223
  return (`You are running unattended (AIDLC_UNATTENDED=1). Follow .aidlc/resources/rules/unattended.md. ` +
194
224
  `CI failed on ${ref(host, item.pr)} for the AIDLC instance "${item.name}": ${failing.join(', ')}. ` +
195
225
  `Find the cause, fix it on this branch, run the tests, commit, and stop. Do not push, merge or release.`);
196
226
  }
227
+ /** The one relaunch to write missing post files; names each by its path (autopilot-checks-post-files-before-pr/AC-1). */
228
+ export function postFilesPrompt(item, missing) {
229
+ return (`You are running unattended (AIDLC_UNATTENDED=1). Follow .aidlc/resources/rules/unattended.md. ` +
230
+ `The AIDLC instance "${item.name}" is at deployment, but its release post files are missing: ` +
231
+ `${missing.join(', ')}. Read .aidlc/guidance/blog-post.md and follow it to write them, commit them ` +
232
+ `on this branch, and stop. Do not push, open a pull request, merge or release.`);
233
+ }
197
234
  export function conflictPrompt(item, host = 'github') {
198
235
  return (`You are running unattended (AIDLC_UNATTENDED=1). Follow .aidlc/resources/rules/unattended.md. ` +
199
236
  `${Ref(host, item.pr)} for the AIDLC instance "${item.name}" conflicts with main. Run ` +
@@ -346,7 +383,7 @@ const logFile = (ctx, item) => `${ctx.paths.logs}/${item.name}.log`;
346
383
  *
347
384
  * @param budget - the run's item budget, which a park here must reach.
348
385
  */
349
- function launchAgent(ctx, io, state, item, prompt, budget, resume, kind = 'build') {
386
+ function launchAgent(ctx, io, state, item, prompt, budget, resume, kind = 'build', phase) {
350
387
  if (launchBlocked(state, ctx.now()) !== null)
351
388
  return false;
352
389
  const capSet = capInForce(ctx.config);
@@ -376,6 +413,10 @@ function launchAgent(ctx, io, state, item, prompt, budget, resume, kind = 'build
376
413
  // Its own file, so a build's outcome is never read as the retrospective's (autopilot-runs-retrospective, design D2).
377
414
  const outcomeFile = `${ctx.paths.dir}/outcomes/${item.name}${check ? '.check' : kind === 'retro' ? '.retro' : ''}.json`;
378
415
  const schemaFile = `${ctx.paths.dir}/${check ? 'check' : 'outcome'}-schema.json`;
416
+ // Only a phase launch carries its tier's model; a resume keeps the stopped launch's
417
+ // phase and flags, never re-reading config (phase-agents-on-tier-models/AC-9, AC-18).
418
+ const named = resume !== undefined ? resume.from?.phase : kind === 'build' ? phase : undefined;
419
+ const tier = resume !== undefined ? resume.from?.tier : named === undefined ? undefined : tierFor(ctx, harness, named);
379
420
  const typed = typedArgv(command, {
380
421
  harness,
381
422
  prompt: check ? prompt : withOutcomeContract(prompt),
@@ -384,6 +425,7 @@ function launchAgent(ctx, io, state, item, prompt, budget, resume, kind = 'build
384
425
  maxBudgetCents: harness === 'claude' ? cents : null,
385
426
  resume: check ? null : resume?.session ?? null,
386
427
  ...(check ? { schema: VERDICT_SCHEMA, disallowedTools: ['Edit', 'Write', 'NotebookEdit'] } : {}),
428
+ ...(tier === undefined || check ? {} : { tier }),
387
429
  });
388
430
  if (typed === null) {
389
431
  if (kind !== 'retro')
@@ -399,6 +441,8 @@ function launchAgent(ctx, io, state, item, prompt, budget, resume, kind = 'build
399
441
  log_offset: 0,
400
442
  ...(harness === 'codex' ? { outcome_file: outcomeFile, progress: emptyCodexProgress() } : {}),
401
443
  ...(resume === undefined ? {} : { resumes: resume.session }),
444
+ ...(named === undefined ? {} : { phase: named }),
445
+ ...(tier === undefined || check ? {} : { tier }),
402
446
  };
403
447
  // A resume continues the thread's rollout, which sits in its first launch's day
404
448
  // directory, and Codex reports the model there once (design D10).
@@ -457,6 +501,76 @@ function launchAgent(ctx, io, state, item, prompt, budget, resume, kind = 'build
457
501
  tell(ctx, item, `${who} started (pid ${item.pid})`);
458
502
  return true;
459
503
  }
504
+ /**
505
+ * The tier flags for a phase launch, from the primary checkout's `skill_tiers` — read at
506
+ * launch, so a `setup` run between phases applies to the next one (design D6). Only the
507
+ * launch's own platform's set (AC-19); unreadable config, no entry, `inherit` or a
508
+ * rejected value is no flag (AC-16).
509
+ */
510
+ function tierFor(ctx, harness, phase) {
511
+ if (!isPhaseName(phase))
512
+ return undefined;
513
+ const text = ctx.fs.read(`${ctx.repo}/.aidlc/config.yaml`);
514
+ if (text === null)
515
+ return undefined;
516
+ let raw;
517
+ try {
518
+ raw = parseYaml(text)?.skill_tiers;
519
+ }
520
+ catch {
521
+ return undefined;
522
+ }
523
+ const tier = resolveSkillTiers(raw, harness === 'codex' ? 'codex' : 'claude-code').tiers[PHASE_TIERS[phase]];
524
+ if (tier === undefined)
525
+ return undefined;
526
+ return { ...(tier.model === undefined ? {} : { model: tier.model }), ...(tier.effort === undefined ? {} : { effort: tier.effort }) };
527
+ }
528
+ /**
529
+ * Release the instance's claim from the item's worktree before a new session takes it.
530
+ * The stopped session's claim outlives it by the 60-minute staleness, and the next
531
+ * session may run under another id, whose `aidlc claim` it would refuse. From the
532
+ * worktree: an in-flight instance's state is on its branch, and `release` refuses an
533
+ * instance it cannot find. A failure is said, and the launch goes ahead
534
+ * (phase-agents-on-tier-models/AC-6).
535
+ */
536
+ function releaseClaim(ctx, io, item, lead, then) {
537
+ const released = io.call(ctx.cli[0], [...ctx.cli.slice(1), 'release', item.name], { cwd: item.worktree });
538
+ if (released.status !== 0) {
539
+ const said = `${lead} — could not release the claim: ${fail(released)}; ${then}`;
540
+ tell(ctx, item, said);
541
+ // The item's own log too: it is where the next session's summary lands.
542
+ appendSummary(ctx, item, [`[autopilot] ${said}`]);
543
+ }
544
+ }
545
+ /**
546
+ * Launch a build agent for the instance's current phase, read from its worktree when
547
+ * the launch is made, so whatever brings an item back starts where it is and redoes no
548
+ * earlier phase (phase-agents-on-tier-models/AC-1, AC-7). `release` frees the claim a
549
+ * session before it holds (AC-6). False when nothing was launched, as `launchAgent`.
550
+ */
551
+ function launchPhase(ctx, io, state, item, budget, opts) {
552
+ const read = currentPhase(ctx, item);
553
+ let phase;
554
+ if (isPhaseName(read))
555
+ phase = read;
556
+ else if (ctx.dryRun)
557
+ phase = '<current phase>';
558
+ else {
559
+ park(ctx, io, state, item, `could not read the instance's current phase${read === null ? '' : ` (${read})`}`, budget);
560
+ return false;
561
+ }
562
+ if (opts.release && !ctx.dryRun)
563
+ releaseClaim(ctx, io, item, `starting ${phase}`, 'launching anyway');
564
+ if (isPhaseName(phase))
565
+ item.build_phase = phase;
566
+ return launchAgent(ctx, io, state, item, phasePrompt(item, phase, itemPauses(item)), budget, undefined, 'build', phase);
567
+ }
568
+ /** Whether a phase's own file reads `status: complete`; false for a name that is not a phase. */
569
+ function namedPhaseComplete(ctx, item, phase) {
570
+ if (!isPhaseName(phase))
571
+ return false;
572
+ return COMPLETE_RE.test(ctx.fs.read(`${item.worktree}/.aidlc/state/${item.name}/phase-${phase}.yaml`) ?? '');
573
+ }
460
574
  function drop(state, item, budget) {
461
575
  state.items = state.items.filter((i) => i !== item);
462
576
  state.queue = state.queue.filter((n) => n !== item.name);
@@ -488,6 +602,56 @@ export function instancePhase(read, item) {
488
602
  function currentPhase(ctx, item) {
489
603
  return instancePhase(ctx.fs.read, item);
490
604
  }
605
+ /**
606
+ * The instance's `template` in its worktree, or null when unreadable. The same shape rule as
607
+ * {@link instancePhase}: the agent writes this file, so only a template-shaped name is read.
608
+ */
609
+ export function instanceTemplate(read, item) {
610
+ const yaml = read(`${item.worktree}/.aidlc/state/${item.name}/instance.yaml`) ?? '';
611
+ return /^template:[ \t]*([A-Za-z0-9_-]{1,64})(?=\s|$)/m.exec(yaml)?.[1] ?? null;
612
+ }
613
+ /**
614
+ * The post files missing for this item, as paths from the project root, `.json` first. Empty
615
+ * when none is owed: the template is not one that ships a post or cannot be read (design D4),
616
+ * or the worktree has no {@link POST_DIR} (autopilot-checks-post-files-before-pr/AC-1, AC-3).
617
+ * Presence only, on disk: CI checks what was committed (design D6).
618
+ */
619
+ export function missingPostFiles(ctx, item) {
620
+ const template = instanceTemplate(ctx.fs.read, item);
621
+ if (template === null || !POST_TEMPLATES.includes(template))
622
+ return [];
623
+ if (!ctx.fs.exists(`${item.worktree}/${POST_DIR}`))
624
+ return [];
625
+ return [`${POST_DIR}/${item.name}-post.json`, `${POST_DIR}/${item.name}-post.md`].filter((path) => !ctx.fs.exists(`${item.worktree}/${path}`));
626
+ }
627
+ /**
628
+ * Whether the push may go ahead. False when a post file is missing, and then this has
629
+ * already relaunched the agent once, parked the item, or said why it waits. One relaunch in
630
+ * the item's life, counted in `state.json`, so nothing loops and a restart resets nothing
631
+ * (autopilot-checks-post-files-before-pr/AC-1, AC-2, design D2, D3).
632
+ */
633
+ function postFilesReady(ctx, io, state, item, budget) {
634
+ const missing = missingPostFiles(ctx, item);
635
+ if (missing.length === 0)
636
+ return true;
637
+ const tries = item.post_file_fixes ?? 0;
638
+ if (tries >= POST_FILE_FIX_LIMIT) {
639
+ park(ctx, io, state, item, `post files still missing after one relaunch: ${missing.join(', ')}`, budget);
640
+ return false;
641
+ }
642
+ const blocked = launchBlocked(state, ctx.now());
643
+ if (blocked !== null) {
644
+ // No attempt is made, so none is counted; still `building`, so the next pass decides again.
645
+ item.step = 'building';
646
+ tell(ctx, item, `post files missing — the relaunch waits for the session limit to reset at ${blocked}`);
647
+ return false;
648
+ }
649
+ item.post_file_fixes = tries + 1;
650
+ item.step = 'building';
651
+ tell(ctx, item, `post files missing (${missing.join(', ')}) — relaunching the agent once to write them`);
652
+ relaunchBuild(ctx, io, state, item, postFilesPrompt(item, missing), budget);
653
+ return false;
654
+ }
491
655
  /** A phase file's own top-level status, not an artifact's indented one. */
492
656
  const COMPLETE_RE = /^status:\s*complete\s*$/m;
493
657
  function phaseComplete(ctx, item, phase) {
@@ -969,23 +1133,22 @@ function resumeWhenDue(ctx, io, state, item, wait, budget) {
969
1133
  return;
970
1134
  }
971
1135
  tell(ctx, item, `${label} — resuming session ${wait.session}`);
972
- // The stopped session's claim outlives it by the 60-minute staleness, and a resume may
973
- // run under another id, whose `aidlc claim` it would refuse. From the worktree: an
974
- // in-flight instance's state is on its branch, and `release` refuses an instance it
975
- // cannot find.
976
- const released = io.call(ctx.cli[0], [...ctx.cli.slice(1), 'release', item.name], { cwd: item.worktree });
977
- if (released.status !== 0) {
978
- const said = `${label} — could not release the claim: ${fail(released)}; resuming anyway`;
979
- tell(ctx, item, said);
980
- // The item's own log too: it is where the resumed session's summary lands next.
981
- appendSummary(ctx, item, [`[autopilot] ${said}`]);
982
- }
1136
+ releaseClaim(ctx, io, item, label, 'resuming anyway');
983
1137
  launchAgent(ctx, io, state, item, resumePrompt(item, label), budget, { session: wait.session, label, from });
984
1138
  }
985
- /** At deployment, the pull request; short of it, parked. `suffix` follows the park reason. */
1139
+ /**
1140
+ * At deployment, the pull request. Short of it: the next phase's agent when the phase
1141
+ * the launch named is complete and the instance has moved on — a custom command has no
1142
+ * outcome to say `shipped`, so its phase file is the evidence (design D4) — and
1143
+ * otherwise parked. `suffix` follows the park reason.
1144
+ */
986
1145
  function byPhase(ctx, io, state, item, budget, suffix = '') {
987
1146
  const phase = currentPhase(ctx, item);
988
1147
  if (phase !== 'deployment') {
1148
+ if (phase !== null && phase !== item.build_phase && namedPhaseComplete(ctx, item, item.build_phase)) {
1149
+ launchPhase(ctx, io, state, item, budget, { release: true });
1150
+ return;
1151
+ }
989
1152
  park(ctx, io, state, item, `agent exited before the release boundary (phase ${phase ?? 'unknown'})${suffix}`, budget);
990
1153
  return;
991
1154
  }
@@ -1044,6 +1207,14 @@ function decideFromResult(ctx, io, state, item, launch, end, budget) {
1044
1207
  openPullRequest(ctx, io, state, item, budget);
1045
1208
  return;
1046
1209
  }
1210
+ // The phase it was told to complete is complete and the instance has moved on: a fresh
1211
+ // agent for the next phase, with no pull request (phase-agents-on-tier-models/AC-3). A
1212
+ // session-limit wait leaves the item `building` with this launch, so the next pass
1213
+ // decides this row again and launches then.
1214
+ if (outcome === 'shipped' && phase !== launch.phase && namedPhaseComplete(ctx, item, launch.phase)) {
1215
+ launchPhase(ctx, io, state, item, budget, { release: true });
1216
+ return;
1217
+ }
1047
1218
  // A `paused` that awaits review was handled before this; one that does not is a stop
1048
1219
  // the phase files do not bear out (AC-11).
1049
1220
  early(`agent reported ${outcome}, but the instance is at ${phase}`);
@@ -1102,11 +1273,15 @@ function advanceApproved(ctx, io, state, item, budget) {
1102
1273
  item.step = 'building';
1103
1274
  tell(ctx, item, 'approved — relaunching the agent to carry on');
1104
1275
  // The run's budget: a park for the cap here must reach `run.finished`, or `--items n` never ends.
1105
- launchAgent(ctx, io, state, item, agentPrompt(item, itemPauses(item)), budget);
1276
+ // A fresh agent for the phase the instance is at (phase-agents-on-tier-models/AC-10).
1277
+ launchPhase(ctx, io, state, item, budget, { release: true });
1106
1278
  }
1107
1279
  /** The primary checkout's `host`; absent or invalid is `github` (gitlab-and-plain-git/AC-2). */
1108
1280
  const hostOf = (ctx) => hostFromConfigText(ctx.fs.read(`${ctx.repo}/.aidlc/config.yaml`));
1109
1281
  function openPullRequest(ctx, io, state, item, budget) {
1282
+ // Here, not in the three callers, so every way to the push is covered (design D1).
1283
+ if (!postFilesReady(ctx, io, state, item, budget))
1284
+ return;
1110
1285
  const push = io.call('git', ['push', '-u', 'origin', item.branch], { cwd: item.worktree });
1111
1286
  if (push.status !== 0) {
1112
1287
  failItem(ctx, state, item, `push failed: ${fail(push)}`, 'building');
@@ -1238,7 +1413,7 @@ function closeOut(ctx, io, state, item, budget) {
1238
1413
  return;
1239
1414
  }
1240
1415
  const report = emptyReport();
1241
- for (const [label, step] of closeSteps(ctx, io, item, report)) {
1416
+ for (const [label, step] of closeSteps(ctx, io, item, report, { released: false, byPerson: true })) {
1242
1417
  const r = step();
1243
1418
  if (r.status !== 0) {
1244
1419
  const error = `${label} failed: ${fail(r)}`;
@@ -1262,26 +1437,55 @@ const DRY_PATHS = '<the paths the close-out changed>';
1262
1437
  * is removed (closeout-carries-worktree-state/AC-4, design D1).
1263
1438
  */
1264
1439
  function dirtyPaths(ctx, io, prefix, pathspec = '.aidlc') {
1440
+ const records = dirtyRecords(ctx, io, prefix, pathspec);
1441
+ return Array.isArray(records) ? records.map((r) => r.path) : records;
1442
+ }
1443
+ /**
1444
+ * `dirtyPaths` with the status letters kept: they are the one thing that tells a tracked
1445
+ * file deleted from the working tree from a staged deletion or a missing untracked one
1446
+ * (closeout-leaves-item-in-two-folders design D1).
1447
+ */
1448
+ function dirtyRecords(ctx, io, prefix, pathspec = '.aidlc') {
1265
1449
  const r = io.call('git', ['status', '--porcelain=v1', '-z', '--no-renames', '--untracked-files=all', '--', pathspec], { cwd: ctx.repo });
1266
1450
  if (r.status !== 0)
1267
1451
  return r;
1268
1452
  return r.stdout
1269
1453
  .split('\0')
1270
1454
  .filter((rec) => rec.length > 3)
1271
- .map((rec) => rec.slice(3))
1272
- .map((p) => (p.startsWith(prefix) ? p.slice(prefix.length) : p));
1455
+ .map((rec) => ({ xy: rec.slice(0, 2), path: rec.slice(3) }))
1456
+ .map(({ xy, path }) => ({ xy, path: path.startsWith(prefix) ? path.slice(prefix.length) : path }));
1273
1457
  }
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'];
1458
+ /**
1459
+ * Is this uncommitted record the closed item's old copy, the move `aidlc start` left
1460
+ * uncommitted? Only a tracked file deleted from the working tree (`xy[1] === 'D'`), so
1461
+ * `git add` stages that deletion and nothing else; only directly in a roadmap folder other
1462
+ * than `done/`, under the item's own file name, compared by segment so `one.md` never
1463
+ * matches `one.md.bak` (closeout-leaves-item-in-two-folders/AC-1, AC-2, design D2).
1464
+ */
1465
+ export function oldItemCopy(path, xy, file) {
1466
+ if (xy[1] !== 'D' || file === '' || file.includes('/'))
1467
+ return false;
1468
+ const root = '.aidlc/roadmap/';
1469
+ if (!path.startsWith(root))
1470
+ return false;
1471
+ const rest = path.slice(root.length).split('/');
1472
+ return rest.length === 2 && rest[0] !== '' && rest[0] !== 'done' && rest[1] === file;
1473
+ }
1474
+ /**
1475
+ * Written in the worktree after its last commit; `pr-check.md` by the pull request check
1476
+ * (pr-checker-earns-merge/AC-17). No `costs.ndjson`: the ledger lives in the git common
1477
+ * directory, which main and every worktree share, so there is nothing to carry
1478
+ * (finished-work-tidies-itself/AC-8).
1479
+ */
1480
+ const LATE_FILES = ['unattended-stops.md', 'pr-check.md'];
1276
1481
  /** `t` without its `**Review:**` lines — the line `withVerdict` inserts or replaces. */
1277
1482
  const withoutVerdicts = (t) => t
1278
1483
  .split('\n')
1279
1484
  .filter((l) => !l.startsWith('**Review:**'))
1280
1485
  .join('\n');
1281
1486
  /**
1282
- * May `from` (the worktree's copy) replace `to` (main's)? The cost hook only appends, so
1283
- * main's ledger is a prefix of the worktree's; a verdict is inserted after its entry, so the
1284
- * stops log is a prefix only once both are read without verdicts
1487
+ * May `from` (the worktree's copy) replace `to` (main's)? A verdict is inserted after its
1488
+ * entry, so the stops log is a prefix only once both are read without verdicts
1285
1489
  * (closeout-carries-worktree-state/AC-1, AC-2).
1286
1490
  */
1287
1491
  export function carries(file, to, from) {
@@ -1289,8 +1493,6 @@ export function carries(file, to, from) {
1289
1493
  return 'copy';
1290
1494
  if (from === to)
1291
1495
  return 'same';
1292
- if (file === 'costs.ndjson')
1293
- return from.startsWith(to) && from.length > to.length ? 'copy' : 'refuse';
1294
1496
  return withoutVerdicts(from).startsWith(withoutVerdicts(to)) ? 'copy' : 'refuse';
1295
1497
  }
1296
1498
  /**
@@ -1331,7 +1533,7 @@ function closeNote(report) {
1331
1533
  * what the close-out changed: `git add .aidlc` swept a stale rule file into the commit and
1332
1534
  * turned main red twice (closeout-carries-worktree-state/AC-4).
1333
1535
  */
1334
- function closeSteps(ctx, io, item, report) {
1536
+ function closeSteps(ctx, io, item, report, how) {
1335
1537
  let prefix = '';
1336
1538
  // Each path uncommitted before the close-out, with its text then; null for a deleted file.
1337
1539
  const before = new Map();
@@ -1354,24 +1556,34 @@ function closeSteps(ctx, io, item, report) {
1354
1556
  for (const p of dirty)
1355
1557
  before.set(p, ctx.fs.read(`${ctx.repo}/${p}`));
1356
1558
  carryLateFiles(ctx, item, report);
1559
+ // After the snapshot, so the written record is a path the close-out changed and goes in
1560
+ // its commit (design D2). A stop here writes nothing and leaves the instance open
1561
+ // (closeout-requires-outcome-half/AC-12).
1562
+ const outcome = closeOutcome(ctx, io, item, how);
1563
+ if (outcome.status !== 0)
1564
+ return outcome;
1357
1565
  if (!markDeploymentComplete(ctx, item.name))
1358
1566
  return { status: 1, stdout: '', stderr: 'no phase-deployment.yaml on main' };
1359
- return transitionFailure(io.cli(['transition', item.name, '--json']));
1567
+ // `--autopilot`: autopilot runs its own retrospective and owns the worktree, so the
1568
+ // transition starts neither (finished-work-tidies-itself/AC-5, design D5).
1569
+ return transitionFailure(io.cli(['transition', item.name, '--json', '--autopilot']));
1360
1570
  },
1361
1571
  ],
1362
1572
  [
1363
1573
  'stage-close',
1364
1574
  () => {
1365
- const after = dirtyPaths(ctx, io, prefix);
1575
+ const after = dirtyRecords(ctx, io, prefix);
1366
1576
  if (!Array.isArray(after))
1367
1577
  return after;
1368
1578
  // Text, not status: ` M` before and after says nothing about whether the transition
1369
1579
  // appended to the file (design D2).
1370
- for (const p of after) {
1580
+ for (const { xy, path: p } of after) {
1371
1581
  if (!before.has(p)) {
1372
1582
  report.paths.push(p);
1373
1583
  }
1374
- else if (ctx.fs.read(`${ctx.repo}/${p}`) !== before.get(p)) {
1584
+ else if (ctx.fs.read(`${ctx.repo}/${p}`) !== before.get(p) || oldItemCopy(p, xy, item.file)) {
1585
+ // The item's old copy is unchanged text (deleted before and after), yet leaving it
1586
+ // out tracks the finished item twice on main (closeout-leaves-item-in-two-folders/AC-1, AC-4).
1375
1587
  report.paths.push(p);
1376
1588
  report.earlier.push(p);
1377
1589
  }
@@ -1605,11 +1817,16 @@ function advanceRetrospective(ctx, io, state, item, budget) {
1605
1817
  return failed(`its commit failed: ${fail(commit)}`, now);
1606
1818
  }
1607
1819
  const counts = `${changes.lessons} ${changes.lessons === 1 ? 'lesson' : 'lessons'}, ${changes.followUps} ${changes.followUps === 1 ? 'follow-up' : 'follow-ups'}`;
1608
- const push = pushMain(ctx, io);
1609
- line =
1610
- push.status === 0
1611
- ? `retrospective committed on main and pushed — ${counts}`
1612
- : `retrospective committed on main (${counts}); the push failed (${fail(push)}) — the next push of main carries it`;
1820
+ if (ctx.retroPush === false) {
1821
+ line = `retrospective committed on main — ${counts}; not pushed, your next push of main carries it`;
1822
+ }
1823
+ else {
1824
+ const push = pushMain(ctx, io);
1825
+ line =
1826
+ push.status === 0
1827
+ ? `retrospective committed on main and pushed — ${counts}`
1828
+ : `retrospective committed on main (${counts}); the push failed (${fail(push)}) — the next push of main carries it`;
1829
+ }
1613
1830
  }
1614
1831
  // Only now, so every failure above still finds the marker where it was (design D2).
1615
1832
  ctx.fs.remove?.(retroMarker(ctx.paths, item.name));
@@ -1618,13 +1835,14 @@ function advanceRetrospective(ctx, io, state, item, budget) {
1618
1835
  }
1619
1836
  /**
1620
1837
  * A failed retrospective (AC-10, design D6): each allowed path it changed goes back to its
1621
- * text at launch and each inbox file it created is deleted; its cost lines are kept and
1622
- * committed alone (Q1); the marker is put back; one line says why; the item is dropped.
1838
+ * text at launch and each inbox file it created is deleted; the marker is put back; one line
1839
+ * says why; the item is dropped. Its cost needs no commit: it is captured into the instance's
1840
+ * ledger in the git common directory (finished-work-tidies-itself/AC-8).
1623
1841
  * Never `park` and never `error`, so the merge lane is never halted.
1624
1842
  */
1625
1843
  function failRetro(ctx, io, state, item, snap, why, budget, known) {
1626
1844
  const now = known ?? readRetroNow(ctx, io, snap.prefix, item.name);
1627
- const { retro, lessons, costs } = retroAllowed(item.name);
1845
+ const { retro, lessons } = retroAllowed(item.name);
1628
1846
  for (const p of [retro, lessons]) {
1629
1847
  const before = snap.allowed[p] ?? null;
1630
1848
  const file = `${ctx.repo}/${p}`;
@@ -1640,37 +1858,14 @@ function failRetro(ctx, io, state, item, snap, why, budget, known) {
1640
1858
  for (const p of seen?.created ?? [])
1641
1859
  ctx.fs.remove?.(`${ctx.repo}/${p}`);
1642
1860
  const leftAlone = [...(seen?.leftAlone ?? [])];
1643
- let costNote = '';
1644
- if (ctx.fs.read(`${ctx.repo}/${costs}`) !== (snap.allowed[costs] ?? null)) {
1645
- if (costs in snap.dirty)
1646
- leftAlone.push(costs);
1647
- else
1648
- costNote = commitRetroCost(ctx, io, item, costs);
1649
- }
1650
1861
  const marker = retroMarker(ctx.paths, item.name);
1651
1862
  if (!ctx.fs.exists(marker))
1652
1863
  ctx.fs.write(marker, snap.marker);
1653
1864
  const unread = 'failed' in now ? `; its new inbox files cannot be told apart (${now.failed})` : '';
1654
- tell(ctx, item, `retrospective failed — ${why}; ${MARKER_STAYS}${costNote}${unread}${leftAloneNote([...new Set(leftAlone)].sort())}`);
1865
+ tell(ctx, item, `retrospective failed — ${why}; ${MARKER_STAYS}${unread}${leftAloneNote([...new Set(leftAlone)].sort())}`);
1655
1866
  notice(ctx, 'retrospective failed', `${item.name}: ${why}`);
1656
1867
  finishRetro(ctx, state, item, budget);
1657
1868
  }
1658
- /**
1659
- * Commit the failed retrospective's cost lines alone and push them: a deleted ledger line
1660
- * cannot be recovered, a commit can be reverted (design-questions Q1). A failure is named
1661
- * and changes nothing else.
1662
- */
1663
- function commitRetroCost(ctx, io, item, costs) {
1664
- const repo = { cwd: ctx.repo };
1665
- const add = io.call('git', ['add', '--', costs], repo);
1666
- const commit = add.status !== 0
1667
- ? add
1668
- : io.call('git', ['commit', '-q', '-m', `chore(aidlc): record the failed retrospective's cost for ${item.name} (autopilot)`, '--', costs], repo);
1669
- if (commit.status !== 0)
1670
- return `; its cost lines are not committed (${fail(commit)})`;
1671
- const push = pushMain(ctx, io);
1672
- return push.status === 0 ? '; its cost lines are committed on main' : `; its cost lines are committed on main, the push failed (${fail(push)})`;
1673
- }
1674
1869
  /** Waiting for a person to merge: only their answer moves it (autopilot-stop-controls/AC-19). */
1675
1870
  function advanceAwaitingMerge(ctx, io, state, item, budget) {
1676
1871
  const view = prView(ctx, io, item);
@@ -1703,45 +1898,11 @@ function handleConflict(ctx, io, state, item, budget) {
1703
1898
  relaunchBuild(ctx, io, state, item, conflictPrompt(item, hostOf(ctx)), budget);
1704
1899
  }
1705
1900
  /**
1706
- * The two `merge=union` cost ledgers a worktree collects between commits. `name` is
1707
- * the one `aidlc start` created and the agent claimed, so it holds no glob or
1708
- * option character (autopilot-merge-refusal-is-not-a-conflict/AC-1).
1901
+ * The two ledger paths a branch made before the move still tracks. Only the checker's
1902
+ * "what did it change" reading excludes them now: nothing writes them any more, and
1903
+ * autopilot no longer commits them (finished-work-tidies-itself/AC-8).
1709
1904
  */
1710
- const ledgerPaths = (name) => ['.aidlc/cost/unattributed.ndjson', `.aidlc/state/${name}/costs.ndjson`];
1711
- const LEDGER_COMMIT_MESSAGE = 'chore(aidlc): commit cost ledgers before updating from main (autopilot)';
1712
- /**
1713
- * Commit the worktree's uncommitted cost ledgers, and nothing else, so git does not
1714
- * refuse the update from main over a ledger both sides appended to — PR #125 on
1715
- * 2026-10-06 (autopilot-merge-refusal-is-not-a-conflict/AC-1..AC-4). Null when
1716
- * nothing needed committing or the commit was made; otherwise git's failure.
1717
- */
1718
- function commitLedgers(ctx, io, item) {
1719
- const wt = { cwd: item.worktree };
1720
- const candidates = ledgerPaths(item.name);
1721
- const status = io.call('git', ['status', '--porcelain=v1', '--untracked-files=all', '--', ...candidates], wt);
1722
- if (status.status !== 0)
1723
- return status;
1724
- // Porcelain paths are relative to the repository's top, the pathspec to the cwd: for
1725
- // a project below the root, the line reads `packages/app/<ledger>`
1726
- // (worktree-start-in-nested-project/AC-8). The pathspec already limits the answer to
1727
- // the two ledgers, so the suffix names one. A quoted path still never matches, and a
1728
- // rename or copy is excluded by status, so both fail safe; a deleted ledger is never
1729
- // committed as a deletion (AC-2).
1730
- const lines = status.stdout.split('\n');
1731
- const names = (l, p) => l.slice(3) === p || l.slice(3).endsWith(`/${p}`);
1732
- const dirty = candidates.filter((p) => lines.some((l) => names(l, p) && !/[DRC]/.test(l.slice(0, 2))));
1733
- if (dirty.length === 0)
1734
- return null;
1735
- const add = io.call('git', ['add', '--', ...dirty], wt);
1736
- if (add.status !== 0)
1737
- return add;
1738
- // By pathspec: another staged change stays staged and outside this commit (AC-2).
1739
- const commit = io.call('git', ['commit', '-q', '-m', LEDGER_COMMIT_MESSAGE, '--', ...dirty], wt);
1740
- if (commit.status !== 0)
1741
- return commit;
1742
- tell(ctx, item, 'committed its cost ledgers before updating from main');
1743
- return null;
1744
- }
1905
+ const legacyLedgerPaths = (name) => ['.aidlc/cost/unattributed.ndjson', `.aidlc/state/${name}/costs.ndjson`];
1745
1906
  /**
1746
1907
  * Bring the item's branch up to date with main in its own worktree, where the
1747
1908
  * repository's merge attributes apply (`merge=union` on the append-only logs),
@@ -1767,13 +1928,6 @@ function upToDateWithMain(ctx, io, state, item, resume, budget) {
1767
1928
  failItem(ctx, state, item, `update from main failed: ${fail(contains)}`, resume);
1768
1929
  return false;
1769
1930
  }
1770
- // Here, not at the end of the build: the cost hook can write after the agent's
1771
- // last commit, and the head is about to move anyway (design D1).
1772
- const ledgers = commitLedgers(ctx, io, item);
1773
- if (ledgers !== null) {
1774
- failItem(ctx, state, item, `update from main failed: could not commit the cost ledgers: ${gitMessage(ledgers)}`, resume);
1775
- return false;
1776
- }
1777
1931
  const merge = io.call('git', ['merge', '--no-edit', 'origin/main'], wt);
1778
1932
  if (merge.status !== 0) {
1779
1933
  // Read before the abort clears them. A merge git refused — local changes it would
@@ -1973,7 +2127,7 @@ function checkerChanged(ctx, io, item, check) {
1973
2127
  const now = trackedSnapshot(ctx, io, item, Object.keys(check.baseline));
1974
2128
  if ('failed' in now)
1975
2129
  return `the tracked files cannot be read (${now.failed})`;
1976
- const changed = changedSince(check.baseline, now.snap, ledgerPaths(item.name).map((p) => `${now.prefix}${p}`));
2130
+ const changed = changedSince(check.baseline, now.snap, legacyLedgerPaths(item.name).map((p) => `${now.prefix}${p}`));
1977
2131
  return changed.length === 0 ? null : `tracked files: ${changed.slice(0, 5).join(', ')}${changed.length > 5 ? ` and ${changed.length - 5} more` : ''}`;
1978
2132
  }
1979
2133
  /** The checker's structured output, or undefined when it wrote none (pr-checker-earns-merge/AC-6). */
@@ -2339,6 +2493,76 @@ function githubVerdict(ctx, io, failed) {
2339
2493
  function gitlabVerdict(p) {
2340
2494
  return classifyJobs(p.jobs.filter((j) => j.bucket === 'fail' || j.bucket === 'cancel'), p.id, p.retried);
2341
2495
  }
2496
+ /**
2497
+ * Read the record's `## Outcome` and, when it is unwritten, write it from what the close-out
2498
+ * can verify: the merge commit, CI as autopilot last read it, whether the release step ran,
2499
+ * and the deploy workflow's run on the merge commit when the project names one
2500
+ * (closeout-requires-outcome-half/AC-9, AC-11). A written outcome — the nothing-deployed line
2501
+ * included — is left as it is, and the deploy workflow is not read (AC-10).
2502
+ *
2503
+ * Anything that cannot be verified is a stop with nothing written (AC-12, AC-13). A dry run
2504
+ * verifies nothing, since no merge happened: it reads only the record and says what it would do
2505
+ * (AC-14).
2506
+ */
2507
+ function closeOutcome(ctx, io, item, how) {
2508
+ const ok = { status: 0, stdout: '', stderr: '' };
2509
+ const record = recordPath(item.name);
2510
+ const file = `${ctx.repo}/${record}`;
2511
+ const text = ctx.fs.read(file) ?? '';
2512
+ const verdict = readOutcome(text);
2513
+ const workflow = ctx.config?.deploy_workflow;
2514
+ if (ctx.dryRun) {
2515
+ const deploy = workflow === undefined ? 'no deploy workflow' : 'name' in workflow ? workflow.name : 'the invalid deploy_workflow';
2516
+ ctx.say(verdict.written
2517
+ ? `[dry-run] ## Outcome in ${record} is written — left as it is`
2518
+ : `[dry-run] would write ## Outcome in ${record} from the merge commit, CI, the release step and ${deploy}`);
2519
+ return ok;
2520
+ }
2521
+ if (verdict.written)
2522
+ return ok;
2523
+ const stop = (why) => ({ status: 1, stdout: '', stderr: outcomeStop(record, why, item.name) });
2524
+ const host = hostOf(ctx);
2525
+ const n = item.pr ?? 0;
2526
+ let merge;
2527
+ if (host === 'gitlab') {
2528
+ const r = io.call('glab', mrViewArgs(n), { cwd: ctx.repo });
2529
+ merge = r.status === 0 ? parseMergeCommit(r.stdout) : null;
2530
+ }
2531
+ else {
2532
+ const r = io.call('gh', ghMergeCommitArgs(n), { cwd: ctx.repo });
2533
+ merge = r.status === 0 ? parseGhMergeCommit(r.stdout) : null;
2534
+ }
2535
+ if (merge === null)
2536
+ return stop(`the merge commit of ${ref(host, item.pr)} cannot be read`);
2537
+ let deploy = null;
2538
+ if (workflow !== undefined) {
2539
+ // Kept as invalid by `loadTeamDefaults`, so a typo stops here instead of passing unchecked (design D4).
2540
+ if ('invalid' in workflow) {
2541
+ return stop(`autopilot.deploy_workflow "${workflow.invalid}" is not a workflow file name ending in .yml or .yaml`);
2542
+ }
2543
+ if (host === 'gitlab')
2544
+ return stop(`a deploy workflow cannot be read on GitLab (autopilot.deploy_workflow names ${workflow.name})`);
2545
+ const r = io.call('gh', deployRunArgs(workflow.name, merge.mergeCommit), { cwd: ctx.repo });
2546
+ if (r.status !== 0)
2547
+ return stop(`the ${workflow.name} runs cannot be read (${fail(r)})`);
2548
+ const run = parseDeployRun(r.stdout, workflow.name);
2549
+ if (!run.ok)
2550
+ return stop(run.why);
2551
+ deploy = { workflow: workflow.name, run: run.run, url: run.url };
2552
+ }
2553
+ const section = renderOutcome({
2554
+ pr: ref(host, item.pr),
2555
+ mergeCommit: merge.mergeCommit,
2556
+ head: merge.head,
2557
+ ci: item.ci,
2558
+ byPerson: how.byPerson,
2559
+ released: how.released,
2560
+ deploy,
2561
+ at: new Date(ctx.now()).toISOString(),
2562
+ });
2563
+ ctx.fs.write(file, withOutcome(text, section));
2564
+ return ok;
2565
+ }
2342
2566
  /**
2343
2567
  * Mark the deployment artifact complete so `aidlc transition` can close the
2344
2568
  * instance — whatever status the agent left it in; replacing only
@@ -2453,7 +2677,7 @@ function serveQueue(ctx, io, state, budget) {
2453
2677
  steps.push(['release', () => io.call(release[0], release.slice(1), { cwd: ctx.repo })]);
2454
2678
  }
2455
2679
  const report = emptyReport();
2456
- steps.push(...closeSteps(ctx, io, item, report));
2680
+ steps.push(...closeSteps(ctx, io, item, report, { released: releases, byPerson: false }));
2457
2681
  // Halt. Only a failed merge resumes on the next `autopilot run`; from the
2458
2682
  // pull on, the merge has happened and a half-done release is for a person (AC-16).
2459
2683
  const halt = (label, error) => {
@@ -2603,8 +2827,9 @@ function startBuilds(ctx, io, state, budget) {
2603
2827
  // Held to these until it leaves, whatever later runs say (autopilot-stop-controls/AC-6).
2604
2828
  stops: stopsInForce(ctx.config),
2605
2829
  };
2606
- // Only the gate can refuse here, and it was checked above; nothing is tracked without an agent.
2607
- if (!launchAgent(ctx, io, state, item, agentPrompt(item, itemPauses(item)), budget))
2830
+ // The gate was checked above; an unreadable phase parks. Nothing is tracked without an
2831
+ // agent. No session has run, so there is no claim to release.
2832
+ if (!launchPhase(ctx, io, state, item, budget, { release: false }))
2608
2833
  return;
2609
2834
  if (ctx.dryRun)
2610
2835
  return;
@@ -2722,6 +2947,34 @@ export function tick(ctx, state, budget) {
2722
2947
  state.last_tick = new Date(ctx.now()).toISOString();
2723
2948
  return state;
2724
2949
  }
2950
+ /** How often the attended retrospective's runner checks on its agent. */
2951
+ export const HAND_RETRO_POLL_MS = 5_000;
2952
+ /**
2953
+ * The retrospective after a person's own close-out (finished-work-tidies-itself/AC-5,
2954
+ * design §5, D4): autopilot's own `afterClose` and `advanceRetrospective`, driven over one
2955
+ * item kept in memory and never written to `state.json`. So the prompt, the 30-minute limit,
2956
+ * the cap, the capture of its cost, the success check, the check of what it may commit, the
2957
+ * commit by pathspec and the failure path that keeps the marker are autopilot's code, not a
2958
+ * copy. `ctx.retroPush` false leaves main unpushed.
2959
+ */
2960
+ export async function runHandRetro(ctx, name, sleep) {
2961
+ const state = emptyState();
2962
+ const item = { name, file: `${name}.md`, worktree: '', branch: '', step: 'retrospective', ci_failures: 0, pr: null, pid: null };
2963
+ state.items.push(item);
2964
+ const io = makeIO(ctx);
2965
+ afterClose(ctx, io, state, item);
2966
+ while (state.items.includes(item)) {
2967
+ await sleep(HAND_RETRO_POLL_MS);
2968
+ try {
2969
+ advanceRetrospective(ctx, io, state, item);
2970
+ }
2971
+ catch (err) {
2972
+ // A rate limit while capturing or committing is waited out, as a pass would.
2973
+ if (!(err instanceof RateLimited))
2974
+ throw err;
2975
+ }
2976
+ }
2977
+ }
2725
2978
  /** Each item's step by name, to compare against after a change (autopilot-live-progress/AC-11). */
2726
2979
  export function stepsOf(state) {
2727
2980
  return new Map(state.items.map((i) => [i.name, i.step]));