yadflow 4.6.0 → 4.8.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 (136) hide show
  1. package/CHANGELOG.md +259 -0
  2. package/README.md +46 -4
  3. package/bin/commands.mjs +9 -2
  4. package/bin/yad.mjs +309 -30
  5. package/cli/agent-guard.mjs +511 -0
  6. package/cli/agent-guide.mjs +83 -0
  7. package/cli/agent-rules.mjs +381 -0
  8. package/cli/argv-flags.mjs +7 -0
  9. package/cli/artifact-status.mjs +88 -20
  10. package/cli/build.mjs +1372 -0
  11. package/cli/checkpoint.mjs +2 -2
  12. package/cli/ci-check.mjs +492 -0
  13. package/cli/commit.mjs +1 -0
  14. package/cli/dial.mjs +21 -1
  15. package/cli/docs.mjs +7 -2
  16. package/cli/doctor.mjs +176 -33
  17. package/cli/epic-state.mjs +360 -12
  18. package/cli/errors.mjs +3 -0
  19. package/cli/find-product.mjs +36 -2
  20. package/cli/fold.mjs +9 -5
  21. package/cli/gate-local.mjs +9 -1
  22. package/cli/gate.mjs +364 -22
  23. package/cli/guide.mjs +549 -0
  24. package/cli/history.mjs +22 -2
  25. package/cli/hook.mjs +35 -4
  26. package/cli/index-command.mjs +2 -2
  27. package/cli/ledger.mjs +60 -0
  28. package/cli/lib.mjs +46 -0
  29. package/cli/lifecycle/defaults/2.json +124 -0
  30. package/cli/lifecycle/lifecycle.schema.json +5 -2
  31. package/cli/lifecycle.mjs +16 -3
  32. package/cli/manifest.mjs +75 -0
  33. package/cli/marked-block.mjs +48 -0
  34. package/cli/members.mjs +19 -5
  35. package/cli/migrate.mjs +17 -19
  36. package/cli/next.mjs +35 -12
  37. package/cli/openpr.mjs +81 -5
  38. package/cli/plan.mjs +326 -22
  39. package/cli/platform.mjs +21 -0
  40. package/cli/pr-list.mjs +5 -3
  41. package/cli/product-index.mjs +6 -3
  42. package/cli/product-token.mjs +186 -0
  43. package/cli/productcommit.mjs +33 -0
  44. package/cli/protection.mjs +50 -0
  45. package/cli/recommend.mjs +3 -1
  46. package/cli/reconcile.mjs +187 -26
  47. package/cli/repo-publish.mjs +2 -2
  48. package/cli/report.mjs +62 -14
  49. package/cli/run-checks.mjs +586 -0
  50. package/cli/setup.mjs +244 -25
  51. package/cli/ship-drift.mjs +49 -18
  52. package/cli/signing.mjs +377 -0
  53. package/cli/standup.mjs +1 -1
  54. package/cli/status.mjs +282 -0
  55. package/cli/test-agents-file.mjs +993 -0
  56. package/cli/test-build.mjs +1559 -0
  57. package/cli/test-ci-check.mjs +616 -0
  58. package/cli/test-guide.mjs +1267 -0
  59. package/cli/test-node.mjs +129 -0
  60. package/cli/test-run-checks.mjs +603 -0
  61. package/cli/test-setup-agent.mjs +352 -0
  62. package/cli/test-signing.mjs +524 -0
  63. package/cli/test-worktree.mjs +520 -0
  64. package/cli/thread.mjs +4 -0
  65. package/cli/tidy.mjs +2 -2
  66. package/cli/toolbox.mjs +37 -6
  67. package/cli/update-commit.mjs +313 -11
  68. package/cli/workspace.mjs +38 -10
  69. package/cli/worktree-record.mjs +53 -0
  70. package/cli/worktree.mjs +379 -0
  71. package/package.json +6 -4
  72. package/skills/sdlc/config.yaml +5 -5
  73. package/skills/sdlc/module-help.csv +2 -1
  74. package/skills/yad-backfill/templates/checks/backfill-check.sh +9 -9
  75. package/skills/yad-change/SKILL.md +5 -1
  76. package/skills/yad-checks/SKILL.md +61 -12
  77. package/skills/yad-checks/references/check-gates.md +78 -14
  78. package/skills/yad-checks/templates/checks/build-test-lint.sh +22 -3
  79. package/skills/yad-checks/templates/checks/commit-message.sh +8 -2
  80. package/skills/yad-checks/templates/checks/contract-check.sh +61 -33
  81. package/skills/yad-checks/templates/checks/epic-open.sh +87 -14
  82. package/skills/yad-checks/templates/checks/ledger-guard.sh +3 -3
  83. package/skills/yad-checks/templates/checks/lineage-check.sh +88 -15
  84. package/skills/yad-checks/templates/checks/member-check.mjs +206 -35
  85. package/skills/yad-checks/templates/checks/package-manager.sh +42 -5
  86. package/skills/yad-checks/templates/checks/product-checkout.sh +161 -13
  87. package/skills/yad-checks/templates/checks/reconcile-debt-check.sh +94 -15
  88. package/skills/yad-checks/templates/checks/risk-map-check.sh +2 -2
  89. package/skills/yad-checks/templates/checks/spec-link.sh +63 -4
  90. package/skills/yad-checks/templates/checks/verified-commits.sh +23 -5
  91. package/skills/yad-checks/templates/github/yad-checks.yml +9 -9
  92. package/skills/yad-checks/templates/gitlab/.gitlab-ci.yml +4 -1
  93. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +5 -5
  94. package/skills/yad-checks/templates/gitlab/yad-product-checks.gitlab-ci.yml +16 -3
  95. package/skills/yad-checks/templates/gitlab/yad-update-guard.gitlab-ci.yml +5 -1
  96. package/skills/yad-checks/templates/gitlab/yad-verified-commits.gitlab-ci.yml +5 -1
  97. package/skills/yad-checks/templates/hooks/agent-guard.mjs +116 -0
  98. package/skills/yad-commit/SKILL.md +8 -5
  99. package/skills/yad-connect-repos/SKILL.md +5 -3
  100. package/skills/yad-connect-repos/references/code-context.md +2 -1
  101. package/skills/yad-connect-repos/references/repos-registry.md +2 -1
  102. package/skills/yad-docs/templates/app/package-lock.json +395 -106
  103. package/skills/yad-docs/templates/app/package.json +2 -2
  104. package/skills/yad-docs-overview/references/pipeline-model.md +2 -2
  105. package/skills/yad-engineer-review/SKILL.md +55 -25
  106. package/skills/yad-engineer-review/references/ship-and-record.md +49 -12
  107. package/skills/yad-epic/SKILL.md +2 -1
  108. package/skills/yad-epic/references/state-schema.md +76 -17
  109. package/skills/yad-guide/SKILL.md +192 -0
  110. package/skills/yad-implement/SKILL.md +75 -13
  111. package/skills/yad-implement/references/implement-conventions.md +8 -1
  112. package/skills/yad-implement/templates/.gitmessage +3 -0
  113. package/skills/yad-open-pr/SKILL.md +21 -0
  114. package/skills/yad-pair-review/SKILL.md +14 -5
  115. package/skills/yad-pr-template/SKILL.md +6 -2
  116. package/skills/yad-pr-template/templates/checks/pr-template.sh +85 -4
  117. package/skills/yad-pr-template/templates/checks/pr-title.sh +1 -1
  118. package/skills/yad-pr-template/templates/github/pull_request_template.md +1 -1
  119. package/skills/yad-pr-template/templates/gitlab/merge_request_templates/Default.md +1 -1
  120. package/skills/yad-product-bridge/SKILL.md +44 -12
  121. package/skills/yad-product-bridge/references/bridge.md +11 -5
  122. package/skills/yad-product-bridge/templates/github/yad-gate-sync.yml +2 -2
  123. package/skills/yad-product-bridge/templates/gitlab/yad-gate-sync.gitlab-ci.yml +9 -4
  124. package/skills/yad-reconcile/SKILL.md +9 -3
  125. package/skills/yad-report/SKILL.md +15 -0
  126. package/skills/yad-review-companion/SKILL.md +5 -3
  127. package/skills/yad-review-gate/SKILL.md +16 -8
  128. package/skills/yad-review-gate/references/gating.md +26 -1
  129. package/skills/yad-run/SKILL.md +61 -33
  130. package/skills/yad-run/references/run-loop.md +44 -22
  131. package/skills/yad-spec/SKILL.md +137 -16
  132. package/skills/yad-spec/references/spec-handoff.md +50 -3
  133. package/skills/yad-status/SKILL.md +7 -0
  134. package/skills/yad-stories/references/story-schema.md +1 -1
  135. package/skills/yad-sync-repos/SKILL.md +2 -1
  136. package/skills/yad-ui/SKILL.md +2 -2
