bmad-method-test-architecture-enterprise 4.0.0 → 4.0.2

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.
@@ -31,7 +31,7 @@
31
31
  "name": "bmad-method-test-architecture-enterprise",
32
32
  "source": "./",
33
33
  "description": "Master Test Architect module for quality strategy, test generation in red and expand modes with automatic run-and-heal, combined framework and CI setup, CI/CD quality gates, and structured testing education. Existing CI and ATDD customizations can be migrated to the new skill names. Part of the BMad Method ecosystem.",
34
- "version": "4.0.0",
34
+ "version": "4.0.2",
35
35
  "author": {
36
36
  "name": "Murat K Ozcan (TEA Creator) & Brian (BMad) Madison"
37
37
  },
@@ -11,8 +11,9 @@
11
11
  * 2. The consuming project's `[modules.tea]` table, merged from
12
12
  * _bmad/config.toml, _bmad/custom/config.toml and
13
13
  * _bmad/custom/config.user.toml (later files win), the three files
14
- * BMad core merges, as `bmad setup tea` writes it. Only when _bmad/config.toml does not exist is a v6
15
- * _bmad/tea/config.yaml read instead, so older installs keep working in CI.
14
+ * BMad core merges, as `bmad setup tea` writes it. Each layer counts when its file exists, so custom
15
+ * layers apply even where the installer-owned _bmad/config.toml is not committed. Only when none of the
16
+ * three exists is a v6 _bmad/tea/config.yaml read instead, so older installs keep working in CI.
16
17
  * 3. The module default declared in skills/bmod-tea/bmod.toml
17
18
  *
