bmad-method-test-architecture-enterprise 3.6.1 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +10 -3
  3. package/cli/lib/automate-prompt.js +3 -7
  4. package/cli/lib/framework-setup.js +1 -2
  5. package/cli/lib/parse-report.js +1 -1
  6. package/cli/lib/resolve-tea-config.js +167 -38
  7. package/cli/lib/trace-command.js +13 -5
  8. package/cli/migrate-customizations.js +853 -77
  9. package/cli/teach.js +0 -1
  10. package/cli/test-review.js +6 -2
  11. package/package.json +3 -2
  12. package/skills/bmad-tea/SKILL.md +2 -2
  13. package/skills/bmad-tea-automate/SKILL.md +12 -11
  14. package/skills/bmad-tea-automate/customize.toml +12 -0
  15. package/skills/bmad-tea-automate/red/atdd-checklist-template.md +4 -4
  16. package/skills/bmad-tea-automate/red/checklist.md +1 -0
  17. package/skills/bmad-tea-automate/red/instructions.md +1 -1
  18. package/skills/bmad-tea-automate/red/steps-c/step-04a-subagent-api-failing.md +5 -0
  19. package/skills/bmad-tea-automate/red/steps-c/step-04b-subagent-e2e-failing.md +4 -0
  20. package/skills/bmad-tea-automate/red/steps-c/step-04c-aggregate.md +3 -2
  21. package/skills/bmad-tea-automate/red/steps-c/step-05-validate-and-complete.md +5 -4
  22. package/skills/bmad-tea-automate/red/steps-e/step-02-apply-edit.md +4 -4
  23. package/skills/bmad-tea-automate/red/steps-v/step-01-validate.md +4 -4
  24. package/skills/bmad-tea-automate/red/workflow.yaml +0 -1
  25. package/skills/bmad-tea-automate/resources/test-generation-routing.md +4 -7
  26. package/skills/bmad-tea-automate/steps-c/step-04-validate-and-summarize.md +4 -4
  27. package/skills/bmad-tea-automate/steps-e/step-02-apply-edit.md +4 -4
  28. package/skills/bmad-tea-automate/steps-v/step-01-validate.md +4 -4
  29. package/skills/bmad-tea-automate/workflow.yaml +0 -1
  30. package/skills/bmad-tea-evaluate/SKILL.md +1 -1
  31. package/skills/bmad-tea-framework/SKILL.md +3 -3
  32. package/skills/bmad-tea-framework/customize.toml +11 -2
  33. package/skills/bmad-tea-framework/resources/hooks/tea-enforce.cjs +366 -46
  34. package/skills/bmad-tea-framework/resources/setup-routing.md +6 -6
  35. package/skills/bmad-tea-framework/steps-c/step-04-docs-and-scripts.md +16 -12
  36. package/skills/bmad-tea-framework/workflow.yaml +0 -1
  37. package/skills/bmad-tea-nfr/SKILL.md +2 -2
  38. package/skills/bmad-tea-nfr/workflow.yaml +0 -1
  39. package/skills/bmad-tea-teach-me-testing/SKILL.md +2 -2
  40. package/skills/bmad-tea-test-design/SKILL.md +2 -2
  41. package/skills/bmad-tea-test-design/workflow.yaml +0 -1
  42. package/skills/bmad-tea-test-review/SKILL.md +2 -2
  43. package/skills/bmad-tea-test-review/workflow.yaml +0 -1
  44. package/skills/bmad-tea-trace/SKILL.md +2 -2
  45. package/skills/bmad-tea-trace/steps-c/step-04-analyze-gaps.md +2 -1
  46. package/skills/bmad-tea-trace/steps-c/step-05-gate-decision.md +30 -13
  47. package/skills/bmad-tea-trace/workflow.yaml +0 -1
  48. package/skills/bmod-tea/bmod.toml +3 -3
  49. package/skills/bmod-tea/help/help.md +10 -9
  50. package/skills/bmod-tea/knowledge/maestro-flows.md +1 -1
  51. package/skills/bmod-tea/migration-1.toml +7 -7
  52. package/skills/bmod-tea/migration-3.toml +50 -0
  53. package/skills/bmod-tea/retired.toml +13 -0
  54. package/skills/bmad-tea-automate/red/customize.toml +0 -38
  55. package/skills/bmad-tea-framework/ci/customize.toml +0 -10
@@ -1,11 +1,15 @@
1
1
  #!/usr/bin/env node
2
- /** Move pre-3.0 TEA customization files and menu references to canonical names. */
2
+ /**
3
+ * Move legacy TEA customizations to their current homes: pre-3.0 files to canonical names, the retired red-mode and CI
4
+ * stems into [workflow.red] and [workflow.ci] of their owning skills, and agent menu references to current skill ids.
5
+ */
3
6
  const fs = require('node:fs');
7
+ const os = require('node:os');
4
8
  const path = require('node:path');
5
9
  const { isDeepStrictEqual } = require('node:util');
6
10
  const TOML = require('smol-toml');
7
11
 
