@rasensio/aidlc 2.19.0 → 2.21.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 (82) hide show
  1. package/dist/autopilot/answers.d.ts.map +1 -1
  2. package/dist/autopilot/answers.js +6 -3
  3. package/dist/autopilot/answers.js.map +1 -1
  4. package/dist/autopilot/decisions.d.ts +42 -5
  5. package/dist/autopilot/decisions.d.ts.map +1 -1
  6. package/dist/autopilot/decisions.js +85 -16
  7. package/dist/autopilot/decisions.js.map +1 -1
  8. package/dist/autopilot/driver.d.ts +25 -5
  9. package/dist/autopilot/driver.d.ts.map +1 -1
  10. package/dist/autopilot/driver.js +277 -82
  11. package/dist/autopilot/driver.js.map +1 -1
  12. package/dist/autopilot/presets.d.ts.map +1 -1
  13. package/dist/autopilot/presets.js +4 -2
  14. package/dist/autopilot/presets.js.map +1 -1
  15. package/dist/autopilot/proposal.d.ts +55 -0
  16. package/dist/autopilot/proposal.d.ts.map +1 -0
  17. package/dist/autopilot/proposal.js +167 -0
  18. package/dist/autopilot/proposal.js.map +1 -0
  19. package/dist/autopilot/review.d.ts +15 -3
  20. package/dist/autopilot/review.d.ts.map +1 -1
  21. package/dist/autopilot/review.js +211 -40
  22. package/dist/autopilot/review.js.map +1 -1
  23. package/dist/autopilot/typed.d.ts +9 -1
  24. package/dist/autopilot/typed.d.ts.map +1 -1
  25. package/dist/autopilot/typed.js +6 -2
  26. package/dist/autopilot/typed.js.map +1 -1
  27. package/dist/commands/autopilot.d.ts +3 -1
  28. package/dist/commands/autopilot.d.ts.map +1 -1
  29. package/dist/commands/autopilot.js +10 -6
  30. package/dist/commands/autopilot.js.map +1 -1
  31. package/dist/commands/init.d.ts +10 -0
  32. package/dist/commands/init.d.ts.map +1 -1
  33. package/dist/commands/init.js +24 -1
  34. package/dist/commands/init.js.map +1 -1
  35. package/dist/commands/roadmap.d.ts.map +1 -1
  36. package/dist/commands/roadmap.js +3 -1
  37. package/dist/commands/roadmap.js.map +1 -1
  38. package/dist/cost/gitignore.d.ts +6 -5
  39. package/dist/cost/gitignore.d.ts.map +1 -1
  40. package/dist/cost/gitignore.js +6 -6
  41. package/dist/cost/gitignore.js.map +1 -1
  42. package/dist/cost/hooks/shim.js +3 -3
  43. package/dist/cost/hooks/shim.js.map +1 -1
  44. package/dist/doctor/migrations/cost-gitignore.d.ts +2 -1
  45. package/dist/doctor/migrations/cost-gitignore.d.ts.map +1 -1
  46. package/dist/doctor/migrations/cost-gitignore.js +13 -11
  47. package/dist/doctor/migrations/cost-gitignore.js.map +1 -1
  48. package/dist/doctor/migrations/index.d.ts.map +1 -1
  49. package/dist/doctor/migrations/index.js +5 -0
  50. package/dist/doctor/migrations/index.js.map +1 -1
  51. package/dist/doctor/migrations/knowledge-gitignore.d.ts +8 -1
  52. package/dist/doctor/migrations/knowledge-gitignore.d.ts.map +1 -1
  53. package/dist/doctor/migrations/knowledge-gitignore.js +20 -13
  54. package/dist/doctor/migrations/knowledge-gitignore.js.map +1 -1
  55. package/dist/doctor/migrations/nested-gitignore.d.ts +24 -5
  56. package/dist/doctor/migrations/nested-gitignore.d.ts.map +1 -1
  57. package/dist/doctor/migrations/nested-gitignore.js +62 -6
  58. package/dist/doctor/migrations/nested-gitignore.js.map +1 -1
  59. package/dist/doctor/migrations/tracked-nested-ignored.d.ts +26 -0
  60. package/dist/doctor/migrations/tracked-nested-ignored.d.ts.map +1 -0
  61. package/dist/doctor/migrations/tracked-nested-ignored.js +69 -0
  62. package/dist/doctor/migrations/tracked-nested-ignored.js.map +1 -0
  63. package/dist/knowledge/engine.d.ts.map +1 -1
  64. package/dist/knowledge/engine.js +5 -0
  65. package/dist/knowledge/engine.js.map +1 -1
  66. package/dist/knowledge/gitignore.d.ts +18 -0
  67. package/dist/knowledge/gitignore.d.ts.map +1 -0
  68. package/dist/knowledge/gitignore.js +25 -0
  69. package/dist/knowledge/gitignore.js.map +1 -0
  70. package/dist/roadmap/next.d.ts +6 -3
  71. package/dist/roadmap/next.d.ts.map +1 -1
  72. package/dist/roadmap/next.js +17 -1
  73. package/dist/roadmap/next.js.map +1 -1
  74. package/dist/roadmap/ready.d.ts +39 -0
  75. package/dist/roadmap/ready.d.ts.map +1 -0
  76. package/dist/roadmap/ready.js +101 -0
  77. package/dist/roadmap/ready.js.map +1 -0
  78. package/dist/roadmap/triage.d.ts +7 -0
  79. package/dist/roadmap/triage.d.ts.map +1 -1
  80. package/dist/roadmap/triage.js +12 -2
  81. package/dist/roadmap/triage.js.map +1 -1
  82. package/package.json +2 -2