package/cli/build.mjs ADDED
@@ -0,0 +1,1372 @@
1
+ // `yad build start|step|trust|ship|done` (issue #346) — one command per Build record, so the records are
2
+ // written in the shape every reader expects instead of by hand. The user's decisions (2026-10-19):
3
+ // - one family, `yad build …`, named after the Build phase the records belong to;
4
+ // - `build ship` reads the merge commit, checks and approvers from the MERGED PR/MR on the platform (as
5
+ // `yad review reconcile` does), and refuses one that is not merged; flags fill in with no platform;
6
+ // - `build done` makes the three "shipped" signals agree — the story's `status:` line, the ship records
7
+ // and every lane step `done` — so `yad next`, the epic seal and `yad tidy up` all read the same answer.
8
+ //
9
+ // The records and their readers are unchanged: the commands write exactly what the skills wrote by hand
10
+ // (skills/yad-epic/references/state-schema.md, skills/yad-engineer-review/references/ship-and-record.md).
11
+ // They write; `yad checkpoint --push` commits, as before.
12
+ //
13
+ // The rules are the PURE planners below (`planStart`, `planStep`, `trustEntry`, `planDone`); the commands
14
+ // read the files, call them, and write.
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ import { randomBytes } from 'node:crypto';
18
+ import { spawnSync } from 'node:child_process';
19
+ import { ok, info, hand, warn, run, readJSON, readJSONStrict, writeJSON, writeFileAtomic, isPlainObject, exists } from './lib.mjs';
20
+ import { epicIds, epicRoot, epicRel, epicStories, loadLedger, stepStatus, laneStarted, isPassed, readFrontmatter, parseFrontmatter, nextAction, loadAutomation, effectiveAdvance, effectiveAction } from './epic-state.mjs';
21
+ import { DEFAULT_LIFECYCLE, laneOrder, laneAuthorSteps } from './lifecycle.mjs';
22
+ import { epicFiles, PROJECT_FILES } from './manifest.mjs';
23
+ import { err } from './errors.mjs';
24
+ import { readShips, readTrustRuns, writeShip, shipBlocked, updateShip, writeTrustRun, updateTrustRun } from './ledger.mjs';
25
+ import { setBuildStatus, readStoryStatus } from './artifact-status.mjs';
26
+ import { readPr, mapApprovers, detectPlatform, cliFor, platformReady, prNumberFromUrl } from './platform.mjs';
27
+ import { repoPathFromGitUrl } from './protection.mjs';
28
+ import { readCommit, tasksOfCommit, prOfCommit, shipDrift } from './ship-drift.mjs';
29
+ import { recordActor } from './skip.mjs';
30
+ import { sealedEpic } from './thread.mjs';
31
+ import { worktreeAt, sameDir } from './worktree-record.mjs';
32
+
33
+ const CODE = 'YAD-STATE-009';
34
+ const STORY_RE = /^EP-[a-z0-9-]+-S\d+$/;
35
+ const TASK_RE = /^T\d+$/;
36
+ export const VERDICTS = ['approved-unchanged', 'approved-with-edits', 'rejected'];
37
+ // The signals each step's trust entry may carry (state-schema.md, "Per-step signals fields").
38
+ export const STEP_SIGNALS = {
39
+ spec: ['human_edited_spec'],
40
+ tasks: ['task_rescoped'],
41
+ implement: ['human_edited_diff', 'scope_overrun', 'contract_touch'],
42
+ checks: ['checks'],
43
+ };
44
+ // The states `build step` moves a step to. `done` closes it; `blocked` halts the lane with a record.
45
+ export const STEP_MOVES = ['in_progress', 'in_review', 'done', 'blocked'];
46
+
47
+ const LANE = laneOrder(DEFAULT_LIFECYCLE);
48
+ const AUTHOR = new Set(laneAuthorSteps(DEFAULT_LIFECYCLE));
49
+ const REVIEW_STEP = LANE.find((id) => !AUTHOR.has(id)) || 'engineer-review';
50
+ // The steps walked once per task (the user's decision, 2026-10-20): `implement` and every author step after
51
+ // it. A story's tasks each go through them in turn, so a later task reopens them.
52
+ export const PER_TASK = new Set(LANE.slice(LANE.indexOf('implement')).filter((id) => AUTHOR.has(id)));
53
+
54
+ export const storyEpic = (story) => String(story).replace(/-S\d+$/, '');
55
+
56
+ // A lane as `yad-run` seeds it: every step `todo`, every dial `human`, the review step locked.
57
+ export function newLane() {
58
+ return {
59
+ currentStep: LANE[0],
60
+ steps: LANE.map((id) => ({ id, automation: 'human_approve', advance: 'human', locked: !AUTHOR.has(id), status: 'todo' })),
61
+ };
62
+ }
63
+
64
+ // A build-state file this can read as a lane map, or a refusal — never overwritten when it cannot be read.
65
+ function lanes(bs, story) {
66
+ if (bs == null) return { story, repos: {} };
67
+ if (!isPlainObject(bs)) throw err(CODE, `build-state/${story}.json is not a JSON object`, 'fix the file by hand — nothing here overwrites content it cannot read');
68
+ if ('repos' in bs && !isPlainObject(bs.repos)) throw err(CODE, `build-state/${story}.json has a \`repos\` that is not an object`, 'fix the file by hand — nothing here overwrites content it cannot read');
69
+ return { ...bs, story: bs.story || story, repos: { ...(bs.repos || {}) } };
70
+ }
71
+
72
+ // PURE: add a repo's lane to a story's build-state. The same refusals as a lane skip (E39): the stories
73
+ // review passed, and the story declares the repo. A lane already there is left as it is.
74
+ export function planStart(buildState, { story, repo, declared = [], storiesPassed = false }) {
75
+ if (!storiesPassed) throw err(CODE, `the stories review has not passed, so ${story} is not approved for Build yet`, 'pass the stories review first (yad gate)');
76
+ if (!declared.includes(repo)) {
77
+ throw err(CODE, `${story} does not declare ${repo}, so it has no lane there`, declared.length ? `its repos: ${declared.join(', ')} (names are case-sensitive)` : 'the story declares no repos at all');
78
+ }
79
+ const bs = lanes(buildState, story);
80
+ const lane = bs.repos[repo];
81
+ if (isPlainObject(lane) && lane.status === 'skipped' && !laneStarted(lane)) {
82
+ throw err(CODE, `${story} / ${repo} is skipped`, `\`yad unskip ${storyEpic(story)} ${story} --repo ${repo}\` if the lane is owed after all`);
83
+ }
84
+ if (lane != null) return { buildState: bs, already: true };
85
+ return { buildState: { ...bs, repos: { ...bs.repos, [repo]: newLane() } }, already: false };
86
+ }
87
+
88
+ // A lane to change, or a refusal naming what to run first.
89
+ function liveLane(bs, story, repo) {
90
+ const lane = bs.repos[repo];
91
+ if (lane == null) throw err(CODE, `${story} has no lane in ${repo} yet`, `\`yad build start ${story} --repo ${repo}\` makes it`);
92
+ if (!isPlainObject(lane) || !Array.isArray(lane.steps)) {
93
+ if (isPlainObject(lane) && lane.status === 'skipped') throw err(CODE, `${story} / ${repo} is skipped`, `\`yad unskip ${storyEpic(story)} ${story} --repo ${repo}\` if the lane is owed after all`);
94
+ throw err(CODE, `${story} / ${repo} has no steps in build-state/${story}.json`, 'fix the file by hand — nothing here overwrites content it cannot read');
95
+ }
96
+ return lane;
97
+ }
98
+
99
+ // The lane's step now: `currentStep` when it is not done, else the first step not done.
100
+ const activeStep = (lane) => {
101
+ const cur = lane.steps.find((s) => s?.id === lane.currentStep);
102
+ return cur && !isPassed(cur) ? cur : lane.steps.find((s) => !isPassed(s)) || null;
103
+ };
104
+
105
+ // PURE: move one step of a lane. Only the lane's active step moves, so a lane is never walked out of order.
106
+ // `done` writes the closing record (E18) and moves `currentStep` on; `blocked` needs a reason, written as
107
+ // the step's record. The review step is closed by `build done`, which checks every task shipped first.
108
+ export function planStep(buildState, { story, repo, step, to, reason = null, by = null, date = null, via = 'human', run = null, task = null, automation = null }) {
109
+ if (task != null && !TASK_RE.test(String(task))) throw err(CODE, `--task must be a task id such as T02 (got '${task}')`, '--task T02');
110
+ if (!STEP_MOVES.includes(to)) throw err(CODE, `'${to}' is not a step state this sets`, `one of: ${STEP_MOVES.join(', ')}`);
111
+ const bs = lanes(buildState, story);
112
+ const lane = liveLane(bs, story, repo);
113
+ const target = lane.steps.find((s) => s?.id === step);
114
+ if (!target) throw err(CODE, `${story} / ${repo} has no step '${step}'`, `its steps: ${lane.steps.map((s) => s?.id).join(', ')}`);
115
+ if (step === REVIEW_STEP && to === 'done') {
116
+ throw err(CODE, `${REVIEW_STEP} is closed by \`yad build done ${story}\``, 'it checks that every task has a ship record first');
117
+ }
118
+ const active = activeStep(lane);
119
+ if (isPassed(target)) {
120
+ // `done --task T02` on a step T01 closed is not "already done": T02 has not been through it.
121
+ if (to === 'done' && task && target.closed?.task !== task) {
122
+ if (!PER_TASK.has(step)) throw err(CODE, `--task does not apply to ${step}`, `${step} is walked once per story, not per task`);
123
+ throw err(CODE, `${step} was closed ${target.closed?.task ? `for ${target.closed.task}` : 'for no task'}, not ${task}`, `reopen it for ${task} first: yad build step ${story} --repo ${repo} implement in_progress --task ${task}`);
124
+ }
125
+ if (to === 'done') return { buildState: bs, already: true };
126
+ // The next task reopens the per-task steps — once the lane has walked them all for the task before
127
+ // (it is at the review step) and the review is not closed. Each close stays in `runs`, by task.
128
+ // The next task starts at implement: reopening checks alone would leave the task no implement run.
129
+ const first = [...PER_TASK][0];
130
+ const reopen = step === first && task && active?.id === REVIEW_STEP && stepStatus(active) !== 'blocked';
131
+ if (!reopen) {
132
+ const hint = !PER_TASK.has(step) ? 'a closed step is not reopened'
133
+ : active?.id === REVIEW_STEP && stepStatus(active) === 'blocked' ? `clear the halt on ${REVIEW_STEP} first`
134
+ : `the next task reopens ${first} once the lane is at ${REVIEW_STEP}: yad build step ${story} --repo ${repo} ${first} ${to} --task <T>`;
135
+ throw err(CODE, `${step} is already done in ${story} / ${repo}`, hint);
136
+ }
137
+ const at = LANE.indexOf(step);
138
+ const keep = (s) => {
139
+ const n = { ...s };
140
+ if (n.closed) {
141
+ const prior = Array.isArray(n.runs) ? n.runs : [];
142
+ n.runs = [...(n.closed.run ? prior.filter((r) => r?.run !== n.closed.run) : prior), n.closed];
143
+ }
144
+ delete n.closed;
145
+ delete n.record;
146
+ return n;
147
+ };
148
+ const steps = lane.steps.map((s) => {
149
+ if (s?.id === step) {
150
+ const n = { ...keep(s), status: to, task };
151
+ if (to === 'blocked') {
152
+ if (reason == null || reason === true || !String(reason).trim()) throw err(CODE, 'a halt needs a reason', `yad build step ${story} --repo ${repo} ${step} blocked --task ${task} --reason "<what a person must resolve>"`);
153
+ n.record = { reason: String(reason).trim(), by, date };
154
+ }
155
+ return n;
156
+ }
157
+ // The per-task steps after it are owed again for this task.
158
+ if (PER_TASK.has(s?.id) && LANE.indexOf(s.id) > at && isPassed(s)) return { ...keep(s), status: 'todo', task };
159
+ return s;
160
+ });
161
+ return { buildState: { ...bs, repos: { ...bs.repos, [repo]: { ...lane, currentStep: step, steps } } }, already: false, reopened: task };
162
+ }
163
+ if (active && active.id !== step) {
164
+ throw err(CODE, `${story} / ${repo} is at ${active.id}, not ${step}`, `move ${active.id} first — the lane is walked in order`);
165
+ }
166
+ if (!['auto', 'human'].includes(via)) throw err(CODE, `--via must be auto or human (got '${via}')`, '--via human, unless the orchestrator advanced it on its own');
167
+ // The dial IN FORCE — the lane's own, held at human while the kill switch is on — not the lane's word alone.
168
+ if (via === 'auto' && to === 'done' && effectiveAdvance(target, automation).advance !== 'auto') {
169
+ const why = effectiveAdvance(target, automation).why;
170
+ throw err(CODE, `${step} is not advancing on its own in ${story} / ${repo}${why === 'kill' ? ' (the kill switch is on)' : ''}, so it is not closed --via auto`,
171
+ why === 'kill' ? '`yad unkill` turns the kill switch off' : `\`yad dial ${storyEpic(story)} ${story} --repo ${repo} ${step} --to auto\` sets the dial first`);
172
+ }
173
+ // A step reopened for a task closes for that task: `--task` defaults to it, and another is refused.
174
+ if (task && target.task && task !== target.task) throw err(CODE, `${step} is open for ${target.task}, not ${task}`, `--task ${target.task}`);
175
+ const forTask = task || target.task || null;
176
+ const next = { ...target, status: to };
177
+ delete next.record;
178
+ if (to === 'blocked') {
179
+ if (reason == null || reason === true || !String(reason).trim()) throw err(CODE, 'a halt needs a reason', `yad build step ${story} --repo ${repo} ${step} blocked --reason "<what a person must resolve>"`);
180
+ next.record = { reason: String(reason).trim(), by, date };
181
+ }
182
+ if (to === 'done') {
183
+ next.closed = { by, date, via, ...(run ? { run } : {}), ...(forTask ? { task: forTask } : {}) };
184
+ delete next.task;
185
+ }
186
+ const steps = lane.steps.map((s) => (s?.id === step ? next : s));
187
+ let currentStep;
188
+ if (to === 'done') {
189
+ const i = LANE.indexOf(step);
190
+ const after = steps.find((s, k) => !isPassed(s) && (LANE.indexOf(s?.id) > i || (LANE.indexOf(s?.id) === -1 && k > steps.indexOf(next))));
191
+ currentStep = after ? after.id : step;
192
+ } else currentStep = step;
193
+ return { buildState: { ...bs, repos: { ...bs.repos, [repo]: { ...lane, currentStep, steps } } }, already: false };
194
+ }
195
+
196
+ // PURE: a trust entry, checked. `signals` is { name: value } from `--signal name=value`.
197
+ export function trustEntry({ story, repo, step, verdict, signals = {}, ranBy = 'human', note = null, date = null, lane = null, uid, task = null, automation = null }) {
198
+ if (task != null && !TASK_RE.test(String(task))) throw err(CODE, `--task must be a task id such as T02 (got '${task}')`, '--task T02');
199
+ if (!AUTHOR.has(step)) throw err(CODE, `'${step}' has no trust entry`, `trust is recorded for: ${[...AUTHOR].join(', ')}`);
200
+ if (!VERDICTS.includes(verdict)) throw err(CODE, `'${verdict}' is not a verdict`, `one of: ${VERDICTS.join(', ')}`);
201
+ if (!['machine', 'human'].includes(ranBy)) throw err(CODE, `--ran-by must be machine or human (got '${ranBy}')`, 'machine when the orchestrator advanced it, else human');
202
+ const allowed = STEP_SIGNALS[step] || [];
203
+ const out = {};
204
+ for (const [k, raw] of Object.entries(signals)) {
205
+ if (!allowed.includes(k)) throw err(CODE, `'${k}' is not a ${step} signal`, `${step} signals: ${allowed.join(', ')}`);
206
+ const v = String(raw);
207
+ if (k === 'checks') {
208
+ if (!['pass', 'fail', 'n/a'].includes(v)) throw err(CODE, `checks=${v}: expected pass, fail or n/a`, '--signal checks=pass');
209
+ out[k] = v;
210
+ } else {
211
+ if (!['true', 'false'].includes(v)) throw err(CODE, `${k}=${v}: expected true or false`, `--signal ${k}=true`);
212
+ out[k] = v === 'true';
213
+ }
214
+ }
215
+ const st = lane?.steps?.find((s) => s?.id === step);
216
+ // The dial in force at run time: the lane's own, held at human while the kill switch is on.
217
+ const advance = st ? effectiveAdvance(st, automation).advance : 'human';
218
+ return {
219
+ story, repo, step, uid,
220
+ automation: advance === 'auto' ? 'machine_advance' : 'human_approve', advance,
221
+ verdict, signals: out, ranBy, date,
222
+ ...(task ? { task } : {}),
223
+ ...(note ? { note: String(note) } : {}),
224
+ };
225
+ }
226
+
227
+ // The tasks a story owes in one repo: the ids in `specs/<story>/tasks.md` on the repo's default branch
228
+ // (merged, not the working tree — the rule the gates read by). Each task line starts with its id (`T01`).
229
+ export function parseTaskIds(text) {
230
+ const ids = [];
231
+ for (const line of String(text).split(/\r?\n/)) {
232
+ const m = line.match(/^\s*(?:[-*+]\s+(?:\[[ xX]\]\s+)?|#{1,6}\s+|\d+[.)]\s+)?\**(T\d+)\b/);
233
+ if (m && !ids.includes(m[1])) ids.push(m[1]);
234
+ }
235
+ return ids;
236
+ }
237
+
238
+ // A light spec (#348) is one spec.md holding the spec, the plan and the tasks; link.md says
239
+ // `spec-mode: light`. The tasks are the lines between the two markers, so a `T01` line in the spec or the
240
+ // plan above them is never read as a task. Exactly one block, opened before it is closed; otherwise null.
241
+ export const LIGHT_TASKS = { begin: '<!-- yad:tasks -->', end: '<!-- /yad:tasks -->' };
242
+ export function lightTasksBlock(text) {
243
+ const lines = String(text).split(/\r?\n/);
244
+ const at = (m) => lines.flatMap((l, i) => (l.trim() === m ? [i] : []));
245
+ const b = at(LIGHT_TASKS.begin);
246
+ const e = at(LIGHT_TASKS.end);
247
+ if (b.length !== 1 || e.length !== 1 || e[0] < b[0]) return null;
248
+ return lines.slice(b[0] + 1, e[0]).join('\n');
249
+ }
250
+ export const isLightSpec = (linkText) => parseFrontmatter(linkText)['spec-mode'] === 'light';
251
+
252
+ // PURE: what `build done` finds. `owed` is { repo: [taskIds] | null } (null: tasks.md could not be read);
253
+ // `ships` the story's ships. A retroactive ship covers its whole repo.
254
+ export function planDone({ story, declared, skipped = [], owed, ships }) {
255
+ const missing = [];
256
+ const unreadable = [];
257
+ for (const repo of declared) {
258
+ if (skipped.includes(repo)) continue;
259
+ const shipped = ships.filter((s) => s.story === story && s.repo === repo);
260
+ if (shipped.some((s) => s.retroactive)) continue;
261
+ const tasks = owed[repo];
262
+ if (tasks == null) { unreadable.push(repo); continue; }
263
+ if (!tasks.length) { unreadable.push(repo); continue; }
264
+ for (const t of tasks) if (!shipped.some((s) => s.task === t)) missing.push(`${repo}/${t}`);
265
+ }
266
+ return { missing, unreadable, shipped: !missing.length && !unreadable.length };
267
+ }
268
+
269
+ // The review step closed by `build done`: done, with its closing record, and no halt record left on it.
270
+ const closeReview = (s, { by, date }) => {
271
+ const n = { ...s, status: 'done', closed: { by, date, via: 'human' } };
272
+ delete n.record;
273
+ return n;
274
+ };
275
+
276
+ // ---- the commands ----------------------------------------------------------------------------------
277
+
278
+ // The story's file, found the way `epicStories` finds the story: by its frontmatter `id`, else its name.
279
+ // One file, named for the story: `yad tidy` and the seal name a story by its file, so a file named other
280
+ // than its id would be shipped here and never folded there.
281
+ function storyFileOf(epicDir, story) {
282
+ const dir = path.join(epicDir, 'stories');
283
+ const claim = fs.readdirSync(dir).filter((n) => n.endsWith('.md')).sort()
284
+ .filter((f) => (readFrontmatter(path.join(dir, f)).id || f.replace(/\.md$/, '')) === story);
285
+ if (!claim.length) throw err(CODE, `no story file for ${story}`, 'check the story id');
286
+ if (claim.length > 1) throw err(CODE, `${claim.length} story files claim ${story}: ${claim.join(', ')}`, 'keep one');
287
+ if (claim[0] !== `${story}.md`) throw err(CODE, `${story} is in stories/${claim[0]}, not stories/${story}.md`, `rename it to ${story}.md: yad tidy and the epic seal read a story by its file name`);
288
+ return path.join(dir, claim[0]);
289
+ }
290
+
291
+ // The status a Build write moves the story from must be one it can place; refused before anything is
292
+ // written, so the lanes and the status line never part.
293
+ function storyStatusOk(ctx, story) {
294
+ const st = readStoryStatus(ctx.storyFile);
295
+ if (!['draft', 'in-review', 'approved', 'in-build', 'shipped'].includes(st)) {
296
+ throw err(CODE, `${path.relative(ctx.epicDir, ctx.storyFile)} has status: ${st ?? '(none)'}, which a Build write cannot move on`, `set it to approved (\`yad sync-status ${storyEpic(story)}\` does), then run this again`);
297
+ }
298
+ return st;
299
+ }
300
+
301
+ function storyContext(root, story) {
302
+ if (!STORY_RE.test(String(story || ''))) throw err(CODE, `'${story}' is not a story id`, 'expected EP-<slug>-S<n>, such as EP-checkout-S01');
303
+ const epic = storyEpic(story);
304
+ const epicDir = epicRoot(root, epic);
305
+ const ledger = loadLedger(epicDir);
306
+ if (!ledger.state) throw err(CODE, `no epic state at ${epicRel(epic)}`, 'seed the epic first with yad-epic');
307
+ const entry = epicStories(epicDir).find((s) => s.id === story);
308
+ if (!entry) throw err(CODE, `no story ${story} under ${epicRel(epic)}/stories/`, 'check the story id');
309
+ const review = ledger.state.steps.find((s) => s?.id === 'stories-review');
310
+ const file = path.join(epicFiles(epicDir).buildStateDir, `${story}.json`);
311
+ return {
312
+ epic, epicDir, entry, file, ledger,
313
+ storiesPassed: ['done', 'satisfied'].includes(stepStatus(review)),
314
+ buildState: readJSONStrict(file, null),
315
+ storyFile: storyFileOf(epicDir, story),
316
+ };
317
+ }
318
+
319
+ const rel = (root, p) => path.relative(root, p);
320
+ const repoArg = (repo, usage) => { if (!repo || repo === true) throw err(CODE, '--repo <name> is required', usage); return repo; };
321
+
322
+ export async function buildStart(root, { story, repo, today } = {}) {
323
+ repoArg(repo, `yad build start ${story || '<story>'} --repo <name>`);
324
+ const ctx = storyContext(root, story);
325
+ const { buildState, already } = planStart(ctx.buildState, { story, repo, declared: ctx.entry.repos, storiesPassed: ctx.storiesPassed });
326
+ if (already) {
327
+ ok(`${story} / ${repo} already has a lane — nothing changed`);
328
+ return { story, repo, changed: false, file: rel(root, ctx.file) };
329
+ }
330
+ writeJSON(ctx.file, buildState);
331
+ ok(`${story} / ${repo} lane started at ${buildState.repos[repo].currentStep}${today ? ` on ${today}` : ''}`);
332
+ hand(`yad next ${ctx.epic} shows it; commit with \`yad checkpoint --push\``);
333
+ return { story, repo, changed: true, lane: buildState.repos[repo], file: rel(root, ctx.file) };
334
+ }
335
+
336
+ export async function buildStep(root, { story, repo, step, to, reason, via = 'human', run: runUid = null, task = null, today } = {}) {
337
+ repoArg(repo, `yad build step ${story || '<story>'} --repo <name> <step> ${STEP_MOVES.join('|')}`);
338
+ if (!step || !to) throw err(CODE, 'a step and the state to move it to are required', `yad build step ${story} --repo ${repo} <step> ${STEP_MOVES.join('|')}`);
339
+ const ctx = storyContext(root, story);
340
+ // A run named must be a run of this step in this lane, for the task the close is for, and not one an
341
+ // earlier close already names: the closing record points at the evidence.
342
+ if (runUid && runUid !== true) {
343
+ const lane = lanes(ctx.buildState, story).repos[repo];
344
+ const st = Array.isArray(lane?.steps) ? lane.steps.find((x) => x?.id === step) : null;
345
+ const forTask = (task && task !== true ? task : null) || st?.task || null;
346
+ const used = [st?.closed?.run, ...(Array.isArray(st?.runs) ? st.runs.map((x) => x?.run) : [])].filter(Boolean);
347
+ // The same close sent again (an orchestrator resuming) is "already done", not a second close.
348
+ const same = st && isPassed(st) && st.closed?.run === runUid && (!forTask || st.closed?.task === forTask);
349
+ if (!same && used.includes(runUid)) throw err(CODE, `trust run ${runUid} already closed ${step} in ${story} / ${repo}`, 'each close names its own run: record this one with `yad build trust`');
350
+ const known = readTrustRuns(ctx.epicDir).some((r) => r.uid === runUid && r.story === story && r.repo === repo && r.step === step
351
+ && !(r.task && forTask && r.task !== forTask));
352
+ if (!known) throw err(CODE, `no trust run ${runUid} for ${story} / ${repo} / ${step}`, `\`yad build trust ${story} --repo ${repo} ${step} --verdict …\` prints the uid of the run it records`);
353
+ }
354
+ // An automatic close names the run that earned it: without one, nothing shows the run was not rejected.
355
+ if (to === 'done' && via === 'auto' && (!runUid || runUid === true)) {
356
+ throw err(CODE, '--via auto needs --run <uid>, the trust run that advanced the step', `yad build trust ${story} --repo ${repo} ${step} --verdict … prints it`);
357
+ }
358
+ if (runUid && runUid !== true && to === 'done' && via === 'auto') {
359
+ const r = readTrustRuns(ctx.epicDir).find((x) => x.uid === runUid && x.story === story && x.repo === repo && x.step === step);
360
+ if (r?.verdict === 'rejected') throw err(CODE, `trust run ${runUid} is rejected, so ${step} does not advance on its own`, `halt instead: yad build step ${story} --repo ${repo} ${step} blocked --reason "<why>"`);
361
+ }
362
+ const { buildState, already, reopened } = planStep(ctx.buildState, {
363
+ story, repo, step, to, reason, by: recordActor(root), date: today, via, run: runUid === true ? null : runUid, task: task === true ? null : task,
364
+ automation: loadAutomation(root),
365
+ });
366
+ if (already) {
367
+ ok(`${step} is already done in ${story} / ${repo} — nothing changed`);
368
+ return { story, repo, step, status: 'done', changed: false };
369
+ }
370
+ writeJSON(ctx.file, buildState);
371
+ const lane = buildState.repos[repo];
372
+ ok(`${story} / ${repo}: ${step} is ${to}${reopened ? ` again, for ${reopened}` : ''}${to === 'blocked' ? ` — ${String(reason).trim()}` : ''}`);
373
+ if (to === 'done') info(`next: ${lane.currentStep}`);
374
+ hand('commit with `yad checkpoint --push`');
375
+ const specKit = SPEC_KIT_STEPS.has(step) && to === 'in_progress' ? pinSpecKit(root, repo, story, step) : null;
376
+ return { story, repo, step, status: to, currentStep: lane.currentStep, changed: true, ...(specKit ? { specKit } : {}) };
377
+ }
378
+
379
+ // Spec Kit finds the story folder it writes into through `.specify/feature.json` (issue #348): pinned to
380
+ // specs/<story> when the spec or tasks step starts (yad-spec runs both, and another story's spec may have
381
+ // moved the file in between), so /speckit.plan and the rest never write into the previous story's folder.
382
+ // Only in a repo that has a `.specify/` folder, i.e. uses Spec Kit. The step is already recorded, so nothing
383
+ // here fails it: a problem is a warning with the fix. The file is the clone's working state, as Spec Kit's
384
+ // own writes are — it is not committed.
385
+ const SPEC_KIT_STEPS = new Set(['spec', 'tasks']);
386
+ // A registered checkout's worktree for an epic, when yad made one beside it (#115); else null.
387
+ function epicWorktreeOf(checkout, epic, repo) {
388
+ const at = path.join(path.dirname(checkout), `${path.basename(checkout)}--${epic}`);
389
+ const rec = worktreeAt(at);
390
+ return rec && rec.repo === repo && rec.epic === epic && sameDir(rec.main, checkout) ? at : null;
391
+ }
392
+
393
+ export function pinSpecKit(root, repo, story, step = 'spec') {
394
+ let checkout;
395
+ try { ({ checkout } = registeredRepo(root, repo)); } catch (e) { warn(`Spec Kit folder not pinned: ${e.message}${e.hint ? ` — ${e.hint}` : ''}`); return null; }
396
+ if (!checkout) { info(`${repo} is not checked out here, so Spec Kit's feature folder was not pinned`); return null; }
397
+ // The story's epic has its own worktree of this repo (#115): the agent specs there, so the pin goes there.
398
+ const wt = epicWorktreeOf(checkout, storyEpic(story), repo);
399
+ const where = wt ? path.basename(wt) : repo;
400
+ const dir = path.join(wt ?? checkout, '.specify');
401
+ const featureDirectory = `specs/${story}`;
402
+ const fix = `set it by hand: {"feature_directory":"${featureDirectory}"} in ${where}/.specify/feature.json`;
403
+ let dirStat;
404
+ try { dirStat = fs.lstatSync(dir, { throwIfNoEntry: false }); } catch (e) { warn(`could not read ${where}/.specify: ${e.message} — ${fix}`); return null; }
405
+ if (!dirStat) return null; // no .specify/: the repo does not use Spec Kit
406
+ // A link is not followed: yad never writes through one.
407
+ if (!dirStat.isDirectory()) { info(`${where}/.specify is not a plain folder, so Spec Kit's feature folder was not pinned — ${fix}`); return null; }
408
+ const file = path.join(dir, 'feature.json');
409
+ let have = {};
410
+ try {
411
+ const st = fs.lstatSync(file, { throwIfNoEntry: false });
412
+ if (st && !st.isFile()) { warn(`${where}/.specify/feature.json is not a plain file, so it was left alone — ${fix}`); return null; }
413
+ if (st) have = JSON.parse(fs.readFileSync(file, 'utf8'));
414
+ } catch { warn(`${where}/.specify/feature.json cannot be read, so it was left alone — ${fix}`); return null; }
415
+ if (!isPlainObject(have)) { warn(`${where}/.specify/feature.json is not a JSON object, so it was left alone — ${fix}`); return null; }
416
+ const changed = have.feature_directory !== featureDirectory;
417
+ if (changed) {
418
+ try { writeFileAtomic(file, JSON.stringify({ ...have, feature_directory: featureDirectory }) + '\n'); } catch (e) { warn(`could not write ${where}/.specify/feature.json: ${e.message} — ${fix}`); return null; }
419
+ }
420
+ ok(`Spec Kit's feature folder in ${where} ${changed ? 'is now' : 'is already'} ${featureDirectory}`);
421
+ if (step === 'spec') hand(`when /speckit.specify runs, give it \`SPECIFY_FEATURE_DIRECTORY=${featureDirectory}\` — it makes a numbered folder of its own without it`);
422
+ return { file: `${where}/.specify/feature.json`, featureDirectory, changed };
423
+ }
424
+
425
+ export async function buildTrust(root, { story, repo, step, verdict, signals = {}, ranBy = 'human', note = null, uid = null, task = null, today } = {}) {
426
+ repoArg(repo, `yad build trust ${story || '<story>'} --repo <name> <step> --verdict <${VERDICTS.join('|')}>`);
427
+ if (!step) throw err(CODE, 'a step is required', `yad build trust ${story} --repo ${repo} <step> --verdict <v>`);
428
+ if (!verdict || verdict === true) throw err(CODE, '--verdict is required', `one of: ${VERDICTS.join(', ')}`);
429
+ const ctx = storyContext(root, story);
430
+ // Finalizing a run that was already recorded: the human gate confirms or overrides the provisional verdict.
431
+ if (uid && uid !== true) {
432
+ if (Object.keys(signals).length) throw err(CODE, '--signal is not changed when finalizing a run', 'the signals are what the run saw; --uid sets only the verdict (and --note)');
433
+ if (!VERDICTS.includes(verdict)) throw err(CODE, `'${verdict}' is not a verdict`, `one of: ${VERDICTS.join(', ')}`);
434
+ const res = updateTrustRun(ctx.epicDir, (r) => r.uid === uid && r.story === story && r.repo === repo && r.step === step, (r) => {
435
+ r.verdict = verdict;
436
+ if (note) r.note = String(note);
437
+ });
438
+ if (!res.found) throw err(CODE, `no trust run ${uid} for ${story} / ${repo} / ${step}`, 'the uid is the one `yad build trust` printed when it recorded the run');
439
+ ok(`trust run ${uid} (${story} / ${repo} / ${step}) is now ${verdict}`);
440
+ hand('commit with `yad checkpoint --push`');
441
+ return { story, repo, step, uid, verdict, changed: true, finalized: true };
442
+ }
443
+ const bs = lanes(ctx.buildState, story);
444
+ const lane = liveLane(bs, story, repo);
445
+ const entry = trustEntry({ story, repo, step, verdict, signals, ranBy, note, date: today, lane, uid: randomBytes(4).toString('hex'), task: task === true ? null : task, automation: loadAutomation(root) });
446
+ const res = writeTrustRun(ctx.epicDir, entry);
447
+ if (!res.written) throw err(CODE, `a trust run named ${path.basename(res.file)} is already there`, 'run it again: a new uid is drawn each time');
448
+ ok(`trust run ${entry.uid} recorded: ${story} / ${repo} / ${step} — ${verdict}`);
449
+ info(`close the step with it: yad build step ${story} --repo ${repo} ${step} done --run ${entry.uid}`);
450
+ hand('commit with `yad checkpoint --push`');
451
+ return { story, repo, step, uid: entry.uid, verdict, changed: true, file: rel(root, res.file) };
452
+ }
453
+
454
+ // The registered repo's checkout, platform and default branch.
455
+ function registeredRepo(root, repo) {
456
+ const reg = readJSON(path.join(root, PROJECT_FILES.reposRegistry), { repos: [] });
457
+ const meta = (reg.repos || []).find((r) => r?.name === repo) || null;
458
+ const product = readJSON(path.join(root, PROJECT_FILES.productConfig), null) || readJSON(path.join(root, '.sdlc/hub.json'), null) || {};
459
+ const dir = meta?.path ? path.resolve(root, meta.path) : null;
460
+ const checkout = dir && exists(path.join(dir, '.git')) ? dir : null;
461
+ const remote = checkout ? run('git', ['remote', 'get-url', 'origin'], { cwd: checkout }).stdout : '';
462
+ // The folder must be the registered repo: a stale path to another clone would read that repo's PR #n.
463
+ // Compared by the repo's path on its host (`team/api`), so a port, an SSH host alias, a token in the URL
464
+ // or a trailing slash do not matter. Never printed as a URL: a remote can hold a token.
465
+ if (checkout && meta?.git_url && remote) {
466
+ const have = repoPathFromGitUrl(remote);
467
+ const want = repoPathFromGitUrl(meta.git_url);
468
+ if (!have !== !want) warn(`${repo}: could not compare the clone with its registered git_url — check ${meta.path} is ${want || 'the registered repo'}`);
469
+ if (have && want && have.toLowerCase() !== want.toLowerCase()) throw err(CODE, `${meta.path} is a clone of ${have}, not ${want}`, `fix the path of ${repo} in .sdlc/repos.json, or clone it with \`yad repo clone ${repo}\``);
470
+ }
471
+ const named = typeof meta?.default_branch === 'string' && meta.default_branch ? meta.default_branch : null;
472
+ if (named && (named.startsWith('-') || !run('git', ['check-ref-format', '--branch', named]).ok)) {
473
+ throw err(CODE, `.sdlc/repos.json names a default_branch for ${repo} git cannot use: ${named}`, 'fix default_branch in .sdlc/repos.json');
474
+ }
475
+ return { meta, checkout, platform: meta?.platform || detectPlatform(remote) || product.platform || null, defaultBranch: named };
476
+ }
477
+
478
+ // A PR/MR's state in one vocabulary: open, merged or closed (closed without a merge). GitLab's `locked` is
479
+ // an MR mid-merge, so still open.
480
+ const ghState = (v) => ({ OPEN: 'open', MERGED: 'merged', CLOSED: 'closed' })[v] || null;
481
+ const glState = (v) => ({ opened: 'open', locked: 'open', merged: 'merged', closed: 'closed' })[v] || null;
482
+
483
+ // The merged PR/MR's facts the ship record holds. `runner` is injectable for tests.
484
+ export function readMergedPr(platform, n, { cwd, runner = run } = {}) {
485
+ if (platform === 'gitlab') {
486
+ const r = runner('glab', ['api', `projects/:id/merge_requests/${n}`], { cwd });
487
+ if (!r.ok) return { ok: false, reason: r.stderr || 'glab api merge_requests failed' };
488
+ let mr; try { mr = JSON.parse(r.stdout); } catch { return { ok: false, reason: 'unreadable glab answer' }; }
489
+ // The gates that passed: the job names of the MR's head pipeline that succeeded.
490
+ // One page of up to 100 jobs; jobs of a child or downstream pipeline are not listed here.
491
+ let checks = [];
492
+ let checksRead = false;
493
+ const pid = mr.head_pipeline?.id;
494
+ if (pid) {
495
+ const j = runner('glab', ['api', `projects/:id/pipelines/${pid}/jobs?per_page=100`], { cwd });
496
+ if (j.ok) { try { checks = [...new Set((JSON.parse(j.stdout) || []).filter((x) => x?.status === 'success').map((x) => x.name).filter(Boolean))].sort(); checksRead = true; } catch { /* unreadable */ } }
497
+ }
498
+ return {
499
+ // A fast-forward merge has no merge commit: the MR's head is what landed.
500
+ ok: true, state: glState(mr.state), merged: mr.state === 'merged', mergeCommit: mr.merge_commit_sha || mr.squash_commit_sha || (mr.state === 'merged' ? mr.sha : null) || null, checksRead,
501
+ mergedAt: mr.merged_at || null, branch: mr.source_branch || null, url: mr.web_url || null, body: mr.description || '', checks,
502
+ };
503
+ }
504
+ const r = runner('gh', ['pr', 'view', String(n), '--json', 'state,mergedAt,mergeCommit,headRefName,url,body,statusCheckRollup'], { cwd });
505
+ if (!r.ok) return { ok: false, reason: r.stderr || 'gh pr view failed' };
506
+ let pr; try { pr = JSON.parse(r.stdout); } catch { return { ok: false, reason: 'unreadable gh answer' }; }
507
+ // The gates that passed on the merged head: a check run's name, or a status context's.
508
+ const checks = [...new Set((pr.statusCheckRollup || [])
509
+ .filter((c) => (c.conclusion || c.state || '').toUpperCase() === 'SUCCESS')
510
+ .map((c) => c.name || c.context).filter(Boolean))].sort();
511
+ return {
512
+ ok: true, state: ghState(pr.state), merged: pr.state === 'MERGED', mergeCommit: pr.mergeCommit?.oid || null, mergedAt: pr.mergedAt || null, checksRead: true,
513
+ branch: pr.headRefName || null, url: pr.url || null, body: pr.body || '', checks,
514
+ };
515
+ }
516
+
517
+ // The task ids a branch names, lower-case: `feat/EP-auth-S01-T02-2fa-setup` → ['ep-auth-s01-t02'], under any
518
+ // folders, in any case. Each id is the shortest one from a folder or `_` boundary that ends at a word
519
+ // boundary, so a slug after the task (`-2fa-setup`, `-then-S02-T03`) is never read as part of it, and
520
+ // `T012` is not `T01`.
521
+ export function tasksInBranch(branch) {
522
+ return [...String(branch || '').matchAll(/(?:^|[/_])(ep-[a-z0-9-]+?-s\d+-t\d+)(?=$|[-_/])/gi)].map((m) => m[1].toLowerCase());
523
+ }
524
+
525
+ // Which task a PR's branch carries, for `story`-`task`: 'this' (it names this task), 'other' (it names
526
+ // another) or 'none'. The expected id first: an epic slug may itself read like a task (`EP-aws-s3-t2-backup`).
527
+ export function branchTask(branch, story, task) {
528
+ const esc = `${story}-${task}`.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
529
+ if (new RegExp(`(?:^|[/_])${esc}(?=$|[-_/])`, 'i').test(branch || '')) return 'this';
530
+ return tasksInBranch(branch).length ? 'other' : 'none';
531
+ }
532
+
533
+ // A follow-up branch of `story`-`task` (issue #350): the task id followed by `-followup`, as in
534
+ // `fix/EP-pay-S01-T01-followup-null-check` — a fix to a task that has already shipped. Its commits keep the
535
+ // task's `Task:` line; its merge is added to the task's ship (`followUps`), never a second ship.
536
+ export function isFollowUpBranch(branch, story, task) {
537
+ const esc = `${story}-${task}`.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
538
+ return new RegExp(`(?:^|[/_])${esc}-followup(?=$|[-_/])`, 'i').test(branch || '');
539
+ }
540
+
541
+ // A commit in the repo's own checkout: it exists and is on the default branch (origin's, fetched first
542
+ // unless --no-fetch; the local one when there is no origin). `strict` (a ship read with the platform's help)
543
+ // also asks that it names the task, by the rules `yad reconcile check` reads every commit with — a `Task:`
544
+ // trailer, a task branch a merge brought in, or the full id in the subject. By hand, where the platform
545
+ // cannot be read, the person vouches for it: it may not name a DIFFERENT task, and naming none is a warning.
546
+ function checkCommit(where, { story, task, repo, mergeCommit, strict = true, fetch = true, noTask = 'recorded as you say it ships', group = null }) {
547
+ const cwd = where.checkout;
548
+ const hasOrigin = run('git', ['remote', 'get-url', 'origin'], { cwd }).ok;
549
+ const head = run('git', ['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD'], { cwd }).stdout;
550
+ const branch = where.defaultBranch || (head.startsWith('origin/') ? head.slice(7) : 'main');
551
+ let ref = `refs/heads/${branch}`;
552
+ if (hasOrigin) {
553
+ if (fetch && !run('git', ['fetch', '--quiet', 'origin', `+refs/heads/${branch}:refs/remotes/origin/${branch}`], { cwd }).ok) {
554
+ throw err(CODE, `could not fetch ${branch} in ${repo} to check the commit`, 'check the network and your login, or pass --no-fetch to check against the last fetched copy');
555
+ }
556
+ ref = `refs/remotes/origin/${branch}`;
557
+ }
558
+ if (!run('git', ['rev-parse', '--verify', '--quiet', ref], { cwd }).ok) {
559
+ throw err(CODE, `${repo} has no ${hasOrigin ? `origin/${branch}` : `branch ${branch}`} to check the commit against`, `set default_branch for ${repo} in .sdlc/repos.json`);
560
+ }
561
+ const sha = run('git', ['rev-parse', '--verify', '--quiet', `${mergeCommit}^{commit}`], { cwd }).stdout;
562
+ if (!sha) throw err(CODE, `${mergeCommit} is not a commit in ${repo}`, 'fetch it, or check the SHA');
563
+ if (!run('git', ['merge-base', '--is-ancestor', sha, ref], { cwd }).ok) {
564
+ throw err(CODE, `${mergeCommit} is not on ${repo}'s ${branch}`, 'a ship is recorded once the work is merged into the default branch');
565
+ }
566
+ const rec = readCommit(cwd, sha);
567
+ if (!rec) throw err(CODE, `${mergeCommit} could not be read in ${repo}`, 'check the SHA');
568
+ const named = tasksOfCommit(rec).map((x) => x.task);
569
+ const want = `${story}-${task}`;
570
+ // A grouped PR (#350): its merge commit names the branch's task; it ships every task the PR carries.
571
+ // By hand there is no PR to ask: the merge commit's own merged range is read (`group: 'range'`).
572
+ if (group === 'range') group = mergeRangeTasks(cwd, sha);
573
+ const inGroup = Array.isArray(group) && group.includes(want) && named.length && named.every((t) => group.includes(t));
574
+ if (!named.includes(want) && !inGroup) {
575
+ if (strict || named.length) {
576
+ throw err(CODE, named.length ? `${mergeCommit} names ${named.join(', ')}, not ${want}` : `${mergeCommit} does not name ${want}`,
577
+ 'the commit must name the task it ships: its Task: trailer, the task branch a merge commit brought in, or the full id in its subject');
578
+ }
579
+ if (noTask) warn(`${mergeCommit} names no task — ${noTask} ${want}`);
580
+ }
581
+ const body = run('git', ['log', '-1', '--format=%b', sha], { cwd }).stdout;
582
+ return { sha, rec, body, date: run('git', ['log', '-1', '--format=%cs', sha], { cwd }).stdout };
583
+ }
584
+
585
+ // Which PRs/MRs merged a commit, asked of the platform — the only reliable answer (the user's decision,
586
+ // 2026-10-20): a squash subject ending "(#N)" may cite an issue, and a GitLab merge names its MR only in
587
+ // the body. Returns { ok, prs: [numbers] } or { ok: false, reason }.
588
+ export function prsForCommit(platform, sha, { cwd, runner = run } = {}) {
589
+ if (platform === 'gitlab') {
590
+ const r = runner('glab', ['api', `projects/:id/repository/commits/${sha}/merge_requests`], { cwd });
591
+ if (!r.ok) return { ok: false, reason: r.stderr || 'glab api failed' };
592
+ try { return { ok: true, prs: (JSON.parse(r.stdout) || []).filter((m) => m?.state === 'merged').map((m) => Number(m.iid)).filter(Boolean) }; } catch { return { ok: false, reason: 'unreadable glab answer' }; }
593
+ }
594
+ const r = runner('gh', ['api', `repos/{owner}/{repo}/commits/${sha}/pulls`], { cwd });
595
+ if (!r.ok) return { ok: false, reason: r.stderr || 'gh api failed' };
596
+ try { return { ok: true, prs: (JSON.parse(r.stdout) || []).filter((p) => p?.merged_at).map((p) => Number(p.number)).filter(Boolean) }; } catch { return { ok: false, reason: 'unreadable gh answer' }; }
597
+ }
598
+
599
+ // The ship of a task merged with no PR/MR, where the platform can be read: the commit names the task, and
600
+ // the platform says no PR merged it. A PR that did is named (so the ship keeps its approvers); a platform
601
+ // that cannot answer is a refusal, never a guess.
602
+ function shipWithoutPr(where, { story, task, repo, mergeCommit, today, runner, fetch }) {
603
+ const c = checkCommit(where, { story, task, repo, mergeCommit, strict: true, fetch });
604
+ const asked = prsForCommit(where.platform, c.sha, { cwd: where.checkout, runner });
605
+ if (!asked.ok) throw err(CODE, `could not ask ${where.platform} whether a PR/MR merged ${mergeCommit}: ${asked.reason}`, `log in with \`${cliFor(where.platform)} auth login\`, or pass --pr <n> if one did`);
606
+ if (asked.prs.length > 1) throw err(CODE, `${mergeCommit} is in more than one merged PR/MR: ${asked.prs.map((x) => `#${x}`).join(', ')}`, `name the one that shipped ${story}-${task}: yad build ship ${story} --task ${task} --repo ${repo} --pr <n>`);
607
+ if (asked.prs.length) throw err(CODE, `${mergeCommit} was merged by PR/MR #${asked.prs[0]}`, `record it from that PR/MR, with its approvers: yad build ship ${story} --task ${task} --repo ${repo} --pr ${asked.prs[0]}`);
608
+ return {
609
+ story, task, repo, branch: null, pr: 'none', mergeCommit: c.sha, gates: [],
610
+ ai_review: null, engineer_review: [], companion: { trailer: false, cards: false, chat: false },
611
+ risk: null, shippedAt: c.date || today,
612
+ };
613
+ }
614
+
615
+ const riskFromBody = (body) => (String(body).match(/^\s*Risk level:\s*(low|medium|high)\b/im) || [])[1]?.toLowerCase() || null;
616
+
617
+ // What a ship of `story`/`task` in `repo` needs before anything is asked or written — shared by `build ship`
618
+ // and `build merged`, so `merged` never answers "merged" for a ship `ship` would then refuse.
619
+ function shipContext(root, { story, task, repo, pr, verb }) {
620
+ repoArg(repo, `yad build ${verb} ${story || '<story>'} --task <T01> --repo <name>`);
621
+ if (!TASK_RE.test(String(task || ''))) throw err(CODE, `--task must be a task id such as T01 (got '${task ?? ''}')`, `yad build ${verb} ${story} --task T01 --repo ${repo}`);
622
+ if (pr && pr !== true && !/^[1-9]\d*$/.test(String(pr))) throw err(CODE, `--pr must be the PR/MR number (got '${pr}')`, 'the number, not a URL or a branch');
623
+ const ctx = storyContext(root, story);
624
+ if (!ctx.storiesPassed) throw err(CODE, `the stories review has not passed, so ${story} is not approved for Build yet`, 'pass the stories review first (yad gate)');
625
+ if (!ctx.entry.repos.includes(repo)) throw err(CODE, `${story} does not declare ${repo}`, `its repos: ${ctx.entry.repos.join(', ') || 'none'}`);
626
+ storyStatusOk(ctx, story);
627
+ const lane = lanes(ctx.buildState, story).repos[repo];
628
+ if (isPlainObject(lane) && lane.status === 'skipped' && !laneStarted(lane)) {
629
+ throw err(CODE, `${story} / ${repo} is skipped`, `\`yad unskip ${ctx.epic} ${story} --repo ${repo}\` before recording a ship there`);
630
+ }
631
+ return { ctx, where: registeredRepo(root, repo) };
632
+ }
633
+
634
+ // The refusal for a ship `writeShip` (or `shipBlocked`) will not write.
635
+ function shipRefused(res, { story, task, repo }) {
636
+ if (res.reason === 'exists') throw err(CODE, `${story} / ${task} already has a ship in ${repo}`, 'one ship per task and repo');
637
+ throw err(CODE, `${repo} shares a ship file name with ${res.repo || 'another repo'}`, 'repo names that differ only in punctuation cannot both ship this task');
638
+ }
639
+
640
+ export async function buildShip(root, { story, task, repo, pr, mergeCommit = null, approvers = [], followUp = false, byHand: byHandOk = true, today, fetch = true, runner = run, prReader = readPr } = {}) {
641
+ if (mergeCommit && mergeCommit !== true && !/^[0-9a-f]{7,64}$/i.test(String(mergeCommit))) throw err(CODE, `--merge-commit must be a commit SHA (got '${mergeCommit}')`, 'the merge commit, 7 to 64 hex characters');
642
+ const { ctx, where } = shipContext(root, { story, task, repo, pr, verb: 'ship' });
643
+ let ship;
644
+ // Read from the platform only in the repo's own checkout: from anywhere else `gh pr view <n>` reads that
645
+ // folder's repo — the Product's own PR #n.
646
+ const readable = where.platform && where.checkout && (runner !== run || platformReady(where.platform));
647
+ // A follow-up (#350) is added to the task's ship, so the ship must be there; where the platform can be
648
+ // read, it is read from its PR/MR, like the ship itself.
649
+ const original = followUp ? readShips(ctx.epicDir).find((s) => s.story === story && s.task === task && s.repo === repo) : null;
650
+ if (followUp && !original) throw err(CODE, `${story} / ${task} has no ship in ${repo} yet, so it has no follow-up`, `record the task's own ship first: yad build ship ${story} --task ${task} --repo ${repo} --pr <n>`);
651
+ if (followUp && readable && (!pr || pr === true)) throw err(CODE, 'a follow-up is read from its merged PR/MR: --pr <n> is required', `yad build ship ${story} --task ${task} --repo ${repo} --pr <n> --follow-up`);
652
+ const byHand = (mergeCommit && mergeCommit !== true) || approvers.length;
653
+ // A task merged with no PR/MR (the user's decision, 2026-10-20): the commit is the evidence, so it must be
654
+ // on the default branch and name the task. Nobody approved a PR, so there are no approvers.
655
+ if (readable && (!pr || pr === true) && mergeCommit && mergeCommit !== true && !approvers.length) {
656
+ ship = shipWithoutPr(where, { story, task, repo, mergeCommit, today, runner, fetch });
657
+ } else if (readable && byHand) throw err(CODE, `the ship is read from PR #${pr || '?'} on ${where.platform}`, '--merge-commit and --approver are for a repo whose platform cannot be read; drop them');
658
+ const usable = readable;
659
+ if (where.platform && !where.checkout && !byHand) {
660
+ throw err(CODE, `${repo} is not checked out here, so its PR cannot be read`, `\`yad repo clone ${repo}\` fetches it; or record it by hand with --merge-commit <sha> and --approver <login>`);
661
+ }
662
+ if (!ship && usable && (!pr || pr === true)) throw err(CODE, '--pr <n> is required', `the merged PR/MR the ship is read from: yad build ship ${story} --task ${task} --repo ${repo} --pr <n>`);
663
+ if (ship) { /* recorded from the commit above */ } else if (usable) {
664
+ const got = readMergedPr(where.platform, pr, { cwd: where.checkout, runner });
665
+ if (!got.ok) throw err(CODE, `could not read PR #${pr} in ${repo}: ${got.reason}`, `log in with \`${cliFor(where.platform)} auth login\`, then run this again`);
666
+ if (!got.merged) throw err(CODE, `PR #${pr} in ${repo} is not merged`, 'a ship is recorded once the PR/MR merges');
667
+ if (!got.mergeCommit) throw err(CODE, `PR #${pr} in ${repo} is merged, but the platform names no merge commit`, 'record it from the commit instead: yad build ship … --merge-commit <sha> with no --pr');
668
+ // The PR carries the task (`prCarries`): its branch names it, or — a grouped PR (#350) — its commits do.
669
+ // The ship is never put on a task the PR does not carry.
670
+ const { carries, tasks: group } = prCarries(where, pr, got, { story, task, runner });
671
+ if (carries === 'other') throw err(CODE, group?.length ? `PR #${pr}'s commits carry ${group.join(', ')}, not ${story}-${task}` : `PR #${pr} is from ${got.branch}, which names another task than ${story}-${task}`, group?.length ? `check --task and --pr; a PR/MR carries a task by a commit's Task: trailer (what spec-link reads), not by a mention in a subject` : 'check --task and --pr');
672
+ if (carries === 'none') warn(`PR #${pr} is from ${got.branch || '(no branch)'}, which names no task — check it is the PR for ${story}-${task}`);
673
+ if (carries === 'group') info(`PR #${pr} is a grouped PR: its commits carry ${group.join(', ')}`);
674
+ // A follow-up branch is never the task's own ship, and a follow-up should come from one. The name is the
675
+ // task's own only when nothing else can be (`ownPrs`): before the ship, with no plain-named PR for the task.
676
+ const follows = isFollowUpBranch(got.branch, story, task);
677
+ if (follows && !followUp && !followUpIsOwn(ctx, where, { story, task, repo, runner, asked: { number: Number(pr), state: got.state || 'merged' } })) throw err(CODE, `PR #${pr} is from ${got.branch}, a follow-up branch of ${story}-${task}`, `add it to the task's ship: yad build ship ${story} --task ${task} --repo ${repo} --pr ${pr} --follow-up`);
678
+ if (followUp && !follows) warn(`PR #${pr} is from ${got.branch || '(no branch)'}, not a follow-up branch (fix/${story}-${task}-followup-<words>) — check it is a follow-up of ${story}-${task}`);
679
+ const pull = prReader(where.platform, pr, { cwd: where.checkout, runner });
680
+ const seen = new Set();
681
+ const engineerReview = [];
682
+ for (const a of pull.ok ? mapApprovers(pull.reviews, { headOid: pull.headOid }) : []) {
683
+ if (seen.has(a.name)) continue;
684
+ seen.add(a.name);
685
+ engineerReview.push({ approver: a.name, engagement: a.engagement === 'verified' ? 'verified' : 'none' });
686
+ }
687
+ if (got.checksRead === false) warn(`could not read the checks of PR #${pr} — gates is left empty`);
688
+ if (!pull.ok) warn(`could not read the approvals of PR #${pr} (${pull.reason}) — engineer_review is left empty; \`yad review reconcile\` fills it later`);
689
+ // What merged must be on the default branch, and may not name another task — the same check as by hand.
690
+ const c = checkCommit(where, { story, task, repo, mergeCommit: got.mergeCommit, strict: false, fetch, group: carries === 'group' ? group : null });
691
+ ship = {
692
+ story, task, repo, branch: got.branch, pr: got.url || `#${pr}`, mergeCommit: c.sha, gates: got.checks,
693
+ ai_review: null, engineer_review: engineerReview,
694
+ companion: { trailer: /<!--\s*yad:trailer\s*-->/.test(got.body), cards: false, chat: false },
695
+ risk: riskFromBody(got.body), shippedAt: (got.mergedAt || '').slice(0, 10) || today,
696
+ };
697
+ } else {
698
+ // No platform to ask: the person says what merged — never `yad build sync`, where no person vouches.
699
+ if (!byHandOk) throw err(CODE, `${where.platform ? `${cliFor(where.platform)} cannot read` : `${repo} has no platform to read`} the PR/MR that merged ${story}-${task}`, 'a person records it: yad build ship … --merge-commit <sha> [--approver <login>]');
700
+ if (!mergeCommit || mergeCommit === true) {
701
+ throw err(CODE, where.platform ? `${cliFor(where.platform)} is not available to read the PR` : `${repo} has no platform to read the PR from`, '--merge-commit <sha> (and --approver <login> for each approver) records it by hand');
702
+ }
703
+ // In the repo's checkout the commit is checked as evidence too; only with no checkout is it taken as given.
704
+ const c = where.checkout ? checkCommit(where, { story, task, repo, mergeCommit, strict: false, fetch, group: 'range' }) : null;
705
+ // A commit whose own merge subject names a PR is that PR's: a different --pr is refused.
706
+ const said = c ? prOfCommit(c.rec.subject, c.body) : null;
707
+ if (said?.certain && pr && pr !== true && Number(pr) !== said.pr) throw err(CODE, `${mergeCommit} merged PR/MR #${said.pr}, not #${pr}`, `--pr ${said.pr}`);
708
+ ship = {
709
+ story, task, repo, branch: null, pr: pr && pr !== true ? `#${pr}` : 'local', mergeCommit: c ? c.sha : mergeCommit, gates: [],
710
+ ai_review: null, engineer_review: approvers.map((a) => ({ approver: a, engagement: 'none' })),
711
+ companion: { trailer: false, cards: false, chat: false }, risk: null, shippedAt: (c && c.date) || today,
712
+ };
713
+ }
714
+ if (followUp) return addFollowUp(root, ctx, original, ship, { story, task, repo });
715
+ const res = writeShip(ctx.epicDir, ship);
716
+ if (!res.written) shipRefused(res, { story, task, repo });
717
+ // The story is in Build now (the skill's rule); `build done` sets it shipped once every task is.
718
+ const moved = setBuildStatus(ctx.storyFile, 'in-build');
719
+ ok(`ship recorded: ${story} / ${task} in ${repo}${ship.mergeCommit ? ` (${String(ship.mergeCommit).slice(0, 12)})` : ''}`);
720
+ if (moved.changed) info(`${story} is now in-build`);
721
+ hand(`when every task has shipped: yad build done ${story}; commit with \`yad checkpoint --push\``);
722
+ return { story, task, repo, changed: true, ship, file: rel(root, res.file) };
723
+ }
724
+
725
+ // Add a follow-up's merge to the task's ship, where the ship lives (its shard, or the folded log). The same
726
+ // PR/MR or merge commit twice is refused; the story's status is left as it is.
727
+ // The task a commit message carries, read as the spec-link gate reads it: git's own trailer parser
728
+ // (`git interpret-trailers --parse --no-divider`, the rules `%(trailers)` applies to a commit — the trailer
729
+ // block, the key in any case, folded values), then the FIRST non-empty `Task:` value, and only when it is a
730
+ // task id. Used on messages the platform returns; local commits are read by git itself (`gitTasks`).
731
+ const TASK_ID_ONLY = /^EP-[a-z0-9-]+-S\d+-T\d+$/;
732
+ // Run in the code repo's own checkout (`cwd`), so its git settings apply as they do to `gitTasks`. Throws
733
+ // when git cannot read the message: that is a failed read, never "no task".
734
+ export function trailerTask(message, { cwd } = {}) {
735
+ const r = spawnSync('git', ['interpret-trailers', '--parse', '--no-divider'], { input: String(message || ''), encoding: 'utf8', cwd });
736
+ if (r.error || r.status !== 0) throw new Error(`git interpret-trailers failed${r.error ? `: ${r.error.message}` : ''}`);
737
+ for (const line of String(r.stdout).split('\n')) {
738
+ const m = line.match(/^task[ \t]*:[ \t]*(.*?)[ \t]*$/i);
739
+ if (m && m[1]) return TASK_ID_ONLY.test(m[1]) ? m[1] : null;
740
+ }
741
+ return null;
742
+ }
743
+
744
+ // The tasks the commits of a `git log` range carry: each commit's FIRST `Task:` trailer, read by git as the
745
+ // spec-link gate reads it. `null` when git cannot read the range.
746
+ function gitTasks(cwd, args) {
747
+ const r = run('git', ['log', '--format=%(trailers:key=Task,valueonly,separator=%x1e)%x00', ...args], { cwd });
748
+ if (!r.ok) return null;
749
+ const ids = r.stdout.split('\0').map((x) => x.split('\x1e')[0].trim()).filter((v) => TASK_ID_ONLY.test(v));
750
+ return [...new Set(ids)].sort((x, y) => x.localeCompare(y, 'en', { numeric: true }));
751
+ }
752
+
753
+ // The tasks a PR/MR's own commits carry by their `Task:` lines (issue #350): a grouped PR carries several
754
+ // small tasks of one story, each commit naming its own. Asked of the platform — the one source every reader
755
+ // uses (`build ship`, `build merged`). `{ ok, tasks, partial }` or `{ ok: false, reason }`.
756
+ const COMMIT_PAGE = 100;
757
+ export function prTasks(platform, n, { cwd, runner = run } = {}) {
758
+ let messages;
759
+ if (platform === 'gitlab') {
760
+ const r = runner('glab', ['api', `projects/:id/merge_requests/${n}/commits?per_page=${COMMIT_PAGE}`], { cwd });
761
+ if (!r.ok) return { ok: false, reason: r.stderr || 'glab api merge_requests commits failed' };
762
+ try { messages = (JSON.parse(r.stdout) || []).map((c) => c?.message || ''); } catch { return { ok: false, reason: 'unreadable glab answer' }; }
763
+ } else {
764
+ // The whole message, as the commit holds it: `gh pr view --json commits` splits it into a headline and a
765
+ // body, and joining them back can make a trailer the commit does not have.
766
+ const r = runner('gh', ['api', `repos/{owner}/{repo}/pulls/${n}/commits?per_page=${COMMIT_PAGE}`], { cwd });
767
+ if (!r.ok) return { ok: false, reason: r.stderr || 'gh api pulls commits failed' };
768
+ try { messages = (JSON.parse(r.stdout) || []).map((c) => c?.commit?.message || ''); } catch { return { ok: false, reason: 'unreadable gh answer' }; }
769
+ }
770
+ if (!Array.isArray(messages)) return { ok: false, reason: 'unreadable answer' };
771
+ let tasks;
772
+ try { tasks = [...new Set(messages.map((m) => trailerTask(m, { cwd })).filter(Boolean))]; } catch (e) { return { ok: false, reason: e.message }; }
773
+ return { ok: true, tasks, partial: messages.length >= COMMIT_PAGE };
774
+ }
775
+
776
+ // Does PR/MR `n` (read as `got`) carry `story`-`task`? `this` — its branch names it; `group` — another task's
777
+ // branch, but its own commits carry this one too (a grouped PR); `other` / `none` — as `branchTask`. `tasks`
778
+ // is what its commits carry, when they were asked. One rule for `build ship` and `build merged`.
779
+ function prCarries(where, n, got, { story, task, runner }) {
780
+ const byBranch = branchTask(got.branch, story, task);
781
+ if (byBranch === 'this') return { carries: 'this', tasks: null };
782
+ const asked = prTasks(where.platform, n, { cwd: where.checkout, runner });
783
+ const id = `${story}-${task}`;
784
+ if (asked.ok && asked.tasks.includes(id)) return { carries: 'group', tasks: asked.tasks };
785
+ // A list cut short could hold the task further on: as unread as a failed read.
786
+ if (!asked.ok || asked.partial) {
787
+ if (byBranch === 'other') throw err(CODE, `PR/MR #${n} is from ${got.branch}, which names another task than ${id}, and its commits could not all be read to see whether it carries ${task} too${asked.ok ? ' (more than one page of them)' : `: ${asked.reason}`}`, asked.ok ? `a grouped PR/MR of ${COMMIT_PAGE} commits or more is not read; a group is for small tasks — give ${task} its own PR/MR` : /interpret-trailers/.test(asked.reason) ? 'check that git runs here, then run this again' : 'log in, then run this again');
788
+ return { carries: byBranch, tasks: null };
789
+ }
790
+ // The commits were read and carry other tasks, not this one: that is evidence, whatever the branch says.
791
+ if (byBranch === 'none' && asked.tasks.length) return { carries: 'other', tasks: asked.tasks };
792
+ return { carries: byBranch, tasks: asked.tasks };
793
+ }
794
+
795
+ // The task ids the commits of `range` carry by `Task:` lines, merges left out — what the spec-link gate reads
796
+ // on a PR. `null` when git cannot read the range.
797
+ export function rangeTasks(cwd, range) {
798
+ return gitTasks(cwd, ['--no-merges', range]);
799
+ }
800
+
801
+ // The size limit of a grouped PR (#350): `group_limit: { lines, files }` in the Product settings, 200 lines
802
+ // and 10 files by default. A value that is not a positive whole number is read as its default, and said.
803
+ export const GROUP_LIMIT = { lines: 200, files: 10 };
804
+ export function groupLimit(settings) {
805
+ const raw = isPlainObject(settings) ? settings.group_limit : undefined;
806
+ const out = { ...GROUP_LIMIT };
807
+ const bad = [];
808
+ if (raw !== undefined && !isPlainObject(raw)) bad.push('group_limit');
809
+ for (const k of ['lines', 'files']) {
810
+ const v = isPlainObject(raw) ? raw[k] : undefined;
811
+ if (v === undefined) continue;
812
+ if (Number.isInteger(v) && v > 0) out[k] = v;
813
+ else bad.push(`group_limit.${k}`);
814
+ }
815
+ return { ...out, bad };
816
+ }
817
+
818
+ // How big a PR's change is, from the merge base (`base...HEAD`, three dots: what the PR adds, not what the
819
+ // base gained since): lines added + deleted, and files. A binary file counts as a file with no lines.
820
+ export function changeSize(cwd, base) {
821
+ const r = run('git', ['diff', '--numstat', '-z', `${base}...HEAD`], { cwd });
822
+ if (!r.ok) return null;
823
+ let lines = 0;
824
+ let files = 0;
825
+ const parts = r.stdout.split('\0');
826
+ for (let i = 0; i < parts.length; i++) {
827
+ const m = parts[i].match(/^(\d+|-)\t(\d+|-)\t(.*)$/s);
828
+ if (!m) continue;
829
+ files += 1;
830
+ if (m[1] !== '-') lines += Number(m[1]);
831
+ if (m[2] !== '-') lines += Number(m[2]);
832
+ // A rename prints its two paths as the next two fields.
833
+ if (m[3] === '') i += 2;
834
+ }
835
+ return { lines, files };
836
+ }
837
+
838
+ // The warning for a grouped PR over its size limit (#350): a group is for SMALL tasks. Warn only; nothing
839
+ // refuses on it. Returns the lines to print, or none.
840
+ export function groupWarnings(cwd, base, ids, settings) {
841
+ if (!ids || new Set(ids).size < 2) return [];
842
+ const out = [];
843
+ const stories = [...new Set(ids.map((t) => t.replace(/-T\d+$/, '')))];
844
+ if (stories.length > 1) out.push(`this PR/MR groups tasks of more than one story (${stories.join(', ')}) — a group is several small tasks of ONE story`);
845
+ const limit = groupLimit(settings);
846
+ if (limit.bad.length) out.push(`${limit.bad.join(', ')} in the Product settings is not a positive whole number — the default (${GROUP_LIMIT.lines} lines, ${GROUP_LIMIT.files} files) is used`);
847
+ const size = changeSize(cwd, base);
848
+ if (!size) out.push(`could not measure the change against ${base}, so the grouped PR's size limit was not checked`);
849
+ else if (size.lines > limit.lines || size.files > limit.files) {
850
+ out.push(`this grouped PR/MR (${ids.length} tasks) changes ${size.lines} lines in ${size.files} files — over the limit for a group (${limit.lines} lines, ${limit.files} files); split it, or open each task on its own`);
851
+ }
852
+ return out;
853
+ }
854
+
855
+ // The tasks a merge commit's own merged range carries by `Task:` lines (`<sha>^1..<sha>^2`) — a grouped PR
856
+ // recorded by hand, where the platform cannot be read. A squash or a fast-forward has no range: none.
857
+ function mergeRangeTasks(cwd, sha) {
858
+ if (!run('git', ['rev-parse', '--verify', '--quiet', `${sha}^2`], { cwd }).ok) return [];
859
+ return gitTasks(cwd, ['--no-merges', `${sha}^1..${sha}^2`]) || [];
860
+ }
861
+
862
+ // The PRs/MRs that can be the task's OWN (issue #350): those not named as follow-ups, and — only when there
863
+ // is none of those that is not closed — the follow-up-named ones, as a task may simply be about follow-ups
864
+ // (`…-T03-followup-reminders`). One rule for `build merged` and `build ship`.
865
+ export function ownPrs(prs) {
866
+ const plain = prs.filter((x) => !x.followUp);
867
+ return plain.some((x) => x.state !== 'closed') ? plain : prs;
868
+ }
869
+
870
+ // May the follow-up-named PR `asked` (`{ number, state }`) be the task's own ship? Not once the task has
871
+ // shipped, and not while a plain-named PR for it is open or merged. The asked PR always counts, even when it
872
+ // is older than the page the listing reads. A listing that fails is a refusal, never a guess.
873
+ function followUpIsOwn(ctx, where, { story, task, repo, runner, asked }) {
874
+ if (readShips(ctx.epicDir).some((s) => s.story === story && s.task === task && s.repo === repo)) return false;
875
+ const found = findTaskPrs(where.platform, { story, task }, { cwd: where.checkout, runner });
876
+ if (!found.ok) throw err(CODE, `could not list the PRs/MRs of ${repo} to see whether this follow-up branch is ${story}-${task}'s own: ${found.reason}`, 'log in, then run this again');
877
+ const prs = [...found.prs.filter((x) => x.number !== asked.number), { ...asked, followUp: true }];
878
+ return ownPrs(prs).some((x) => x.number === asked.number);
879
+ }
880
+
881
+ // Two commit ids for the same commit: a ship recorded by hand may hold the short or upper-case form.
882
+ const sameSha = (a, b) => {
883
+ const x = String(a || '').toLowerCase();
884
+ const y = String(b || '').toLowerCase();
885
+ return x.length >= 7 && y.length >= 7 && (x.startsWith(y) || y.startsWith(x));
886
+ };
887
+
888
+ function addFollowUp(root, ctx, original, ship, { story, task, repo }) {
889
+ const prNo = (v) => (v == null ? null : prNumberFromUrl(String(v)) || String(v).replace(/^#/, ''));
890
+ const entry = { pr: ship.pr, branch: ship.branch, mergeCommit: ship.mergeCommit, date: ship.shippedAt };
891
+ const known = [original, ...(Array.isArray(original.followUps) ? original.followUps : [])];
892
+ const bySha = (x) => sameSha(x?.mergeCommit, ship.mergeCommit);
893
+ const dup = known.find((x) => bySha(x) || (!['local', 'none'].includes(entry.pr) && prNo(x?.pr) === prNo(entry.pr)));
894
+ if (dup) throw err(CODE, `${dup === original ? `${story} / ${task}'s own ship` : `a follow-up of ${story} / ${task}`} already records ${bySha(dup) ? `merge ${String(ship.mergeCommit).slice(0, 12)}` : `PR/MR ${entry.pr}`}`, 'each follow-up is recorded once');
895
+ const res = updateShip(ctx.epicDir, (s) => s.story === story && s.task === task && s.repo === repo, (s) => {
896
+ s.followUps = [...(Array.isArray(s.followUps) ? s.followUps : []), entry];
897
+ });
898
+ if (!res.found) throw err(CODE, `${story} / ${task}'s ship in ${repo} could not be found to add the follow-up to`, 'run it again; if it repeats, check the build-log files');
899
+ ok(`follow-up recorded on ${story} / ${task} in ${repo}${entry.mergeCommit ? ` (${String(entry.mergeCommit).slice(0, 12)})` : ''}`);
900
+ hand('commit with `yad checkpoint --push`');
901
+ return { story, task, repo, changed: true, followUp: entry, file: rel(root, res.file) };
902
+ }
903
+
904
+ // The PRs/MRs whose source branch carries `story`-`task`, newest first, from one page of the repo's PRs/MRs
905
+ // (any state). `{ ok, prs: [{ number, state, branch, url }], partial }` — `partial` when the page was full,
906
+ // so an older PR may not be in it — or `{ ok: false, reason }`. Run in the repo's own checkout: from anywhere
907
+ // else gh and glab read that folder's repo.
908
+ const PR_PAGE = 100;
909
+ export function findTaskPrs(platform, { story, task }, { cwd, runner = run } = {}) {
910
+ let rows;
911
+ if (platform === 'gitlab') {
912
+ const r = runner('glab', ['api', `projects/:id/merge_requests?state=all&order_by=updated_at&sort=desc&per_page=${PR_PAGE}`], { cwd });
913
+ if (!r.ok) return { ok: false, reason: r.stderr || 'glab api merge_requests failed' };
914
+ try { rows = (JSON.parse(r.stdout) || []).map((m) => ({ number: Number(m?.iid), state: glState(m?.state), branch: m?.source_branch || null, url: m?.web_url || null })); } catch { return { ok: false, reason: 'unreadable glab answer' }; }
915
+ } else {
916
+ const r = runner('gh', ['pr', 'list', '--state', 'all', '--limit', String(PR_PAGE), '--json', 'number,state,headRefName,url'], { cwd });
917
+ if (!r.ok) return { ok: false, reason: r.stderr || 'gh pr list failed' };
918
+ try { rows = (JSON.parse(r.stdout) || []).map((p) => ({ number: Number(p?.number), state: ghState(p?.state), branch: p?.headRefName || null, url: p?.url || null })); } catch { return { ok: false, reason: 'unreadable gh answer' }; }
919
+ }
920
+ if (!Array.isArray(rows)) return { ok: false, reason: 'unreadable answer' };
921
+ return {
922
+ ok: true, partial: rows.length >= PR_PAGE,
923
+ prs: rows.filter((x) => x.number > 0 && x.state && branchTask(x.branch, story, task) === 'this').map((x) => ({ ...x, followUp: isFollowUpBranch(x.branch, story, task) })),
924
+ };
925
+ }
926
+
927
+ // `yad build merged <story> --task <T> --repo <r> [--pr <n>] [--ship]` (issue #355) — asks the platform
928
+ // whether the task's PR/MR has merged, so the agent need not wait for a person to say so. The user's
929
+ // decisions (2026-10-20): one check per run (the agent runs it again later; nothing waits); the PR is found
930
+ // by the task's branch unless --pr names it; --ship records the ship through `build ship` once merged.
931
+ // Every answer is a `state`: shipped (a ship is already recorded), merged, open, closed (closed without a
932
+ // merge) or none (no PR/MR carries the task yet). A refusal is only for what the agent must fix.
933
+ //
934
+ // `--follow-up` (issue #350) asks the same of the task's FOLLOW-UP PRs/MRs instead — branches named
935
+ // `fix/<story>-<task>-followup-<words>` — after the task has shipped; `--ship` adds the merge to the ship's
936
+ // `followUps`. Without it, a shipped task is answered `shipped`, and before the ship a follow-up-named PR is
937
+ // the task's own only when no plain-named one is open or merged (`ownPrs`).
938
+ export async function buildMerged(root, { story, task, repo, pr = null, ship = false, followUp = false, today, fetch = true, runner = run, prReader = readPr } = {}) {
939
+ const { ctx, where } = shipContext(root, { story, task, repo, pr, verb: 'merged' });
940
+ const id = `${story}-${task}`;
941
+ const shipCmd = (n) => `yad build ship ${story} --task ${task} --repo ${repo} --pr ${n}${followUp ? ' --follow-up' : ''}`;
942
+ const out = (state, extra = {}) => ({ story, task, repo, state, pr: null, url: null, mergeCommit: null, changed: false, ...(followUp ? { followUp: true } : {}), ...extra });
943
+ const had = readShips(ctx.epicDir).find((s) => s.story === story && s.task === task && s.repo === repo);
944
+ // A follow-up needs the task's ship; the PRs/MRs it already records are answered `shipped`.
945
+ if (followUp && !had) throw err(CODE, `${story} / ${task} has no ship in ${repo} yet, so it has no follow-up`, `ask about the task's own PR first: yad build merged ${story} --task ${task} --repo ${repo}`);
946
+ const prNo = (v) => (v == null ? null : prNumberFromUrl(String(v)) || String(v).replace(/^#/, ''));
947
+ const recorded = new Set(followUp ? [had.pr, ...(Array.isArray(had.followUps) ? had.followUps.map((x) => x?.pr) : [])].map(prNo).filter(Boolean) : []);
948
+ if (followUp && pr && pr !== true && recorded.has(String(Number(pr)))) {
949
+ ok(`PR/MR #${Number(pr)} is already recorded on ${id}'s ship in ${repo}`);
950
+ return out('shipped', { pr: Number(pr) });
951
+ }
952
+ // Already recorded: the same answer every time it is asked, with or without --ship.
953
+ if (had && !followUp) {
954
+ ok(`${id} already has a ship in ${repo}${had.mergeCommit ? ` (${String(had.mergeCommit).slice(0, 12)})` : ''}`);
955
+ return out('shipped', { mergeCommit: had.mergeCommit || null });
956
+ }
957
+ if (!where.platform || !where.checkout || !(runner !== run || platformReady(where.platform))) {
958
+ const why = !where.platform ? `${repo} has no platform to ask` : !where.checkout ? `${repo} is not checked out here` : `${cliFor(where.platform)} is not available`;
959
+ throw err(CODE, `${why}, so yad cannot see whether ${id} merged`,
960
+ !where.platform || where.checkout ? `once it has merged, record it by hand: yad build ship ${story} --task ${task} --repo ${repo} --merge-commit <sha>` : `\`yad repo clone ${repo}\` fetches it`);
961
+ }
962
+ let n = pr && pr !== true ? Number(pr) : null;
963
+ // A PR/MR the dial opened (#356) is recorded on the lane: that number, before any search.
964
+ const lane = lanes(ctx.buildState, story).repos[repo];
965
+ const opened = !n && !followUp && isPlainObject(lane) && Array.isArray(lane.opened) ? lane.opened.filter((o) => o?.task === task && Number(o.pr) > 0).pop() : null;
966
+ if (opened) {
967
+ n = Number(opened.pr);
968
+ info(`PR/MR #${n} was opened by the dial on ${opened.date || 'an earlier day'}`);
969
+ }
970
+ // The recorded PR closed without a merge: a person may have opened another, so search as usual.
971
+ let first = null;
972
+ if (opened) {
973
+ first = readMergedPr(where.platform, n, { cwd: where.checkout, runner });
974
+ if (first.ok && first.state === 'closed') {
975
+ info(`PR/MR #${n}, opened by the dial, was closed without a merge — looking for another`);
976
+ n = null;
977
+ first = null;
978
+ }
979
+ }
980
+ if (!n) {
981
+ const found = findTaskPrs(where.platform, { story, task }, { cwd: where.checkout, runner });
982
+ if (!found.ok) throw err(CODE, `could not list the PRs/MRs of ${repo}: ${found.reason}`, `log in with \`${cliFor(where.platform)} auth login\`, or pass --pr <n>`);
983
+ // The task's own PRs, or (--follow-up) its follow-up PRs not yet recorded. A PR closed without a merge
984
+ // never competes with a later one for the same task.
985
+ // Without --follow-up the task has not shipped (a shipped task was answered above): its own PRs (`ownPrs`).
986
+ const mine = followUp ? found.prs.filter((x) => x.followUp && !recorded.has(String(x.number))) : ownPrs(found.prs);
987
+ const live = mine.filter((x) => x.state !== 'closed');
988
+ if (live.length > 1) throw err(CODE, `more than one ${followUp ? 'follow-up ' : ''}PR/MR carries ${id}: ${live.map((x) => `#${x.number} (${x.state})`).join(', ')}`, `name the one to ask about: yad build merged ${story} --task ${task} --repo ${repo}${followUp ? ' --follow-up' : ''} --pr <n>`);
989
+ // A closed follow-up owes nothing — the task has shipped — so it is `none`, not `closed`.
990
+ if (!live.length && mine.length && !followUp) {
991
+ const last = mine[0];
992
+ warn(`PR/MR #${last.number} for ${id} was closed without a merge`);
993
+ hand('open a new PR/MR for the task, or ask the person who closed it');
994
+ return out('closed', { pr: last.number, url: last.url });
995
+ }
996
+ if (!live.length) {
997
+ info(`no ${followUp ? 'follow-up ' : ''}PR/MR carries ${id} in ${repo} yet${followUp && recorded.size > 1 ? ' that is not already recorded' : ''}${found.partial ? ` among its newest ${PR_PAGE}` : ''}`);
998
+ hand(found.partial ? `if it is older, name it: yad build merged ${story} --task ${task} --repo ${repo}${followUp ? ' --follow-up' : ''} --pr <n>`
999
+ : followUp ? `a follow-up is opened from fix/${id}-followup-<words>`
1000
+ : `open it with \`yad open-pr\`, then run this again; in a grouped PR named after another task, name it: --pr <n>`);
1001
+ return out('none', { partial: found.partial });
1002
+ }
1003
+ n = live[0].number;
1004
+ }
1005
+ const got = first?.ok ? first : readMergedPr(where.platform, n, { cwd: where.checkout, runner });
1006
+ if (!got.ok) throw err(CODE, `could not read PR/MR #${n} in ${repo}: ${got.reason}`, `log in with \`${cliFor(where.platform)} auth login\`, then run this again`);
1007
+ // A number given by hand must carry this task: its branch, or (a grouped PR, #350) its commits.
1008
+ const { carries, tasks: group } = prCarries(where, n, got, { story, task, runner });
1009
+ if (carries === 'other') throw err(CODE, group?.length ? `PR/MR #${n}'s commits carry ${group.join(', ')}, not ${id}` : `PR/MR #${n} is from ${got.branch}, which names another task than ${id}`, 'check --task and --pr');
1010
+ const follows = isFollowUpBranch(got.branch, story, task);
1011
+ // A follow-up-named PR — named by --pr, recorded by the dial, or found — is the task's own only by the rule
1012
+ // `build ship` applies, so `merged` is never answered for a PR the ship then refuses.
1013
+ if (follows && !followUp) {
1014
+ if (!followUpIsOwn(ctx, where, { story, task, repo, runner, asked: { number: n, state: got.state || (got.merged ? 'merged' : 'open') } })) throw err(CODE, `PR/MR #${n} is from ${got.branch}, a follow-up branch, while ${id}'s own PR/MR is another`, `ask about the task's own: yad build merged ${story} --task ${task} --repo ${repo}`);
1015
+ }
1016
+ const state = got.state || (got.merged ? 'merged' : null);
1017
+ if (followUp && !follows && carries !== 'none' && !(ship && state === 'merged')) warn(`PR/MR #${n} is from ${got.branch}, not a follow-up branch (fix/${id}-followup-<words>) — check it is a follow-up of ${id}`);
1018
+ // Once, here — unless --ship hands a merged PR to `build ship`, which gives this warning itself.
1019
+ if (carries === 'none' && !(ship && state === 'merged')) warn(`PR/MR #${n} is from ${got.branch || '(no branch)'}, which names no task — check it is the PR for ${id}`);
1020
+ if (!state) throw err(CODE, `${where.platform} gave PR/MR #${n} a state yad does not know`, 'check it on the platform');
1021
+ const facts = { pr: n, url: got.url };
1022
+ if (state === 'open') {
1023
+ info(`PR/MR #${n} for ${id} is open — not merged yet`);
1024
+ hand(`run this again later; a person merges it`);
1025
+ return out('open', facts);
1026
+ }
1027
+ if (state === 'closed') {
1028
+ warn(`PR/MR #${n} for ${id} was closed without a merge`);
1029
+ hand('open a new PR/MR for the task, or ask the person who closed it');
1030
+ return out('closed', facts);
1031
+ }
1032
+ // Merged, but only an answer `build ship` would accept is `merged`: the same merge-commit checks run here
1033
+ // first (on the default branch, not naming another task), so a PR merged into a release branch or a
1034
+ // stacked parent is a refusal now, not a `merged` the ship then refuses.
1035
+ if (!got.mergeCommit) throw err(CODE, `PR/MR #${n} in ${repo} is merged, but the platform names no merge commit`, 'record it from the commit instead: yad build ship … --merge-commit <sha> with no --pr');
1036
+ // The warning for a commit naming no task is `build ship`'s to give, once, when it records; a read only asks.
1037
+ const c = checkCommit(where, { story, task, repo, mergeCommit: got.mergeCommit, strict: false, fetch, noTask: ship ? null : 'check it ships', group: carries === 'group' ? group : null });
1038
+ // A ship file `build ship` would not write (another repo's of the same file name, or one it cannot read).
1039
+ const blocked = followUp ? null : shipBlocked(ctx.epicDir, { story, task, repo });
1040
+ if (blocked) shipRefused(blocked, { story, task, repo });
1041
+ // A follow-up whose merge the ship already records is `shipped`, as `build ship --follow-up` would refuse it.
1042
+ if (followUp && [had, ...(Array.isArray(had.followUps) ? had.followUps : [])].some((x) => sameSha(x?.mergeCommit, c.sha))) {
1043
+ ok(`merge ${c.sha.slice(0, 12)} is already recorded on ${id}'s ship in ${repo}`);
1044
+ return out('shipped', { ...facts, mergeCommit: c.sha });
1045
+ }
1046
+ ok(`PR/MR #${n} for ${id} merged (${c.sha.slice(0, 12)})`);
1047
+ if (!ship) {
1048
+ hand(`record the ship: ${shipCmd(n)} (or run this again with --ship)`);
1049
+ return out('merged', { ...facts, mergeCommit: c.sha });
1050
+ }
1051
+ // The ship is written by `build ship` itself, never by a second path.
1052
+ const res = await buildShip(root, { story, task, repo, pr: String(n), followUp, today, fetch, runner, prReader });
1053
+ const rec = res.ship || res.followUp;
1054
+ return out('merged', { ...facts, mergeCommit: rec.mergeCommit, changed: true, ...(res.ship ? { ship: res.ship } : { entry: res.followUp }), file: res.file });
1055
+ }
1056
+
1057
+ // `yad open-pr --via auto` (issue #356): the standing approval to open a task's PR/MR once its checks pass,
1058
+ // without asking. The user's decisions (2026-10-20): one project-wide dial, `yad dial open-pr --to auto`,
1059
+ // set by a person (nothing earned); `yad open-pr --via auto` refuses unless the dial is auto and THIS
1060
+ // task's `checks` close names a run that passed and was not rejected; the opened PR is recorded on the lane
1061
+ // (`opened`), so `yad build merged` and people can see the dial opened it. The merge stays a person's.
1062
+ //
1063
+ // PURE: may the PR/MR carrying `tasks` (one, or a group of one story's small tasks — #350) be opened without
1064
+ // asking? `{ ok, runs: { T: run } }` or `{ ok: false, message, hint }`. One rule, for one task or several:
1065
+ // - the `checks` step is passed NOW — a step reopened (for a task of the group or the next) and not closed
1066
+ // again holds every task, so work its runs never checked is not opened;
1067
+ // - each task's NEWEST close (the current one, else the latest kept in `runs`) names it — on the close
1068
+ // (`--task`) or on the run it names; a close naming no task counts for none — and that run passed
1069
+ // (`checks=pass`) and was not rejected;
1070
+ // - no task of the group was already opened by the dial.
1071
+ export function planAutoOpen(lane, trustRuns, { story, repo, task = null, tasks = null }) {
1072
+ const want = tasks || [task];
1073
+ const no = (message, hint) => ({ ok: false, message, hint });
1074
+ const at = `${story} / ${repo}`;
1075
+ if (!isPlainObject(lane) || !Array.isArray(lane.steps)) return no(`${at} has no lane`, 'the yad-run skill walks the lane before a PR is opened');
1076
+ const prior = (Array.isArray(lane.opened) ? lane.opened : []).find((o) => want.includes(o?.task));
1077
+ if (prior) return no(`${story}-${prior.task}'s PR/MR was already opened by the dial: #${prior.pr}`, 'ask the platform whether it merged: yad build merged … --ship; a new PR/MR for the task is opened by a person');
1078
+ const row = lane.steps.find((s) => s?.id === 'checks');
1079
+ const closeHint = (t) => `run the checks for ${t}, then close the step with its run and the task: yad build step ${story} --repo ${repo} checks done --run <uid> --task ${t}`;
1080
+ if (!isPassed(row) || !isPlainObject(row.closed) || !row.closed.run) return no(`${at}: checks is not closed${row?.task ? ` (it is open for ${row.task})` : ''}`, closeHint(row?.task || want[0]));
1081
+ const runOf = (uid) => (trustRuns || []).find((r) => r?.uid === uid && r.story === story && r.repo === repo && r.step === 'checks') || null;
1082
+ // Oldest first: `runs` in the order the closes were kept, then the current close.
1083
+ const closes = [...(Array.isArray(row.runs) ? row.runs : []), row.closed].filter((c) => isPlainObject(c) && c.run);
1084
+ const runs = {};
1085
+ for (const t of want) {
1086
+ const close = closes.filter((c) => (c.task || runOf(c.run)?.task || null) === t).pop();
1087
+ if (!close) return no(`${at}: checks has not closed for ${t}`, closeHint(t));
1088
+ const run = runOf(close.run);
1089
+ if (!run) return no(`${at}: the checks close for ${t} names trust run ${close.run}, which is not recorded`, 'record the run with `yad build trust`, then close the step with it');
1090
+ if (run.task && run.task !== t) return no(`${at}: the checks close for ${t} names run ${run.uid}, which is for ${run.task}`, closeHint(t));
1091
+ if (run.verdict === 'rejected') return no(`${at}: the checks run for ${t} (${run.uid}) is rejected`, 'fix what failed, run the checks again, and ask a person to open the PR/MR');
1092
+ if (run.signals?.checks !== 'pass') return no(`${at}: the checks run for ${t} (${run.uid}) did not record checks=pass`, 'a PR/MR is opened without asking only after the checks passed: yad build trust … checks --signal checks=pass');
1093
+ runs[t] = run;
1094
+ }
1095
+ return { ok: true, runs, run: runs[want[want.length - 1]] };
1096
+ }
1097
+
1098
+ // The tasks a branch could carry, as `{ story, task }`, that are stories of this Product. A branch name has
1099
+ // no end marker, so every reading is listed — each id starting at the branch's start or after a `/` or `_`,
1100
+ // and ending where `-`, `_`, `/` or the end follows — and only those whose story file exists are kept:
1101
+ // `feat/EP-x-S01-T01-then-S02-T03` and `feat/EP-aws-s3-t2-backup-S01-T01` each keep the one real task, and a
1102
+ // branch carrying two real tasks keeps both (the caller refuses it).
1103
+ export function branchTasks(root, branch) {
1104
+ const b = String(branch || '');
1105
+ const seen = new Map();
1106
+ for (let i = 0; i < b.length; i++) {
1107
+ if (i > 0 && !'/_'.includes(b[i - 1])) continue;
1108
+ if (b.slice(i, i + 3).toLowerCase() !== 'ep-') continue;
1109
+ for (let j = i + 1; j <= b.length; j++) {
1110
+ if (j < b.length && !'-_/'.includes(b[j])) continue;
1111
+ const m = b.slice(i, j).toLowerCase().match(/^ep-([a-z0-9-]+)-s(\d+)-t(\d+)$/);
1112
+ if (!m) continue;
1113
+ const story = `EP-${m[1]}-S${m[2]}`;
1114
+ if (!fs.existsSync(path.join(epicRoot(root, storyEpic(story)), 'stories', `${story}.md`))) continue;
1115
+ seen.set(`${story}-T${m[3]}`, { story, task: `T${m[3]}` });
1116
+ }
1117
+ }
1118
+ return [...seen.values()];
1119
+ }
1120
+
1121
+ // The facts `yad open-pr --via auto` needs from the Product before anything is pushed: the dial, the lane
1122
+ // and its checks run. Throws a refusal; returns `{ file }`, the build-state the record is written to.
1123
+ export function autoOpenCheck(root, { story, task = null, tasks = null, repo }) {
1124
+ const want = tasks || [task];
1125
+ const eff = effectiveAction(loadAutomation(root), 'open-pr');
1126
+ if (eff.advance !== 'auto') {
1127
+ throw err(CODE, eff.why === 'kill' ? 'the open-pr dial is auto, but the kill switch (or an unreadable .sdlc/automation.json) holds it at human' : 'the open-pr dial is human, so a person approves opening this PR/MR',
1128
+ eff.why === 'kill' ? '`yad unkill` once the reason is gone, or ask a person to open it' : 'ask the person to approve it, then run `yad open-pr` without --via auto; `yad dial open-pr --to auto` is the standing approval');
1129
+ }
1130
+ const ctx = storyContext(root, story);
1131
+ if (!ctx.entry.repos.includes(repo)) throw err(CODE, `${story} does not declare ${repo}`, `its repos: ${ctx.entry.repos.join(', ') || 'none'}`);
1132
+ // A shipped task's checks close is the shipped work's: a follow-up is opened by a person.
1133
+ const shipped = want.find((t) => readShips(ctx.epicDir).some((s) => s.story === story && s.task === t && s.repo === repo));
1134
+ if (shipped) throw err(CODE, `${story}-${shipped} has already shipped in ${repo}`, `a follow-up PR/MR (fix/${story}-${shipped}-followup-<words>) is opened by a person`);
1135
+ const lane = lanes(ctx.buildState, story).repos[repo];
1136
+ const plan = planAutoOpen(lane, readTrustRuns(ctx.epicDir), { story, repo, tasks: want });
1137
+ if (!plan.ok) throw err(CODE, plan.message, plan.hint);
1138
+ return { file: ctx.file, run: plan.run.uid, runs: Object.fromEntries(Object.entries(plan.runs).map(([t, r]) => [t, r.uid])) };
1139
+ }
1140
+
1141
+ // Record the PR/MR the dial opened on its lane. Re-read strictly: the file may have changed while the PR was
1142
+ // being opened, and nothing here writes over content it cannot read.
1143
+ // A grouped PR (#350) is recorded once per task it carries, each with its own checks run.
1144
+ export function recordAutoOpen(file, { story, repo, task = null, tasks = null, runs = {}, pr, url, run, by, date }) {
1145
+ const bs = lanes(readJSONStrict(file, null), story);
1146
+ const lane = liveLane(bs, story, repo);
1147
+ const opened = [...(Array.isArray(lane.opened) ? lane.opened : []), ...(tasks || [task]).map((t) => ({ task: t, pr, url, via: 'auto', run: runs[t] || run, by, date }))];
1148
+ writeJSON(file, { ...bs, repos: { ...bs.repos, [repo]: { ...lane, opened } } });
1149
+ }
1150
+
1151
+ export async function buildDone(root, { story, today, fetch = true } = {}) {
1152
+ const ctx = storyContext(root, story);
1153
+ // The epic is in Build — what featureStatus asks too: a reopened stories review takes it out again.
1154
+ if (nextAction(ctx.ledger).kind !== 'build') throw err(CODE, `${ctx.epic} is not in Build (its Shape chain is not finished)`, `\`yad next ${ctx.epic}\` says what is open`);
1155
+ storyStatusOk(ctx, story);
1156
+ const bs = lanes(ctx.buildState, story);
1157
+ const skipped = ctx.entry.repos.filter((r) => isPlainObject(bs.repos[r]) && bs.repos[r].status === 'skipped' && !laneStarted(bs.repos[r]));
1158
+ const ships = readShips(ctx.epicDir).filter((s) => s.story === story);
1159
+ // What each repo owes: its tasks.md on the repo's default branch, fetched first.
1160
+ const owed = {};
1161
+ const why = {};
1162
+ for (const repo of ctx.entry.repos) {
1163
+ if (skipped.includes(repo)) continue;
1164
+ const where = registeredRepo(root, repo);
1165
+ if (!where.checkout) { owed[repo] = null; why[repo] = 'not checked out here (`yad repo clone` fetches it)'; continue; }
1166
+ const head = run('git', ['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD'], { cwd: where.checkout }).stdout;
1167
+ const branch = where.defaultBranch || (head.startsWith('origin/') ? head.slice(7) : 'main');
1168
+ // A stale copy could miss a task added since: a failed fetch refuses, unless --no-fetch asked for the copy.
1169
+ if (fetch && !run('git', ['fetch', '--quiet', 'origin', `+refs/heads/${branch}:refs/remotes/origin/${branch}`], { cwd: where.checkout }).ok) {
1170
+ throw err(CODE, `could not fetch ${branch} in ${repo} to read the tasks it owes`, `check the network and your login, and that ${branch} is ${repo}'s default branch (default_branch in .sdlc/repos.json); or pass --no-fetch to read the last fetched copy`);
1171
+ }
1172
+ const show = (file) => run('git', ['show', `refs/remotes/origin/${branch}:specs/${story}/${file}`], { cwd: where.checkout });
1173
+ const shown = show('tasks.md');
1174
+ if (shown.ok) {
1175
+ owed[repo] = parseTaskIds(shown.stdout);
1176
+ if (!owed[repo].length) why[repo] = `specs/${story}/tasks.md on origin/${branch} names no task (T01, T02, …)`;
1177
+ continue;
1178
+ }
1179
+ // A light spec keeps its tasks in spec.md (#348) — only when its link.md says so.
1180
+ const link = show('link.md');
1181
+ const spec = link.ok ? show('spec.md') : null;
1182
+ if (!link.ok || !isLightSpec(link.stdout)) {
1183
+ owed[repo] = null;
1184
+ // A tasks block with no light mode named is most likely a link.md the reader cannot parse (CRLF, a
1185
+ // quoted value): say so, rather than only that tasks.md is missing.
1186
+ why[repo] = spec?.ok && lightTasksBlock(spec.stdout) !== null
1187
+ ? `no specs/${story}/tasks.md on origin/${branch}, and its link.md does not say \`spec-mode: light\` (plain, on its own line), so the tasks block in spec.md is not read`
1188
+ : `no specs/${story}/tasks.md on origin/${branch}`;
1189
+ continue;
1190
+ }
1191
+ const block = spec.ok ? lightTasksBlock(spec.stdout) : null;
1192
+ if (block === null) {
1193
+ owed[repo] = null;
1194
+ why[repo] = spec.ok
1195
+ ? `specs/${story}/spec.md on origin/${branch} is a light spec without one ${LIGHT_TASKS.begin} … ${LIGHT_TASKS.end} block`
1196
+ : `specs/${story}/link.md on origin/${branch} says spec-mode: light, but there is no spec.md`;
1197
+ continue;
1198
+ }
1199
+ owed[repo] = parseTaskIds(block);
1200
+ if (!owed[repo].length) why[repo] = `the tasks block of specs/${story}/spec.md on origin/${branch} names no task (T01, T02, …)`;
1201
+ }
1202
+ const plan = planDone({ story, declared: ctx.entry.repos, skipped, owed, ships });
1203
+ if (!plan.shipped) {
1204
+ for (const r of plan.unreadable) warn(`${r}: ${why[r]} — the tasks it owes cannot be read`);
1205
+ if (plan.missing.length) warn(`no ship yet for: ${plan.missing.join(', ')}`);
1206
+ throw err(CODE, `${story} is not shipped yet`, plan.missing.length ? `record each with \`yad build ship ${story} --task <T> --repo <r> --pr <n>\`` : 'make each repo\'s tasks.md (or a light spec\'s tasks block in spec.md) readable on its default branch, then run this again');
1207
+ }
1208
+ // Every owed repo has a lane, and every lane's earlier steps are done: `yad next` reads a repo with no
1209
+ // lane as still owed, so a story marked shipped without one would read shipped in one place and in-build
1210
+ // in another. A pre-tracking story (shipped before the Build ledger) takes `yad checkpoint --retro-ship`.
1211
+ if (!ctx.entry.repos.some((r) => !skipped.includes(r))) {
1212
+ throw err(CODE, `${story} owes no lane in any repo, so there is nothing to have shipped`, 'a story that needs no change in any repo is a question for its stories review');
1213
+ }
1214
+ // An empty `steps` is a half-seeded lane, which `yad next` reads as not started — never as shipped.
1215
+ const noLane = ctx.entry.repos.filter((r) => !skipped.includes(r) && !(isPlainObject(bs.repos[r]) && Array.isArray(bs.repos[r].steps) && bs.repos[r].steps.length));
1216
+ if (noLane.length) {
1217
+ throw err(CODE, `${story} has no lane in ${noLane.join(', ')}, so \`yad next\` would still read it in Build`,
1218
+ `\`yad build start ${story} --repo <r>\` and close its steps with \`yad build step\`; a story shipped before the Build ledger existed is recorded with \`yad checkpoint --retro-ship\` instead`);
1219
+ }
1220
+ const open = [];
1221
+ for (const repo of ctx.entry.repos.filter((r) => !skipped.includes(r))) {
1222
+ const lane = bs.repos[repo];
1223
+ for (const s of lane.steps) if (s?.id !== REVIEW_STEP && !isPassed(s)) open.push(`${repo}/${s?.id ?? '?'}`);
1224
+ }
1225
+ // Any other lane on disk (a repo the story does not declare, a name in another case) is read by `yad next`
1226
+ // too: one not finished would keep the story in Build there.
1227
+ const dupe = fs.existsSync(path.dirname(ctx.file)) ? fs.readdirSync(path.dirname(ctx.file)).filter((n) => n.endsWith('.json') && n !== `${story}.json`)
1228
+ .find((n) => readJSON(path.join(path.dirname(ctx.file), n), null)?.story === story) : null;
1229
+ if (dupe) throw err(CODE, `build-state/${dupe} also says story: ${story}`, 'yad next reads every file under build-state/: keep one per story');
1230
+ if (bs.story !== story) throw err(CODE, `build-state/${story}.json says story: ${bs.story}`, `set it to ${story}: yad next matches a lane to its story by that field`);
1231
+ const stray = Object.entries(bs.repos).filter(([r, l]) => !ctx.entry.repos.includes(r)
1232
+ && !(isPlainObject(l) && ((l.status === 'skipped' && !laneStarted(l)) || (Array.isArray(l.steps) && l.steps.length && l.steps.every(isPassed)))));
1233
+ if (stray.length) throw err(CODE, `build-state/${story}.json has a lane the story does not declare: ${stray.map(([r]) => r).join(', ')}`, '`yad doctor` reports it; remove it from the file, or add the repo to the story');
1234
+ const review = ctx.entry.repos.filter((r) => !skipped.includes(r)).filter((r) => bs.repos[r].steps.some((s) => s?.id === REVIEW_STEP && stepStatus(s) === 'blocked'));
1235
+ if (review.length) throw err(CODE, `${REVIEW_STEP} is blocked in ${review.join(', ')}`, `clear the halt first: \`yad build step ${story} --repo <r> ${REVIEW_STEP} in_progress\``);
1236
+ if (open.length) {
1237
+ throw err(CODE, `${story} has every task shipped, but these lane steps are still open: ${open.join(', ')}`, `close each with \`yad build step ${story} --repo <r> <step> done\`, then run this again`);
1238
+ }
1239
+ const by = recordActor(root);
1240
+ let changedLanes = 0;
1241
+ for (const repo of ctx.entry.repos.filter((r) => !skipped.includes(r))) {
1242
+ const lane = bs.repos[repo];
1243
+ const steps = lane.steps.map((s) => (s?.id === REVIEW_STEP && !isPassed(s) ? (changedLanes++, closeReview(s, { by, date: today })) : s));
1244
+ bs.repos[repo] = { ...lane, currentStep: REVIEW_STEP, steps };
1245
+ }
1246
+ // The lanes first, the status line last: if the run stops between the two, the story still reads in
1247
+ // Build to the seal and tidy — the safe side. A status line that cannot be set puts the lanes back.
1248
+ const storyText = fs.readFileSync(ctx.storyFile, 'utf8');
1249
+ const laneText = fs.existsSync(ctx.file) ? fs.readFileSync(ctx.file, 'utf8') : null;
1250
+ // The lanes first: a story file that could not be written (the usual cause) cannot be written back either.
1251
+ const restore = () => {
1252
+ if (laneText === null) fs.rmSync(ctx.file, { force: true }); else fs.writeFileSync(ctx.file, laneText);
1253
+ try { if (fs.readFileSync(ctx.storyFile, 'utf8') !== storyText) fs.writeFileSync(ctx.storyFile, storyText); } catch { /* left as it was */ }
1254
+ };
1255
+ if (changedLanes || !ctx.buildState?.story) writeJSON(ctx.file, bs);
1256
+ let moved;
1257
+ try {
1258
+ moved = setBuildStatus(ctx.storyFile, 'shipped');
1259
+ } catch (e) {
1260
+ restore();
1261
+ throw e;
1262
+ }
1263
+ if (moved.unknown || readFrontmatter(ctx.storyFile).status !== 'shipped') {
1264
+ restore();
1265
+ throw err(CODE, `could not set status: shipped in ${path.relative(ctx.epicDir, ctx.storyFile)}`, 'make it one plain `status:` line (with LF line endings), then run this again');
1266
+ }
1267
+ ok(`${story} is shipped${changedLanes ? ` — ${REVIEW_STEP} closed in ${changedLanes} lane${changedLanes > 1 ? 's' : ''}` : ''}`);
1268
+ if (sealedEpic(root, ctx.epic)) info(`${ctx.epic} is now sealed: every story shipped — new work there needs a change epic (yad-change)`);
1269
+ hand('commit with `yad checkpoint --push`');
1270
+ return { story, shipped: true, changed: changedLanes > 0 || !!moved.changed, lanesClosed: changedLanes };
1271
+ }
1272
+
1273
+ // Does `story` have a Build lane in `repo` — the lanes `yad build start` and `yad-run` write? A skipped lane
1274
+ // and a build-state that does not parse count as there: `yad build ship` refuses each with its own cause
1275
+ // and fix (unskip; repair the file), which a person reads in the list — never "may predate tracking".
1276
+ function laneIn(root, story, repo) {
1277
+ let bs;
1278
+ try { bs = readJSONStrict(path.join(epicFiles(epicRoot(root, storyEpic(story))).buildStateDir, `${story}.json`), null); } catch { return true; }
1279
+ if (bs == null) return false;
1280
+ // A file of the wrong shape is `yad build ship`'s to refuse, by its own cause.
1281
+ if (!isPlainObject(bs) || ('repos' in bs && !isPlainObject(bs.repos))) return true;
1282
+ const lane = isPlainObject(bs.repos) ? bs.repos[repo] : null;
1283
+ return isPlainObject(lane) && (Array.isArray(lane.steps) || lane.status === 'skipped');
1284
+ }
1285
+
1286
+ // `yad build sync [<epic>]` (issue #365) — record the ships the code repos already show, so nobody has to
1287
+ // type each `yad build ship` after a merge. The user's decisions (2026-10-21):
1288
+ // - a local command, run on the Product with the person's own gh/glab login; they commit the result with
1289
+ // `yad checkpoint --push` (no CI job);
1290
+ // - what it records is `yad reconcile check`'s list of tasks merged with no ship (`shipDrift`), each through
1291
+ // `yad build ship` itself: from the PR/MR that merged it, or — merged with no PR/MR — from its merge
1292
+ // commit where the platform confirms no PR/MR merged it;
1293
+ // - then `yad build done` for each story whose every task now has a ship.
1294
+ // Nothing is guessed: a task it cannot record, a possible match, a story no file holds, a refusal from
1295
+ // `build ship` or `build done` — each is listed with what to do, and the rest go on.
1296
+ export async function buildSync(root, { epic = null, dryRun = false, today, fetch = true, runner = run, prReader = readPr, env = process.env } = {}) {
1297
+ if (epic && !/^EP-[a-z0-9-]+$/.test(String(epic))) throw err(CODE, `'${epic}' is not an epic id`, 'expected EP-<slug>, such as EP-checkout');
1298
+ if (epic && !epicIds(root).includes(epic)) throw err(CODE, `no epic ${epic} in this Product`, 'check the epic id: `yad next` lists the epics');
1299
+ const drift = shipDrift(root, { epics: epic ? new Set([epic]) : null, ...(runner !== run ? { runner } : {}), env });
1300
+ const recorded = [];
1301
+ const planned = [];
1302
+ const left = [];
1303
+ const touched = new Set();
1304
+ for (const f of drift.findings.filter((x) => x.kind === 'merged-no-ship')) {
1305
+ const at = { story: f.story, task: f.task, repo: f.repo };
1306
+ // Only a story yad tracks in Build there — a lane in that repo. One with no lane may predate tracking,
1307
+ // where `yad checkpoint --retro-ship` is the record, and a normal ship would close that door: a person
1308
+ // decides (the `fix` says both ways).
1309
+ if (!laneIn(root, f.story, f.repo)) { left.push({ ...at, why: `${f.story} has no Build lane in ${f.repo} — it may predate tracking`, fix: f.fix }); continue; }
1310
+ // The PR/MR that merged it: the platform's word when it has one; else the merge commit asks it.
1311
+ const pr = Number.isInteger(f.pr) ? f.pr : null;
1312
+ const how = pr ? { pr: String(pr) } : f.sha ? { mergeCommit: f.sha } : null;
1313
+ if (!how) { left.push({ ...at, why: 'no PR/MR and no merge commit is known for it', fix: f.fix }); continue; }
1314
+ const cmd = `yad build ship ${f.story} --task ${f.task} --repo ${f.repo} ${pr ? `--pr ${pr}` : `--merge-commit ${f.sha.slice(0, 12)}`}`;
1315
+ if (dryRun) { planned.push({ ...at, ...how, command: cmd }); touched.add(f.story); continue; }
1316
+ const ship = (h) => buildShip(root, { ...at, ...h, byHand: false, today, fetch, runner, prReader });
1317
+ try {
1318
+ let res;
1319
+ try { res = await ship(how); } catch (e) {
1320
+ // A merge commit the platform says a PR/MR merged: recorded from that PR/MR, with its approvers.
1321
+ const by = !pr && String(e.message).match(/was merged by PR\/MR #(\d+)$/);
1322
+ if (!by) throw e;
1323
+ res = await ship({ pr: by[1] });
1324
+ }
1325
+ recorded.push({ ...at, pr: res.ship.pr, mergeCommit: res.ship.mergeCommit, file: res.file });
1326
+ touched.add(f.story);
1327
+ } catch (e) {
1328
+ left.push({ ...at, why: e.message, fix: e.hint || f.fix, command: cmd });
1329
+ }
1330
+ }
1331
+ // Stories every task of which now has a ship — and those `reconcile check` already sees as shipped in the
1332
+ // code but not in their status — are set shipped by `build done`, which checks it all again.
1333
+ const done = [];
1334
+ const notDone = [];
1335
+ const candidates = [...new Set([...touched, ...drift.findings.filter((x) => x.kind === 'looks-shipped').map((x) => x.story)])].sort();
1336
+ for (const story of candidates) {
1337
+ if (dryRun) { planned.push({ story, command: `yad build done ${story}` }); continue; }
1338
+ try {
1339
+ await buildDone(root, { story, today, fetch });
1340
+ done.push(story);
1341
+ } catch (e) {
1342
+ notDone.push({ story, why: e.message, fix: e.hint || null });
1343
+ }
1344
+ }
1345
+ // What a person checks: a match by a short tag, a task naming a story no file holds, a repo not read.
1346
+ const forPerson = drift.findings.filter((x) => ['possible', 'no-story'].includes(x.kind));
1347
+ // What was not read is unknown, never an all-clear: a repo not read in full, an epic whose ledger does not
1348
+ // parse, a story that cannot be compared, a registry that cannot be read — as `yad reconcile check` says.
1349
+ const unread = [
1350
+ ...drift.repos.filter((r) => !r.read || r.partial),
1351
+ ...drift.unreadEpics.map((e) => ({ epic: e, read: false, why: 'its build ledger could not be read (`yad doctor` says why)' })),
1352
+ ...drift.uncompared.map((st) => ({ story: st, read: false, why: 'it names no repo while the Product registers more than one, or two story files claim its ID' })),
1353
+ ...(drift.registry ? [{ registry: true, read: false, why: `.sdlc/repos.json could not be read in full — ${drift.registry}` }] : []),
1354
+ ];
1355
+
1356
+ if (dryRun) for (const p of planned) info(`would run: ${p.command}`);
1357
+ for (const r of recorded) ok(`recorded ${r.story} / ${r.task} in ${r.repo}`);
1358
+ for (const d of done) ok(`${d} is shipped`);
1359
+ for (const l of left) warn(`not recorded: ${l.story} / ${l.task} in ${l.repo} — ${l.why}${l.fix ? ` (${l.fix})` : ''}`);
1360
+ for (const n of notDone) info(`${n.story} not set shipped yet — ${n.why}`);
1361
+ for (const x of forPerson) warn(x.kind === 'possible' ? `${x.repo} ${String(x.sha || '').slice(0, 12)} may be ${x.stories.join(', ')} (${x.token}) — check it by hand` : `${x.repo} ${String(x.sha || '').slice(0, 12)} names ${x.task}, a story no file holds — check the trailer`);
1362
+ for (const r of unread) warn(`${r.repo || r.epic || r.story || 'repos.json'}: ${r.read ? 'read in part' : 'not read'}${r.why ? ` — ${r.why}` : r.note ? ` — ${r.note}` : ''}`);
1363
+ if (!dryRun && !recorded.length && !done.length && !left.length) {
1364
+ if (unread.length) info(`nothing recorded in what was read — ${unread.length} repo(s), ledger(s), stories or registry not read in full, so merged work there is unknown`);
1365
+ else ok('nothing to record — every merged task has a ship');
1366
+ }
1367
+ if (recorded.length || done.length) hand('commit with `yad checkpoint --push`');
1368
+ return {
1369
+ epic, dryRun, changed: recorded.length > 0 || done.length > 0,
1370
+ recorded, done, ...(dryRun ? { planned } : {}), left, notDone, forPerson, unread,
1371
+ };
1372
+ }