yadflow 4.5.2 → 4.6.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.
package/cli/pr-list.mjs CHANGED
@@ -123,3 +123,47 @@ function listGitLab(t, sinceMs, runner) {
123
123
  return { ...t, ok: true, open, merged, openPartial: o.body.length >= PAGE, mergedPartial: m.body.length >= PAGE };
124
124
  }
125
125
 
126
+
127
+ // #365 — the merged PRs/MRs of one repo, newest first, for `yad reconcile check`: which task branches
128
+ // merged. yad's task branches carry the task ID (`feat/EP-x-S01-T01-…`), and a squash merge on GitLab keeps
129
+ // only the MR title — so the branch name is the one place a squashed task still shows. Only the number,
130
+ // the source branch and the merge commit are read, and the caller prints only the task ID it finds in a
131
+ // branch name: never a title, a body, or the rest of a branch name.
132
+ // `base` keeps only those merged INTO it (the repo's default branch): a task merged into a release branch, a
133
+ // stacked parent or `develop` has not reached it (review 1).
134
+ // `{ ok: true, merged: [{ number, branch, commit }], partial }` or `{ ok: false, kind, why }`.
135
+ // What the platform says is printed and pasted (review 2): a number only when it is one, a SHA only when hex.
136
+ const hexSha = (v) => (typeof v === 'string' && /^[0-9a-f]{7,64}$/i.test(v) ? v.toLowerCase() : null);
137
+ // The day it merged, `YYYY-MM-DD` — what a retroactive ship's date is compared with (#365 review 3).
138
+ const dayOf = (v) => (typeof v === 'string' && !Number.isNaN(Date.parse(v)) ? new Date(v).toISOString().slice(0, 10) : null);
139
+ const GH_MERGED_BRANCHES = `query($owner:String!,$name:String!,$base:String){repository(owner:$owner,name:$name){
140
+ pullRequests(states:MERGED,baseRefName:$base,first:${PAGE},orderBy:{field:UPDATED_AT,direction:DESC}){nodes{number headRefName baseRefName mergedAt mergeCommit{oid}}}}}`;
141
+ export function listMergedBranches(target, { base = null, runner = run, env = process.env, authCache = new Map() } = {}) {
142
+ const t = target?.cli ? target : prTarget(target, { runner, env, authCache });
143
+ if (!t.ok) return t;
144
+ if (t.platform === 'github') {
145
+ const parts = t.repo.split('/');
146
+ const fail = (res) => ({ ...t, ok: false, kind: 'other', why: whyFailed(res, { platform: 'github', host: t.host, what: `the merged pull requests of ${shown(t.repo)}`, plural: true }) });
147
+ if (parts.length !== 2) return { ...t, ok: false, kind: 'no-url', why: `${shown(t.repo)} is not an owner/name GitHub repo path` };
148
+ const r = runner('gh', ['api', '--hostname', t.host, 'graphql', '-f', `query=${GH_MERGED_BRANCHES}`, '-f', `owner=${parts[0]}`, '-f', `name=${parts[1]}`, ...(base ? ['-f', `base=${base}`] : [])], { timeout: TIMEOUT });
149
+ if (!r.ok && httpStatus(r) == null && /\bGraphQL:/.test(`${r.stderr || ''}${r.stdout || ''}`)) {
150
+ return { ...t, ok: false, kind: 'other', why: `GitHub answered the pull-request query for ${shown(t.repo)} with an error (the repo may not exist, or your login may not see it)` };
151
+ }
152
+ if (!r.ok) return fail({ ok: false, status: httpStatus(r) });
153
+ let body;
154
+ try { body = JSON.parse(r.stdout); } catch { return fail({ unreadable: true }); }
155
+ const nodes = body?.data?.repository?.pullRequests?.nodes;
156
+ if (!Array.isArray(nodes)) return fail({ unreadable: true });
157
+ const merged = nodes.filter((n) => !base || n.baseRefName === base)
158
+ .map((n) => ({ number: Number.isInteger(n.number) ? n.number : null, branch: typeof n.headRefName === 'string' ? n.headRefName : null, commit: hexSha(n.mergeCommit?.oid), date: dayOf(n.mergedAt) }));
159
+ return { ...t, ok: true, merged, partial: nodes.length >= PAGE };
160
+ }
161
+ const m = api(runner, 'glab', t.host, `projects/${encodeURIComponent(t.repo)}/merge_requests?state=merged${base ? `&target_branch=${encodeURIComponent(base)}` : ''}&order_by=updated_at&sort=desc&per_page=${PAGE}`);
162
+ if (!m.ok) return { ...t, ok: false, kind: 'other', why: whyFailed(m, { platform: 'gitlab', host: t.host, what: `the merged merge requests of ${shown(t.repo)}`, plural: true }) };
163
+ if (!Array.isArray(m.body)) return { ...t, ok: false, kind: 'other', why: whyFailed({ unreadable: true }, { platform: 'gitlab', host: t.host, what: `the merged merge requests of ${shown(t.repo)}`, plural: true }) };
164
+ const merged = m.body.filter((x) => !base || x.target_branch === base).map((x) => ({
165
+ number: Number.isInteger(x.iid) ? x.iid : null, branch: typeof x.source_branch === 'string' ? x.source_branch : null,
166
+ commit: hexSha(x.squash_commit_sha) || hexSha(x.merge_commit_sha), date: dayOf(x.merged_at),
167
+ }));
168
+ return { ...t, ok: true, merged, partial: m.body.length >= PAGE };
169
+ }
@@ -0,0 +1,353 @@
1
+ // Issue #365 — merged work the Product's build ledger does not record. When task MRs merge in the code
2
+ // repos, nothing writes the build-log ship or the story's `status: shipped` on its own (the
3
+ // yad-engineer-review skill does, by hand), and `yad reconcile check` could not see the gap. This reads
4
+ // what merged and compares it with the ledger. READ-ONLY: it reports, with the command that fixes each
5
+ // line where one exists; it never writes a ship (that is #346).
6
+ //
7
+ // What counts as merged, per repo the Product registers (.sdlc/repos.json):
8
+ // - on the repo's default branch, in its clone here (as the clone last saw it — nothing is fetched): a
9
+ // `Task: EP-<slug>-S<n>-T<n>` trailer, a merge commit naming a task branch, or a full task ID in a
10
+ // commit subject (a squash commit titled with its task) — the full ID only (the user's decision);
11
+ // - a PR/MR merged INTO the default branch whose source branch names a task (`feat/EP-x-S01-T01-…`),
12
+ // when the platform answers: a GitLab squash keeps only the MR title, so the branch is where a
13
+ // squashed task still shows (the user's decision, 2026-10-18).
14
+ // A full STORY ID in a subject, or a short scope tag such as `feat(s06):`, is only a POSSIBLE match: listed
15
+ // to check by hand, never counted (2026-10-17). A story ID only in a commit body is not evidence.
16
+ //
17
+ // git runs only in a repo `judgeRepo` finds present — the guard `yad doctor` and `yad repo clone` use: a
18
+ // committed folder shaped like a bare repo would have git read its config, and a path outside the
19
+ // workspace is not this Product's to read (review 1). Facts only: a SHA, a PR/MR number and an ID — never
20
+ // a subject, a body or a branch name. Never an all-clear over what was not read (review 2): a repo, a
21
+ // registry, a ledger or a story that could not be read or compared is said and counted as unknown.
22
+ import fs from 'node:fs';
23
+ import path from 'node:path';
24
+ import { spawnSync } from 'node:child_process';
25
+ import { readJSONStrict, exists, forTerminal, asArg } from './lib.mjs';
26
+ import { PROJECT_FILES, TASK_ID_RE, TASK_TRAILER } from './manifest.mjs';
27
+ import { taskFromBranch } from './commit.mjs';
28
+ import { epicIds, epicRoot, readFrontmatter, declaredRepos } from './epic-state.mjs';
29
+ import { readShips } from './ledger.mjs';
30
+ import { listMergedBranches } from './pr-list.mjs';
31
+ import { judgeRepo } from './workspace.mjs';
32
+ import { hostFromGitUrl, plainHost } from './platform.mjs';
33
+ import { repoPathFromGitUrl } from './protection.mjs';
34
+
35
+ const STORY_IN_TEXT = /\bEP-[a-z0-9-]+-S\d+\b(?!-T\d)/g;
36
+ const TASK_IN_TEXT = /\bEP-[a-z0-9-]+-S\d+-T\d+\b/g;
37
+ const SHORT_TAG = /^[a-z]+\(\s*(s\d+)\s*\)!?:/i;
38
+ const SHA = /^[0-9a-f]{7,64}$/;
39
+ // A branch NAME, never revision syntax: `main~1`, `main@{1}`, `HEAD` or a leading `-` would read another
40
+ // commit than the branch's tip, and hide what merged (review 3).
41
+ const BRANCH = /^(?!-)(?!HEAD$)(?!.*(?:\.\.|@\{|\/\/|\.lock$|\/$|\.$))[A-Za-z0-9._/-]+$/;
42
+ const storyOf = (task) => task.replace(/-T\d+$/, '');
43
+ const shaOf = (v) => (typeof v === 'string' && SHA.test(v.toLowerCase()) ? v.toLowerCase() : null);
44
+
45
+ // git, raw: `run()` trims its output, and these records are split on NUL and unit separators. Signatures
46
+ // are never checked (`log.showSignature` in a repo's config runs a program of its choosing), and a partial
47
+ // clone never fetches a missing object on git 2.44+ (review 2): "nothing is fetched".
48
+ const git = (cwd, args) => {
49
+ // TZ=UTC: commit dates read as the UTC day, as ship dates and the platform's are (review 4).
50
+ const r = spawnSync('git', ['-c', 'log.showSignature=false', ...args], { cwd, encoding: 'utf8', maxBuffer: 1 << 28, env: { ...process.env, GIT_NO_LAZY_FETCH: '1', TZ: 'UTC' } });
51
+ return { ok: r.status === 0, status: r.status, out: r.stdout || '' };
52
+ };
53
+
54
+ // The default branch of one clone: origin's copy when the clone has one, else the local branch — named as
55
+ // a full ref, so no tag or other name of the same spelling is read instead. `{ ref (shown), full }`.
56
+ function defaultRef(dir, branch) {
57
+ if (!BRANCH.test(branch)) return null;
58
+ for (const [ref, full] of [[`origin/${branch}`, `refs/remotes/origin/${branch}`], [branch, `refs/heads/${branch}`]]) {
59
+ if (git(dir, ['rev-parse', '--verify', '--quiet', '--end-of-options', `${full}^{commit}`]).ok) return { ref, full };
60
+ }
61
+ return null;
62
+ }
63
+
64
+ // The branches a merge commit's subject says it brought in — never the "into …" part: GitLab's "Merge
65
+ // branch 'X' into 'main'", a local merge of a remote-tracking branch, an octopus "Merge branches 'a' and
66
+ // 'b'", GitHub's "Merge pull request #N from owner/X".
67
+ function mergedBranches(subject) {
68
+ const gh = subject.match(/^Merge pull request #\d+ from [^/\s]+\/(\S+)/);
69
+ if (gh) return [gh[1]];
70
+ const head = subject.match(/^Merge (?:remote-tracking )?branch(?:es)? ((?:'[^']+'(?:,\s*|\s+and\s+)?)+)/);
71
+ return head ? [...head[1].matchAll(/'(?:origin\/)?([^']+)'/g)].map((m) => m[1]) : [];
72
+ }
73
+
74
+ // The commits of one `git log`, as { sha, date, parents, subject, trailers } — or null when git could not
75
+ // read them. `skipped` counts a record that cannot be read safely (a 0x1f in a subject or trailer makes
76
+ // more fields).
77
+ function logRecords(dir, args, counter) {
78
+ const log = git(dir, ['log', '--no-show-signature', '-z', '--date=format-local:%Y-%m-%d', `--format=%H%x1f%cd%x1f%P%x1f%s%x1f%(trailers:key=${TASK_TRAILER},valueonly,separator=%x1e)`, ...args]);
79
+ if (!log.ok) return null;
80
+ const out = [];
81
+ for (const rec of log.out.split('\0')) {
82
+ if (!rec.trim()) continue;
83
+ const fields = rec.replace(/^\n/, '').split('\x1f');
84
+ if (fields.length !== 5 || !/^[0-9a-f]{40,64}$/.test(fields[0])) { counter.skipped++; continue; }
85
+ out.push({ sha: fields[0], date: fields[1], parents: fields[2].split(' ').filter(Boolean), subject: fields[3], trailers: fields[4] });
86
+ }
87
+ return out;
88
+ }
89
+
90
+ // One repo's merged work, read from its clone. `{ read: true, ref, sha, dir, shared, tasks: Map(task ->
91
+ // evidence), possible, skipped, mergesUnread? }` (`mergesUnread`: a folder, whose merge titles are not read) or `{ read: false, why }` — a repo that cannot be read says so, and is
92
+ // never "nothing merged".
93
+ export function readRepoMerges(root, repo) {
94
+ const judged = judgeRepo(root, repo);
95
+ if (judged.state === 'missing') return { read: false, why: 'not cloned here (`yad repo clone`)' };
96
+ // `path: "."` — the Product's own checkout IS the code repo (a supported monorepo layout, review 2). Only
97
+ // when the Product folder holds its own `.git`: otherwise git would walk up into whatever repo encloses
98
+ // it (review 3).
99
+ if (judged.state === 'product' && !exists(path.join(root, '.git'))) return { read: false, why: 'the Product folder is not a git checkout of its own' };
100
+ if (judged.state !== 'present' && judged.state !== 'product') return { read: false, why: judged.reason };
101
+ if (judged.linked) return { read: false, why: 'it is reached through a link inside a repo, so git would read somewhere else' };
102
+ const dir = judged.state === 'product' ? path.resolve(root) : judged.target;
103
+ const branch = typeof repo.default_branch === 'string' ? repo.default_branch : '';
104
+ if (branch && !BRANCH.test(branch)) return { read: false, why: 'its default_branch in repos.json is not a branch name' };
105
+ const found = defaultRef(dir, branch);
106
+ const ref = found?.ref;
107
+ if (!found) return { read: false, why: branch ? `no branch ${forTerminal(branch)} in the clone` : 'no default_branch in repos.json' };
108
+ // A shallow clone holds only its newest commits: what merged before its edge is not there, and reading it
109
+ // would be an all-clear over history it does not have (review 5). Said, not read.
110
+ const shallow = git(dir, ['rev-parse', '--is-shallow-repository']);
111
+ if (!shallow.ok || shallow.out.trim() !== 'false') return { read: false, why: shallow.ok ? 'a shallow clone — run `git fetch --unshallow` in it, then run again' : 'git could not tell whether it is a shallow clone' };
112
+ // A repo folder inside a shared checkout (the monorepo layout) reads only its own folder's NON-MERGE
113
+ // commits: their `Task:` trailers and task IDs in their subjects (what `yad commit` writes). The whole
114
+ // history would credit every other folder's tasks to it (review 1); a merge commit cannot be told to
115
+ // belong to one folder without edge cases that kept turning up — shallow edges, criss-cross merges, a
116
+ // stacked branch carrying another task's work — so a merge's title is not read for a folder (the user's
117
+ // decision, 2026-10-19, review 5), and the output says so. The folder is named as it is on disk (its true
118
+ // letter case) and matched literally (review 2).
119
+ let only = null;
120
+ if (judged.inside) {
121
+ try { only = path.relative(fs.realpathSync.native(judged.inside), fs.realpathSync.native(dir)).split(path.sep).join('/'); } catch { return { read: false, why: 'its folder could not be resolved' }; }
122
+ }
123
+ const counter = { skipped: 0 };
124
+ const spec = only ? ['--', `:(top,literal)${only}`] : ['--'];
125
+ const records = logRecords(dir, [...(only ? ['--no-merges'] : []), '--end-of-options', found.full, ...spec], counter);
126
+ if (!records) return { read: false, why: `git could not read ${forTerminal(ref)}` };
127
+ const tasks = new Map();
128
+ const possible = [];
129
+ const add = (task, ev) => { if (!tasks.has(task)) tasks.set(task, ev); };
130
+ // The Product's own checkpoint commits name a story in their subject; they are yad's records, not merged
131
+ // work (review 3).
132
+ const ownRecord = (subject) => judged.state === 'product' && /^chore\(product\):/.test(subject);
133
+ for (const { sha, date, parents, subject, trailers } of records) {
134
+ const isMerge = parents.length > 1;
135
+ let hadTask = false;
136
+ for (const v of trailers.split('\x1e').map((s) => s.trim())) {
137
+ if (TASK_ID_RE.test(v)) { add(v, { sha, date, via: 'trailer' }); hadTask = true; }
138
+ }
139
+ const brought = isMerge ? mergedBranches(subject) : [];
140
+ for (const b of brought) {
141
+ const branchTask = taskFromBranch(b);
142
+ if (branchTask && TASK_ID_RE.test(branchTask)) { add(branchTask, { sha, date, via: 'merge commit' }); hadTask = true; }
143
+ }
144
+ // A subject may carry a full task ID: a squash titled with its task, or a merge titled with its pull
145
+ // request (review 5). A "Merge branch 'x' into 'y'" subject is read only for the branches it brought
146
+ // in, never for an ID in its "into …" part (review 4).
147
+ if (!brought.length && !/^Merge (?:remote-tracking branch|branch(?:es)?|commit|tag)s? '/.test(subject) && !/^Revert\b/i.test(subject) && !ownRecord(subject)) {
148
+ for (const t of subject.match(TASK_IN_TEXT) || []) { add(t, { sha, date, via: 'task ID in the subject' }); hadTask = true; }
149
+ }
150
+ if (hadTask || ownRecord(subject)) continue;
151
+ for (const id of subject.match(STORY_IN_TEXT) || []) possible.push({ sha, story: id, via: 'story ID in the subject' });
152
+ const tag = subject.match(SHORT_TAG);
153
+ // `s06` and `s6` name the same story number; stories are keyed by the number itself.
154
+ if (tag) possible.push({ sha, tag: `s${Number(tag[1].slice(1))}`, via: `short tag ${tag[1].toLowerCase()}` });
155
+ }
156
+ const sha = git(dir, ['rev-parse', '--verify', '--quiet', '--end-of-options', found.full]).out.trim();
157
+ return { read: true, ref, sha, dir, shared: !!only, tasks, possible, skipped: counter.skipped, ...(only ? { mergesUnread: true } : {}) };
158
+ }
159
+
160
+ // The task branches merged INTO the default branch that the platform knows of, when it answers. Adds to
161
+ // `tasks`, never replaces a commit already found. Returns `{ note, partial }`: turned off on purpose, or no
162
+ // platform to ask, is a note; a platform that should have answered and did not is partial. A full page is
163
+ // a note only: local git sees every merge but a squash, and a busy repo would otherwise never read in full.
164
+ function addPlatformMerges(repo, merges, { runner, env, authCache }) {
165
+ const t = { platform: repo.platform || null, gitUrl: repo.git_url || '' };
166
+ const r = listMergedBranches(t, { base: repo.default_branch, ...(runner ? { runner } : {}), env, authCache });
167
+ if (!r.ok) {
168
+ const deliberate = ['off', 'no-platform', 'no-url'].includes(r.kind);
169
+ const how = ['no-cli', 'no-login'].includes(r.kind) ? ' — install and log in to read squash-merged tasks, or set YAD_PLATFORM_READ=0 to read git only' : '';
170
+ return { note: `platform not read — ${r.why}${how}`, partial: !deliberate };
171
+ }
172
+ for (const m of r.merged) {
173
+ const task = m.branch ? taskFromBranch(m.branch) : null;
174
+ if (task && TASK_ID_RE.test(task) && !merges.tasks.has(task)) merges.tasks.set(task, { sha: m.commit, pr: m.number, date: m.date, via: 'merged branch' });
175
+ }
176
+ return { note: r.partial ? 'the platform listed only its 100 most recently updated merged PRs/MRs — an older squash merge may be missing' : null, partial: false };
177
+ }
178
+
179
+ // Does a retroactive ship stand for this merged task? It covers what merged up to it: a task commit its
180
+ // merge commit holds, else one dated on or before it. Only a hex SHA that resolves to a commit here is
181
+ // asked about — `main` or `:/text` would cover everything (review 2); one this clone lacks falls back to the
182
+ // date. A retro ship with neither a commit nor a date recorded stands for the whole story here, as before;
183
+ // one whose recorded commit cannot be checked and has no date covers nothing it cannot prove (review 3).
184
+ function retroCovers(retro, ev, dir) {
185
+ const recorded = shaOf(retro.mergeCommit);
186
+ const mc = recorded && dir && git(dir, ['rev-parse', '--verify', '--quiet', '--end-of-options', `${recorded}^{commit}`]).ok ? recorded : null;
187
+ const evSha = shaOf(ev.sha);
188
+ if (mc && evSha) {
189
+ const r = git(dir, ['merge-base', '--is-ancestor', '--end-of-options', evSha, mc]);
190
+ if (r.status === 0) return true;
191
+ if (r.status === 1) return false;
192
+ // anything else (an object this clone lacks): fall back to the date
193
+ }
194
+ const shipped = typeof retro.shippedAt === 'string' ? retro.shippedAt.slice(0, 10) : null;
195
+ if (shipped && ev.date) return ev.date <= shipped;
196
+ return !retro.mergeCommit && !shipped;
197
+ }
198
+
199
+ // The platform repo a registry entry names, the same however its URL is spelled (review 3).
200
+ const platformKey = (url) => {
201
+ const host = plainHost(hostFromGitUrl(url || ''));
202
+ const repo = repoPathFromGitUrl(url || '');
203
+ return host && repo ? `${host}/${repo}`.toLowerCase().replace(/\.git$/, '') : null;
204
+ };
205
+
206
+ // The whole comparison. `epics` (a Set) limits it to those epics, and then only the repos their stories
207
+ // name are read. Returns { repos, unreadEpics, uncompared, registry, findings }:
208
+ // repos: [{ repo, read, why? | ref, sha, note?, partial? }]
209
+ // uncompared: stories that name no repo, when the registry holds more than one — they cannot be compared
210
+ // registry: null when it was read; else why it was not (the file does not parse, or an entry is not one)
211
+ // finding.kind 'merged-no-ship' { epic, story, task, repo, sha, pr, via, fix } — counted
212
+ // 'looks-shipped' { epic, story, status, repos } — a hint
213
+ // 'possible' { repo, sha, token, via, stories } — check by hand
214
+ // 'no-story' { repo, sha, task, epic } — a task naming a story no file holds
215
+ export function shipDrift(root, { platform = true, epics = null, runner, env = process.env, authCache = new Map() } = {}) {
216
+ // The registry first: a story that names no repo takes the one repo the Product registers, as
217
+ // `yad checkpoint --retro-ship` does. A file that does not parse is not "no repos" (review 2).
218
+ let registry = null;
219
+ let entries = [];
220
+ try {
221
+ const reg = readJSONStrict(path.join(root, PROJECT_FILES.reposRegistry), { repos: [] });
222
+ entries = Array.isArray(reg?.repos) ? reg.repos : null;
223
+ if (!entries) { registry = 'its `repos` is not a list'; entries = []; }
224
+ } catch { registry = 'it does not parse'; }
225
+ const usable = entries.filter((r) => r && typeof r === 'object' && typeof r.name === 'string' && r.name);
226
+ if (!registry && usable.length !== entries.length) registry = `${entries.length - usable.length} entry(ies) are not a repo with a name`;
227
+
228
+ const stories = [];
229
+ const unreadEpics = [];
230
+ const uncompared = [];
231
+ const knownEpics = new Set();
232
+ const knownIds = new Set();
233
+ for (const epic of epicIds(root)) {
234
+ knownEpics.add(epic);
235
+ if (epics && !epics.has(epic)) continue;
236
+ const dir = path.join(epicRoot(root, epic), 'stories');
237
+ if (!exists(dir)) continue;
238
+ const idOk = (x) => new RegExp(`^${epic}-S\\d+$`).test(x);
239
+ const files = fs.readdirSync(dir).filter((x) => x.endsWith('.md')).sort().map((f) => {
240
+ const fm = readFrontmatter(path.join(dir, f));
241
+ const fileId = f.replace(/\.md$/, '');
242
+ // An `id:` that is not this epic's story ID (a typo) falls back to the file's name (review 4).
243
+ const story = typeof fm.id === 'string' && idOk(fm.id) ? fm.id : fileId;
244
+ return { fm, fileId, story };
245
+ }).filter((x) => idOk(x.story));
246
+ // Two files claiming one story ID (an `id:` copied by hand): each falls back to its own file name; a
247
+ // clash that remains is not compared, and is said (review 5).
248
+ const claims = new Map();
249
+ for (const x of files) claims.set(x.story, (claims.get(x.story) || 0) + 1);
250
+ for (const x of files) if (claims.get(x.story) > 1 && idOk(x.fileId)) x.story = x.fileId;
251
+ const seenIds = new Map();
252
+ for (const x of files) seenIds.set(x.story, (seenIds.get(x.story) || 0) + 1);
253
+ // Its story IDs are known even when its ledger is not: a merged task of it is never "no such story".
254
+ for (const x of files) knownIds.add(x.story);
255
+ let ships;
256
+ try { ships = readShips(epicRoot(root, epic)); } catch { unreadEpics.push(epic); continue; }
257
+ for (const { fm, fileId, story } of files) {
258
+ if (seenIds.get(story) > 1) { if (!uncompared.includes(story)) uncompared.push(story); continue; }
259
+ let repos = declaredRepos(fm);
260
+ let fallback = false;
261
+ // A story that names no repo was never compared (review 3): with one registered repo it is that one;
262
+ // with more it cannot be told, and is said.
263
+ if (!repos.length) {
264
+ if (usable.length === 1) { repos = [usable[0].name]; fallback = true; } else { uncompared.push(story); continue; }
265
+ }
266
+ stories.push({ epic, story, sameFile: story === fileId, fallback, status: typeof fm.status === 'string' ? fm.status : '', repos, ships: ships.filter((s) => s.story === story) });
267
+ }
268
+ }
269
+
270
+ const wanted = new Set(stories.flatMap((s) => s.repos));
271
+ const repos = usable.filter((r) => !epics || wanted.has(r.name));
272
+ // The same platform repo under two names (monorepo folders share their checkout's `origin`), however its
273
+ // URL is spelled: its merged branches cannot be told apart by name, so it is not asked for any of them.
274
+ const keyCount = new Map();
275
+ // From the whole registry, so a `--thread` run asks exactly what a full run does (review 4).
276
+ for (const r of usable) { const k = platformKey(r.git_url); if (k) keyCount.set(k, (keyCount.get(k) || 0) + 1); }
277
+ const read = new Map();
278
+ const reposOut = [];
279
+ for (const repo of repos) {
280
+ if (read.has(repo.name)) continue; // a name registered twice is read once
281
+ const m = readRepoMerges(root, repo);
282
+ let pl = { note: null, partial: false };
283
+ if (m.read && platform) {
284
+ const k = platformKey(repo.git_url);
285
+ pl = m.shared || (k && keyCount.get(k) > 1)
286
+ ? { note: 'platform not asked — another registered repo shares this one, so a squash-merged task that shows only in its branch name is not seen here', partial: false }
287
+ : addPlatformMerges(repo, m, { runner, env, authCache });
288
+ }
289
+ const partial = pl.partial || (m.read && m.skipped > 0);
290
+ const notes = [pl.note, m.read && m.skipped ? `${m.skipped} commit(s) could not be read` : null,
291
+ m.mergesUnread ? 'merge-commit titles are not read for a folder in a shared checkout — a task seen only in one is not found' : null].filter(Boolean);
292
+ read.set(repo.name, m);
293
+ reposOut.push({ repo: repo.name, read: m.read, ...(m.read ? { ref: m.ref, sha: m.sha } : { why: m.why }), ...(notes.length ? { note: notes.join('; ') } : {}), ...(partial ? { partial: true } : {}) });
294
+ }
295
+ // A repo a story names that the registry does not hold is not read either — said, not assumed empty.
296
+ for (const name of [...wanted].sort()) {
297
+ if (!read.has(name)) reposOut.push({ repo: name, read: false, why: registry ? 'repos.json could not be read' : 'a story names it, but it is not in repos.json' });
298
+ }
299
+
300
+ const findings = [];
301
+ for (const s of stories) {
302
+ let everyRepoHasWork = s.repos.length > 0;
303
+ for (const repoName of s.repos) {
304
+ const m = read.get(repoName);
305
+ const recorded = s.ships.filter((x) => x.repo === repoName);
306
+ const retros = recorded.filter((x) => x.retroactive);
307
+ const merged = m?.read ? [...m.tasks].filter(([task]) => storyOf(task) === s.story) : [];
308
+ if (!recorded.length && !merged.length) everyRepoHasWork = false;
309
+ let suggested = false;
310
+ for (const [task, ev] of merged) {
311
+ const t = task.slice(s.story.length + 1);
312
+ // A hand-written ship may hold the full ID as its task (review 3).
313
+ if (recorded.some((x) => x.task === t || x.task === task)) continue;
314
+ if (retros.some((x) => retroCovers(x, ev, m.dir))) continue;
315
+ // `yad checkpoint --retro-ship` records ONE ship per (story, repo), marked as a pre-tracking backfill,
316
+ // and needs the story `in-build` or `shipped` first. So it is offered once, only while (story, repo)
317
+ // has no ship at all and the story's file carries its ID, and only for a story that predates
318
+ // tracking; every other line says to record the ship as yad-engineer-review does (review 1).
319
+ const engineer = 'record the ship as yad-engineer-review does (a command for it is #346)';
320
+ const evSha = shaOf(ev.sha);
321
+ let fix = engineer;
322
+ if (!recorded.length && !suggested && s.sameFile && asArg(repoName) === repoName) {
323
+ fix = `if ${s.story} predates ledger tracking: yad checkpoint --retro-ship ${s.epic}/${s.story} --repo ${repoName} --task ${t}${evSha ? ` --merge-commit ${evSha.slice(0, 12)}` : ''} (the story's status must be in-build or shipped first); otherwise ${engineer}`;
324
+ suggested = true;
325
+ }
326
+ findings.push({ kind: 'merged-no-ship', epic: s.epic, story: s.story, task: t, repo: repoName, sha: evSha, pr: Number.isInteger(ev.pr) ? ev.pr : null, via: ev.via, fix });
327
+ }
328
+ }
329
+ if (everyRepoHasWork && s.status !== 'shipped') findings.push({ kind: 'looks-shipped', epic: s.epic, story: s.story, status: s.status || null, repos: s.repos, ...(s.fallback ? { fallback: true } : {}) });
330
+ }
331
+
332
+ // Possible matches, for stories not already shipped or recorded in that repo — a match for one that is
333
+ // has nothing left to check, and the list would only grow with history (review 1). A short tag names a
334
+ // story number, not an epic, so every such story in an epic that names the repo is a candidate.
335
+ const open = (repoName) => stories.filter((s) => s.repos.includes(repoName) && s.status !== 'shipped' && !s.ships.some((x) => x.repo === repoName));
336
+ for (const [repoName, m] of read) {
337
+ if (!m.read) continue;
338
+ const candidates = open(repoName);
339
+ for (const p of m.possible) {
340
+ const hit = candidates.filter((s) => (p.story ? s.story === p.story : `s${Number(s.story.match(/-S(\d+)$/)[1])}` === p.tag)).map((s) => s.story);
341
+ if (hit.length) findings.push({ kind: 'possible', repo: repoName, sha: p.sha, token: p.story || p.tag, via: p.via, stories: hit });
342
+ }
343
+ // A merged task whose story no file holds — a typo in a trailer is exactly the drift this looks for
344
+ // (review 3). Only for an epic that exists, and in scope.
345
+ for (const [task, ev] of m.tasks) {
346
+ const story = storyOf(task);
347
+ const epic = story.replace(/-S\d+$/, '');
348
+ if (knownIds.has(story) || !knownEpics.has(epic) || (epics && !epics.has(epic))) continue;
349
+ findings.push({ kind: 'no-story', repo: repoName, sha: shaOf(ev.sha), task, epic });
350
+ }
351
+ }
352
+ return { repos: reposOut, unreadEpics, uncompared, registry, findings };
353
+ }
package/cli/thread.mjs CHANGED
@@ -4,8 +4,9 @@
4
4
  // this only DISCOVERS, exactly as yad-docs-sync flags and the build gates block. Node built-ins only.
5
5
  import path from 'node:path';
6
6
  import fs from 'node:fs';
7
- import { c, log, ok, info, warn, hand, readJSON, exists, emitJSON, refuse } from './lib.mjs';
7
+ import { c, log, ok, info, warn, hand, readJSON, exists, emitJSON, refuse, forTerminal } from './lib.mjs';
8
8
  import { readShips } from './ledger.mjs';
9
+ import { shipDrift } from './ship-drift.mjs';
9
10
  import {
10
11
  epicRoot, isValidEpicId, epicLineage, readFrontmatter, isStubEpic, typeNoun, currentPhase, isProductLevel,
11
12
  resolveThread, threadEpics, resolveCurrentArtifacts, resolveCurrentStories, THREAD_ARTIFACT_BASES,
@@ -170,7 +171,7 @@ function threadRoots(root) {
170
171
  return [...roots].sort();
171
172
  }
172
173
 
173
- export async function runReconcile(root, { action = 'check', thread = null } = {}) {
174
+ export async function runReconcile(root, { action = 'check', thread = null, runner, env } = {}) {
174
175
  const roots = thread ? [resolveThread(root, thread).rootId] : threadRoots(root);
175
176
  if (!roots.length) { info('no feature threads found (no epics with epic.md yet)'); return { action, flags: 0, threads: [] }; }
176
177
 
@@ -190,6 +191,47 @@ export async function runReconcile(root, { action = 'check', thread = null } = {
190
191
  for (const i of issues) hand(i);
191
192
  }
192
193
 
194
+ // #365: merged work the build ledger does not record — a merged task with no ship record, a story whose
195
+ // repos all hold merged work but whose status is not `shipped` (a hint), and possible matches to check by
196
+ // hand. `check` only: it reads every repo's history and may ask the platform (review 1).
197
+ let ships = null;
198
+ let unknown = 0;
199
+ if (action === 'check') {
200
+ const drift = shipDrift(root, { epics: thread ? new Set(threadEpics(root, roots[0])) : null, ...(runner ? { runner } : {}), ...(env ? { env } : {}) });
201
+ ships = drift;
202
+ if (drift.repos.length || drift.unreadEpics.length || drift.registry || drift.uncompared.length) {
203
+ log(c.bold('\nBuild records'));
204
+ const short = (sha) => (sha ? sha.slice(0, 7) : null);
205
+ if (drift.registry) warn(`.sdlc/repos.json could not be read in full — ${drift.registry}; merged work in what it lists is unknown`);
206
+ for (const r of drift.repos) {
207
+ if (!r.read) warn(`${forTerminal(r.repo)}: not read — ${forTerminal(r.why)}`);
208
+ else (r.partial ? warn : info)(`${forTerminal(r.repo)}: read ${forTerminal(r.ref)} at ${short(r.sha)} (this clone's view — nothing fetched)${r.note ? `; ${forTerminal(r.note)}` : ''}`);
209
+ }
210
+ for (const e of drift.unreadEpics) warn(`${e}: its build ledger could not be read — \`yad doctor\` says why`);
211
+ for (const st of drift.uncompared) warn(`${st}: not compared — it names no repo while the Product registers more than one (add \`repos: [...]\`), or two story files claim its ID`);
212
+ for (const f of drift.findings) {
213
+ if (f.kind === 'merged-no-ship') {
214
+ const where = [short(f.sha), f.pr != null ? `PR/MR ${f.pr}` : null].filter(Boolean).join(', ');
215
+ warn(`${f.story}-${f.task} merged in ${forTerminal(f.repo)} (${where || 'no commit named'}, by ${f.via}) — no ship record`);
216
+ hand(forTerminal(f.fix));
217
+ } else if (f.kind === 'looks-shipped') {
218
+ info(`${f.story}: ${f.fallback ? `the one registered repo (${f.repos.map(forTerminal).join(', ')}), used because it names none,` : `every repo it names (${f.repos.map(forTerminal).join(', ')})`} has merged work, but its status is ${forTerminal(f.status || 'unset')} — if no task is left, set \`status: shipped\` (\`yad checkpoint\` commits it with the ledger)`);
219
+ } else if (f.kind === 'no-story') {
220
+ warn(`${f.task} merged in ${forTerminal(f.repo)} (${short(f.sha) || 'no commit named'}) — ${f.epic} has no story ${f.task.replace(/-T\d+$/, '')}; a typo in its Task trailer, or a story file missing`);
221
+ } else {
222
+ info(`${forTerminal(f.repo)} ${short(f.sha)}: ${f.via} — a possible match for ${f.stories.join(', ')}; check by hand`);
223
+ }
224
+ }
225
+ const counted = drift.findings.filter((f) => f.kind === 'merged-no-ship' || f.kind === 'no-story').length;
226
+ flags += counted;
227
+ // Never an all-clear over what was not read, or read in part (review 2): each such repo, ledger or
228
+ // registry is counted as unknown, and the closing line says so too.
229
+ unknown = drift.repos.filter((r) => !r.read || r.partial).length + drift.unreadEpics.length + drift.uncompared.length + (drift.registry ? 1 : 0);
230
+ if (!counted && !unknown) ok('every merged task has a ship record');
231
+ else if (!counted) info(`no merged task without a ship record in what was read — ${unknown} repo(s), ledger(s), stories or registry not read in full, so merged work there is unknown`);
232
+ }
233
+ }
234
+
193
235
  if (action === 'refresh') {
194
236
  log('');
195
237
  info('refresh is advisory: open a reconcile change-epic with `yad-change` (type change) threaded to');
@@ -205,6 +247,7 @@ export async function runReconcile(root, { action = 'check', thread = null } = {
205
247
 
206
248
  log('');
207
249
  if (flags) { warn(`${flags} item(s) need attention — reconcile is advisory; the gates block at merge`); }
250
+ else if (unknown) { info(`no drift and no open debt found — but ${unknown} repo(s), ledger(s), stories or registry were not read in full`); }
208
251
  else { ok('all threads reconciled — no drift, no open debt'); }
209
- return { action, flags, threads };
252
+ return { action, flags, threads, ...(ships ? { ships } : {}) };
210
253
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yadflow",
3
- "version": "4.5.2",
3
+ "version": "4.6.0",
4
4
  "description": "Shared project memory and workflows for teams building with AI: a versioned record of plans, decisions, contracts and reviews across repos, human-approved review gates, and a zero-dependency `yad` CLI plus 38 skills for your AI assistant.",
5
5
  "type": "module",
6
6
  "author": "AbdelRahman Nasr",
@@ -28,6 +28,7 @@
28
28
  "!cli/test-detect.mjs",
29
29
  "!cli/test-members.mjs",
30
30
  "!cli/test-standup.mjs",
31
+ "!cli/test-lifecycle.mjs",
31
32
  "!cli/test-fuzz.js",
32
33
  "!cli/fixtures",
33
34
  "skills/",
@@ -45,10 +46,10 @@
45
46
  "scripts": {
46
47
  "yad": "node bin/yad.mjs",
47
48
  "lint": "eslint cli bin",
48
- "test": "node --test cli/test.mjs cli/test-checks.mjs cli/test-threads.mjs cli/test-golden.mjs cli/test-migrate.mjs cli/test-hooks.mjs cli/test-detect.mjs cli/test-members.mjs cli/test-standup.mjs cli/test-fuzz.js",
49
+ "test": "node --test cli/test.mjs cli/test-checks.mjs cli/test-threads.mjs cli/test-golden.mjs cli/test-migrate.mjs cli/test-hooks.mjs cli/test-detect.mjs cli/test-members.mjs cli/test-standup.mjs cli/test-lifecycle.mjs cli/test-fuzz.js",
49
50
  "test:e2e": "bash test/e2e/run.sh",
50
51
  "release-check": "bash scripts/release-check.sh",
51
- "coverage": "node --test --experimental-test-coverage --test-coverage-exclude='cli/test*.mjs' --test-coverage-exclude='cli/test*.js' --test-coverage-lines=70 --test-coverage-branches=70 cli/test.mjs cli/test-checks.mjs cli/test-threads.mjs cli/test-golden.mjs cli/test-migrate.mjs cli/test-hooks.mjs cli/test-detect.mjs cli/test-members.mjs cli/test-standup.mjs cli/test-fuzz.js",
52
+ "coverage": "node --test --experimental-test-coverage --test-coverage-exclude='cli/test*.mjs' --test-coverage-exclude='cli/test*.js' --test-coverage-lines=70 --test-coverage-branches=70 cli/test.mjs cli/test-checks.mjs cli/test-threads.mjs cli/test-golden.mjs cli/test-migrate.mjs cli/test-hooks.mjs cli/test-detect.mjs cli/test-members.mjs cli/test-standup.mjs cli/test-lifecycle.mjs cli/test-fuzz.js",
52
53
  "diagrams": "npx -y @mermaid-js/mermaid-cli@11.15.0 -i docs/diagrams/sdlc-overview.mmd -o docs/diagrams/sdlc-overview.svg -b transparent && npx -y @mermaid-js/mermaid-cli@11.15.0 -i docs/diagrams/review-loop.mmd -o docs/diagrams/review-loop.svg -b transparent && npx -y @mermaid-js/mermaid-cli@11.15.0 -i docs/diagrams/work-and-memory.mmd -o docs/diagrams/work-and-memory.svg -b transparent && npx -y @mermaid-js/mermaid-cli@11.15.0 -i docs/diagrams/feature-evolution.mmd -o docs/diagrams/feature-evolution.svg -b transparent",
53
54
  "prepublishOnly": "npm test"
54
55
  },
@@ -42,26 +42,27 @@ document_output_language: English
42
42
  #
43
43
  # A phase is DERIVED from a step's id and is never written into `state.json` — there is nothing to
44
44
  # author here, nothing to keep in step, and no way for it to disagree with the step it describes.
45
- # `stepPhase` in cli/epic-state.mjs is the one definition; this block is the same table in the file
46
- # people read. A review gate takes the phase of the artifact it reviews, so `epic-review` is Discover.
45
+ # The phase of each step is set in the lifecycle default (`cli/lifecycle/defaults/1.json`), which
46
+ # `stepPhase` in cli/epic-state.mjs reads; this block is generated from it for people to read. A review gate takes the phase of the artifact it reviews, so `epic-review` is Discover.
47
47
  #
48
48
  # Release and Operate are NAMED and not built. No step, skill or gate exists for either yet.
49
49
  #
50
50
  # NOTE the word: "phase" here means one of these six. It does NOT mean the numbered development
51
51
  # phases of yadflow itself (docs/phase-N-build-plan.md), which is what "Phase 4a/4b" means elsewhere
52
52
  # in these files, nor a gate's internal merge phase.
53
- # The step CATALOGUE lives in code — `STEPS` in `cli/epic-state.mjs` (E4). It is the one place that
54
- # says what a step is: its phase, whether it authors or gates, what artifact it writes, which skill
55
- # runs it, and which step a gate reviews. The phase rows below mirror the `steps:` half of it and a
56
- # test holds the two together row for row; everything else about a step is read from the code, not
57
- # from here. `yad doctor` reports a project chain that disagrees with the catalogue and rewrites
58
- # nothing — for this whole major the FILE wins (rule 3), because the five authoring skills still
59
- # hand-write their `state.json` seed. E5 makes a profile seed the chain from the catalogue instead.
53
+ # The step CATALOGUE is the lifecycle default that ships with yadflow, `cli/lifecycle/defaults/1.json`
54
+ # (E134; the engine reads it as `STEPS` in `cli/epic-state.mjs`). It is the one place that says what a
55
+ # step is: its phase, whether it authors or gates, what artifact it writes, which skill runs it, and
56
+ # which step a gate reviews. The lines between the `generated` markers below are written from it by
57
+ # `scripts/lifecycle-config.mjs`, and a test fails when they differ; everything else about a step is
58
+ # read from the default, not from here. `yad doctor` reports a project chain that disagrees with the
59
+ # catalogue and rewrites nothing — for this whole major the FILE wins (rule 3): a project may hold a step
60
+ # from a newer yadflow, or a chain written by hand. `yad epic new` seeds a chain from its route (E5, E17).
60
61
  lifecycle:
61
- parts: [Shape, Build, Run]
62
- # Lifecycle PROFILES (E5) — the route an epic takes through the steps, defined in code as
63
- # `LIFECYCLE_PROFILES` (`cli/epic-state.mjs`). Three were routes the skills already seeded by hand:
64
- # `classic` (the 10-step chain, `epic` first — yad-epic / yad-stub / yad-change), `analysis-first`
62
+ # Lifecycle PROFILES (E5) — the route an epic takes through the steps, defined as the `routes` of the
63
+ # lifecycle default and read by the engine as `LIFECYCLE_PROFILES` (`cli/epic-state.mjs`). The
64
+ # default's `lane` route (the Build order) is not a profile, so it is not in `profiles`. Three were
65
+ # routes the skills already seeded by hand: `classic` (the 10-step chain, `epic` first — yad-epic / yad-stub / yad-change), `analysis-first`
65
66
  # (the 12-step chain, `analysis` before `epic` — yad-analysis) and `discovery` (the product
66
67
  # front-zero — yad-discovery, now the OLD spelling of the Product level). `foundation` is that level
67
68
  # as E75 writes it — `yad foundation new`. Two are the short lanes E40 added, which nobody seeded before:
@@ -72,9 +73,13 @@ lifecycle:
72
73
  # field `yad migrate` fills it in by matching the chain. The chain stays the truth — `yad doctor`
73
74
  # compares the two. NOT the `product.json` `profile`, which is the unrelated setup record
74
75
  # { codebase, repo_layout, team_size }.
76
+ # The PRODUCT level's phase (E75), `product_phases` — a ladder of its own, run once per product before
77
+ # any epic, and part of no Part. `discovery` is listed because it is the old spelling of the same level.
78
+ # Release and Operate are planned: E32 builds Release, E33 builds Operate.
79
+ # `sentinels` are `currentStep` markers that are NOT steps: they never appear in `steps[]` and have no phase.
80
+ # >>> generated: lifecycle — from cli/lifecycle/defaults/1.json by scripts/lifecycle-config.mjs; do not edit by hand
81
+ parts: [Shape, Build, Run]
75
82
  profiles: [classic, analysis-first, chore, spike, discovery, foundation]
76
- # The PRODUCT level's phase (E75) — a ladder of its own, run once per product before any epic, and
77
- # part of no Part. `discovery` is listed because it is the old spelling of the same level.
78
83
  product_phases:
79
84
  - { id: foundation, name: Foundation, level: product, built: true, steps: [foundation, discovery] }
80
85
  phases:
@@ -82,10 +87,10 @@ lifecycle:
82
87
  - { id: design, name: Design, part: Shape, built: true, steps: [architecture, ui-design] }
83
88
  - { id: plan, name: Plan, part: Shape, built: true, steps: [stories, test-cases] }
84
89
  - { id: build, name: Build, part: Build, built: true, steps: [spec, tasks, implement, checks, engineer-review] }
85
- - { id: release, name: Release, part: Run, built: false, steps: [] } # E32 builds it
86
- - { id: operate, name: Operate, part: Run, built: false, steps: [] } # E33 builds it
87
- # `currentStep` markers that are NOT steps: they never appear in `steps[]` and have no phase.
90
+ - { id: release, name: Release, part: Run, built: false, steps: [] }
91
+ - { id: operate, name: Operate, part: Run, built: false, steps: [] }
88
92
  sentinels: [ready-for-build, backfill-pending, backfill-done, discovery-done, foundation-done]
93
+ # <<< generated: lifecycle
89
94
 
90
95
  defaults:
91
96
  # The two dials: who does the work, and who moves it forward. Renamed in shape 4; BOTH names are
@@ -197,7 +202,7 @@ build:
197
202
  # the separate security gate (a platform-Verified signature only; no author allowlist since E62). All blocking in CI; both repos + Product.
198
203
  pattern_gates: [commit-message, pr-title, pr-template]
199
204
  ci_platforms: [github, gitlab] # both wired from skills/yad-checks/templates/; GitHub is this product repo's platform
200
- contract_surface_glob: "specs/*/contracts/**" # the repo's quoted contract slice; a diff here needs Contract-Change + a re-locked contract
205
+ contract_surface_glob: "specs/*/contracts/**" # the repo's quoted contract slice; a diff here needs Contract-Change + a re-locked contract, unless it is an exact CONTRACT-QUOTE of the lock (#344)
201
206
  # Step D (yad-pr-template) — platform-matched PR/MR template + risk routing.
202
207
  pr_templates:
203
208
  github: ".github/pull_request_template.md"
@@ -350,7 +355,10 @@ product:
350
355
  # stops the file being updated — and nothing reads `kill_switch` now. `yad doctor` fails on one left `true`.
351
356
  automation:
352
357
  # The only steps that MAY be automated, safest-end first (phase-4-build-plan.md build order).
358
+ # The Build lane's author steps — every lane step but the merge gate, `engineer-review`.
359
+ # >>> generated: back_steps — from cli/lifecycle/defaults/1.json by scripts/lifecycle-config.mjs; do not edit by hand
353
360
  back_steps: [spec, tasks, implement, checks]
361
+ # <<< generated: back_steps
354
362
  default: human_approve # = `advance: human`. Every lane step starts manual; `yad dial` turns one to auto
355
363
 
356
364
  # Phase 6 (post-lock change management) — FEATURE THREADS. After the contract locks and code ships, a
@@ -58,7 +58,14 @@ follow the convention. Never finalise a boundary silently.
58
58
 
59
59
  ## The gate — `checks/backfill-check.sh`
60
60
 
61
- A change is blocked **only until the features it touches** have approved specs — not the whole repo:
61
+ A change is blocked **only until the features it touches** have approved specs — not the whole repo.
62
+ "The features it touches" are what merging the branch into the target would change (issue #363):
63
+ `git merge-tree --write-tree <base> HEAD` (git 2.38+), diffed from the target. A file that changed on the
64
+ target after the branch split off is not this branch's change; a file the target renamed into a feature
65
+ that the branch edits at its old path IS (the merge carries the edit there); and with several merge bases
66
+ nothing a hand-resolved merge undid is missed. A branch that does not merge cleanly, or a base that shares
67
+ no history with HEAD (a shallow clone), **FAILS** closed. An older git reads from the merge base and fails
68
+ closed on several merge bases, or when the target removed or moved a file the branch modifies.
62
69
 
63
70
  - For each `src/<feature>/` the diff touches, if `specs/backfill/<feature>/spec.md` exists it must be
64
71
  `verified: true`; otherwise **FAIL** (run backfill + approve for that feature first).