@@ -15,7 +15,7 @@
15
15
  *
16
16
  * @module
17
17
  */
18
- import { join, resolve } from 'node:path';
18
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
19
19
  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';
@@ -46,6 +46,19 @@ export function isPid(pid) {
46
46
  const RATE_LIMIT_RE = /rate limit|secondary rate|\b(?:HTTP|error:?|status:?)\s*429\b|\b429 Too Many Requests\b/i;
47
47
  /** The git subcommands that reach the remote — the only git a host can rate-limit. */
48
48
  const GIT_NETWORK = new Set(['push', 'fetch', 'pull', 'ls-remote']);
49
+ /**
50
+ * The `aidlc` commands that reach GitHub or GitLab — the only `aidlc` output a host can put
51
+ * a rate limit in. Every other `aidlc` command prints text autopilot or the item gave it: a
52
+ * park reason, an item title, a spec requirement named "Reading a rate limit" in
53
+ * `transition --json` (transition-output-reads-as-rate-limit/AC-2). A new `aidlc` command
54
+ * autopilot runs that reaches a host is read only once it is listed here.
55
+ */
56
+ const AIDLC_HOST_COMMANDS = [
57
+ ['roadmap', 'sync'],
58
+ ['roadmap', 'import'],
59
+ ['init'],
60
+ ['cost', 'rates', 'update'],
61
+ ];
49
62
  const BACKOFF_FIRST_MS = 5 * 60 * 1000;
50
63
  const BACKOFF_MAX_MS = 2 * 60 * 60 * 1000;
51
64
  const CI_FAILURE_LIMIT = 2;
@@ -68,16 +81,33 @@ function isReadOnly(cmd, args) {
68
81
  return /^(rev-parse|status|merge-base)\b/.test(a);
69
82
  return /\broadmap next\b/.test(a) || (/\bcost\b/.test(a) && /--json/.test(a));
70
83
  }
84
+ /** `args` past `cli`'s own, when `cmd args` is an `aidlc` invocation; else undefined. */
85
+ function aidlcArgs(cli, cmd, args) {
86
+ if (cmd !== cli[0])
87
+ return undefined;
88
+ const own = cli.slice(1);
89
+ return own.every((a, i) => args[i] === a) ? args.slice(own.length) : undefined;
90
+ }
71
91
  /**
72
- * The line of `r` that reports a rate limit, if any. Local git is never read: it cannot be
73
- * rate-limited. Network git is read on stderr only, where git reports an HTTP error — its
74
- * stdout after a pull is a diffstat (autopilot-reads-429-in-a-diffstat/AC-1, AC-2).
92
+ * The line of `r` that reports a rate limit, if any — decided by the command alone, so no
93
+ * call site can forget to opt out (transition-output-reads-as-rate-limit/AC-6). `gh` and
94
+ * `glab` are read on both streams. Network git is read on stderr only, where git reports an
95
+ * HTTP error — its stdout after a pull is a diffstat (autopilot-reads-429-in-a-diffstat/AC-1,
96
+ * AC-2). An `aidlc` command is read only when it is on the host list, from the primary
97
+ * checkout or a worktree alike (AC-5). Anything else — local git, the release step, every
98
+ * other `aidlc` command — cannot be rate-limited and is never read (AC-3).
75
99
  */
76
- function rateLimitLine(cmd, args, r) {
77
- if (cmd === 'git' && !GIT_NETWORK.has(args[0] ?? ''))
100
+ export function rateLimitLine(cli, cmd, args, r) {
101
+ const find = (text) => text.split('\n').find((l) => RATE_LIMIT_RE.test(l))?.trim();
102
+ if (cmd === 'gh' || cmd === 'glab')
103
+ return find(`${r.stderr}\n${r.stdout}`);
104
+ if (cmd === 'git')
105
+ return GIT_NETWORK.has(args[0] ?? '') ? find(r.stderr) : undefined;
106
+ const words = aidlcArgs(cli, cmd, args);
107
+ if (words === undefined)
78
108
  return undefined;
79
- const text = cmd === 'git' ? r.stderr : `${r.stderr}\n${r.stdout}`;
80
- return text.split('\n').find((l) => RATE_LIMIT_RE.test(l))?.trim();
109
+ const reaches = AIDLC_HOST_COMMANDS.some((c) => c.every((w, i) => words[i] === w));
110
+ return reaches ? find(`${r.stderr}\n${r.stdout}`) : undefined;
81
111
  }
82
112
  function makeIO(ctx) {
83
113
  const call = (cmd, args, opts = {}) => {
@@ -86,12 +116,12 @@ function makeIO(ctx) {
86
116
  return { status: 0, stdout: '', stderr: '', dry: true };
87
117
  }
88
118
  const r = ctx.run(cmd, args, opts.cwd === undefined ? {} : { cwd: opts.cwd });
89
- const line = opts.echoes === true ? undefined : rateLimitLine(cmd, args, r);
119
+ const line = rateLimitLine(ctx.cli, cmd, args, r);
90
120
  if (line !== undefined)
91
121
  throw new RateLimited(`${cmd} ${args.slice(0, 2).join(' ')}: ${line}`);
92
122
  return r;
93
123
  };
94
- const cli = (args, opts = {}) => call(ctx.cli[0], [...ctx.cli.slice(1), ...args], { cwd: ctx.repo, ...opts });
124
+ const cli = (args) => call(ctx.cli[0], [...ctx.cli.slice(1), ...args], { cwd: ctx.repo });
95
125
  return { call, cli };
96
126
  }
97
127
  const fail = (r) => (r.stderr || r.stdout || `exit ${r.status}`).trim().split('\n').slice(-1)[0];
@@ -141,8 +171,9 @@ const Ref = (host, n) => {
141
171
  return r[0].toUpperCase() + r.slice(1);
142
172
  };
143
173
  /**
144
- * @param pauses - `AIDLC_PAUSE_AFTER` as the agent will see it. Empty adds nothing,
145
- * so an item with no pauses gets the prompt it always did.
174
+ * @param pauses - `AIDLC_PAUSE_AFTER` as the agent will see it. Empty is said in words,
175
+ * because the rule reads a prompt silent on the list as "nobody told me" and pauses
176
+ * everywhere (scoped-preset-cannot-read-unattended-env/AC-2).
146
177
  */
147
178
  export function agentPrompt(item, pauses = '') {
148
179
  return (`You are running unattended (AIDLC_UNATTENDED=1). Follow .aidlc/resources/rules/unattended.md. ` +
@@ -152,7 +183,7 @@ export function agentPrompt(item, pauses = '') {
152
183
  (pauses
153
184
  ? ` AIDLC_PAUSE_AFTER=${pauses}: when one of those phases completes, stop there instead — that is ` +
154
185
  `the rule's review boundary: commit, release your claim, and stop.`
155
- : ''));
186
+ : ` AIDLC_PAUSE_AFTER is empty: no phase is a review boundary, so carry on through every phase.`));
156
187
  }
157
188
  export function fixPrompt(item, failing, host = 'github') {
158
189
  return (`You are running unattended (AIDLC_UNATTENDED=1). Follow .aidlc/resources/rules/unattended.md. ` +
@@ -320,11 +351,21 @@ function launchAgent(ctx, io, state, item, prompt, budget, resume) {
320
351
  else {
321
352
  const outcomeFile = `${ctx.paths.dir}/outcomes/${item.name}.json`;
322
353
  const schemaFile = `${ctx.paths.dir}/outcome-schema.json`;
354
+ // `ctx.paths.dir` is `<common>/aidlc/autopilot`, already realpath'd by
355
+ // `coordinationRoot`: the dir every worktree's `aidlc` resolves under, with no git
356
+ // spawn per launch (codex-sandbox-blocks-commit/AC-1, design D2).
357
+ const gitCommonDir = dirname(dirname(ctx.paths.dir));
358
+ // Checked before the id, so the two park reasons stay apart (design, Interfaces).
359
+ if (harness === 'codex' && !isAbsolute(gitCommonDir)) {
360
+ park(ctx, io, state, item, 'agent launch — no git common dir', budget);
361
+ return false;
362
+ }
323
363
  const typed = typedArgv(command, {
324
364
  harness,
325
365
  prompt: withOutcomeContract(prompt),
326
366
  schemaFile,
327
367
  outcomeFile,
368
+ gitCommonDir,
328
369
  maxBudgetCents: harness === 'claude' ? cents : null,
329
370
  resume: resume?.session ?? null,
330
371
  });
@@ -397,7 +438,7 @@ function drop(state, item, budget) {
397
438
  budget?.onFinish(item.name);
398
439
  }
399
440
  function park(ctx, io, state, item, reason, budget) {
400
- const r = io.cli(['roadmap', 'park', item.name, '--reason', reason], { echoes: true });
441
+ const r = io.cli(['roadmap', 'park', item.name, '--reason', reason]);
401
442
  if (r.status !== 0) {
402
443
  failItem(ctx, state, item, `park failed: ${fail(r)}`);
403
444
  tell(ctx, item, `could not park — ${item.error}`);
@@ -562,9 +603,9 @@ const modelLookupGaveUp = (launch) => launch.model === undefined &&
562
603
  * What a Codex launch's summed `turn.completed` usage costs, in micro-USD, priced as the
563
604
  * Codex cost provider prices a turn — cached input counted inside input, not on top of
564
605
  * it — at the effective rate for its model; null when it cannot be priced
565
- * (autopilot-reads-agent-result/AC-20, AC-21). The one place the reading of Codex's
566
- * usage lives: if the release run finds it a running total, this changes and nothing
567
- * else does (design, Risk 1).
606
+ * (autopilot-reads-agent-result/AC-20, AC-21). A resumed launch's usage is the thread's
607
+ * running total, not its own turns', so the figure is the thread's cost to date; callers
608
+ * subtract what is on record for the thread (codex-resume-double-counts/AC-1).
568
609
  */
569
610
  export function launchUsageMicro(ctx, launch) {
570
611
  const usage = launch.progress?.usage;
@@ -591,21 +632,36 @@ export function launchUsageMicro(ctx, launch) {
591
632
  function sessionSoFar(launch, costMicro) {
592
633
  return launch.harness === 'codex' && launch.progress !== undefined ? codexEnd(launch.progress, null, costMicro) : null;
593
634
  }
635
+ /**
636
+ * The id a launch's spend is recorded under: the id it reported, else a UUID it resumes —
637
+ * a resumed Codex thread writes no second `thread.started` (codex-resume-double-counts/AC-3).
638
+ */
639
+ function spendKey(launch, reported) {
640
+ if (reported !== null)
641
+ return reported;
642
+ return launch.resumes !== undefined && UUID_RE.test(launch.resumes) ? launch.resumes : null;
643
+ }
644
+ /** What is on record for a session: nothing without a key. */
645
+ const onRecord = (record, key) => key === null ? 0 : record?.[key] ?? 0;
594
646
  /**
595
647
  * Stop a running Codex launch whose priced usage, on top of the item's recorded spend,
596
648
  * has reached the cap less the 10% margin (autopilot-reads-agent-result/AC-20). Codex has
597
649
  * no budget flag, so this is the cap inside its run. Usage that cannot be priced is said
598
- * once and stops nothing (AC-21).
650
+ * once and stops nothing (AC-21). The usage is the thread's running total, so what is on
651
+ * record for the thread comes off first (codex-resume-double-counts/AC-5, AC-6).
599
652
  *
600
653
  * @returns whether it stopped and parked the item.
601
654
  */
602
655
  function stoppedAtCap(ctx, io, state, item, launch, capSet, budget) {
603
656
  if ((launch.progress?.turns ?? 0) === 0)
604
657
  return false;
658
+ const thread = launch.progress?.thread_id ?? null;
659
+ const key = spendKey(launch, thread !== null && UUID_RE.test(thread) ? thread : null);
605
660
  // Tokens need no rate, so a token cap stops a run its model's price cannot (cost-in-tokens/AC-15).
606
661
  if (capSet.unit === 'tokens') {
607
662
  const usage = launch.progress?.usage;
608
- const used = (item.spent_tokens ?? 0) + (usage === undefined ? 0 : usage.input + usage.output);
663
+ const total = usage === undefined ? 0 : usage.input + usage.output;
664
+ const used = (item.spent_tokens ?? 0) + Math.max(0, total - onRecord(item.session_tokens, key));
609
665
  if (tokensLeft(capSet.tokens, used) >= 1)
610
666
  return false;
611
667
  if (!ctx.dryRun && item.pid !== null)
@@ -620,7 +676,7 @@ function stoppedAtCap(ctx, io, state, item, launch, capSet, budget) {
620
676
  noteUnpriced(ctx, item, launch);
621
677
  return false;
622
678
  }
623
- const spent = (item.spent_micro_usd ?? 0) + priced;
679
+ const spent = (item.spent_micro_usd ?? 0) + Math.max(0, priced - onRecord(item.session_costs, key));
624
680
  if (spent < Math.round(cap * 1e6) - Math.round(cap * 1e5))
625
681
  return false;
626
682
  if (!ctx.dryRun && item.pid !== null)
@@ -677,46 +733,37 @@ function endSession(ctx, item, launch) {
677
733
  }
678
734
  launch.end = end;
679
735
  if (end !== null)
680
- recordSpend(item, end);
736
+ recordSpend(item, end, launch.harness === 'codex' ? spendKey(launch, end.session_id) : end.session_id);
681
737
  appendSummary(ctx, item, summaryLines(end));
682
738
  return true;
683
739
  }
684
740
  /**
685
- * Add a session's cost to the item's spend (autopilot-reads-agent-result/AC-19). A
686
- * session already on record adds only its increase. Claude reports a session's cost;
687
- * a resumed Codex launch's usage counts only its own turns, so a Codex session's cost
688
- * is what was recorded plus this launch's (design, Risk 1). Unpriced adds nothing.
741
+ * Add a session's cost to the item's spend (autopilot-reads-agent-result/AC-19), recorded
742
+ * under `key` — the session id, or for Codex the thread a launch resumes when it reported
743
+ * none. A session already on record adds only its increase. Claude reports a session's
744
+ * cost, and a resumed Codex launch's usage is the thread's running total, so both are the
745
+ * session's figure to date (codex-resume-double-counts/AC-1, AC-4). Unpriced adds nothing.
689
746
  */
690
- function recordSpend(item, end) {
691
- recordTokens(item, end);
747
+ function recordSpend(item, end, key) {
748
+ recordTokens(item, end, key);
692
749
  if (end.cost_micro === null)
693
750
  return;
694
- const costs = item.session_costs ?? {};
695
- const id = end.session_id;
696
- const previous = id === null ? 0 : costs[id] ?? 0;
697
- const sessionCost = end.harness === 'codex' ? previous + end.cost_micro : end.cost_micro;
698
- item.spent_micro_usd = (item.spent_micro_usd ?? 0) + Math.max(0, sessionCost - previous);
699
- if (id !== null) {
700
- costs[id] = Math.max(previous, sessionCost);
701
- item.session_costs = costs;
702
- }
751
+ const previous = onRecord(item.session_costs, key);
752
+ item.spent_micro_usd = (item.spent_micro_usd ?? 0) + Math.max(0, end.cost_micro - previous);
753
+ if (key !== null)
754
+ item.session_costs = { ...item.session_costs, [key]: Math.max(previous, end.cost_micro) };
703
755
  }
704
756
  /**
705
- * {@link recordSpend}'s bookkeeping in tokens: a resumed session adds only its
706
- * increase, a Codex launch's tokens add to its session's (cost-in-tokens/AC-18).
757
+ * {@link recordSpend}'s bookkeeping in tokens: a session already on record adds only its
758
+ * increase (cost-in-tokens/AC-18, codex-resume-double-counts/AC-2).
707
759
  */
708
- function recordTokens(item, end) {
760
+ function recordTokens(item, end, key) {
709
761
  if (end.tokens === null)
710
762
  return;
711
- const used = item.session_tokens ?? {};
712
- const id = end.session_id;
713
- const previous = id === null ? 0 : used[id] ?? 0;
714
- const session = end.harness === 'codex' ? previous + end.tokens : end.tokens;
715
- item.spent_tokens = (item.spent_tokens ?? 0) + Math.max(0, session - previous);
716
- if (id !== null) {
717
- used[id] = Math.max(previous, session);
718
- item.session_tokens = used;
719
- }
763
+ const previous = onRecord(item.session_tokens, key);
764
+ item.spent_tokens = (item.spent_tokens ?? 0) + Math.max(0, end.tokens - previous);
765
+ if (key !== null)
766
+ item.session_tokens = { ...item.session_tokens, [key]: Math.max(previous, end.tokens) };
720
767
  }
721
768
  /** Append lines to the item's log, on a line of their own. Nothing in a dry run. */
722
769
  function appendSummary(ctx, item, lines) {
@@ -828,8 +875,7 @@ function decideResume(ctx, io, state, item, launch, end, error, stop, budget) {
828
875
  const line = firstLine(error, REASON_MAX) ?? 'error';
829
876
  // A resume that stops again is AC-27's whether or not it reported its id again: a
830
877
  // resumed Codex thread writes no second `thread.started`.
831
- const resumed = launch.resumes !== undefined && UUID_RE.test(launch.resumes) ? launch.resumes : null;
832
- const id = end.session_id ?? resumed;
878
+ const id = spendKey(launch, end.session_id);
833
879
  if (launch.resumes !== undefined && id !== null) {
834
880
  park(ctx, io, state, item, `${label} — resumed once, stopped again: ${line}; session ${id}`, budget);
835
881
  return;
@@ -890,8 +936,8 @@ function resumeWhenDue(ctx, io, state, item, wait, budget) {
890
936
  // The stopped session's claim outlives it by the 60-minute staleness, and a resume may
891
937
  // run under another id, whose `aidlc claim` it would refuse. From the worktree: an
892
938
  // in-flight instance's state is on its branch, and `release` refuses an instance it
893
- // cannot find. `echoes`: it prints the instance name (unattended-agent-ends-turn-to-wait/AC-7).
894
- const released = io.call(ctx.cli[0], [...ctx.cli.slice(1), 'release', item.name], { cwd: item.worktree, echoes: true });
939
+ // cannot find.
940
+ const released = io.call(ctx.cli[0], [...ctx.cli.slice(1), 'release', item.name], { cwd: item.worktree });
895
941
  if (released.status !== 0) {
896
942
  const said = `${label} — could not release the claim: ${fail(released)}; resuming anyway`;
897
943
  tell(ctx, item, said);
@@ -983,8 +1029,7 @@ function endedEarly(ctx, io, state, item, launch, end, reason, budget) {
983
1029
  return;
984
1030
  }
985
1031
  // As `decideResume` reads it: a resumed Codex thread writes no second `thread.started`.
986
- const resumed = launch.resumes !== undefined && UUID_RE.test(launch.resumes) ? launch.resumes : null;
987
- const id = end.session_id ?? resumed;
1032
+ const id = spendKey(launch, end.session_id);
988
1033
  // A resume of any kind: a session is resumed once (AC-5).
989
1034
  if (launch.resumes !== undefined) {
990
1035
  park(ctx, io, state, item, `${reason}; resumed once${id === null ? '' : `, session ${id}`}${refusals}`, budget);
@@ -1148,7 +1193,8 @@ function closeOut(ctx, io, state, item, budget) {
1148
1193
  drop(state, item, budget);
1149
1194
  return;
1150
1195
  }
1151
- for (const [label, step] of closeSteps(ctx, io, item)) {
1196
+ const report = emptyReport();
1197
+ for (const [label, step] of closeSteps(ctx, io, item, report)) {
1152
1198
  const r = step();
1153
1199
  if (r.status !== 0) {
1154
1200
  const error = `${label} failed: ${fail(r)}`;
@@ -1157,23 +1203,152 @@ function closeOut(ctx, io, state, item, budget) {
1157
1203
  return;
1158
1204
  }
1159
1205
  }
1160
- tell(ctx, item, `${ref(hostOf(ctx), item.pr)} merged by you, and closed`);
1161
- notice(ctx, 'item closed', `${item.name}: ${ref(hostOf(ctx), item.pr)} merged by you, and closed`);
1206
+ const closed = `${ref(hostOf(ctx), item.pr)} merged by you, and closed${closeNote(report)}`;
1207
+ tell(ctx, item, closed);
1208
+ notice(ctx, 'item closed', `${item.name}: ${closed}`);
1162
1209
  drop(state, item, budget);
1163
1210
  }
1164
- /** Close the instance on main. Shared by both close-outs so they cannot drift. */
1165
- function closeSteps(ctx, io, item) {
1211
+ const emptyReport = () => ({ paths: [], leftOut: [], earlier: [], notCopied: [] });
1212
+ /** Shown by a dry run in place of the pathspec, which is only known once the transition has written (design D6). */
1213
+ const DRY_PATHS = '<the paths the close-out changed>';
1214
+ /**
1215
+ * Uncommitted paths under `.aidlc`, relative to `ctx.repo`, or git's failure. `-z` leaves a
1216
+ * name with a space unquoted, `--no-renames` makes a moved roadmap item one deletion and one
1217
+ * new file; porcelain paths are relative to the repository's top, so the project's `prefix`
1218
+ * is removed (closeout-carries-worktree-state/AC-4, design D1).
1219
+ */
1220
+ function dirtyPaths(ctx, io, prefix) {
1221
+ const r = io.call('git', ['status', '--porcelain=v1', '-z', '--no-renames', '--untracked-files=all', '--', '.aidlc'], { cwd: ctx.repo });
1222
+ if (r.status !== 0)
1223
+ return r;
1224
+ return r.stdout
1225
+ .split('\0')
1226
+ .filter((rec) => rec.length > 3)
1227
+ .map((rec) => rec.slice(3))
1228
+ .map((p) => (p.startsWith(prefix) ? p.slice(prefix.length) : p));
1229
+ }
1230
+ const LATE_FILES = ['costs.ndjson', 'unattended-stops.md'];
1231
+ /** `t` without its `**Review:**` lines — the line `withVerdict` inserts or replaces. */
1232
+ const withoutVerdicts = (t) => t
1233
+ .split('\n')
1234
+ .filter((l) => !l.startsWith('**Review:**'))
1235
+ .join('\n');
1236
+ /**
1237
+ * May `from` (the worktree's copy) replace `to` (main's)? The cost hook only appends, so
1238
+ * main's ledger is a prefix of the worktree's; a verdict is inserted after its entry, so the
1239
+ * stops log is a prefix only once both are read without verdicts
1240
+ * (closeout-carries-worktree-state/AC-1, AC-2).
1241
+ */
1242
+ export function carries(file, to, from) {
1243
+ if (to === null)
1244
+ return 'copy';
1245
+ if (from === to)
1246
+ return 'same';
1247
+ if (file === 'costs.ndjson')
1248
+ return from.startsWith(to) && from.length > to.length ? 'copy' : 'refuse';
1249
+ return withoutVerdicts(from).startsWith(withoutVerdicts(to)) ? 'copy' : 'refuse';
1250
+ }
1251
+ /**
1252
+ * Copy the late files the worktree wrote after its last commit over main's, where `carries`
1253
+ * allows; a refused one is named, never written (closeout-carries-worktree-state/AC-1..AC-3).
1254
+ * No worktree, or no file in it, is nothing to do. A dry run copies nothing.
1255
+ */
1256
+ function carryLateFiles(ctx, item, report) {
1257
+ if (!item.worktree)
1258
+ return;
1259
+ for (const file of LATE_FILES) {
1260
+ const rel = `.aidlc/state/${item.name}/${file}`;
1261
+ const from = ctx.fs.read(`${item.worktree}/${rel}`);
1262
+ if (from === null)
1263
+ continue;
1264
+ const verdict = carries(file, ctx.fs.read(`${ctx.repo}/${rel}`), from);
1265
+ if (verdict === 'refuse')
1266
+ report.notCopied.push(rel);
1267
+ else if (verdict === 'copy' && !ctx.dryRun)
1268
+ ctx.fs.write(`${ctx.repo}/${rel}`, from);
1269
+ }
1270
+ }
1271
+ /**
1272
+ * What the closing line adds, separator included: '' when there is nothing to name, so the
1273
+ * line is then exactly what it was (closeout-carries-worktree-state/AC-3, AC-5).
1274
+ */
1275
+ function closeNote(report) {
1276
+ const parts = [
1277
+ ['left out of the close-out commit, already uncommitted on main', report.leftOut],
1278
+ ['committed with earlier uncommitted changes', report.earlier],
1279
+ ["not copied from the worktree, main's copy differs", report.notCopied],
1280
+ ];
1281
+ const named = parts.filter(([, paths]) => paths.length > 0).map(([what, paths]) => `${what}: ${paths.join(', ')}`);
1282
+ return named.length === 0 ? '' : ` — ${named.join('; ')}`;
1283
+ }
1284
+ /**
1285
+ * Close the instance on main. Shared by both close-outs so they cannot drift. Commits only
1286
+ * what the close-out changed: `git add .aidlc` swept a stale rule file into the commit and
1287
+ * turned main red twice (closeout-carries-worktree-state/AC-4).
1288
+ */
1289
+ function closeSteps(ctx, io, item, report) {
1290
+ let prefix = '';
1291
+ // Each path uncommitted before the close-out, with its text then; null for a deleted file.
1292
+ const before = new Map();
1166
1293
  return [
1167
1294
  [
1168
1295
  'close',
1169
1296
  () => {
1297
+ // First, before anything is written: marking a record that does not exist complete
1298
+ // closed instances with no deployment record (closeout-carries-worktree-state/AC-6).
1299
+ if (!ctx.fs.exists(`${ctx.repo}/.aidlc/state/${item.name}/deployment-record.md`)) {
1300
+ return { status: 1, stdout: '', stderr: `deployment-record.md is missing from .aidlc/state/${item.name} on main` };
1301
+ }
1302
+ const top = io.call('git', ['rev-parse', '--show-prefix'], { cwd: ctx.repo });
1303
+ if (top.status !== 0)
1304
+ return top;
1305
+ prefix = top.stdout.trim();
1306
+ const dirty = dirtyPaths(ctx, io, prefix);
1307
+ if (!Array.isArray(dirty))
1308
+ return dirty;
1309
+ for (const p of dirty)
1310
+ before.set(p, ctx.fs.read(`${ctx.repo}/${p}`));
1311
+ carryLateFiles(ctx, item, report);
1170
1312
  if (!markDeploymentComplete(ctx, item.name))
1171
1313
  return { status: 1, stdout: '', stderr: 'no phase-deployment.yaml on main' };
1172
1314
  return transitionFailure(io.cli(['transition', item.name, '--json']));
1173
1315
  },
1174
1316
  ],
1175
- ['stage-close', () => io.call('git', ['add', '.aidlc'], { cwd: ctx.repo })],
1176
- ['commit-close', () => io.call('git', ['commit', '-q', '-m', `chore(aidlc): close out ${item.name} (autopilot)`], { cwd: ctx.repo })],
1317
+ [
1318
+ 'stage-close',
1319
+ () => {
1320
+ const after = dirtyPaths(ctx, io, prefix);
1321
+ if (!Array.isArray(after))
1322
+ return after;
1323
+ // Text, not status: ` M` before and after says nothing about whether the transition
1324
+ // appended to the file (design D2).
1325
+ for (const p of after) {
1326
+ if (!before.has(p)) {
1327
+ report.paths.push(p);
1328
+ }
1329
+ else if (ctx.fs.read(`${ctx.repo}/${p}`) !== before.get(p)) {
1330
+ report.paths.push(p);
1331
+ report.earlier.push(p);
1332
+ }
1333
+ else {
1334
+ report.leftOut.push(p);
1335
+ }
1336
+ }
1337
+ if (ctx.dryRun)
1338
+ return io.call('git', ['add', '--', DRY_PATHS], { cwd: ctx.repo });
1339
+ // An empty pathspec would commit the whole index, the defect being removed (design D5).
1340
+ if (report.paths.length === 0)
1341
+ return { status: 1, stdout: '', stderr: 'the close-out changed nothing under .aidlc' };
1342
+ return io.call('git', ['add', '--', ...report.paths], { cwd: ctx.repo });
1343
+ },
1344
+ ],
1345
+ [
1346
+ 'commit-close',
1347
+ // By pathspec: a path someone had already staged stays staged and outside the commit (AC-4).
1348
+ () => io.call('git', ['commit', '-q', '-m', `chore(aidlc): close out ${item.name} (autopilot)`, '--', ...(ctx.dryRun ? [DRY_PATHS] : report.paths)], {
1349
+ cwd: ctx.repo,
1350
+ }),
1351
+ ],
1177
1352
  ['push-close', () => io.call('git', ['push', 'origin', 'main'], { cwd: ctx.repo })],
1178
1353
  ];
1179
1354
  }
@@ -1587,24 +1762,39 @@ function serveQueue(ctx, io, state, budget) {
1587
1762
  // or when the item stops at the merge (autopilot-stop-controls/AC-25).
1588
1763
  const releases = Array.isArray(release) && release.length > 0 && itemStops(item).stop_at === 'release';
1589
1764
  if (releases) {
1590
- // `echoes`: the release prints the commit subjects it ships, and one naming a rate limit
1591
- // threw after the merge, leaving the release half-run (autopilot-reads-429-in-a-diffstat/AC-5).
1592
- steps.push(['release', () => io.call(release[0], release.slice(1), { cwd: ctx.repo, echoes: true })]);
1593
- }
1594
- steps.push(...closeSteps(ctx, io, item));
1765
+ steps.push(['release', () => io.call(release[0], release.slice(1), { cwd: ctx.repo })]);
1766
+ }
1767
+ const report = emptyReport();
1768
+ steps.push(...closeSteps(ctx, io, item, report));
1769
+ // Halt. Only a failed merge resumes on the next `autopilot run`; from the
1770
+ // pull on, the merge has happened and a half-done release is for a person (AC-16).
1771
+ const halt = (label, error) => {
1772
+ failItem(ctx, state, item, error, label === 'merge' ? 'queued' : undefined);
1773
+ tell(ctx, item, `${error} — queue halted`);
1774
+ };
1595
1775
  for (const [label, step] of steps) {
1596
- const r = step();
1776
+ let r;
1777
+ try {
1778
+ r = step();
1779
+ }
1780
+ catch (err) {
1781
+ // A rate limit on the merge is retried after the back-off: nothing irreversible
1782
+ // happened. After it, the merge is done; backing off alone left the item at its
1783
+ // pre-merge step, and the next pass dropped it as merged outside autopilot
1784
+ // (rate-limit-after-merge-remerges/AC-1, AC-3).
1785
+ if (!(err instanceof RateLimited) || label === 'merge')
1786
+ throw err;
1787
+ halt(label, `${label} failed: ${err.message}`);
1788
+ throw err; // the pass still backs off (rate-limit-after-merge-remerges/AC-4)
1789
+ }
1597
1790
  if (r.status !== 0) {
1598
- // Halt. Only a failed merge resumes on the next `autopilot run`; from the
1599
- // pull on, the merge has happened and a half-done release is for a person (AC-16).
1600
- const error = `${label} failed: ${fail(r)}`;
1601
- failItem(ctx, state, item, error, label === 'merge' ? 'queued' : undefined);
1602
- tell(ctx, item, `${error} — queue halted`);
1791
+ halt(label, `${label} failed: ${fail(r)}`);
1603
1792
  return;
1604
1793
  }
1605
1794
  }
1606
- tell(ctx, item, `merged${releases ? ', released' : ''} and closed`);
1607
- notice(ctx, releases ? 'item released' : 'item merged', `${item.name}: merged${releases ? ', released' : ''} and closed`);
1795
+ const closed = `merged${releases ? ', released' : ''} and closed${closeNote(report)}`;
1796
+ tell(ctx, item, closed);
1797
+ notice(ctx, releases ? 'item released' : 'item merged', `${item.name}: ${closed}`);
1608
1798
  drop(state, item, budget);
1609
1799
  }
1610
1800
  /**
@@ -1616,8 +1806,7 @@ function serveQueue(ctx, io, state, budget) {
1616
1806
  */
1617
1807
  function parkUnstartable(ctx, io, file, failure) {
1618
1808
  const error = failure.trim();
1619
- // The start failure was read for a rate limit already, when `aidlc start` printed it.
1620
- const r = io.cli(['roadmap', 'park', '--item', file, '--reason', `could not start: ${error}`], { echoes: true });
1809
+ const r = io.cli(['roadmap', 'park', '--item', file, '--reason', `could not start: ${error}`]);
1621
1810
  if (r.status !== 0) {
1622
1811
  ctx.say(`could not start ${file}: ${error} — and could not park it: ${fail(r)}`);
1623
1812
  return false;
@@ -1656,13 +1845,11 @@ function startBuilds(ctx, io, state, budget) {
1656
1845
  const template = ctx.config?.template ?? 'quick-feature';
1657
1846
  let busy = building(state);
1658
1847
  const tried = new Set();
1659
- let toldAttended = false;
1848
+ let toldSkipped = false;
1660
1849
  while (busy < max && (budget?.remaining ?? 1) > 0) {
1661
1850
  // `--autopilot`: an item marked `run: attended` is never started unattended
1662
1851
  // (autopilot-or-attended-field/AC-8).
1663
- // `echoes`: it prints the item's title, and a title naming a 429 or a rate limit backed
1664
- // the run off before it built anything (autopilot-reads-429-in-a-diffstat/AC-4).
1665
- const r = io.cli(['roadmap', 'next', '--json', '--autopilot'], { echoes: true });
1852
+ const r = io.cli(['roadmap', 'next', '--json', '--autopilot']);
1666
1853
  let next = null;
1667
1854
  let skipped = [];
1668
1855
  try {
@@ -1676,9 +1863,17 @@ function startBuilds(ctx, io, state, budget) {
1676
1863
  }
1677
1864
  // Once a pass; the run loop drops it on later passes while it is unchanged (AC-9).
1678
1865
  const attended = skipped.filter((s) => s.reason === 'attended').map((s) => s.file);
1679
- if (!toldAttended && attended.length > 0)
1866
+ if (!toldSkipped && attended.length > 0)
1680
1867
  ctx.say(`left for a person (run: attended): ${attended.join(', ')}`);
1681
- toldAttended = true;
1868
+ // The detail already starts `not ready: `; the file goes between that and the rest
1869
+ // (autopilot-refuses-unready-items/AC-8, design D4).
1870
+ if (!toldSkipped) {
1871
+ for (const s of skipped.filter((x) => x.reason === 'not-ready')) {
1872
+ const rest = typeof s.detail === 'string' ? s.detail.replace(/^not ready: /, '') : '';
1873
+ ctx.say(rest === '' ? `not ready: ${s.file}` : `not ready: ${s.file}: ${rest}`);
1874
+ }
1875
+ }
1876
+ toldSkipped = true;
1682
1877
  if (!next) {
1683
1878
  ctx.say('nothing ready in the backlog');
1684
1879
  return;