18
19
  * Step 01 of the workflow branches on these keys (Playwright Utils loading
@@ -32,7 +33,7 @@ const TOML = require('smol-toml');
32
33
  const { minimatch } = require('minimatch');
33
34
  const { globSync } = require('glob');
34
35
 
35
- /** The central config layers, lowest precedence first, the three files BMad core merges. Only the first is required. */
36
+ /** The central config layers, lowest precedence first, the three files BMad core merges. Each applies when its file exists. */
36
37
  const CONFIG_LAYER_RELATIVE_PATHS = [
37
38
  path.join('_bmad', 'config.toml'),
38
39
  path.join('_bmad', 'custom', 'config.toml'),
@@ -44,8 +45,18 @@ const LEGACY_CONFIG_RELATIVE_PATH = path.join('_bmad', 'tea', 'config.yaml');
44
45
  const LEGACY_USER_CONFIG_RELATIVE_PATH = path.join('_bmad', 'config.user.toml');
45
46
  const warnedLegacyUserConfig = new Set();
46
47
 
47
- /** Tell the user once per process that `[modules.tea]` keys in the legacy personal layer are ignored. */
48
- function warnLegacyUserConfig(source, tea) {
48
+ /**
49
+ * Tell the user once per process that `[modules.tea]` keys in the legacy personal layer are ignored.
50
+ *
51
+ * The old core order was config.toml, config.user.toml, custom/config.toml, custom/config.user.toml
52
+ * (later wins), so the legacy file outranked only `_bmad/config.toml`. A legacy key lost its effect
53
+ * when neither custom layer holds it. When `_bmad/config.toml` holds the same value, nothing
54
+ * changed and the key stays quiet; a different value there is shown next to the legacy one.
55
+ *
56
+ * @param {object} source - Working-tree or pinned-base configuration reader.
57
+ * @param {{label: string, tea: object}[]} layers - The central layers in merge order, each with its own `[modules.tea]` table.
58
+ */
59
+ function warnLegacyUserConfig(source, layers) {
49
60
  const content = source.read(LEGACY_USER_CONFIG_RELATIVE_PATH);
50
61
  if (content === null) return;
51
62
  const label = source.label(LEGACY_USER_CONFIG_RELATIVE_PATH);
@@ -57,11 +68,25 @@ function warnLegacyUserConfig(source, tea) {
57
68
  return;
58
69
  }
59
70
  if (!isPlainObject(legacyTea)) return;
60
- const ignored = Object.keys(legacyTea).filter((key) => !Object.hasOwn(tea, key));
71
+ const [base, ...custom] = layers;
72
+ const ignored = [];
73
+ const shadowed = [];
74
+ for (const [key, value] of Object.entries(legacyTea)) {
75
+ if (custom.some((layer) => Object.hasOwn(layer.tea, key))) continue;
76
+ if (!Object.hasOwn(base.tea, key)) {
77
+ ignored.push(key);
78
+ } else if (JSON.stringify(base.tea[key]) !== JSON.stringify(value)) {
79
+ ignored.push(key);
80
+ shadowed.push(
81
+ `${key} is ${JSON.stringify(value)} in ${label} and ${JSON.stringify(base.tea[key])} in ${base.label}, which TEA uses.`,
82
+ );
83
+ }
84
+ }
61
85
  if (ignored.length === 0) return;
62
86
  warnedLegacyUserConfig.add(label);
87
+ const detail = shadowed.length === 0 ? '' : ` ${shadowed.join(' ')}`;
63
88
  process.stderr.write(
64
- `Warning: ${label} is no longer merged. TEA ignores its [modules.tea] keys (${ignored.join(', ')}). Run \`bmad migrate tea\` to move them into _bmad/custom/config.user.toml.\n`,
89
+ `Warning: ${label} is no longer merged. TEA ignores its [modules.tea] keys (${ignored.join(', ')}).${detail} Run \`bmad migrate tea\` to move them into _bmad/custom/config.user.toml.\n`,
65
90
  );
66
91
  }
67
92
 
@@ -427,28 +452,38 @@ function unionEqualCustomizationValues(legacy, current) {
427
452
  return result;
428
453
  }
429
454
 
430
- /** Coerce the keys this CLI cares about out of a raw TEA config table. */
455
+ /**
456
+ * Coerce the keys this CLI cares about out of a raw TEA config table.
457
+ *
458
+ * @param {object} table - Raw `[modules.tea]` keys.
459
+ * @param {string|Record<string, string>} source - One label for every key, or the label of the file that supplied each key.
460
+ */
431
461
  function pickTeaValues(table, source) {
462
+ const labelOf = (key) => (typeof source === 'string' ? source : (source[key] ?? 'the configuration'));
432
463
  const values = {};
433
464
  if ('tea_use_playwright_utils' in table) {
434
- values.tea_use_playwright_utils = coerceBoolean(table.tea_use_playwright_utils, 'tea_use_playwright_utils', source);
465
+ values.tea_use_playwright_utils = coerceBoolean(
466
+ table.tea_use_playwright_utils,
467
+ 'tea_use_playwright_utils',
468
+ labelOf('tea_use_playwright_utils'),
469
+ );
435
470
  }
436
471
  if ('tea_use_pactjs_utils' in table) {
437
- values.tea_use_pactjs_utils = coerceBoolean(table.tea_use_pactjs_utils, 'tea_use_pactjs_utils', source);
472
+ values.tea_use_pactjs_utils = coerceBoolean(table.tea_use_pactjs_utils, 'tea_use_pactjs_utils', labelOf('tea_use_pactjs_utils'));
438
473
  }
439
474
  if ('tea_pact_mcp' in table) {
440
- values.tea_pact_mcp = coercePactMcp(table.tea_pact_mcp, source);
475
+ values.tea_pact_mcp = coercePactMcp(table.tea_pact_mcp, labelOf('tea_pact_mcp'));
441
476
  }
442
477
  if ('tea_execution_mode' in table) {
443
- values.tea_execution_mode = coerceExecutionMode(table.tea_execution_mode, source);
478
+ values.tea_execution_mode = coerceExecutionMode(table.tea_execution_mode, labelOf('tea_execution_mode'));
444
479
  }
445
480
  if ('tea_capability_probe' in table) {
446
- values.tea_capability_probe = coerceBoolean(table.tea_capability_probe, 'tea_capability_probe', source);
481
+ values.tea_capability_probe = coerceBoolean(table.tea_capability_probe, 'tea_capability_probe', labelOf('tea_capability_probe'));
447
482
  }
448
483
  if ('test_stack_type' in table) {
449
484
  const stack = typeof table.test_stack_type === 'string' ? table.test_stack_type.trim().toLowerCase() : '';
450
485
  if (!['auto', 'frontend', 'backend', 'fullstack', 'mobile'].includes(stack)) {
451
- throw configError(`test_stack_type in ${source} must be auto, frontend, backend, fullstack or mobile`);
486
+ throw configError(`test_stack_type in ${labelOf('test_stack_type')} must be auto, frontend, backend, fullstack or mobile`);
452
487
  }
453
488
  values.test_stack_type = stack;
454
489
  }
@@ -457,31 +492,47 @@ function pickTeaValues(table, source) {
457
492
 
458
493
  /**
459
494
  * Merge the central TOML layers and return their core and TEA tables.
495
+ * Each layer is shape-checked before the merge, and every `[modules.tea]` key
496
+ * remembers the file that supplied its final value, so errors name that file.
460
497
  *
461
498
  * @param {object} source - Working-tree or pinned-base configuration reader.
462
- * @returns {{core: object, tea: object}}
499
+ * @returns {{core: object, tea: object, teaSources: Record<string, string>, found: string[]}}
500
+ * `found` lists the labels of the layer files that exist.
463
501
  */
464
502
  function readCentralConfig(source) {
465
503
  let merged = {};
504
+ const layers = [];
505
+ const found = [];
506
+ const teaSources = {};
466
507
  for (const relativePath of CONFIG_LAYER_RELATIVE_PATHS) {
508
+ const label = source.label(relativePath);
467
509
  const content = source.read(relativePath);
468
- if (content === null) continue;
469
- const parsed = parseToml(content, source.label(relativePath));
510
+ if (content === null) {
511
+ layers.push({ label, tea: {} });
512
+ continue;
513
+ }
514
+ found.push(label);
515
+ const parsed = parseToml(content, label);
516
+ const { modules, core } = parsed;
517
+ if (modules !== undefined && !isPlainObject(modules)) {
518
+ throw configError(`[modules] in ${label} must be a table`);
519
+ }
520
+ if (modules?.tea !== undefined && !isPlainObject(modules.tea)) {
521
+ throw configError(`[modules.tea] in ${label} must be a table of config keys`);
522
+ }
523
+ if (core !== undefined && !isPlainObject(core)) {
524
+ throw configError(`[core] in ${label} must be a table of config keys`);
525
+ }
526
+ layers.push({ label, tea: modules?.tea || {} });
527
+ for (const key of Object.keys(modules?.tea || {})) teaSources[key] = label;
470
528
  merged = mergeTables(merged, parsed);
471
529
  }
472
- const modules = merged.modules;
473
- if (modules !== undefined && (!isPlainObject(modules) || (modules.tea !== undefined && !isPlainObject(modules.tea)))) {
474
- throw configError(`[modules.tea] in ${source.label(CONFIG_RELATIVE_PATH)} must be a table of config keys`);
475
- }
476
- warnLegacyUserConfig(source, modules?.tea || {});
477
- if (merged.core !== undefined && !isPlainObject(merged.core)) {
478
- throw configError(`[core] in ${source.label(CONFIG_RELATIVE_PATH)} must be a table of config keys`);
479
- }
480
- return { core: merged.core || {}, tea: modules?.tea || {} };
530
+ warnLegacyUserConfig(source, layers);
531
+ return { core: merged.core || {}, tea: merged.modules?.tea || {}, teaSources, found };
481
532
  }
482
533
 
483
534
  /**
484
- * Read a v6 _bmad/tea/config.yaml, used only when _bmad/config.toml is absent.
535
+ * Read a v6 _bmad/tea/config.yaml, used only when none of the central TOML layers exists.
485
536
  *
486
537
  * @param {string} configPath
487
538
  * @param {string} content
@@ -510,17 +561,20 @@ function readLegacyTeaTable(configPath, content) {
510
561
  *
511
562
  * @param {string} projectRoot - Consuming project root.
512
563
  * @param {string} [baseRef] - Base commit or ref; omitted for working-tree config.
513
- * @returns {{present: boolean, path: string, format: 'toml'|'yaml'|null, values: object}}
564
+ * @returns {{present: boolean, path: string, paths: string[], format: 'toml'|'yaml'|null, values: object}}
565
+ * Present when any of the three central layers exists. `paths` lists the files read; `path` is the base
566
+ * file when it exists, else the first layer found, else the base file's expected location.
514
567
  */
515
568
  function readTeaConfigFile(projectRoot, baseRef, source = configSource(projectRoot, baseRef)) {
516
569
  const centralPath = source.label(CONFIG_RELATIVE_PATH);
517
- if (source.read(CONFIG_RELATIVE_PATH) !== null) {
518
- const config = readCentralConfig(source);
570
+ const config = readCentralConfig(source);
571
+ if (config.found.length > 0) {
519
572
  return {
520
573
  present: true,
521
- path: centralPath,
574
+ path: config.found.includes(centralPath) ? centralPath : config.found[0],
575
+ paths: config.found,
522
576
  format: 'toml',
523
- values: pickTeaValues(config.tea, centralPath),
577
+ values: pickTeaValues(config.tea, config.teaSources),
524
578
  core: config.core,
525
579
  tea: config.tea,
526
580
  };
@@ -534,9 +588,17 @@ function readTeaConfigFile(projectRoot, baseRef, source = configSource(projectRo
534
588
  .filter((key) => key in table)
535
589
  .map((key) => [key, table[key]]),
536
590
  );
537
- return { present: true, path: legacyPath, format: 'yaml', values: pickTeaValues(table, legacyPath), core, tea: table };
591
+ return {
592
+ present: true,
593
+ path: legacyPath,
594
+ paths: [legacyPath],
595
+ format: 'yaml',
596
+ values: pickTeaValues(table, legacyPath),
597
+ core,
598
+ tea: table,
599
+ };
538
600
  }
539
- return { present: false, path: centralPath, format: null, values: {}, core: {}, tea: {} };
601
+ return { present: false, path: centralPath, paths: [], format: null, values: {}, core: {}, tea: {} };
540
602
  }
541
603
 
542
604
  /**
@@ -599,7 +661,7 @@ const KEY_TO_INSTALLED_FIELD = {
599
661
  * FLAG_TO_KEY are read, and only when not undefined.
600
662
  * @param {Set<string>} [options.inputPaths] - Receives working-tree inputs, including missing optional layers.
601
663
  * @param {Map<string, string[]>} [options.inputPatterns] - Receives policy glob membership used during resolution.
602
- * @returns {{values: object, sources: object, installed: object, configSnapshot: object, workflowCustomization: object, configCommit: string|null, configPath: string, configPresent: boolean, configFormat: string|null}}
664
+ * @returns {{values: object, sources: object, installed: object, configSnapshot: object, workflowCustomization: object, configCommit: string|null, configPath: string, configPaths: string[], configPresent: boolean, configFormat: string|null}}
603
665
  * `installed` carries one boolean per library gate, read from the project
604
666
  * manifest rather than left to the agent.
605
667
  * @throws {Error} With code TEA_CONFIG_INVALID on unusable config content.
@@ -655,6 +717,7 @@ function resolveTeaConfig({ projectRoot, flags = {}, baseRef, skillRoot, skillNa
655
717
  workflowCustomization,
656
718
  configCommit: source.commit ?? null,
657
719
  configPath: file.path,
720
+ configPaths: file.paths,
658
721
  configPresent: file.present,
659
722
  configFormat: file.format,
660
723
  };
@@ -1310,7 +1310,7 @@ function validateTraceOutputs({
1310
1310
  ) {
1311
1311
  throw new Error(`Trace coverage ${name} has invalid counts.`);
1312
1312
  }
1313
- const expected = bucket.total === 0 ? 100 : Math.round((bucket.covered / bucket.total) * 100);
1313
+ const expected = bucket.total === 0 ? 100 : Math.floor((bucket.covered * 100) / bucket.total);
1314
1314
  if (bucket.pct !== expected) throw new Error(`Trace coverage ${name} percentage does not match its counts.`);
1315
1315
  }
1316
1316
  const priorities = ['P0', 'P1', 'P2', 'P3'].map((key) => summary.coverage.priority_breakdown[key]);
@@ -1415,7 +1415,7 @@ function validateTraceOutputs({
1415
1415
  const p0 = summary.coverage.priority_breakdown.P0.pct;
1416
1416
  const p1 = summary.coverage.priority_breakdown.P1.pct;
1417
1417
  const overall = summary.coverage.inventory.pct;
1418
- // Percentages remain rounded for display; decisions compare the source counts.
1418
+ // Displayed percentages round down, so they reach a whole-number threshold exactly when the counts do; decisions compare the source counts.
1419
1419
  const meets = (bucket, threshold) => bucket.total === 0 || bucket.covered * 100 >= threshold * bucket.total;
1420
1420
  const p0Met = meets(summary.coverage.priority_breakdown.P0, 100);
1421
1421
  const p1TargetMet = meets(summary.coverage.priority_breakdown.P1, 90);
@@ -4,6 +4,7 @@
4
4
  * stems into [workflow.red] and [workflow.ci] of their owning skills, and agent menu references to current skill ids.
5
5
  */
6
6
  const fs = require('node:fs');
7
+ const os = require('node:os');
7
8
  const path = require('node:path');
8
9
  const { isDeepStrictEqual } = require('node:util');
9
10
  const TOML = require('smol-toml');
@@ -296,17 +297,31 @@ function legacyConfigNotice(root, backups) {
296
297
  if (!legacy) return null;
297
298
  const tea = tryParse(legacy.text)?.modules?.tea;
298
299
  if (!isTable(tea)) return null;
299
- const held = new Set();
300
- for (const segments of CONFIG_LAYERS) {
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) => {
301
302
  const file = path.join(root, ...segments);
302
303
  const text = readOptional(file);
303
- if (text === null) continue;
304
- const layer = parse(file, text).modules?.tea;
305
- if (isTable(layer)) for (const key of Object.keys(layer)) held.add(key);
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
+ }
306
321
  }
307
- const ignored = Object.keys(tea).filter((key) => !held.has(key));
308
322
  if (ignored.length === 0) return null;
309
- const line = `Not migrated by this command: ${legacy.file} [modules.tea] keys ${ignored.join(', ')} are ignored by TEA. Run \`bmad migrate tea\` to move them.`;
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.`;
310
325
  return { kind: 'notice', messages: [{ done: line, check: line }] };
311
326
  }
312
327
 
@@ -787,26 +802,179 @@ function migrate(projectRoot, { check = false, keepExisting = false, beforeActio
787
802
  fs.mkdirSync(customRoot);
788
803
  }
789
804
  const lock = path.join(customRoot, '.tea-migration.lock');
805
+ const recovered = [];
806
+ holdSignals();
790
807
  try {
791
- fs.mkdirSync(lock, { mode: 0o700 });
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) {
873
+ try {
874
+ process.kill(pid, 0);
875
+ return false;
792
876
  } catch (error) {
793
- if (error.code === 'EEXIST') {
794
- throw new Error(
795
- `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`,
796
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}`);
797
935
  }
798
- throw new Error(`Cannot lock ${customRoot} for migration: ${error.message}`);
936
+ return;
799
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`;
800
951
  try {
801
- const plan = preflight(root, customRoot, { keepExisting });
802
- applyActions(plan.actions, customRoot, beforeAction);
803
- if (!isDeepStrictEqual(plan.nextRecord, plan.record)) writeRecord(customRoot, plan.nextRecord);
804
- return plan.actions;
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
+ );
958
+ }
959
+ try {
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')) });
805
968
  } finally {
806
- fs.rmdirSync(lock);
969
+ fs.rmdirSync(claim);
807
970
  }
808
971
  }
809
972
 
973
+ function releaseLock(lock) {
974
+ fs.rmSync(path.join(lock, LOCK_OWNER), { force: true });
975
+ fs.rmdirSync(lock);
976
+ }
977
+
810
978
  function describe(action, check) {
811
979
  const lines = (action.messages ?? []).map((message) => (check ? message.check : message.done));
812
980
  if (action.kind === 'rewrite') lines.push(`${check ? 'Would update' : 'Updated'} menu references in ${action.oldFile}`);
@@ -850,6 +1018,7 @@ function main(argv = process.argv.slice(2)) {
850
1018
  }
851
1019
 
852
1020
  if (require.main === module) {
1021
+ signalState.exitOnSignal = true;
853
1022
  try {
854
1023
  process.exitCode = main();
855
1024
  } catch (error) {
@@ -1117,7 +1117,11 @@ async function runReview(session) {
1117
1117
  configSnapshot = resolvedTeaConfig.configSnapshot;
1118
1118
  workflowCustomization = resolvedTeaConfig.workflowCustomization;
1119
1119
  configCommit = resolvedTeaConfig.configCommit;
1120
- console.error(`tea-test-review: config ${resolvedTeaConfig.configPath}`);
1120
+ console.error(
1121
+ resolvedTeaConfig.configPresent
1122
+ ? `tea-test-review: config ${resolvedTeaConfig.configPaths.join(', ')}`
1123
+ : 'tea-test-review: no config found; using module defaults',
1124
+ );
1121
1125
  } catch (error) {
1122
1126
  if (error.code === 'TEA_CONFIG_INVALID') {
1123
1127
  fail(EXIT.ENV_ERROR, error.message);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "bmad-method-test-architecture-enterprise",
4
- "version": "4.0.0",
4
+ "version": "4.0.2",
5
5
  "description": "Master Test Architect for quality strategy, test automation, and release gates",
6
6
  "keywords": [
7
7
  "bmad",
@@ -21,7 +21,7 @@ This is an **isolated subagent** running in parallel with E2E red-phase test gen
21
21
 
22
22
  **When `use_playwright_utils` is `true`, `playwright-utils-mandate.md` binds this worker.** A red-phase scaffold is real test code; generate it in the playwright-utils style without being asked.
23
23
 
24
- **If `use_pactjs_utils` is enabled AND the relevance gate opened in Step 1 AND `@seontechnologies/pactjs-utils` is installed:** Also generate consumer contract tests alongside API tests. All three are required. The flag on its own means "write Pact this way when you write it", never "this story needs a contract test", and scaffolding against an uninstalled package produces imports that do not resolve. When any of the three is false, generate the API tests and say in the output which condition was missing. `pactjs-utils-mandate.md` binds them: `.given(...createProviderState({ name, params }))`, `setJsonContent` / `setJsonBody` for builder callbacks, `createRequestFilter` for auth injection, `zodToPactMatchers` where a Zod schema exists, and the `pact-consumer-di.md` injection so `executeTest` exercises the real client instead of raw `fetch`. A red-phase contract test is still the file the developer keeps. Use the loaded pactjs-utils fragments (`pactjs-utils-overview`, `pactjs-utils-consumer-helpers`, `pactjs-utils-provider-verifier`, `pactjs-utils-request-filter`, `pact-consumer-di`, `pact-consumer-framework-setup`) for patterns. When generating consumer tests, enforce **one `pact.addInteraction()` per `it()` block** (see `pactjs-utils-consumer-helpers.md` Example 6) — PactV4's Rust FFI non-deterministically drops interactions if multiple are chained in one test. Gate broker calls on `pact_mcp_reachable`, not on `pact_mcp`. When it is `true`, use the SmartBear MCP tools (Fetch Provider States, Generate Pact Tests). When it is `false`, take provider states from `pact_fallback_source` and say so in the output. Step 1 probed once; do not probe again.
24
+ **If `use_pactjs_utils` is enabled AND the relevance gate opened in Step 1 AND `@seontechnologies/pactjs-utils` is installed:** Also generate consumer contract tests alongside API tests. All three are required. The flag on its own means "write Pact this way when you write it", never "this story needs a contract test", and scaffolding against an uninstalled package produces imports that do not resolve. When any of the three is false, generate the API tests and say in the output which condition was missing. `pactjs-utils-mandate.md` binds them: `.given(...createProviderState({ name, params }))`, `setJsonContent` / `setJsonBody` for builder callbacks, `createRequestFilter` for auth injection, `zodToPactMatchers` where a Zod schema exists, and the `pact-consumer-di.md` injection so `executeTest` exercises the real client instead of raw `fetch`. A red-phase contract test is still the file the developer keeps. Use the loaded pactjs-utils fragments (`pactjs-utils-overview`, `pactjs-utils-consumer-helpers`, `pactjs-utils-provider-verifier`, `pactjs-utils-request-filter`, `pact-consumer-di`, `pact-consumer-framework-setup`) for patterns. When generating consumer tests, enforce **one `pact.addInteraction()` per `it()` block** (see `pactjs-utils-consumer-helpers.md` Example 6) — PactV4's Rust FFI non-deterministically drops interactions if multiple are chained in one test. Gate broker calls on `pact_mcp_reachable`, not on `pact_mcp`. When it is `true`, use the read-only SmartBear MCP tools (`contract-testing_get_provider_states`, `contract-testing_list_pacticipants`). Call `contract-testing_generate_pact_tests` only when the user asked for PactFlow AI output: it sends code to the hosted service and spends workspace credits (`pact-mcp.md` § PactFlow AI tools need an explicit request). When it is `false`, take provider states from `pact_fallback_source` and say so in the output. Step 1 probed once; do not probe again.
25
25
 
26
26
  **Your task:** Generate API test scaffolds for the feature's expected behavior. They stay in `test.skip()` until the developer activates them for the current task (TDD RED PHASE).
27
27
 
@@ -177,7 +177,7 @@ When generating Pact consumer contract tests in the ATDD red phase, provider scr
177
177
  **Graceful degradation when provider source is inaccessible:**
178
178
 
179
179
  1. **OpenAPI/Swagger spec available**: Use the spec as the source of truth for response shapes, status codes, and field names
180
- 2. **Pact Broker available** (when `pact_mcp` is `"mcp"`): Use SmartBear MCP tools to fetch existing provider states and verified interactions as reference
180
+ 2. **Pact Broker available** (when `pact_mcp_reachable` is `true`): Use the read-only SmartBear MCP tools to fetch existing provider states and verified interactions as reference
181
181
  3. **Neither available**: For new endpoints, use acceptance criteria; for existing endpoints, use consumer-side types. Mark with `// Provider endpoint: TODO — provider source not accessible, verify manually` and set `provider_scrutiny: "pending"` in output JSON
182
182
  4. **Never silently guess**: Document all assumptions in the scrutiny evidence block
183
183
 
@@ -32,7 +32,7 @@ Apply pactjs-utils conventions from the loaded fragments (`pactjs-utils-overview
32
32
  - **Consumer `package.json`**: generate both `test:pact:consumer` (determinism gate calling `scripts/check-pact-determinism.sh`) and `test:pact:consumer:run` (inner vitest invocation).
33
33
  - **Publish script**: `scripts/publish-pact.sh` normalizes interactions with `jq -S '.interactions |= sort_by(...)'` before `pact-broker publish`.
34
34
 
35
- Gate broker calls on `pact_mcp_reachable`, not on `pact_mcp`. The mode says the user allows a broker; the probe result says whether one answered. When `pact_mcp_reachable` is `true`, use the SmartBear MCP tools (Fetch Provider States, Generate Pact Tests) to inform generation. When it is `false`, take provider states from `pact_fallback_source` and say so in the output. Do not probe again: Step 1 already did, once.
35
+ Gate broker calls on `pact_mcp_reachable`, not on `pact_mcp`. The mode says the user allows a broker; the probe result says whether one answered. When `pact_mcp_reachable` is `true`, use the read-only SmartBear MCP tools (`contract-testing_get_provider_states`, `contract-testing_list_pacticipants`) to inform generation. Call `contract-testing_generate_pact_tests` only when the user asked for PactFlow AI output: it sends code to the hosted service and spends workspace credits (`pact-mcp.md` § PactFlow AI tools need an explicit request). When it is `false`, take provider states from `pact_fallback_source` and say so in the output. Do not probe again: Step 1 already did, once.
36
36
 
37
37
  ---
38
38
 
@@ -218,7 +218,7 @@ The seven points to verify for each interaction:
218
218
 
219
219
  6. **Graceful degradation** when provider source is not accessible (follows the canonical four-step protocol from `contract-testing.md`):
220
220
  1. **OpenAPI/Swagger spec available**: Use the spec as the source of truth for response shapes, status codes, and field names
221
- 2. **Pact Broker available** (when `pact_mcp` is `"mcp"` in `subagentContext.config`): Use SmartBear MCP tools to fetch existing provider states and verified interactions as reference
221
+ 2. **Pact Broker available** (when `pact_mcp_reachable` is `true` in `subagentContext.config`): Use the read-only SmartBear MCP tools to fetch existing provider states and verified interactions as reference
222
222
  3. **Neither available**: Generate from consumer types but use the TODO form of the mandatory comment: `// Provider endpoint: TODO — provider source not accessible, verify manually`. Set `provider_scrutiny: "pending"` in output JSON
223
223
  4. **Never silently guess**: Document all assumptions in the scrutiny evidence block
224
224