8
- const NAMES = ['automate', 'evaluate', 'framework', 'nfr', 'test-design', 'test-review', 'trace', 'atdd', 'ci'];
12
+ const NAMES = ['automate', 'evaluate', 'framework', 'nfr', 'test-design', 'test-review', 'trace'];
9
13
  const PAIRS = [
10
14
  ...NAMES.map((suffix) => [`bmad-testarch-${suffix}`, `bmad-tea-${suffix}`]),
11
15
  ['bmad-teach-me-testing', 'bmad-tea-teach-me-testing'],
@@ -13,6 +17,25 @@ const PAIRS = [
13
17
  const MENU_NAMES = new Map(PAIRS);
14
18
  MENU_NAMES.set('bmad-testarch-atdd', 'bmad-tea-automate');
15
19
  MENU_NAMES.set('bmad-testarch-ci', 'bmad-tea-framework');
20
+ /** Retired customization stems whose [workflow] table now lives as a sub-table of the owning skill. */
21
+ const SURFACES = [
22
+ { target: 'bmad-tea-automate', table: 'red', sources: ['bmad-tea-atdd', 'bmad-testarch-atdd'] },
23
+ { target: 'bmad-tea-framework', table: 'ci', sources: ['bmad-tea-ci', 'bmad-testarch-ci'], moveCiPlatform: true },
24
+ ];
25
+ const LAYERS = ['.toml', '.user.toml'];
26
+ const BACKUP_PREFIX = '.v6-v7-migration-backup-';
27
+ /** Which backup values this command already restored or deliberately kept, so reruns never repeat or question them. */
28
+ const RECORD_NAME = '.tea-customization-migration.json';
29
+ const RECORD_VERSION = 1;
30
+ /** The pre-v7 personal config layer BMad core no longer merges, and the layers TEA reads `[modules.tea]` from. */
31
+ const LEGACY_USER_CONFIG = ['_bmad', 'config.user.toml'];
32
+ const CONFIG_LAYERS = [
33
+ ['_bmad', 'config.toml'],
34
+ ['_bmad', 'custom', 'config.toml'],
35
+ ['_bmad', 'custom', 'config.user.toml'],
36
+ ];
37
+ const HEADER = /^\s*(\[\[?)\s*([^[\]]*?)\s*(\]\]?)\s*(?:#.*)?$/;
38
+ const CI_PLATFORM_LINE = /^\s*(?:ci_platform|"ci_platform"|'ci_platform')\s*=/;
16
39
 
17
40
  function isTable(value) {
18
41
  return value !== null && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date);
@@ -38,6 +61,14 @@ function parse(file, source) {
38
61
  }
39
62
  }
40
63
 
64
+ function tryParse(source) {
65
+ try {
66
+ return TOML.parse(source);
67
+ } catch {
68
+ return null;
69
+ }
70
+ }
71
+
41
72
  /** Reject links and non-files before any content is read or changed. */
42
73
  function readFile(file) {
43
74
  let stat;
@@ -65,6 +96,432 @@ function checkDirectory(directory, required = false) {
65
96
  return true;
66
97
  }
67
98
 
99
+ /** Split text into lines that each keep their own line ending, so joining them restores every byte. */
100
+ function toLines(text) {
101
+ const parts = text.split(/(\r?\n)/);
102
+ const lines = [];
103
+ for (let index = 0; index < parts.length; index += 2) lines.push({ text: parts[index], eol: parts[index + 1] ?? '' });
104
+ return lines;
105
+ }
106
+
107
+ function joinLines(lines) {
108
+ return lines.map((line) => line.text + line.eol).join('');
109
+ }
110
+
111
+ function lineEnding(text) {
112
+ return text.includes('\r\n') ? '\r\n' : '\n';
113
+ }
114
+
115
+ function headerPath(line) {
116
+ const match = HEADER.exec(line);
117
+ if (!match || match[1].length !== match[3].length) return null;
118
+ const unquote = (part) => part.trim().replace(/^"(.*)"$|^'(.*)'$/, '$1$2');
119
+ return { array: match[1] === '[[', path: match[2].split('.').map((part) => unquote(part)) };
120
+ }
121
+
122
+ /** Locate a `[a.b]` table header and the lines up to the next header. */
123
+ function findSection(lines, tablePath) {
124
+ for (let start = 0; start < lines.length; start++) {
125
+ const header = headerPath(lines[start].text);
126
+ if (!header || header.array || header.path.join('.') !== tablePath) continue;
127
+ let end = start + 1;
128
+ while (end < lines.length && headerPath(lines[end].text) === null) end++;
129
+ return { start, end };
130
+ }
131
+ return null;
132
+ }
133
+
134
+ /** Edit only the files whose structure is provably understood; anything else needs a person. */
135
+ function manualEdit(file, reason, table) {
136
+ return new Error(`Cannot safely edit ${file}: ${reason}. Add the settings under ${table} by hand, then rerun.`);
137
+ }
138
+
139
+ /** Add lines at the end of a table section, before any trailing comments that introduce the next table. */
140
+ function insertIntoSection(file, text, tablePath, newLines) {
141
+ const lines = toLines(text);
142
+ const section = findSection(lines, tablePath);
143
+ if (!section) throw manualEdit(file, `no [${tablePath}] header to add keys under`, `[${tablePath}]`);
144
+ let at = section.start;
145
+ for (let index = section.start + 1; index < section.end; index++) {
146
+ const trimmed = lines[index].text.trim();
147
+ if (trimmed !== '' && !trimmed.startsWith('#')) at = index;
148
+ }
149
+ const eol = lineEnding(text);
150
+ const inserted = newLines.map((line) => ({ text: line, eol }));
151
+ if (lines[at].eol === '') {
152
+ lines[at].eol = eol;
153
+ inserted.at(-1).eol = '';
154
+ }
155
+ lines.splice(at + 1, 0, ...inserted);
156
+ return joinLines(lines);
157
+ }
158
+
159
+ /** Append a block after existing content, separated by one blank line, leaving every existing byte in place. */
160
+ function appendBlock(text, block) {
161
+ if (text === '') return block;
162
+ const eol = lineEnding(text);
163
+ let result = text.endsWith('\n') ? text : text + eol;
164
+ if (result.trim() !== '' && !/\r?\n\r?\n$/.test(result)) result += eol;
165
+ return result + block;
166
+ }
167
+
168
+ /** Comment lines of a legacy file, which no parsed value carries. */
169
+ function commentLines(text) {
170
+ return toLines(text)
171
+ .map((line) => line.text.trim())
172
+ .filter((line) => line.startsWith('#'));
173
+ }
174
+
175
+ /** Keep a legacy file's comments (notes and commented-out settings) when its values merge into an existing table. */
176
+ function withComments(text, candidate) {
177
+ const comments = commentLines(candidate.text);
178
+ if (comments.length === 0) return text;
179
+ const eol = lineEnding(text === '' ? candidate.text : text);
180
+ return appendBlock(text, [`# Comments from ${candidate.name}`, ...comments].join(eol) + eol);
181
+ }
182
+
183
+ /**
184
+ * Turn a legacy file's [workflow] table into [workflow.<table>], keeping its comments and layout when that is provably exact.
185
+ * Bare and quoted spellings of `workflow` are rewritten; anything else falls back to a fresh rendering plus the file's comments.
186
+ */
187
+ function nestedSource(candidate, table) {
188
+ const lines = toLines(candidate.text);
189
+ for (const line of lines) {
190
+ const match = /^(\s*\[\[?\s*(?:workflow|"workflow"|'workflow'))(\s*(?:\.[^\]]*)?\]\]?\s*(?:#.*)?)$/.exec(line.text);
191
+ if (match) line.text = `${match[1]}.${table}${match[2]}`;
192
+ }
193
+ const rewritten = joinLines(lines);
194
+ const expected = { workflow: { [table]: candidate.table } };
195
+ if (isDeepStrictEqual(tryParse(rewritten), expected)) return rewritten;
196
+ return withComments(TOML.stringify(expected), candidate);
197
+ }
198
+
199
+ function renderKey(file, key, value, table) {
200
+ const rendered = TOML.stringify({ [key]: value }).trimEnd();
201
+ if (/^\s*\[/m.test(rendered)) throw manualEdit(file, `${key} is a table and cannot be inserted inside ${table}`, table);
202
+ return rendered.split(/\r?\n/);
203
+ }
204
+
205
+ function provenance(candidate) {
206
+ if (candidate.topLevel) return `${candidate.file} [workflow] (live)`;
207
+ return candidate.live ? `${candidate.file} (live)` : `${candidate.file} (from ${candidate.provenance})`;
208
+ }
209
+
210
+ /** Folders a v6 to v7 upgrade left behind, newest first by name. */
211
+ function listBackups(root) {
212
+ return fs
213
+ .readdirSync(root)
214
+ .filter((name) => name.startsWith(BACKUP_PREFIX))
215
+ .toSorted()
216
+ .toReversed();
217
+ }
218
+
219
+ /** The newest backup that actually holds the file wins; a newer backup without it never hides an older one. */
220
+ function findInBackups(root, backups, segments) {
221
+ search: for (const folder of backups) {
222
+ let directory = path.join(root, folder);
223
+ if (!checkDirectory(directory)) continue;
224
+ for (const segment of segments.slice(0, -1)) {
225
+ directory = path.join(directory, segment);
226
+ if (!checkDirectory(directory)) continue search;
227
+ }
228
+ const found = readFile(path.join(directory, segments.at(-1)));
229
+ if (found) return { ...found, provenance: folder };
230
+ }
231
+ return null;
232
+ }
233
+
234
+ function emptyRecord() {
235
+ return { version: RECORD_VERSION, restored: {}, kept: {} };
236
+ }
237
+
238
+ /** Read the migration record; a damaged record stops the run so no decision recorded in it is lost. */
239
+ function readRecord(customRoot) {
240
+ const file = path.join(customRoot, RECORD_NAME);
241
+ const found = readFile(file);
242
+ if (!found) return emptyRecord();
243
+ let value;
244
+ try {
245
+ value = JSON.parse(found.text);
246
+ } catch (error) {
247
+ throw new Error(`Cannot read migration record ${file}: ${error.message}. Fix or remove it, then rerun.`);
248
+ }
249
+ const isNameMap = (map) => isTable(map) && Object.values(map).every((folder) => typeof folder === 'string');
250
+ if (!isTable(value) || value.version !== RECORD_VERSION || !isNameMap(value.restored) || !isNameMap(value.kept)) {
251
+ throw new Error(
252
+ `Cannot read migration record ${file}: expected {"version": ${RECORD_VERSION}, "restored": {...}, "kept": {...}}. Fix or remove it, then rerun.`,
253
+ );
254
+ }
255
+ return { version: RECORD_VERSION, restored: { ...value.restored }, kept: { ...value.kept } };
256
+ }
257
+
258
+ function sortedNames(map) {
259
+ return Object.fromEntries(Object.entries(map).toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
260
+ }
261
+
262
+ /** Replace the record in one rename; a failure here is reported but never undoes the finished migration. */
263
+ function writeRecord(customRoot, record) {
264
+ const file = path.join(customRoot, RECORD_NAME);
265
+ const temp = path.join(customRoot, `${RECORD_NAME}.${process.pid}.tmp`);
266
+ const text = `${JSON.stringify({ version: RECORD_VERSION, restored: sortedNames(record.restored), kept: sortedNames(record.kept) }, null, 2)}\n`;
267
+ try {
268
+ readFile(file);
269
+ fs.writeFileSync(temp, text, { flag: 'wx', mode: 0o644 });
270
+ fs.renameSync(temp, file);
271
+ } catch (error) {
272
+ if (fs.existsSync(temp)) fs.unlinkSync(temp);
273
+ throw new Error(
274
+ `The customizations were migrated, but the migration record ${file} could not be written: ${error.message}. Fix the cause and rerun; a rerun may ask about backup values again.`,
275
+ );
276
+ }
277
+ }
278
+
279
+ function recordKey(targetName, table, key) {
280
+ return `${targetName}|${table}|${key}`;
281
+ }
282
+
283
+ function readOptional(file) {
284
+ try {
285
+ return fs.readFileSync(file, 'utf8');
286
+ } catch (error) {
287
+ if (error.code === 'ENOENT') return null;
288
+ throw new Error(`Cannot read ${file}: ${error.message}`);
289
+ }
290
+ }
291
+
292
+ /** Name `[modules.tea]` keys a pre-v7 personal config holds that TEA no longer reads; this command leaves that file alone. */
293
+ function legacyConfigNotice(root, backups) {
294
+ const liveFile = path.join(root, ...LEGACY_USER_CONFIG);
295
+ const liveText = readOptional(liveFile);
296
+ const legacy = liveText === null ? findInBackups(root, backups, LEGACY_USER_CONFIG) : { file: liveFile, text: liveText };
297
+ if (!legacy) return null;
298
+ const tea = tryParse(legacy.text)?.modules?.tea;
299
+ if (!isTable(tea)) return null;
300
+ // The old core order was config.toml, config.user.toml, custom/config.toml, custom/config.user.toml, so only the custom layers outranked the legacy file.
301
+ const teaTable = (segments) => {
302
+ const file = path.join(root, ...segments);
303
+ const text = readOptional(file);
304
+ const layer = text === null ? undefined : parse(file, text).modules?.tea;
305
+ return { file, tea: isTable(layer) ? layer : {} };
306
+ };
307
+ const held = new Set();
308
+ for (const segments of CONFIG_LAYERS.slice(1)) for (const key of Object.keys(teaTable(segments).tea)) held.add(key);
309
+ const base = teaTable(CONFIG_LAYERS[0]);
310
+ const ignored = [];
311
+ const shadowed = [];
312
+ for (const [key, value] of Object.entries(tea)) {
313
+ if (held.has(key)) continue;
314
+ if (Object.hasOwn(base.tea, key) && JSON.stringify(base.tea[key]) === JSON.stringify(value)) continue;
315
+ ignored.push(key);
316
+ if (Object.hasOwn(base.tea, key)) {
317
+ shadowed.push(
318
+ `${key} is ${JSON.stringify(value)} in ${legacy.file} and ${JSON.stringify(base.tea[key])} in ${base.file}, which TEA uses.`,
319
+ );
320
+ }
321
+ }
322
+ if (ignored.length === 0) return null;
323
+ const detail = shadowed.length === 0 ? '' : ` ${shadowed.join(' ')}`;
324
+ const line = `Not migrated by this command: ${legacy.file} [modules.tea] keys ${ignored.join(', ')} are ignored by TEA.${detail} Run \`bmad migrate tea\` to move them.`;
325
+ return { kind: 'notice', messages: [{ done: line, check: line }] };
326
+ }
327
+
328
+ function collectCandidates(context, surface, suffix, targetName) {
329
+ const candidates = [];
330
+ for (const stem of surface.sources) {
331
+ const name = stem + suffix;
332
+ const live = readFile(path.join(context.customRoot, name));
333
+ const backupSegments = ['_bmad', 'custom', name];
334
+ let found = null;
335
+ if (live) {
336
+ // A backup copy of a file migrated from the live tree must never resurface on a later run.
337
+ found = { ...live, provenance: 'live', shadowed: findInBackups(context.root, context.backups, backupSegments) !== null };
338
+ } else if (!Object.hasOwn(context.record.restored, name)) {
339
+ found = findInBackups(context.root, context.backups, backupSegments);
340
+ }
341
+ if (!found) continue;
342
+ const value = parse(found.file, found.text);
343
+ for (const key of Object.keys(value)) {
344
+ if (key !== 'workflow')
345
+ throw new Error(`${found.file} has ${key} outside [workflow]; move it manually into ${targetName}, then rerun.`);
346
+ }
347
+ if (value.workflow !== undefined && !isTable(value.workflow))
348
+ throw new Error(`Expected a [workflow] table in ${found.file}; move its settings manually into ${targetName}, then rerun.`);
349
+ const isLive = found.provenance === 'live';
350
+ const table = { ...value.workflow };
351
+ if (!isLive) {
352
+ for (const key of Object.keys(table)) {
353
+ const recorded = recordKey(targetName, surface.table, key);
354
+ if (Object.hasOwn(context.record.restored, recorded) || Object.hasOwn(context.record.kept, recorded)) delete table[key];
355
+ }
356
+ }
357
+ candidates.push({ name, ...found, live: isLive, table });
358
+ }
359
+ return candidates;
360
+ }
361
+
362
+ /** Find value conflicts and kept backup values against the target as it stands before this run. */
363
+ function analyse(candidates, targetTable, targetFile, tableLabel, keepExisting) {
364
+ const conflicts = [];
365
+ const kept = [];
366
+ const keys = [...new Set(candidates.flatMap((candidate) => Object.keys(candidate.table)))];
367
+ for (const key of keys) {
368
+ const holders = candidates.filter((candidate) => Object.hasOwn(candidate.table, key));
369
+ if (Object.hasOwn(targetTable, key)) {
370
+ for (const candidate of holders) {
371
+ if (isDeepStrictEqual(candidate.table[key], targetTable[key])) continue;
372
+ const both = `${JSON.stringify(candidate.table[key])} in ${provenance(candidate)} and ${JSON.stringify(targetTable[key])} in ${targetFile} ${tableLabel}`;
373
+ if (candidate.live) conflicts.push(`Conflicting ${key}: ${both}. Make them agree, then rerun.`);
374
+ else if (keepExisting) kept.push({ key, candidate, value: targetTable[key] });
375
+ else conflicts.push(`Conflicting ${key}: ${both}. Make them agree, or rerun with --keep-existing to keep the existing value.`);
376
+ }
377
+ continue;
378
+ }
379
+ const [first, ...rest] = holders;
380
+ for (const candidate of rest) {
381
+ if (isDeepStrictEqual(candidate.table[key], first.table[key])) continue;
382
+ conflicts.push(
383
+ `Conflicting ${key}: ${JSON.stringify(first.table[key])} in ${provenance(first)} and ${JSON.stringify(candidate.table[key])} in ${provenance(candidate)}. Make them agree, or set ${key} under ${tableLabel} in ${targetFile} to the value you want, then rerun.`,
384
+ );
385
+ }
386
+ }
387
+ return { conflicts, kept };
388
+ }
389
+
390
+ /** Move `ci_platform` from [workflow] into [workflow.ci] of the same file, line and all. */
391
+ function moveCiPlatform(file, text, current) {
392
+ const lines = toLines(text);
393
+ const section = findSection(lines, 'workflow');
394
+ const hits = [];
395
+ for (let index = (section?.start ?? 0) + 1; section && index < section.end; index++) {
396
+ if (CI_PLATFORM_LINE.test(lines[index].text)) hits.push(index);
397
+ }
398
+ if (hits.length !== 1) throw manualEdit(file, 'ci_platform is not a single line under a [workflow] header', '[workflow.ci]');
399
+ const [moved] = lines.splice(hits[0], 1);
400
+ const removed = joinLines(lines);
401
+ const expected = parse(file, text);
402
+ delete expected.workflow.ci_platform;
403
+ if (!isDeepStrictEqual(tryParse(removed), expected))
404
+ throw manualEdit(file, 'ci_platform could not be removed from [workflow] exactly', '[workflow.ci]');
405
+ const ci = current.workflow?.ci;
406
+ if (ci && Object.hasOwn(ci, 'ci_platform')) return removed;
407
+ const line = moved.text.trim();
408
+ if (ci) return insertIntoSection(file, removed, 'workflow.ci', [line]);
409
+ return appendBlock(removed, `[workflow.ci]${lineEnding(text)}${line}${lineEnding(text)}`);
410
+ }
411
+
412
+ /** Plan the merge of one retired surface into one layer of its owning skill. */
413
+ function planSurface(context, surface, suffix) {
414
+ const targetName = surface.target + suffix;
415
+ const targetFile = path.join(context.customRoot, targetName);
416
+ const tableLabel = `[workflow.${surface.table}]`;
417
+ const base = context.staged.get(targetFile) ?? readFile(targetFile);
418
+ const baseLabel = base?.source ?? targetFile;
419
+ const baseValue = base ? parse(baseLabel, base.text) : {};
420
+ if (baseValue.workflow !== undefined && !isTable(baseValue.workflow))
421
+ throw manualEdit(baseLabel, '[workflow] is not a table', tableLabel);
422
+ const existing = baseValue.workflow?.[surface.table];
423
+ if (existing !== undefined && !isTable(existing)) throw manualEdit(baseLabel, `${tableLabel} is not a table`, tableLabel);
424
+ const candidates = collectCandidates(context, surface, suffix, targetName);
425
+ if (surface.moveCiPlatform && baseValue.workflow && Object.hasOwn(baseValue.workflow, 'ci_platform')) {
426
+ candidates.push({
427
+ name: targetName,
428
+ file: targetFile,
429
+ provenance: 'live',
430
+ live: true,
431
+ topLevel: true,
432
+ table: { ci_platform: baseValue.workflow.ci_platform },
433
+ });
434
+ }
435
+ if (candidates.length === 0) return;
436
+ const { conflicts, kept } = analyse(candidates, existing ?? {}, targetFile, tableLabel, context.keepExisting);
437
+ if (conflicts.length > 0) {
438
+ context.conflicts.push(...conflicts);
439
+ return;
440
+ }
441
+
442
+ const record = context.nextRecord;
443
+ const baseText = base?.text ?? null;
444
+ let text = baseText;
445
+ let mode;
446
+ const messages = [];
447
+ const expected = parse(baseLabel, baseText ?? '');
448
+ for (const candidate of candidates) {
449
+ const current = text === null ? {} : parse(targetFile, text);
450
+ const have = current.workflow?.[surface.table];
451
+ const missing = Object.keys(candidate.table).filter((key) => !have || !Object.hasOwn(have, key));
452
+ const from = candidate.live ? '' : ` (from ${candidate.provenance})`;
453
+ if (candidate.topLevel) {
454
+ text = moveCiPlatform(targetFile, text, current);
455
+ delete expected.workflow.ci_platform;
456
+ expected.workflow.ci ??= {};
457
+ expected.workflow.ci.ci_platform ??= candidate.table.ci_platform;
458
+ const move = `${targetName} [workflow].ci_platform -> ${targetName} ${tableLabel}`;
459
+ messages.push({ done: move, check: `Would move ${move}` });
460
+ continue;
461
+ }
462
+ if (!candidate.live || candidate.shadowed) record.restored[candidate.name] = candidate.provenance;
463
+ if (missing.length > 0) {
464
+ mode ??= candidate.stat.mode & 0o777;
465
+ const additions = Object.fromEntries(missing.map((key) => [key, candidate.table[key]]));
466
+ expected.workflow ??= {};
467
+ expected.workflow[surface.table] = { ...expected.workflow[surface.table], ...additions };
468
+ let next = have
469
+ ? insertIntoSection(
470
+ targetFile,
471
+ text,
472
+ `workflow.${surface.table}`,
473
+ missing.flatMap((key) => renderKey(targetFile, key, candidate.table[key], tableLabel)),
474
+ )
475
+ : appendBlock(text ?? '', nestedSource(candidate, surface.table));
476
+ if (have) next = withComments(next, candidate);
477
+ if (!isDeepStrictEqual(tryParse(next), expected))
478
+ throw manualEdit(targetFile, `the merged ${tableLabel} could not be verified`, tableLabel);
479
+ text = next;
480
+ if (!candidate.live) for (const key of missing) record.restored[recordKey(targetName, surface.table, key)] = candidate.provenance;
481
+ }
482
+ if (missing.length === 0 && candidate.live) {
483
+ const withNote = withComments(text ?? '', candidate);
484
+ if (withNote !== text) text = withNote;
485
+ }
486
+ if (missing.length > 0 || candidate.live) {
487
+ const move = `${candidate.name} [workflow] -> ${targetName} ${tableLabel}${from}${missing.length === 0 ? ' (values already present)' : ''}`;
488
+ messages.push({ done: move, check: `Would move ${move}` });
489
+ }
490
+ }
491
+ for (const { key, candidate, value } of kept) {
492
+ record.kept[recordKey(targetName, surface.table, key)] = candidate.provenance;
493
+ const notice = `${key} = ${JSON.stringify(value)} in ${targetName} ${tableLabel}; ignoring ${JSON.stringify(candidate.table[key])} from ${candidate.name} (from ${candidate.provenance})`;
494
+ messages.push({ done: `Kept ${notice}`, check: `Would keep ${notice}` });
495
+ }
496
+
497
+ const group = [];
498
+ let writer = null;
499
+ if (text !== baseText) {
500
+ if (!isDeepStrictEqual(tryParse(text), expected))
501
+ throw manualEdit(targetFile, `the merged ${tableLabel} could not be verified`, tableLabel);
502
+ if (base?.pending) {
503
+ // The file is itself being restored from a backup in this run: fold the merge into that creation.
504
+ writer = base.pending;
505
+ writer.text = text;
506
+ writer.expected = expected;
507
+ } else {
508
+ writer = base
509
+ ? { kind: 'update', oldFile: targetFile, newFile: targetFile, old: base, text, expected }
510
+ : { kind: 'create', oldFile: null, newFile: targetFile, text, mode: mode ?? 0o644, expected };
511
+ group.push(writer);
512
+ }
513
+ }
514
+ for (const candidate of candidates) {
515
+ if (!candidate.live || candidate.topLevel) continue;
516
+ const old = { file: candidate.file, stat: candidate.stat, text: candidate.text };
517
+ group.push({ kind: 'remove', oldFile: candidate.file, newFile: targetFile, old, requires: text });
518
+ }
519
+ const carrier = writer ?? group[0];
520
+ if (carrier) carrier.messages = [...(carrier.messages ?? []), ...messages];
521
+ else if (messages.length > 0) context.actions.push({ kind: 'notice', messages });
522
+ context.actions.push(...group);
523
+ }
524
+
68
525
  /** Edit only skill assignments inside agent menu entries, retaining every other byte. */
69
526
  function rewriteMenu(file, source) {
70
527
  const original = parse(file, source);
@@ -99,35 +556,79 @@ function rewriteMenu(file, source) {
99
556
  return rewritten;
100
557
  }
101
558
 
102
- function preflight(customRoot) {
103
- const actions = [];
104
- for (const [oldName, newName] of PAIRS) {
105
- for (const suffix of ['.toml', '.user.toml']) {
106
- const oldFile = path.join(customRoot, oldName + suffix);
107
- const newFile = path.join(customRoot, newName + suffix);
108
- const old = readFile(oldFile);
109
- const current = readFile(newFile);
110
- if (!old) continue;
111
- const oldValue = parse(oldFile, old.text);
112
- if (current) {
113
- const newValue = parse(newFile, current.text);
114
- const conflict = conflictAt(oldValue, newValue);
115
- if (conflict) throw new Error(`Conflicting ${conflict} in ${oldFile} and ${newFile}`);
116
- throw new Error(
117
- `Both ${oldFile} and ${newFile} exist. Merge their values and comments manually into ${newFile}, then remove ${oldFile} and rerun.`,
118
- );
119
- }
120
- actions.push({ kind: 'move', oldFile, newFile, old });
559
+ /**
560
+ * Stage a pre-3.0 rename, or the restore of an owning-skill file a v6 to v7 cleanup removed, so later merges land on the
561
+ * file that will exist after this run.
562
+ */
563
+ function planRename(context, oldName, newName, suffix) {
564
+ const { customRoot, staged, actions } = context;
565
+ const oldFile = path.join(customRoot, oldName + suffix);
566
+ const newFile = path.join(customRoot, newName + suffix);
567
+ const old = readFile(oldFile);
568
+ const current = readFile(newFile);
569
+ if (old) {
570
+ const oldValue = parse(oldFile, old.text);
571
+ if (current) {
572
+ const newValue = parse(newFile, current.text);
573
+ const conflict = conflictAt(oldValue, newValue);
574
+ if (conflict) throw new Error(`Conflicting ${conflict} in ${oldFile} and ${newFile}`);
575
+ throw new Error(
576
+ `Both ${oldFile} and ${newFile} exist. Merge their values and comments manually into ${newFile}, then remove ${oldFile} and rerun.`,
577
+ );
121
578
  }
579
+ actions.push({ kind: 'move', oldFile, newFile, old });
580
+ staged.set(newFile, { file: newFile, stat: old.stat, text: old.text, source: oldFile });
581
+ return;
582
+ }
583
+ if (current || Object.hasOwn(context.record.restored, newName + suffix)) return;
584
+ const found =
585
+ findInBackups(context.root, context.backups, ['_bmad', 'custom', oldName + suffix]) ??
586
+ findInBackups(context.root, context.backups, ['_bmad', 'custom', newName + suffix]);
587
+ if (!found) return;
588
+ const move = `${path.basename(found.file)} -> ${newName + suffix} (from ${found.provenance})`;
589
+ const pending = {
590
+ kind: 'create',
591
+ oldFile: null,
592
+ newFile,
593
+ text: found.text,
594
+ mode: found.stat.mode & 0o777,
595
+ expected: parse(found.file, found.text),
596
+ messages: [{ done: move, check: `Would move ${move}` }],
597
+ };
598
+ actions.push(pending);
599
+ staged.set(newFile, { file: newFile, text: found.text, source: found.file, pending });
600
+ context.nextRecord.restored[newName + suffix] = found.provenance;
601
+ }
602
+
603
+ /** Read every input, stage every change and surface every conflict before anything is written. */
604
+ function preflight(root, customRoot, { keepExisting = false } = {}) {
605
+ const record = readRecord(customRoot);
606
+ const context = {
607
+ root,
608
+ customRoot,
609
+ backups: listBackups(root),
610
+ staged: new Map(),
611
+ actions: [],
612
+ conflicts: [],
613
+ keepExisting,
614
+ record,
615
+ nextRecord: structuredClone(record),
616
+ };
617
+ for (const [oldName, newName] of PAIRS) for (const suffix of LAYERS) planRename(context, oldName, newName, suffix);
618
+ for (const surface of SURFACES) for (const suffix of LAYERS) planSurface(context, surface, suffix);
619
+ if (context.conflicts.length > 0) {
620
+ throw new Error(`Customization conflicts found; nothing was changed.\n${context.conflicts.map((line) => `- ${line}`).join('\n')}`);
122
621
  }
123
- for (const suffix of ['.toml', '.user.toml']) {
622
+ for (const suffix of LAYERS) {
124
623
  const file = path.join(customRoot, 'bmad-tea' + suffix);
125
624
  const old = readFile(file);
126
625
  if (!old) continue;
127
626
  const rewritten = rewriteMenu(file, old.text);
128
- if (rewritten !== null) actions.push({ kind: 'rewrite', oldFile: file, newFile: file, old, text: rewritten });
627
+ if (rewritten !== null) context.actions.push({ kind: 'rewrite', oldFile: file, newFile: file, old, text: rewritten });
129
628
  }
130
- return actions;
629
+ const notice = legacyConfigNotice(root, context.backups);
630
+ if (notice) context.actions.push(notice);
631
+ return { actions: context.actions, record, nextRecord: context.nextRecord };
131
632
  }
132
633
 
133
634
  function unchanged(snapshot) {
@@ -141,108 +642,383 @@ function unchanged(snapshot) {
141
642
  );
142
643
  }
143
644
 
645
+ /** Re-read a written customization and confirm both its bytes and its parsed values. */
646
+ function verifyWrite(action) {
647
+ const current = readFile(action.newFile);
648
+ if (current?.text !== action.text || !isDeepStrictEqual(tryParse(current.text), action.expected)) {
649
+ throw new Error(`Could not verify ${action.newFile} after writing it`);
650
+ }
651
+ }
652
+
653
+ /** Perform one staged action; `completed` records it as soon as there is something to undo. */
654
+ function applyAction(action, index, customRoot, completed) {
655
+ const backup = path.join(customRoot, `.tea-migration-${process.pid}-${index}.bak`);
656
+ switch (action.kind) {
657
+ case 'move': {
658
+ if (readFile(action.newFile) !== null) throw new Error(`Customization appeared during migration: ${action.newFile}`);
659
+ fs.linkSync(action.oldFile, action.newFile);
660
+ completed.push(action);
661
+ fs.unlinkSync(action.oldFile);
662
+ break;
663
+ }
664
+ case 'create': {
665
+ if (readFile(action.newFile) !== null) throw new Error(`Customization appeared during migration: ${action.newFile}`);
666
+ fs.linkSync(action.temp, action.newFile);
667
+ completed.push(action);
668
+ verifyWrite(action);
669
+ break;
670
+ }
671
+ case 'remove': {
672
+ if ((readFile(action.newFile)?.text ?? null) !== action.requires)
673
+ throw new Error(`Customization changed during migration: ${action.newFile}`);
674
+ fs.linkSync(action.oldFile, backup);
675
+ action.backup = backup;
676
+ completed.push(action);
677
+ fs.unlinkSync(action.oldFile);
678
+ break;
679
+ }
680
+ default: {
681
+ fs.linkSync(action.oldFile, backup);
682
+ action.backup = backup;
683
+ completed.push(action);
684
+ fs.renameSync(action.temp, action.oldFile);
685
+ if (action.kind === 'update') verifyWrite(action);
686
+ }
687
+ }
688
+ }
689
+
690
+ function currentText(file) {
691
+ try {
692
+ return fs.readFileSync(file, 'utf8');
693
+ } catch (error) {
694
+ if (error.code === 'ENOENT') return null;
695
+ throw error;
696
+ }
697
+ }
698
+
699
+ /**
700
+ * Undo one completed action unless someone changed the file since this run touched it; then the newer content stays,
701
+ * the recovery copy stays, and the returned line says where it is.
702
+ */
703
+ function rollbackAction(action) {
704
+ switch (action.kind) {
705
+ case 'move': {
706
+ if (fs.existsSync(action.oldFile))
707
+ return `rollback skipped for ${action.newFile}: ${action.oldFile} reappeared after the migration moved it`;
708
+ fs.linkSync(action.newFile, action.oldFile);
709
+ fs.unlinkSync(action.newFile);
710
+ return null;
711
+ }
712
+ case 'create': {
713
+ const current = currentText(action.newFile);
714
+ if (current === null) return null;
715
+ if (current !== action.text)
716
+ return `rollback skipped for ${action.newFile}: it changed after the migration wrote it; it did not exist before the migration`;
717
+ fs.unlinkSync(action.newFile);
718
+ return null;
719
+ }
720
+ case 'remove': {
721
+ const current = currentText(action.oldFile);
722
+ if (current === null) fs.linkSync(action.backup, action.oldFile);
723
+ else if (current !== action.old.text) {
724
+ action.keepBackup = true;
725
+ return `rollback skipped for ${action.oldFile}: it changed after the migration removed it; the previous content is in ${action.backup}`;
726
+ }
727
+ fs.unlinkSync(action.backup);
728
+ return null;
729
+ }
730
+ default: {
731
+ const current = currentText(action.oldFile);
732
+ if (current === action.old.text) {
733
+ fs.unlinkSync(action.backup);
734
+ return null;
735
+ }
736
+ if (current !== null && current !== action.text) {
737
+ action.keepBackup = true;
738
+ return `rollback skipped for ${action.oldFile}: it changed after the migration wrote it; the previous content is in ${action.backup}`;
739
+ }
740
+ if (current !== null) fs.unlinkSync(action.oldFile);
741
+ fs.linkSync(action.backup, action.oldFile);
742
+ fs.unlinkSync(action.backup);
743
+ return null;
744
+ }
745
+ }
746
+ }
747
+
144
748
  /** Apply staged changes under one exclusive lock and undo completed actions on failure. */
145
- function applyActions(actions, customRoot, beforeAction) {
749
+ function applyActions(allActions, customRoot, beforeAction) {
750
+ const actions = allActions.filter((action) => action.kind !== 'notice');
146
751
  const completed = [];
147
752
  const temporary = [];
148
753
  let rollbackSafe = true;
149
754
  try {
150
755
  for (const [index, action] of actions.entries()) {
151
- if (action.kind !== 'rewrite') continue;
756
+ if (!['rewrite', 'update', 'create'].includes(action.kind)) continue;
757
+ const mode = action.kind === 'create' ? action.mode : action.old.stat.mode & 0o777;
152
758
  const temp = path.join(customRoot, `.tea-migration-${process.pid}-${index}.tmp`);
153
- fs.writeFileSync(temp, action.text, { flag: 'wx', mode: action.old.stat.mode & 0o777 });
154
- fs.chmodSync(temp, action.old.stat.mode & 0o777);
759
+ fs.writeFileSync(temp, action.text, { flag: 'wx', mode });
760
+ fs.chmodSync(temp, mode);
155
761
  action.temp = temp;
156
762
  temporary.push(temp);
157
763
  }
158
764
  for (const [index, action] of actions.entries()) {
159
765
  beforeAction?.(action, index);
160
- if (!unchanged(action.old)) throw new Error(`Customization changed during migration: ${action.oldFile}`);
161
- if (action.kind === 'move') {
162
- if (readFile(action.newFile) !== null) throw new Error(`Customization appeared during migration: ${action.newFile}`);
163
- fs.linkSync(action.oldFile, action.newFile);
164
- completed.push(action);
165
- fs.unlinkSync(action.oldFile);
166
- } else {
167
- const backup = path.join(customRoot, `.tea-migration-${process.pid}-${index}.bak`);
168
- fs.linkSync(action.oldFile, backup);
169
- action.backup = backup;
170
- completed.push(action);
171
- fs.renameSync(action.temp, action.oldFile);
172
- }
766
+ if (action.old && !unchanged(action.old)) throw new Error(`Customization changed during migration: ${action.oldFile}`);
767
+ applyAction(action, index, customRoot, completed);
173
768
  }
174
769
  } catch (error) {
175
770
  const rollbackErrors = [];
771
+ const skipped = [];
176
772
  for (const action of completed.toReversed()) {
177
773
  try {
178
- if (action.kind === 'move') {
179
- if (!fs.existsSync(action.oldFile)) fs.linkSync(action.newFile, action.oldFile);
180
- fs.unlinkSync(action.newFile);
181
- } else {
182
- if (fs.existsSync(action.oldFile)) fs.unlinkSync(action.oldFile);
183
- fs.linkSync(action.backup, action.oldFile);
184
- fs.unlinkSync(action.backup);
185
- }
774
+ const skip = rollbackAction(action);
775
+ if (skip) skipped.push(skip);
186
776
  } catch (rollbackError) {
187
- rollbackErrors.push(`${action.oldFile}: ${rollbackError.message}`);
777
+ rollbackErrors.push(`${action.oldFile ?? action.newFile}: ${rollbackError.message}`);
188
778
  }
189
779
  }
190
780
  rollbackSafe = rollbackErrors.length === 0;
191
- throw new Error(`${error.message}${rollbackErrors.length > 0 ? `; rollback needs manual repair: ${rollbackErrors.join('; ')}` : ''}`);
781
+ const notes = [...skipped, ...(rollbackErrors.length > 0 ? [`rollback needs manual repair: ${rollbackErrors.join('; ')}`] : [])];
782
+ throw new Error([error.message, ...notes].join('; '));
192
783
  } finally {
193
- if (rollbackSafe) for (const action of actions) if (action.backup && fs.existsSync(action.backup)) fs.unlinkSync(action.backup);
784
+ if (rollbackSafe) {
785
+ for (const action of actions) if (action.backup && !action.keepBackup && fs.existsSync(action.backup)) fs.unlinkSync(action.backup);
786
+ }
194
787
  for (const temp of temporary) if (fs.existsSync(temp)) fs.unlinkSync(temp);
195
788
  }
196
789
  }
197
790
 
198
- function migrate(projectRoot, { check = false, beforeAction } = {}) {
791
+ function migrate(projectRoot, { check = false, keepExisting = false, beforeAction } = {}) {
199
792
  const root = path.resolve(projectRoot);
200
793
  checkDirectory(root, true);
201
794
  const bmadRoot = path.join(root, '_bmad');
202
795
  if (!checkDirectory(bmadRoot)) return [];
203
796
  const customRoot = path.join(bmadRoot, 'custom');
204
- if (!checkDirectory(customRoot)) return [];
205
- if (check) return preflight(customRoot);
797
+ if (check) return preflight(root, customRoot, { keepExisting }).actions;
798
+ if (!checkDirectory(customRoot)) {
799
+ // A cleanup may have removed the whole folder while a backup still holds settings to restore.
800
+ const planned = preflight(root, customRoot, { keepExisting }).actions;
801
+ if (planned.every((action) => action.kind === 'notice')) return planned;
802
+ fs.mkdirSync(customRoot);
803
+ }
206
804
  const lock = path.join(customRoot, '.tea-migration.lock');
805
+ const recovered = [];
806
+ holdSignals();
807
+ try {
808
+ acquireLock(lock, customRoot, recovered);
809
+ try {
810
+ const plan = preflight(root, customRoot, { keepExisting });
811
+ applyActions(plan.actions, customRoot, beforeAction);
812
+ if (!isDeepStrictEqual(plan.nextRecord, plan.record)) writeRecord(customRoot, plan.nextRecord);
813
+ return [...recovered.map(recoveryNotice), ...plan.actions];
814
+ } finally {
815
+ releaseLock(lock);
816
+ }
817
+ } finally {
818
+ releaseSignals();
819
+ }
820
+ }
821
+
822
+ const LOCK_OWNER = 'owner.json';
823
+ const SIGNALS = ['SIGINT', 'SIGTERM'];
824
+ const signalState = { holders: 0, installed: false, exitOnSignal: false };
825
+
826
+ /**
827
+ * The apply phase is synchronous, so Node cannot run a signal handler until it returns. Holding a listener keeps the
828
+ * default kill from interrupting the apply: the run finishes, the lock and temp files are released, and only then does
829
+ * the deferred signal take effect.
830
+ */
831
+ function onSignal(signal) {
832
+ dropSignals();
833
+ const code = 128 + os.constants.signals[signal];
834
+ if (signalState.exitOnSignal) {
835
+ process.stderr.write(`Received ${signal}; the migration finished its current run and released the lock.\n`);
836
+ process.exitCode = code;
837
+ } else if (process.listenerCount(signal) === 0) {
838
+ process.kill(process.pid, signal);
839
+ }
840
+ }
841
+
842
+ function dropSignals() {
843
+ for (const signal of SIGNALS) process.removeListener(signal, onSignal);
844
+ signalState.installed = false;
845
+ }
846
+
847
+ function holdSignals() {
848
+ signalState.holders++;
849
+ if (signalState.installed) return;
850
+ for (const signal of SIGNALS) process.on(signal, onSignal);
851
+ signalState.installed = true;
852
+ }
853
+
854
+ function releaseSignals() {
855
+ signalState.holders--;
856
+ // A signal that arrived during the synchronous run is delivered on the next event-loop pass; keep the listener until then.
857
+ setImmediate(() => {
858
+ if (signalState.holders === 0 && signalState.installed) dropSignals();
859
+ });
860
+ }
861
+
862
+ function readLockOwner(lock) {
863
+ try {
864
+ const owner = JSON.parse(fs.readFileSync(path.join(lock, LOCK_OWNER), 'utf8'));
865
+ if (Number.isInteger(owner?.pid) && owner.pid > 0 && typeof owner.hostname === 'string') return owner;
866
+ } catch {
867
+ // No readable owner record: the lock stays until a person inspects it.
868
+ }
869
+ return null;
870
+ }
871
+
872
+ function processIsGone(pid) {
207
873
  try {
208
- fs.mkdirSync(lock, { mode: 0o700 });
874
+ process.kill(pid, 0);
875
+ return false;
209
876
  } catch (error) {
210
- if (error.code === 'EEXIST') {
211
- throw new Error(
212
- `Migration lock exists at ${lock}. Check for a running migration; if none is running, inspect and remove the stale lock directory, then retry.`,
877
+ return error.code === 'ESRCH';
878
+ }
879
+ }
880
+
881
+ function leftoverFiles(customRoot, pid) {
882
+ const own = new RegExp(`^\\.tea-migration-${pid}-\\d+\\.(tmp|bak)$`);
883
+ const any = /^\.tea-migration-\d+-\d+\.(tmp|bak)$/;
884
+ let names = [];
885
+ try {
886
+ names = fs.readdirSync(customRoot);
887
+ } catch {
888
+ // The folder is checked before the lock is taken; an unreadable listing only shortens the report.
889
+ }
890
+ return names.filter((name) => (pid === undefined ? any : own).test(name)).map((name) => path.join(customRoot, name));
891
+ }
892
+
893
+ function describeOwner(owner) {
894
+ return `held by pid ${owner.pid} on ${owner.hostname}${owner.started_at ? ` since ${owner.started_at}` : ''}`;
895
+ }
896
+
897
+ function lockHeldMessage(lock, customRoot, owner) {
898
+ const leftovers = leftoverFiles(customRoot, owner?.pid);
899
+ const parts = [`Migration lock exists at ${lock}${owner ? ` (${describeOwner(owner)})` : ''}.`];
900
+ parts.push(
901
+ owner && owner.hostname === os.hostname()
902
+ ? 'The owning process is still running; wait for it to finish, then retry.'
903
+ : 'Check for a running migration; if none is running, inspect and remove the stale lock directory, then retry.',
904
+ );
905
+ if (leftovers.length > 0) parts.push(`Files left by an interrupted run: ${leftovers.join(', ')}.`);
906
+ return parts.join(' ');
907
+ }
908
+
909
+ function recoveryNotice({ lock, owner, removed, backups }) {
910
+ const line =
911
+ `Recovered the stale migration lock ${lock} (${describeOwner(owner)}, no longer running)` +
912
+ `${removed.length > 0 ? `; removed ${removed.join(', ')}` : ''}` +
913
+ `${backups.length > 0 ? `; left ${backups.join(', ')} holding file contents from before the interrupted run` : ''}.`;
914
+ return { kind: 'notice', messages: [{ done: line, check: line }] };
915
+ }
916
+
917
+ function acquireLock(lock, customRoot, recovered) {
918
+ for (let attempt = 0; ; attempt++) {
919
+ try {
920
+ fs.mkdirSync(lock, { mode: 0o700 });
921
+ } catch (error) {
922
+ if (error.code !== 'EEXIST') throw new Error(`Cannot lock ${customRoot} for migration: ${error.message}`);
923
+ takeOverStaleLock(lock, customRoot, recovered, attempt);
924
+ continue;
925
+ }
926
+ try {
927
+ fs.writeFileSync(
928
+ path.join(lock, LOCK_OWNER),
929
+ `${JSON.stringify({ pid: process.pid, hostname: os.hostname(), started_at: new Date().toISOString() })}\n`,
213
930
  );
931
+ } catch (error) {
932
+ // An ownerless lock could never be recovered automatically, so give the directory back before failing.
933
+ fs.rmSync(lock, { recursive: true, force: true });
934
+ throw new Error(`Cannot record the migration lock owner in ${lock}: ${error.message}`);
214
935
  }
215
- throw new Error(`Cannot lock ${customRoot} for migration: ${error.message}`);
936
+ return;
937
+ }
938
+ }
939
+
940
+ const isStale = (owner) => owner !== null && owner.hostname === os.hostname() && processIsGone(owner.pid);
941
+
942
+ /**
943
+ * Clear a lock whose same-host owner process is gone, with its temp files; any other existing lock is an error.
944
+ *
945
+ * Two runs can both see the same dead owner. The recovery claim is an exclusive directory, and the owner is read
946
+ * again while holding it, so a run that saw the dead owner can never delete a lock another run has since acquired.
947
+ */
948
+ function takeOverStaleLock(lock, customRoot, recovered, attempt) {
949
+ if (attempt > 0 || !isStale(readLockOwner(lock))) throw new Error(lockHeldMessage(lock, customRoot, readLockOwner(lock)));
950
+ const claim = `${lock}.recovery`;
951
+ try {
952
+ fs.mkdirSync(claim, { mode: 0o700 });
953
+ } catch (error) {
954
+ if (error.code !== 'EEXIST') throw new Error(`Cannot claim stale lock recovery at ${claim}: ${error.message}`);
955
+ throw new Error(
956
+ `${lockHeldMessage(lock, customRoot, readLockOwner(lock))} Another run is recovering it (${claim}); if none is running, remove that directory too.`,
957
+ );
216
958
  }
217
959
  try {
218
- const actions = preflight(customRoot);
219
- applyActions(actions, customRoot, beforeAction);
220
- return actions;
960
+ const owner = readLockOwner(lock);
961
+ if (!fs.existsSync(lock)) return;
962
+ if (!isStale(owner)) throw new Error(lockHeldMessage(lock, customRoot, owner));
963
+ const leftovers = leftoverFiles(customRoot, owner.pid);
964
+ const removed = leftovers.filter((file) => file.endsWith('.tmp'));
965
+ for (const file of removed) fs.rmSync(file, { force: true });
966
+ fs.rmSync(lock, { recursive: true, force: true });
967
+ recovered.push({ lock, owner, removed, backups: leftovers.filter((file) => file.endsWith('.bak')) });
221
968
  } finally {
222
- fs.rmdirSync(lock);
969
+ fs.rmdirSync(claim);
223
970
  }
224
971
  }
225
972
 
973
+ function releaseLock(lock) {
974
+ fs.rmSync(path.join(lock, LOCK_OWNER), { force: true });
975
+ fs.rmdirSync(lock);
976
+ }
977
+
978
+ function describe(action, check) {
979
+ const lines = (action.messages ?? []).map((message) => (check ? message.check : message.done));
980
+ if (action.kind === 'rewrite') lines.push(`${check ? 'Would update' : 'Updated'} menu references in ${action.oldFile}`);
981
+ if (action.kind === 'move') lines.push(`${check ? 'Would move ' : ''}${action.oldFile} -> ${action.newFile}`);
982
+ return lines;
983
+ }
984
+
226
985
  function main(argv = process.argv.slice(2)) {
227
- const usage = 'Usage: tea-migrate-customizations [--project-root PATH] [--check]';
228
- const rootIndex = argv.indexOf('--project-root');
229
- if (rootIndex !== -1 && (!argv[rootIndex + 1] || argv[rootIndex + 1].startsWith('--'))) throw new Error('--project-root requires a path');
230
- if (argv.some((arg, index) => arg !== '--check' && arg !== '--project-root' && index !== rootIndex + 1)) throw new Error(usage);
231
- const projectRoot = rootIndex < 0 ? process.cwd() : path.resolve(argv[rootIndex + 1]);
232
- const check = argv.includes('--check');
233
- const actions = migrate(projectRoot, { check });
234
- for (const action of actions) {
235
- process.stdout.write(
236
- action.kind === 'rewrite'
237
- ? `${check ? 'Would update' : 'Updated'} menu references in ${action.oldFile}\n`
238
- : `${check ? 'Would move ' : ''}${action.oldFile} -> ${action.newFile}\n`,
239
- );
986
+ const usage =
987
+ 'Usage: tea-migrate-customizations [--project-root PATH] [--check] [--keep-existing] [--help]\nFor a directory beginning with a dash, use --project-root ./-name.';
988
+ let projectRoot = process.cwd();
989
+ let check = false;
990
+ let keepExisting = false;
991
+ let help = false;
992
+ const seen = new Set();
993
+ for (let index = 0; index < argv.length; index++) {
994
+ const arg = argv[index];
995
+ if (arg === '--help' || arg === '-h') {
996
+ help = true;
997
+ } else if (arg === '--check' && !seen.has(arg)) {
998
+ check = true;
999
+ } else if (arg === '--keep-existing' && !seen.has(arg)) {
1000
+ keepExisting = true;
1001
+ } else if (arg === '--project-root' && !seen.has(arg)) {
1002
+ const value = argv[++index];
1003
+ if (!value || value.startsWith('-')) throw new Error('--project-root requires a path');
1004
+ projectRoot = path.resolve(value);
1005
+ } else {
1006
+ throw new Error(usage);
1007
+ }
1008
+ seen.add(arg);
1009
+ }
1010
+ if (help) {
1011
+ process.stdout.write(`${usage}\n`);
1012
+ return 0;
240
1013
  }
1014
+ const actions = migrate(projectRoot, { check, keepExisting });
1015
+ for (const action of actions) for (const line of describe(action, check)) process.stdout.write(`${line}\n`);
241
1016
  if (actions.length === 0) process.stdout.write('No legacy TEA customizations found.\n');
242
1017
  return 0;
243
1018
  }
244
1019
 
245
1020
  if (require.main === module) {
1021
+ signalState.exitOnSignal = true;
246
1022
  try {
247
1023
  process.exitCode = main();
248
1024
  } catch (error) {