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.
@@ -0,0 +1,695 @@
1
+ // The lifecycle definition — the phases, steps and routes as one versioned JSON file (E134, the first row
2
+ // of the lifecycle spine; docs/roadmap-idea-1.md, "The lifecycle spine").
3
+ //
4
+ // WHERE THE LIFECYCLE LIVES NOW. yadflow ships its default as `cli/lifecycle/defaults/<n>.json`. Until
5
+ // E134 the same facts were lists written in `cli/epic-state.mjs` (`STEPS`, `LIFECYCLE_PROFILES`,
6
+ // `PHASES`, `PRODUCT_PHASES`, the Build order). Those names still exist, with the same contents, but they
7
+ // are now VIEWS of the default, built by the functions at the bottom of this file. A test compares each
8
+ // view, field by field and in key order, with a frozen copy of the lists as they stood before this row
9
+ // (`cli/fixtures/lifecycle-v4-catalogue.json`), so the move changed nothing the engine does.
10
+ //
11
+ // WHAT IS NOT READ YET. Nothing reads a team's own file in this row: `.sdlc/lifecycle.json` is E135. The
12
+ // validator below (`lifecycleProblems`) and the behaviour registry are built and tested now so the file
13
+ // format is settled before anyone can write one. Several fields of a step (`behaviours`, `inputs`,
14
+ // `extraPaths`, `provider`, `replaces`) are checked by the validator now; the engine starts to act on
15
+ // them in later rows (E136, E141).
16
+ //
17
+ // A PAST DEFAULT NEVER CHANGES. A team's file will say which default it was copied from (`extends:
18
+ // "yadflow-default@<n>"`), and `yad lifecycle upgrade` (E141) compares the old default, the team's file
19
+ // and the new default. That only works if `1.json` stays exactly what it was on the day it shipped. A
20
+ // change to the default is a new file, `2.json`. The release check refuses a release that edits a
21
+ // default an earlier release carried (scripts/release-check.sh).
22
+ //
23
+ // IT IS JSON, NOT AN IMPORT. The file is read with `fs` rather than `import … with { type: 'json' }`,
24
+ // because the published package supports Node 18, where that import form is not stable on every release.
25
+ import fs from 'node:fs';
26
+
27
+ // The newest shipped default — the one every reader uses until a team file exists (E135).
28
+ export const DEFAULT_VERSION = 1;
29
+
30
+ const DEFAULTS_DIR = new URL('./lifecycle/defaults/', import.meta.url);
31
+
32
+ // Every default this package ships, oldest first, as numbers. E141's three-way upgrade needs the old ones.
33
+ export function shippedDefaults() {
34
+ return fs.readdirSync(DEFAULTS_DIR).map((f) => /^([1-9]\d*)\.json$/.exec(f)?.[1]).filter(Boolean)
35
+ .map(Number).sort((a, b) => a - b);
36
+ }
37
+
38
+ // One shipped default, exactly as the file says (not normalized).
39
+ export function loadDefault(n = DEFAULT_VERSION) {
40
+ return JSON.parse(fs.readFileSync(new URL(`${n}.json`, DEFAULTS_DIR), 'utf8'));
41
+ }
42
+
43
+ // YADFLOW'S CLAIMS: every step yadflow has ever shipped, by its original id (`provider.origin`), with the
44
+ // files it claims — its artifact (path and type) and the files it commits beside it (`extraPaths`, such as
45
+ // the contract beside the architecture). Read from the shipped defaults, so the rule cannot drift from the
46
+ // data; a test ties these files to what the engine itself commits for each step (`stepPaths`, cli/fold.mjs).
47
+ //
48
+ // byOrigin origin -> { type, path, version, extras } (`version`: the newest `provider.version`
49
+ // shipped). A step that names a yadflow origin must name one of these (a step with no origin
50
+ // is matched by its id), or the upgrade merge (E141), which matches yadflow's steps by origin, would have
51
+ // nothing to match it to.
52
+ // byKey the key a review branch finds a file by (`artifactKey`) -> the origin that owns it. Once
53
+ // yadflow ships a name it stays reserved for that step, even in a file that deleted the step:
54
+ // the engine treats several of these names specially by name (`architecture` is hashed with
55
+ // the contract lock, `discovery` is read back as the discovery set), so another step taking
56
+ // one would be read the wrong way.
57
+ //
58
+ // Read when the validator first needs it, not when this module loads: every `yad` command imports this
59
+ // module, and only the validator needs the older defaults.
60
+ let claims = null;
61
+ export function yadflowClaims() {
62
+ if (claims) return claims;
63
+ const byOrigin = new Map();
64
+ const byKey = new Map();
65
+ for (const n of shippedDefaults()) {
66
+ for (const st of arr(loadDefault(n).steps)) {
67
+ if (!isObj(st) || st.provider?.id !== 'yadflow' || typeof st.provider.origin !== 'string') continue;
68
+ const o = st.provider.origin;
69
+ const art = isObj(st.artifact) && typeof st.artifact.path === 'string' ? st.artifact : null;
70
+ const extras = arr(st.extraPaths).filter((x) => typeof x === 'string');
71
+ const version = Math.max(byOrigin.get(o)?.version ?? 0, Number.isInteger(st.provider.version) ? st.provider.version : 0);
72
+ byOrigin.set(o, { type: art?.type ?? null, path: art?.path ?? null, version, extras: [...new Set([...(byOrigin.get(o)?.extras ?? []), ...extras])] });
73
+ for (const f of [art?.path, ...extras]) if (f) byKey.set(artifactKey(f), o);
74
+ }
75
+ }
76
+ claims = { byOrigin, byKey };
77
+ return claims;
78
+ }
79
+
80
+ // `currentStep` markers that are NOT steps: they never appear in `steps[]`, and no phase claims them.
81
+ // They stay in code on purpose (the roadmap's "What stays in code"): they describe an epic's state, not a
82
+ // step a team may define. They live in this file, not `epic-state.mjs`, because the validator needs them
83
+ // (a step may not be called `ready-for-build`) and `epic-state.mjs` imports this file; it re-exports
84
+ // them under the same name.
85
+ export const SENTINELS = ['ready-for-build', 'backfill-pending', 'backfill-done', 'discovery-done', 'foundation-done'];
86
+
87
+ // The values this release understands. A value outside these lists is not an error for the whole file:
88
+ // a team file may come from a newer yadflow, so a step using an unknown value is only marked unusable
89
+ // for new epics, and the rest of the file still loads (the roadmap's unknown-value rule).
90
+ export const STEP_KINDS = ['author', 'review'];
91
+ export const ARTIFACT_TYPES = ['file', 'folder', 'set'];
92
+ export const PHASE_RUNS = ['once', 'loop'];
93
+ export const PHASE_LEVELS = ['feature', 'product'];
94
+ export const PARTS = ['Shape', 'Build', 'Run'];
95
+
96
+ // THE BEHAVIOUR REGISTRY. A behaviour is something the engine does because of a step, not because of a
97
+ // step's name: the epic step is where the work-item type is read, the architecture step locks the
98
+ // contract, and so on. A team may rename, re-skill, move or make optional a step that carries one, but
99
+ // the rules below say what it may not do, because the engine and the CI checks depend on them.
100
+ // Only yadflow defines behaviours; a team cannot invent one.
101
+ //
102
+ // where which part of the lifecycle the step must sit in: `shape` (a Shape phase), `product` (the
103
+ // Foundation level), or `lane` (the Build loop).
104
+ // artifacts the artifact names a step with this behaviour may have. The engine and the CI checks read
105
+ // these files by name (until E136 at least), so moving the behaviour to a step with another
106
+ // file, or renaming the file, would leave them reading nothing. `product-level` allows two,
107
+ // because it sits on both `foundation` and the retired `discovery`.
108
+ // keepGate the step must keep its review gate. Every Shape and Foundation behaviour does, except
109
+ // `parallel-with-build`, whose step (test-cases) may drop it.
110
+ // review the step must be a standalone `review` step (the merge gate).
111
+ // route how many steps with this behaviour each route of that kind must hold: [min, max].
112
+ //
113
+ // What each behaviour DOES is still code in the engine (`advanceState`, the contract lock, …). E136 moves
114
+ // the engine from step ids to these names.
115
+ export const BEHAVIOURS = {
116
+ 'work-item-source': { where: 'shape', keepGate: true, artifacts: ['epic.md'], route: [1, 1] },
117
+ 'locks-contract': { where: 'shape', keepGate: true, artifacts: ['architecture.md'], route: [0, 1] },
118
+ 'ends-shape': { where: 'shape', keepGate: true, artifacts: ['stories/'], route: [1, 1] },
119
+ 'parallel-with-build': { where: 'shape', keepGate: false, artifacts: ['test-cases.md'], route: [0, 1] },
120
+ 'product-level': { where: 'product', keepGate: true, artifacts: ['foundation/', 'discovery/'], route: [1, 1] },
121
+ 'spec-source': { where: 'lane', keepGate: false, route: [1, 1] },
122
+ 'code-change': { where: 'lane', keepGate: false, route: [1, 1] },
123
+ 'ci-gates': { where: 'lane', keepGate: false, route: [1, 1] },
124
+ 'merge-gate': { where: 'lane', keepGate: false, review: true, route: [1, 1] },
125
+ };
126
+
127
+ // The second half of the same rule is yadflow's claims (`yadflowClaims`, above): a step yadflow ships keeps
128
+ // the files it shipped with even when a team takes its behaviour away. Until E136 the engine finds these
129
+ // files through step id literals (`'epic'`, `base === 'architecture'` in cli/epic-state.mjs), not through
130
+ // behaviours or `provider`. `provider.origin` is how the validator still recognises a yadflow step a team
131
+ // renamed, and a step whose id is one yadflow ships must say so (`provider: { id: "yadflow", origin: <its
132
+ // id> }`), so deleting the record cannot free its files.
133
+
134
+ // The keys this release knows at each level. Anything else is kept as it is and reported as a warning,
135
+ // so a file from a newer yadflow still loads.
136
+ export const KNOWN_KEYS = {
137
+ file: ['$schema', 'schemaVersion', 'extends', 'phases', 'steps', 'routes', 'plugins'],
138
+ phase: ['id', 'name', 'description', 'part', 'level', 'runs', 'over', 'built'],
139
+ step: ['id', 'name', 'description', 'phase', 'kind', 'artifact', 'optional', 'gate', 'skills', 'behaviours',
140
+ 'extraPaths', 'inputs', 'retired', 'replaces', 'provider'],
141
+ route: ['id', 'name', 'description', 'steps', 'bindings', 'retired', 'provider'],
142
+ gate: ['riskTags', 'skills'],
143
+ artifact: ['type', 'path', 'unit', 'files', 'optional', 'in'],
144
+ provider: ['id', 'version', 'origin'],
145
+ routeStep: ['id', 'optional'],
146
+ };
147
+
148
+ // The suffix the engine gives a gate it derives from an author step. It stays in code (rule 1 of the
149
+ // spine: a gate is never automatic, and its id is not something a team chooses).
150
+ export const GATE_SUFFIX = '-review';
151
+ export const gateIdOf = (id) => `${id}${GATE_SUFFIX}`;
152
+
153
+ const arr = (x) => (Array.isArray(x) ? x : []);
154
+ const isObj = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
155
+ const own = (o, k) => typeof k === 'string' && Object.hasOwn(o, k);
156
+ const isStrings = (x) => Array.isArray(x) && x.every((v) => typeof v === 'string');
157
+
158
+ const ID_RE = /^[a-z][a-z0-9-]*$/;
159
+
160
+ // A path inside the epic folder, as the engine joins it: no `..`, no leading `/` or drive letter, no
161
+ // backslash, no empty or `.` part. A folder may end in `/`.
162
+ export function cleanPath(p) {
163
+ if (typeof p !== 'string' || !p || p.includes('\\') || p.startsWith('/') || /^[a-z]:/i.test(p)) return false;
164
+ return p.replace(/\/$/, '').split('/').every((part) => part && part !== '.' && part !== '..');
165
+ }
166
+
167
+ // The key a review branch is found by: `review/EP-<slug>/<base>`. The same rule as `artifactBase` in
168
+ // cli/epic-state.mjs (which this module cannot import: that file imports this one), compared without
169
+ // letter case, because macOS and Windows file systems treat `Epic.md` and `epic.md` as one file.
170
+ // `stories/<anything>-S01.md` maps to `stories-s01`, which the engine reads back as the stories gate.
171
+ export function artifactKey(p) {
172
+ const a = String(p).replace(/\/$/, '');
173
+ const m = a.match(/stories\/.*?(S\d+)\.md$/i);
174
+ if (m) return `stories-${m[1]}`.toLowerCase();
175
+ return a.split('/').pop().replace(/\.md$/i, '').toLowerCase();
176
+ }
177
+
178
+ // The definition with every optional field filled in, so readers never have to ask "is it there". Unknown
179
+ // keys are kept as they are. The input is never changed; the result is a new object.
180
+ export function normalizeLifecycle(raw) {
181
+ const def = isObj(raw) ? raw : {};
182
+ return {
183
+ ...def,
184
+ phases: arr(def.phases).map((p) => ({
185
+ ...p,
186
+ runs: p?.runs ?? 'once',
187
+ over: arr(p?.over),
188
+ built: p?.built ?? true,
189
+ })),
190
+ steps: arr(def.steps).map((s) => ({
191
+ ...s,
192
+ artifact: s?.artifact ?? null,
193
+ optional: !!s?.optional,
194
+ gate: s?.gate ? { ...s.gate, riskTags: arr(s.gate.riskTags) } : null,
195
+ skills: arr(s?.skills),
196
+ behaviours: arr(s?.behaviours),
197
+ extraPaths: arr(s?.extraPaths),
198
+ inputs: arr(s?.inputs),
199
+ retired: !!s?.retired,
200
+ })),
201
+ routes: arr(def.routes).map((r) => ({
202
+ ...r,
203
+ steps: arr(r?.steps).map((x) => (typeof x === 'string' ? { id: x } : { ...x })),
204
+ bindings: isObj(r?.bindings) ? r.bindings : {},
205
+ retired: !!r?.retired,
206
+ })),
207
+ plugins: arr(def.plugins),
208
+ };
209
+ }
210
+
211
+ // Where a phase sits: `product` (the Foundation level), `lane` (the Build loop — the Build part's loop
212
+ // phase), `shape` (a Shape phase), or `run` (Release, Operate). The lane is told apart by its part, not by
213
+ // `runs: loop` alone, because Release loops too (over releases) and is not the Build lane.
214
+ //
215
+ // A Build phase whose `runs` is a value this release does not know still counts as the lane: its steps
216
+ // are reported unusable, and the rest of the file keeps its one lane (the unknown-value rule).
217
+ function phaseWhere(p) {
218
+ if (!p) return null;
219
+ if (p.level === 'product') return 'product';
220
+ if (p.part === 'Build') return p.runs === 'once' ? null : 'lane';
221
+ if (p.part === 'Shape') return 'shape';
222
+ return p.part === 'Run' ? 'run' : null;
223
+ }
224
+
225
+ // Which kind of route this is, worked out from the phases of its steps (a route has no `level` field):
226
+ // `product` (the Foundation level), `lane` (the Build loop), `feature` (the Shape phases), `run` (the Run
227
+ // phases, none built yet), or null when its steps mix two of those, or name a step or phase that does
228
+ // not exist.
229
+ export function routeKind(def, route) {
230
+ const phase = new Map(def.phases.map((p) => [p.id, p]));
231
+ const step = new Map(def.steps.map((s) => [s.id, s]));
232
+ const kinds = new Set(route.steps.map((x) => {
233
+ const w = phaseWhere(phase.get(step.get(x.id)?.phase));
234
+ return w === 'shape' ? 'feature' : w;
235
+ }));
236
+ return kinds.size === 1 && !kinds.has(null) ? [...kinds][0] : null;
237
+ }
238
+
239
+ // Where a step sits, in the registry's words. Null when its phase is unknown.
240
+ const stepWhere = (def, s) => phaseWhere(def.phases.find((x) => x.id === s.phase));
241
+
242
+ // A `provider` record: who ships the step or route, which version of their lifecycle, and the step's
243
+ // original id. Every field is optional, but each has one type.
244
+ const PROVIDER_SHAPE = '"provider" must be { "id": text, "version": a whole number, "origin": text }';
245
+ const providerOk = (p) => isObj(p) && (p.id === undefined || typeof p.id === 'string')
246
+ && (p.version === undefined || Number.isInteger(p.version)) && (p.origin === undefined || typeof p.origin === 'string');
247
+
248
+ // THE VALIDATOR. Every problem with a lifecycle definition, as a list. An empty list means the file can
249
+ // be used as it is. Hand-written on purpose: the package has no runtime dependencies, and each rule says
250
+ // why it exists in a sentence a person can act on.
251
+ //
252
+ // Each problem is `{ level, where, message }`:
253
+ // error the file cannot be used.
254
+ // unusable one step (or route) uses a value this release does not know; it cannot be used for new
255
+ // epics, and the rest of the file still loads.
256
+ // warn an unknown key, kept as it is, or a reference that names nothing where nothing breaks.
257
+ // `where` names the place: `file`, `phase <id>`, `step <id>` or `route <id>`.
258
+ export function lifecycleProblems(raw) {
259
+ const out = [];
260
+ const add = (level, where, message) => out.push({ level, where, message });
261
+ if (!isObj(raw)) {
262
+ add('error', 'file', 'the lifecycle definition must be a JSON object');
263
+ return out;
264
+ }
265
+ const def = normalizeLifecycle(raw);
266
+ // An unknown key is kept and warned about, at every level — a nested object (`gate`, `artifact`,
267
+ // `provider`, a route's step entry) included, so a field a newer yadflow adds is never silently ignored.
268
+ const NESTED = { gate: ' in "gate"', artifact: ' in "artifact"', provider: ' in "provider"', routeStep: ' in a route step' };
269
+ const unknownKeys = (obj, level, where) => {
270
+ if (!isObj(obj)) return;
271
+ for (const k of Object.keys(obj)) if (!KNOWN_KEYS[level].includes(k)) add('warn', where, `unknown key "${k}"${NESTED[level] ?? ''} is kept and not read`);
272
+ };
273
+
274
+ // The file.
275
+ unknownKeys(raw, 'file', 'file');
276
+ if (!Number.isInteger(raw.schemaVersion)) add('error', 'file', '"schemaVersion" must be a whole number (the project\'s file shape)');
277
+ if (raw.extends !== undefined && !(typeof raw.extends === 'string' && /^yadflow-default@[1-9]\d*$/.test(raw.extends))) {
278
+ add('error', 'file', '"extends" must look like "yadflow-default@<n>", naming the shipped default the file was copied from');
279
+ }
280
+ for (const key of ['phases', 'steps', 'routes']) {
281
+ if (!Array.isArray(raw[key])) add('error', 'file', `"${key}" must be a list`);
282
+ }
283
+ if (raw.plugins !== undefined && !Array.isArray(raw.plugins)) add('error', 'file', '"plugins" must be a list');
284
+
285
+ // Phases.
286
+ const phaseIds = new Set();
287
+ for (const [i, p] of arr(raw.phases).entries()) {
288
+ const where = `phase ${p?.id ?? `#${i + 1}`}`;
289
+ if (!isObj(p) || typeof p.id !== 'string' || !p.id) { add('error', where, 'a phase needs an "id"'); continue; }
290
+ unknownKeys(p, 'phase', where);
291
+ if (!ID_RE.test(p.id)) add('error', where, 'a phase id is lower-case letters, digits and dashes, starting with a letter');
292
+ if (typeof p.name !== 'string' || !p.name) add('error', where, 'a phase needs a "name"');
293
+ if (phaseIds.has(p.id)) add('error', where, 'two phases share this id');
294
+ phaseIds.add(p.id);
295
+ if (!PHASE_LEVELS.includes(p.level)) add('error', where, `"level" must be one of: ${PHASE_LEVELS.join(', ')}`);
296
+ if (p.level === 'feature' && !PARTS.includes(p.part)) add('error', where, `a feature phase needs a "part": ${PARTS.join(', ')}`);
297
+ if (p.level === 'product' && p.part !== undefined) add('error', where, 'a product phase belongs to no part, so it has no "part"');
298
+ if (p.description !== undefined && typeof p.description !== 'string') add('error', where, '"description" must be text');
299
+ if (p.runs !== undefined && typeof p.runs !== 'string') add('error', where, '"runs" must be a word: once or loop');
300
+ else if (p.runs !== undefined && !PHASE_RUNS.includes(p.runs)) add('unusable', where, `"runs" is "${p.runs}", which this yadflow does not know; its steps cannot be used for new epics`);
301
+ if (p.part === 'Build' && def.phases[i].runs === 'once') add('error', where, 'a Build phase runs in a loop (over each story and repo), so its "runs" is "loop"');
302
+ if (p.over !== undefined && !isStrings(p.over)) add('error', where, '"over" must be a list of words');
303
+ if (p.runs === 'loop' && arr(p.over).length === 0) add('error', where, 'a loop phase needs "over" (what it loops over, such as "story" and "repo")');
304
+ if (p.built !== undefined && typeof p.built !== 'boolean') add('error', where, '"built" must be true or false');
305
+ }
306
+ const unknownRuns = new Set(def.phases.filter((p) => !PHASE_RUNS.includes(p.runs)).map((p) => p.id));
307
+
308
+ // Steps.
309
+ const stepById = new Map();
310
+ const claimsList = [];
311
+ const origins = new Map();
312
+ const folders = [];
313
+ const allPaths = [];
314
+ for (const [i, s] of arr(raw.steps).entries()) {
315
+ const where = `step ${s?.id ?? `#${i + 1}`}`;
316
+ if (!isObj(s) || typeof s.id !== 'string') { add('error', where, 'a step needs an "id"'); continue; }
317
+ const n = def.steps[i];
318
+ unknownKeys(s, 'step', where);
319
+ unknownKeys(s.gate, 'gate', where);
320
+ unknownKeys(s.artifact, 'artifact', where);
321
+ unknownKeys(s.provider, 'provider', where);
322
+ if (!ID_RE.test(s.id)) add('error', where, 'a step id is lower-case letters, digits and dashes, starting with a letter');
323
+ if (/-s\d+$/.test(s.id)) add('error', where, 'a step id must not end like a story id (-s01)');
324
+ if (SENTINELS.includes(s.id)) add('error', where, `"${s.id}" is a word the engine uses for an epic's state, not a step`);
325
+ if (typeof s.name !== 'string' || !s.name) add('error', where, 'a step needs a "name"');
326
+ if (stepById.has(s.id)) add('error', where, 'two steps share this id');
327
+ stepById.set(s.id, n);
328
+ // A wrong type is reported, never quietly read as empty: `skills: "yad-epic"` would otherwise lose
329
+ // the step its skill without a word.
330
+ for (const key of ['skills', 'behaviours', 'extraPaths', 'inputs']) {
331
+ if (s[key] !== undefined && !(isStrings(s[key]) && s[key].every(Boolean))) add('error', where, `"${key}" must be a list of names, none of them empty`);
332
+ }
333
+ for (const key of ['optional', 'retired']) {
334
+ if (s[key] !== undefined && typeof s[key] !== 'boolean') add('error', where, `"${key}" must be true or false`);
335
+ }
336
+ if (s.replaces !== undefined && typeof s.replaces !== 'string') add('error', where, '"replaces" must be a step id');
337
+ if (s.description !== undefined && typeof s.description !== 'string') add('error', where, '"description" must be text');
338
+ if (s.provider !== undefined && !providerOk(s.provider)) add('error', where, PROVIDER_SHAPE);
339
+ if (!phaseIds.has(s.phase)) add('error', where, `its phase "${s.phase}" does not exist`);
340
+ else if (unknownRuns.has(s.phase)) add('unusable', where, `its phase "${s.phase}" uses a "runs" value this yadflow does not know`);
341
+
342
+ if (typeof s.kind !== 'string') add('error', where, `a step needs a "kind": ${STEP_KINDS.join(' or ')}`);
343
+ else if (!STEP_KINDS.includes(s.kind)) {
344
+ add('unusable', where, `"kind" is "${s.kind}", which this yadflow does not know; the step cannot be used for new epics`);
345
+ } else if (s.kind === 'author' && s.id.endsWith(GATE_SUFFIX)) {
346
+ add('error', where, `an author step id must not end in "${GATE_SUFFIX}": that ending belongs to the gate the engine adds`);
347
+ }
348
+ if (s.kind === 'review' && n.gate) add('error', where, 'a review step is a gate on its own, so its "gate" must be null');
349
+ if (s.kind === 'review' && n.artifact !== null) add('error', where, 'a review step reviews the work before it and writes no artifact of its own, so its "artifact" is null');
350
+ if (s.gate !== undefined && s.gate !== null && (!isObj(s.gate) || (s.gate.riskTags !== undefined && !isStrings(s.gate.riskTags))
351
+ || (s.gate.skills !== undefined && !isStrings(s.gate.skills)))) {
352
+ add('error', where, '"gate" must be null or { "riskTags": [ … ], "skills": [ … ] }');
353
+ }
354
+
355
+ if (n.artifact !== null) {
356
+ const a = n.artifact;
357
+ if (!isObj(a) || typeof a.path !== 'string' || !a.path || typeof a.type !== 'string') {
358
+ add('error', where, '"artifact" must be null or { "type", "path", … }');
359
+ } else {
360
+ if (!ARTIFACT_TYPES.includes(a.type)) add('unusable', where, `artifact type "${a.type}" is one this yadflow does not know; the step cannot be used for new epics`);
361
+ if (a.type === 'set' && !isStrings(a.files)) add('error', where, 'a "set" artifact lists its "files" by name');
362
+ if (a.unit !== undefined && typeof a.unit !== 'string') add('error', where, 'an artifact\'s "unit" is one word, such as "story"');
363
+ if (a.in !== undefined && a.in !== 'product') {
364
+ if (a.in === 'repo') add('unusable', where, 'an artifact kept in a code repo ("in": "repo") is reserved; this yadflow cannot use the step for new epics');
365
+ else add('error', where, 'an artifact\'s "in" is "product" or "repo"');
366
+ }
367
+ if (a.type === 'set' && a.optional !== undefined && !(isStrings(a.optional) && a.optional.every((f) => arr(a.files).includes(f)))) {
368
+ add('error', where, 'a "set" artifact\'s "optional" lists some of its "files"');
369
+ }
370
+ }
371
+ }
372
+ // THE FILES A STEP CLAIMS: its artifact, its `extraPaths`, and — for a `set` — each file the set lists
373
+ // (the engine commits those as the step's files, directly in the epic folder). Each must be a clean
374
+ // path inside the epic folder; a `.sdlc` path is ledger unless it is exactly a path yadflow ships for
375
+ // this step's origin; a name yadflow ships
376
+ // belongs to that yadflow step only; and no two steps may claim files a review branch finds by one key
377
+ // (`artifactKey`), or they would share one gate (checked after every step is read, below).
378
+ const isYadflow = isObj(s.provider) && s.provider.id === 'yadflow';
379
+ const origin = isYadflow && typeof s.provider.origin === 'string' ? s.provider.origin : null;
380
+ const { byOrigin, byKey } = yadflowClaims();
381
+ const artPath = isObj(n.artifact) && typeof n.artifact.path === 'string' && n.artifact.path ? n.artifact.path : null;
382
+ // A step from a newer yadflow — a `provider.version` this release never shipped for its origin, or an
383
+ // origin this release does not know at all — or with an artifact type this release does not know may
384
+ // have moved its files on purpose. Every rule about which names it may claim (reserved names, the
385
+ // ledger, the behaviour's names, the files it shipped with) then reports it unusable here, never a
386
+ // broken file (the unknown-value rule). The shape rules (a clean path, no name twice, no story-like
387
+ // name) and the rules between two steps stay errors.
388
+ const shippedVersion = origin !== null ? byOrigin.get(origin)?.version : undefined;
389
+ const newer = (origin !== null && shippedVersion === undefined)
390
+ || (shippedVersion !== undefined && Number.isInteger(s.provider.version) && s.provider.version > shippedVersion)
391
+ || (isObj(n.artifact) && !ARTIFACT_TYPES.includes(n.artifact.type));
392
+ const level = newer ? 'unusable' : 'error';
393
+ const extras = isStrings(s.extraPaths) ? s.extraPaths : [];
394
+ for (const x of extras) if (x.endsWith('/')) add('error', where, `"${x}" in "extraPaths" is a folder; list the files, or make the folder the step's artifact`);
395
+ const isSet = n.artifact?.type === 'set';
396
+ const members = isSet && isStrings(n.artifact.files) ? n.artifact.files : [];
397
+ if (isSet && isStrings(n.artifact.files) && members.length === 0) add('error', where, 'a "set" artifact lists at least one file');
398
+ for (const f of members) if (f.includes('/')) add('error', where, `"${f}" in a set's "files" is a file name: the set's files sit directly in its epic folder`);
399
+ const stepLevel = def.phases.find((x) => x.id === s.phase)?.level ?? null;
400
+ const productSet = isSet && stepLevel === 'product';
401
+ const ownFiles = new Set();
402
+ for (const [claimed, member] of [[artPath, false], ...extras.map((x) => [x, false]), ...members.map((x) => [x, true])]) {
403
+ if (claimed === null) continue;
404
+ if (!cleanPath(claimed)) { add('error', where, `"${claimed}" must be a path inside the epic folder: not empty, no "..", no leading "/", no "\\"`); continue; }
405
+ // One step naming one file twice (`a.md` and `A.md` are one file on macOS and Windows) would count it twice.
406
+ const bareOwn = claimed.replace(/\/$/, '').toLowerCase();
407
+ if (ownFiles.has(bareOwn)) add('error', where, `"${claimed}" is listed twice among this step's files (letter case ignored)`);
408
+ ownFiles.add(bareOwn);
409
+ if (claimed === artPath && n.artifact.type === 'file' && claimed.endsWith('/')) add('error', where, `"${claimed}" is a file, so it does not end in "/"`);
410
+ const key = artifactKey(claimed);
411
+ if (/-s\d+$/.test(key)) add('error', where, `"${claimed}" is named like a story (-S01), which the engine reads as the stories gate`);
412
+ const reservedFor = byKey.get(key);
413
+ const bare = claimed.replace(/\/$/, '').toLowerCase();
414
+ if (reservedFor !== undefined && reservedFor !== origin) {
415
+ add(level, where, `"${claimed}" is a file of yadflow's "${reservedFor}" step (found as "${key}"); only that step may claim it`);
416
+ }
417
+ // The ledger folder: only the exact `.sdlc/` paths yadflow ships for this step's origin are allowed,
418
+ // never another path that merely shares their review key (`.sdlc/x/contract.md`).
419
+ const shippedPaths = origin !== null && byOrigin.has(origin)
420
+ ? [byOrigin.get(origin).path, ...byOrigin.get(origin).extras].filter(Boolean).map((x) => x.toLowerCase()) : [];
421
+ if ((bare === '.sdlc' || bare.startsWith('.sdlc/')) && !shippedPaths.includes(claimed.toLowerCase())) {
422
+ add(level, where, `"${claimed}" is in .sdlc/, which holds the ledger; a step's files live beside it`);
423
+ }
424
+ claimsList.push({ step: s.id, where, path: claimed, key, level: stepLevel, member, productSet });
425
+ }
426
+ if (n.artifact?.type === 'folder' && artPath) folders.push({ step: s.id, level: stepLevel, prefix: artPath.replace(/\/?$/, '/').toLowerCase() });
427
+ allPaths.push(...[artPath, ...extras].filter((x) => typeof x === 'string').map((x) => ({ step: s.id, level: stepLevel, path: x })));
428
+
429
+ // Behaviours.
430
+ const at = stepWhere(def, n);
431
+ for (const b of n.behaviours) {
432
+ if (!own(BEHAVIOURS, b)) { add('unusable', where, `behaviour "${b}" is one this yadflow does not know; the step cannot be used for new epics`); continue; }
433
+ const rule = BEHAVIOURS[b];
434
+ if (at !== rule.where) add('error', where, `behaviour "${b}" belongs in ${rule.where === 'shape' ? 'a Shape phase' : rule.where === 'product' ? 'the product level' : 'the Build loop'}`);
435
+ if (rule.keepGate && !n.gate) add('error', where, `behaviour "${b}" needs the step to keep its review gate`);
436
+ if (rule.review && s.kind !== 'review') add('error', where, `behaviour "${b}" must stay a "review" step: it is the merge gate`);
437
+ if (rule.artifacts && !rule.artifacts.includes(n.artifact?.path)) {
438
+ add(level, where, `behaviour "${b}" needs the artifact ${rule.artifacts.map((x) => `"${x}"`).join(' or ')}: the engine and the CI checks read it by that name`);
439
+ }
440
+ }
441
+
442
+ // yadflow's own steps: a step whose id is one yadflow ships says so; a known origin is used once and
443
+ // keeps the artifact (path and type) and the extra files it shipped with. An origin this release does
444
+ // not know is from a newer yadflow: that step is unusable here, and the rest of the file still loads.
445
+ if (byOrigin.has(s.id) && origin !== s.id) {
446
+ add('error', where, `"${s.id}" is a step yadflow ships, so it keeps "provider": { "id": "yadflow", "origin": "${s.id}" } — to make a step of your own, give it another id`);
447
+ }
448
+ if (origin !== null) {
449
+ const shipped = byOrigin.get(origin);
450
+ if (!shipped) add('unusable', where, `"provider.origin" is "${origin}", a yadflow step this release does not know; the step cannot be used for new epics`);
451
+ else {
452
+ if (origins.has(origin)) add('error', where, `step ${origins.get(origin)} already has the origin "${origin}"; each yadflow step appears once`);
453
+ else origins.set(origin, s.id);
454
+ if (artPath !== shipped.path || (n.artifact?.type ?? null) !== shipped.type) {
455
+ add(level, where, shipped.path ? `its artifact must stay "${shipped.path}" (a ${shipped.type}): the engine and the CI checks read it by that name` : 'its artifact must stay null: yadflow\'s step writes code in a repo, not a file here');
456
+ }
457
+ for (const x of shipped.extras) if (!extras.includes(x)) add(level, where, `its "extraPaths" must keep "${x}": the engine commits it with this step's review`);
458
+ }
459
+ }
460
+
461
+ // A Build-loop step has no gate of its own and is never optional: the lane walks its route in order,
462
+ // and the human merge gate is a step of its own (`engineer-review`), never skipped.
463
+ if (stepWhere(def, n) === 'lane') {
464
+ if (n.gate) add('error', where, 'a Build-loop step has no "gate": the lane\'s review is its merge-gate step');
465
+ if (n.optional) add('error', where, 'a Build-loop step is never optional: the lane walks every step in order');
466
+ }
467
+ }
468
+ // No two steps claim files a review branch finds by one key. A set's member files live in that set's own
469
+ // epic folder, so they are compared only with steps at the same level — and two product-level sets
470
+ // (the Foundation and the retired Discovery, each its own folder) never with each other. Reported on the
471
+ // later of the two steps in the file.
472
+ for (const [j, c] of claimsList.entries()) {
473
+ const first = claimsList.slice(0, j).find((o) => o.step !== c.step && o.key === c.key
474
+ && !(o.productSet && c.productSet && o.member && c.member)
475
+ && (!(o.member || c.member) || o.level === c.level));
476
+ if (first) {
477
+ add('error', c.where, (c.member || first.member)
478
+ ? `"${c.path}" is the same file as step ${first.step}'s "${first.path}" (letter case ignored); two steps cannot write one file`
479
+ : `"${c.path}" is found by the same name as step ${first.step}'s "${first.path}" ("${c.key}", letter case ignored); two steps cannot share one, or they would share one review`);
480
+ }
481
+ }
482
+ // A file inside another step's folder belongs to that folder's review (the stories gate hashes every
483
+ // file under `stories/`), so no other step at the same level may claim one there — checked both ways,
484
+ // whatever the order. A product step and a feature step live in different epic folders on disk.
485
+ for (const f of folders) {
486
+ for (const x of allPaths) {
487
+ if (x.step !== f.step && x.level === f.level && x.path.toLowerCase().startsWith(f.prefix)) {
488
+ add('error', `step ${x.step}`, `"${x.path}" is inside step ${f.step}'s folder "${f.prefix}", whose review covers every file in it`);
489
+ }
490
+ }
491
+ }
492
+ // The gate the engine derives must not take a name another step already has.
493
+ for (const s of def.steps) {
494
+ if (s.kind === 'author' && s.gate && stepById.has(gateIdOf(s.id))) {
495
+ add('error', `step ${s.id}`, `its gate would be called "${gateIdOf(s.id)}", which is already a step`);
496
+ }
497
+ // A team may delete a retired step; the record of what replaced it then names nothing, which harms nothing.
498
+ if (typeof s.replaces === 'string' && !stepById.has(s.replaces)) add('warn', `step ${s.id}`, `it replaces "${s.replaces}", which is not a step in this file`);
499
+ for (const input of isStrings(s.inputs) ? s.inputs : []) {
500
+ if (!stepById.has(input)) add('warn', `step ${s.id}`, `its input "${input}" is not a step in this file`);
501
+ }
502
+ }
503
+
504
+ // Routes.
505
+ const routeIds = new Set();
506
+ let lanes = 0;
507
+ for (const [i, r] of arr(raw.routes).entries()) {
508
+ const where = `route ${r?.id ?? `#${i + 1}`}`;
509
+ if (!isObj(r) || typeof r.id !== 'string' || !r.id) { add('error', where, 'a route needs an "id"'); continue; }
510
+ const n = def.routes[i];
511
+ unknownKeys(r, 'route', where);
512
+ unknownKeys(r.provider, 'provider', where);
513
+ if (Array.isArray(r.steps)) for (const x of r.steps) unknownKeys(x, 'routeStep', where);
514
+ if (!ID_RE.test(r.id)) add('error', where, 'a route id is lower-case letters, digits and dashes, starting with a letter');
515
+ if (typeof r.name !== 'string' || !r.name) add('error', where, 'a route needs a "name"');
516
+ if (routeIds.has(r.id)) add('error', where, 'two routes share this id');
517
+ routeIds.add(r.id);
518
+ if (r.bindings !== undefined && !isObj(r.bindings)) add('error', where, '"bindings" must be an object');
519
+ if (r.retired !== undefined && typeof r.retired !== 'boolean') add('error', where, '"retired" must be true or false');
520
+ if (r.description !== undefined && typeof r.description !== 'string') add('error', where, '"description" must be text');
521
+ if (r.provider !== undefined && !providerOk(r.provider)) add('error', where, PROVIDER_SHAPE);
522
+ if (!Array.isArray(r.steps)) { add('error', where, '"steps" must be a list'); continue; }
523
+ const bad = r.steps.filter((x) => !(typeof x === 'string' || (isObj(x) && typeof x.id === 'string'
524
+ && (x.optional === undefined || typeof x.optional === 'boolean'))));
525
+ if (bad.length) { add('error', where, 'each step is a step id, or { "id": "<step>", "optional": true | false }'); continue; }
526
+ if (n.steps.length === 0) { add('error', where, 'a route needs at least one step'); continue; }
527
+ const seen = new Set();
528
+ let missing = false;
529
+ for (const x of n.steps) {
530
+ if (!stepById.has(x.id)) { add('error', where, `step "${x.id}" does not exist`); missing = true; }
531
+ if (seen.has(x.id)) add('error', where, `step "${x.id}" is listed twice`);
532
+ seen.add(x.id);
533
+ }
534
+ if (missing) continue;
535
+ // A route new epics take cannot hold a step that is never seeded for new epics.
536
+ if (!n.retired) for (const x of n.steps) if (stepById.get(x.id).retired) add('error', where, `step "${x.id}" is retired, so only a retired route may list it`);
537
+ // A step whose phase does not exist is already reported on the step; the route says nothing more.
538
+ if (n.steps.some((x) => !stepWhere(def, stepById.get(x.id)))) continue;
539
+ const kind = routeKind(def, n);
540
+ if (!kind) { add('error', where, 'its steps mix the product level, the Shape phases, the Build loop and the Run phases; a route stays in one'); continue; }
541
+ if (kind === 'lane') {
542
+ lanes += 1;
543
+ if (n.steps.some((x) => x.optional !== undefined)) add('error', where, 'the Build lane walks every step in order, so its steps carry no "optional"');
544
+ }
545
+ // Each behaviour's route rule, for the routes of its kind.
546
+ const scope = { shape: 'feature', product: 'product', lane: 'lane' };
547
+ for (const [b, rule] of Object.entries(BEHAVIOURS)) {
548
+ if (scope[rule.where] !== kind) continue;
549
+ const count = n.steps.filter((x) => stepById.get(x.id).behaviours.includes(b)).length;
550
+ const [min, max] = rule.route;
551
+ if (count < min || count > max) {
552
+ const want = min === max ? `exactly ${min}` : `at most ${max}`;
553
+ add('error', where, `a ${kind} route needs ${want} step with behaviour "${b}"; it has ${count}`);
554
+ }
555
+ }
556
+ }
557
+ if (lanes !== 1) add('error', 'file', `there must be exactly one Build lane route (a route whose steps are in the Build part's loop phase); there are ${lanes}`);
558
+ return out;
559
+ }
560
+
561
+ // ---- the views ---------------------------------------------------------------------------------------
562
+ //
563
+ // The shapes the engine has always read, built from a definition. Each one keeps the fields, the key
564
+ // order and the array order of the list it replaces, which the frozen-fixture test holds.
565
+
566
+ // The step catalogue, as `STEPS` (cli/epic-state.mjs). An author step with a gate becomes two rows: the
567
+ // step, then its gate `<id>-review` right after it. The gate row carries `reviews` (the step it gates) and
568
+ // the gate's risk tags; it has no skill, because `yad gate` drives Shape reviews. A standalone review step
569
+ // (`engineer-review`) is one row with its skill and no `reviews`.
570
+ export function expandSteps(def) {
571
+ const level = new Map(def.phases.map((p) => [p.id, p.level]));
572
+ const rows = [];
573
+ for (const s of def.steps) {
574
+ const artifact = s.artifact ? s.artifact.path : null;
575
+ const row = { id: s.id, phase: s.phase, kind: s.kind, artifact };
576
+ if (s.skills.length) row.skill = s.skills[0];
577
+ rows.push({ ...row, level: level.get(s.phase), risk_tags: [] });
578
+ if (s.kind === 'author' && s.gate) {
579
+ rows.push({ id: gateIdOf(s.id), phase: s.phase, kind: 'review', artifact, reviews: s.id, level: level.get(s.phase), risk_tags: [...s.gate.riskTags] });
580
+ }
581
+ }
582
+ return rows;
583
+ }
584
+
585
+ // The routes an epic can take, as `LIFECYCLE_PROFILES`. The Build lane is not one of them: an epic does not
586
+ // walk it, each story walks it in each repo. A step is optional on a route when the route says so, or,
587
+ // when the route says nothing, when the step says so (decision 2: the route wins). A non-optional step is
588
+ // written as its bare id, an optional one as `{ id, optional: true }`, and its gate follows the same way.
589
+ export function expandRoutes(def) {
590
+ const step = new Map(def.steps.map((s) => [s.id, s]));
591
+ return def.routes.filter((r) => routeKind(def, r) !== 'lane').map((r) => ({
592
+ id: r.id,
593
+ title: r.name,
594
+ level: routeKind(def, r),
595
+ steps: r.steps.flatMap((x) => {
596
+ const s = step.get(x.id);
597
+ const optional = x.optional ?? s.optional;
598
+ const ids = s.kind === 'author' && s.gate ? [s.id, gateIdOf(s.id)] : [s.id];
599
+ return ids.map((id) => (optional ? { id, optional: true } : id));
600
+ }),
601
+ }));
602
+ }
603
+
604
+ // The feature phases, as `PHASES`: the six-phase strip, Discover to Operate.
605
+ export const featurePhases = (def) => def.phases.filter((p) => p.level === 'feature')
606
+ .map((p) => ({ id: p.id, name: p.name, part: p.part, built: p.built }));
607
+
608
+ // The product level's phases, as `PRODUCT_PHASES`: the Foundation.
609
+ export const productPhases = (def) => def.phases.filter((p) => p.level === 'product')
610
+ .map((p) => ({ id: p.id, name: p.name, level: p.level, built: p.built }));
611
+
612
+ // The Build lane's order, as `BUILD_STEP_ORDER`: the steps one story walks in one repo.
613
+ export function laneOrder(def) {
614
+ const lane = def.routes.find((r) => routeKind(def, r) === 'lane');
615
+ return lane ? lane.steps.map((x) => x.id) : [];
616
+ }
617
+
618
+ // The lane steps that may ever be automated: every one but the review steps (the merge gate is locked to a
619
+ // human). `config.yaml`'s `automation.back_steps` is generated from this.
620
+ export function laneAuthorSteps(def) {
621
+ const step = new Map(def.steps.map((s) => [s.id, s]));
622
+ return laneOrder(def).filter((id) => step.get(id)?.kind === 'author');
623
+ }
624
+
625
+ // The shipped default, normalized — what every reader uses in this release.
626
+ export const DEFAULT_LIFECYCLE = normalizeLifecycle(loadDefault(DEFAULT_VERSION));
627
+
628
+ // ---- the copy in skills/sdlc/config.yaml ---------------------------------------------------------------
629
+ //
630
+ // `config.yaml` carries the phase table, the route ids, the sentinels and the steps that may be automated,
631
+ // for the skills and for people to read. They are GENERATED from the default, never typed: each generated
632
+ // part sits between two marker lines, and only the lines between them are ever replaced
633
+ // (`scripts/lifecycle-config.mjs`). A test fails when the file and the default disagree.
634
+ //
635
+ // # >>> generated: <name> — … the begin marker, with a note saying not to edit by hand
636
+ // # <<< generated: <name> the end marker
637
+ //
638
+ // The markers bound the region, so nothing has to guess where a YAML block ends.
639
+ export const CONFIG_REGIONS = ['lifecycle', 'back_steps'];
640
+ const BEGIN = (name) => `# >>> generated: ${name} — from cli/lifecycle/defaults/${DEFAULT_VERSION}.json by scripts/lifecycle-config.mjs; do not edit by hand`;
641
+ const END = (name) => `# <<< generated: ${name}`;
642
+
643
+ // Inline YAML maps in aligned columns, one per line, the way the table has always been laid out.
644
+ function alignedRows(rows) {
645
+ const keys = Object.keys(rows[0] ?? {});
646
+ const cell = (k, v) => `${k}: ${Array.isArray(v) ? `[${v.join(', ')}]` : v}`;
647
+ const width = Object.fromEntries(keys.map((k) => [k, Math.max(...rows.map((r) => cell(k, r[k]).length))]));
648
+ return rows.map((r) => `- { ${keys.map((k, i) => (i === keys.length - 1 ? cell(k, r[k]) : `${cell(k, r[k])},`.padEnd(width[k] + 1))).join(' ')} }`);
649
+ }
650
+
651
+ // Each region's lines, without indentation, for one definition.
652
+ export function configRegions(def) {
653
+ const rows = expandSteps(def).filter((r) => !r.reviews);
654
+ const stepsOf = (phase) => rows.filter((r) => r.phase === phase).map((r) => r.id);
655
+ const features = featurePhases(def);
656
+ return {
657
+ lifecycle: [
658
+ `parts: [${[...new Set(features.map((p) => p.part))].join(', ')}]`,
659
+ `profiles: [${expandRoutes(def).map((r) => r.id).join(', ')}]`,
660
+ 'product_phases:',
661
+ ...alignedRows(productPhases(def).map((p) => ({ ...p, steps: stepsOf(p.id) }))).map((l) => ` ${l}`),
662
+ 'phases:',
663
+ ...alignedRows(features.map((p) => ({ ...p, steps: stepsOf(p.id) }))).map((l) => ` ${l}`),
664
+ `sentinels: [${SENTINELS.join(', ')}]`,
665
+ ],
666
+ back_steps: [`back_steps: [${laneAuthorSteps(def).join(', ')}]`],
667
+ };
668
+ }
669
+
670
+ // The file's text with every region rewritten from `def`. Returns the new text, the regions whose lines
671
+ // changed (`stale`), and why a region could not be found (`refused`). A refused file is returned unchanged.
672
+ //
673
+ // A file checked out with Windows line endings (CRLF) is read without them and written back with them,
674
+ // so the comparison is about the content, never the line endings.
675
+ export function applyConfigRegions(text, def = DEFAULT_LIFECYCLE) {
676
+ const eol = text.includes('\r\n') ? '\r\n' : '\n';
677
+ const lines = text.split(/\r?\n/);
678
+ const regions = configRegions(def);
679
+ const stale = [];
680
+ const refused = [];
681
+ for (const name of CONFIG_REGIONS) {
682
+ const begins = lines.flatMap((l, i) => (l.trim().startsWith(`# >>> generated: ${name} `) ? [i] : []));
683
+ const ends = lines.flatMap((l, i) => (l.trim() === END(name) ? [i] : []));
684
+ if (begins.length !== 1 || ends.length !== 1 || ends[0] < begins[0]) {
685
+ refused.push(`the "${name}" region needs exactly one begin marker followed by one end marker ("${END(name)}")`);
686
+ continue;
687
+ }
688
+ const [b, e] = [begins[0], ends[0]];
689
+ const indent = lines[b].match(/^\s*/)[0];
690
+ const want = [`${indent}${BEGIN(name)}`, ...regions[name].map((l) => `${indent}${l}`), `${indent}${END(name)}`];
691
+ if (lines.slice(b, e + 1).join('\n') !== want.join('\n')) stale.push(name);
692
+ lines.splice(b, e - b + 1, ...want);
693
+ }
694
+ return refused.length ? { text, stale, refused } : { text: lines.join(eol), stale, refused };
695
+ }