bmad-method-test-architecture-enterprise 3.4.0 → 3.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.
Files changed (41) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/cli/lib/trace-command.js +972 -48
  3. package/cli/lib/trace-live.js +46 -8
  4. package/cli/trace.js +16 -3
  5. package/package.json +1 -1
  6. package/skills/bmad-tea-automate/SKILL.md +1 -0
  7. package/skills/bmad-tea-automate/red/atdd-checklist-template.md +7 -2
  8. package/skills/bmad-tea-automate/red/checklist.md +1 -1
  9. package/skills/bmad-tea-automate/red/resources/atdd-checklist-2-4-guest-checkout.example.md +5 -2
  10. package/skills/bmad-tea-automate/red/steps-c/step-01-preflight-and-context.md +12 -14
  11. package/skills/bmad-tea-automate/red/steps-c/step-01b-resume.md +4 -2
  12. package/skills/bmad-tea-automate/red/steps-c/step-04c-aggregate.md +7 -5
  13. package/skills/bmad-tea-automate/red/steps-c/step-05-validate-and-complete.md +5 -3
  14. package/skills/bmad-tea-automate/steps-c/step-01-preflight-and-context.md +4 -2
  15. package/skills/bmad-tea-automate/steps-c/step-01b-resume.md +2 -0
  16. package/skills/bmad-tea-automate/steps-c/step-02-identify-targets.md +1 -1
  17. package/skills/bmad-tea-evaluate/references/ci.md +2 -2
  18. package/skills/bmad-tea-framework/resources/framework-setup-progress.example.md +1 -1
  19. package/skills/bmad-tea-framework/resources/hooks/tea-enforce.cjs +295 -39
  20. package/skills/bmad-tea-framework/steps-c/step-04-docs-and-scripts.md +2 -2
  21. package/skills/bmad-tea-nfr/SKILL.md +1 -0
  22. package/skills/bmad-tea-nfr/steps-c/step-01-load-context.md +4 -2
  23. package/skills/bmad-tea-nfr/steps-c/step-01b-resume.md +2 -0
  24. package/skills/bmad-tea-test-design/steps-c/step-01-detect-mode.md +4 -1
  25. package/skills/bmad-tea-test-review/SKILL.md +2 -1
  26. package/skills/bmad-tea-test-review/steps-c/step-01-load-context.md +7 -4
  27. package/skills/bmad-tea-test-review/steps-c/step-01b-resume.md +2 -0
  28. package/skills/bmad-tea-trace/SKILL.md +1 -0
  29. package/skills/bmad-tea-trace/checklist.md +20 -1
  30. package/skills/bmad-tea-trace/resources/traceability-matrix.example.md +8 -8
  31. package/skills/bmad-tea-trace/steps-c/step-01-load-context.md +126 -8
  32. package/skills/bmad-tea-trace/steps-c/step-01b-resume.md +16 -4
  33. package/skills/bmad-tea-trace/steps-c/step-02-discover-tests.md +4 -0
  34. package/skills/bmad-tea-trace/steps-c/step-03-map-criteria.md +172 -8
  35. package/skills/bmad-tea-trace/steps-c/step-04-analyze-gaps.md +52 -10
  36. package/skills/bmad-tea-trace/steps-c/step-05-gate-decision.md +81 -10
  37. package/skills/bmad-tea-trace/trace-template.md +50 -3
  38. package/skills/bmod-tea/bmod.toml +1 -1
  39. package/skills/bmod-tea/contracts/story-identity.md +79 -0
  40. package/skills/bmod-tea/help/help.md +38 -6
  41. package/skills/bmod-tea/migration-2.toml +100 -0
@@ -32,19 +32,24 @@
32
32
  * 3. A whole-file rule (H5's 1000-line ceiling, C4's "this flow asserts nothing
33
33
  * anywhere") cannot be decided from a fragment at all.
34
34
  *
35
- * So: `--pre` is the fast block on the fragment about to be written; `--post`
35
+ * So: `--pre` is the fast block on the write about to land. For an Edit or
36
+ * MultiEdit it applies the edit to the file on disk and scans the result whole,
37
+ * reporting only what the edit introduced, so a fragment inside an existing
38
+ * comment is read as a comment and a violation spanning the fragment's edge is
39
+ * seen; it scans the bare fragment only when the file cannot be read. `--post`
36
40
  * re-reads the affected file(s) from disk in full and applies the same rules,
37
- * which is what catches Bash writes and split edits; `--stop` sweeps recently
38
- * modified test files at the end of a turn, which is what catches a codegen script
39
- * that wrote files it never named. File-scope rules (H5, C4) run in `--pre` only
40
- * for `Write`, where the whole content is genuinely present.
41
+ * which is what catches Bash writes; `--stop` sweeps recently modified test files
42
+ * at the end of a turn, which is what catches a codegen script that wrote files it
43
+ * never named. File-scope rules (H5, C4) skip only that bare-fragment fallback.
41
44
  *
42
45
  * FALSE POSITIVES
43
46
  *
44
47
  * Comments and string literals are stripped, per language, before any pattern runs.
45
48
  * A doc example that writes `await page.waitForTimeout(500)` inside a fenced block
46
49
  * in a `.md` is not a violation and this hook does not claim it is. Line numbers
47
- * survive stripping because stripped characters are replaced by spaces.
50
+ * survive stripping because stripped characters are replaced by spaces. Rules
51
+ * whose construct a formatter splits across lines (C2, C3) match the whole
52
+ * stripped source and map each match back to the line it starts on.
48
53
  *
49
54
  * GATES
50
55
  *
@@ -282,7 +287,31 @@ function blank(length) {
282
287
  return ' '.repeat(length);
283
288
  }
284
289
 
285
- function stripCLike(source) {
290
+ /**
291
+ * A string or regex literal, rendered for the requested view: blanked (the
292
+ * default, for matching), kept (for reading operands), or masked with `x` (for
293
+ * knowing which characters of a kept operand are inside a literal; see
294
+ * `codeInMask` for everything else in that view). Every view
295
+ * is the same length, so offsets line up across all three. The blanked view keeps
296
+ * newlines so line numbers survive; the mask marks them too, because a newline
297
+ * inside a literal is part of its value.
298
+ */
299
+ function literal(source, start, end, mode) {
300
+ const text = source.slice(start, end);
301
+ if (mode === 'keep') return text;
302
+ if (mode === 'mask') return 'x'.repeat(text.length);
303
+ return text.replaceAll(/[^\n]/g, ' ');
304
+ }
305
+
306
+ /**
307
+ * Code outside a literal, in the masked view: blank, newlines kept. The mask must
308
+ * hold nothing but `x` for literal positions, or an identifier ending in `x`
309
+ * would merge with the literal after it (a template tagged `x` would read as a
310
+ * literal opening with `x`, not with a backtick).
311
+ */
312
+ const codeInMask = (character) => (character === '\n' ? '\n' : ' ');
313
+
314
+ function stripCLike(source, literals) {
286
315
  let out = '';
287
316
  let index = 0;
288
317
  // Whether a `/` at this position could open a regex literal rather than divide.
@@ -329,7 +358,7 @@ function stripCLike(source) {
329
358
  scan += 1;
330
359
  }
331
360
  if (closed) {
332
- out += blank(scan - index);
361
+ out += literal(source, index, scan, literals);
333
362
  index = scan;
334
363
  regexAllowed = false;
335
364
  continue;
@@ -351,20 +380,20 @@ function stripCLike(source) {
351
380
  if (quote !== '`' && source[scan] === '\n') break;
352
381
  scan += 1;
353
382
  }
354
- for (let position = index; position < scan; position += 1) out += source[position] === '\n' ? '\n' : ' ';
383
+ out += literal(source, index, scan, literals);
355
384
  index = scan;
356
385
  regexAllowed = true;
357
386
  continue;
358
387
  }
359
388
 
360
- out += character;
389
+ out += literals === 'mask' ? codeInMask(character) : character;
361
390
  if (!/\s/.test(character)) regexAllowed = /[(,=:[!&|?{};+\-*%<>~^]/.test(character);
362
391
  index += 1;
363
392
  }
364
393
  return out;
365
394
  }
366
395
 
367
- function stripPython(source) {
396
+ function stripPython(source, literals) {
368
397
  let out = '';
369
398
  let index = 0;
370
399
  while (index < source.length) {
@@ -382,7 +411,7 @@ function stripPython(source) {
382
411
  if (triple === '"""' || triple === "'''") {
383
412
  const end = source.indexOf(triple, index + 3);
384
413
  const stop = end === -1 ? source.length : end + 3;
385
- for (let scan = index; scan < stop; scan += 1) out += source[scan] === '\n' ? '\n' : ' ';
414
+ out += literal(source, index, stop, literals);
386
415
  index = stop;
387
416
  continue;
388
417
  }
@@ -401,12 +430,12 @@ function stripPython(source) {
401
430
  }
402
431
  scan += 1;
403
432
  }
404
- out += blank(scan - index);
433
+ out += literal(source, index, scan, literals);
405
434
  index = scan;
406
435
  continue;
407
436
  }
408
437
 
409
- out += character;
438
+ out += literals === 'mask' ? codeInMask(character) : character;
410
439
  index += 1;
411
440
  }
412
441
  return out;
@@ -461,20 +490,98 @@ function stripNoise(source, kind) {
461
490
  }
462
491
  }
463
492
 
493
+ /**
494
+ * Comments blanked, string and regex literals kept (`mode: 'keep'`) or masked
495
+ * (`mode: 'mask'`), same length as the input.
496
+ *
497
+ * `stripNoise` is right for deciding WHERE a pattern matches, and wrong for
498
+ * deciding what an operand IS: once literal contents are blanked,
499
+ * `result['actual']` and `result['expected']` are both `result[ ]`.
500
+ * C3 finds its match on the stripped text and reads the operands from the kept
501
+ * view, at the same offsets; the masked view says which of those characters sit
502
+ * inside a literal, where whitespace is part of the value.
503
+ */
504
+ function stripComments(source, kind, mode) {
505
+ switch (kind) {
506
+ case 'js':
507
+ case 'java':
508
+ case 'go':
509
+ case 'pactconfig': {
510
+ return stripCLike(source, mode);
511
+ }
512
+ case 'py': {
513
+ return stripPython(source, mode);
514
+ }
515
+ default: {
516
+ // Maestro YAML has no C3 and no kept view; callers use the stripped text.
517
+ return null;
518
+ }
519
+ }
520
+ }
521
+
464
522
  // ---------------------------------------------------------------------------
465
523
  // Helpers shared by the rule predicates
466
524
  // ---------------------------------------------------------------------------
467
525
 
468
- const normalizeOperand = (value) => String(value).replaceAll(/\s+/g, '').replace(/;$/, '');
526
+ /**
527
+ * An operand with the whitespace outside its literals removed.
528
+ *
529
+ * Whitespace inside a string or regex literal is part of the value: `'a b'` and
530
+ * `'ab'` differ, as do `/a b/` and `/ab/`, and collapsing them would turn a
531
+ * comparison that can fail into a reported tautology. `mask` is the same slice of
532
+ * the masked view, `x` wherever the character is inside a literal.
533
+ */
534
+ function normalizeOperand(value, mask) {
535
+ return value.replaceAll(/\s/g, (character, offset) => (mask[offset] === 'x' ? character : '')).replace(/;$/, '');
536
+ }
469
537
 
470
- /** A pair of equal operands is the mechanical core of C3. */
471
- function selfComparison(line, pattern) {
472
- const matches = [...line.matchAll(pattern)];
473
- return matches.some((match) => {
474
- const left = normalizeOperand(match[1] ?? '');
475
- const right = normalizeOperand(match[2] ?? '');
476
- return left.length > 0 && left === right;
477
- });
538
+ /**
539
+ * Whether a JavaScript operand contains a template literal that interpolates.
540
+ * Stripping blanks the whole template, `${...}` included, so the operand pattern
541
+ * cannot see a call or an `i++` inside it, and two textually equal templates can
542
+ * still evaluate to different values. Such operands are never reported.
543
+ *
544
+ * Only a literal that OPENS with a backtick is a template. A backtick inside a
545
+ * quoted string is data, and Go's backtick raw strings never interpolate, so
546
+ * `${` in either is a constant.
547
+ */
548
+ function interpolates(text, mask, kind) {
549
+ if (kind !== 'js') return false;
550
+ for (const run of mask.matchAll(/x+/g)) {
551
+ const body = text.slice(run.index, run.index + run[0].length);
552
+ if (body.startsWith('`') && body.includes('${')) return true;
553
+ }
554
+ return false;
555
+ }
556
+
557
+ /**
558
+ * `[start, end]` of every match whose two operands are the same expression: the
559
+ * mechanical core of C3.
560
+ *
561
+ * The pattern runs on the stripped source, so a quote or comment cannot fake a
562
+ * match. The operands are read from the kept view (comments blanked, literals
563
+ * intact) at the match's group offsets, so two operands that differ only inside
564
+ * a literal still compare different. Each operand group must span everything
565
+ * between its delimiters, surrounding whitespace included: a group that stops at
566
+ * the last non-blank stripped character would cut `x + 'a'` down to `x +`.
567
+ */
568
+ function selfComparisons(stripped, views, pattern) {
569
+ const spans = [];
570
+ for (const match of stripped.matchAll(pattern)) {
571
+ const operands = [1, 2].map((group) => {
572
+ const [start, end] = match.indices[group] ?? [0, 0];
573
+ return { text: views.code.slice(start, end), mask: views.mask.slice(start, end) };
574
+ });
575
+ if (operands.some(({ text, mask }) => interpolates(text, mask, views.kind))) continue;
576
+ const [left, right] = operands.map(({ text, mask }) => normalizeOperand(text, mask));
577
+ if (left.length > 0 && left === right) spans.push([match.index, match.index + match[0].length]);
578
+ }
579
+ return spans;
580
+ }
581
+
582
+ /** `[start, end]` of every match of `pattern` (which must carry the `g` flag). */
583
+ function matchSpans(source, pattern) {
584
+ return [...source.matchAll(pattern)].map((match) => [match.index, match.index + match[0].length]);
478
585
  }
479
586
 
480
587
  const SKIP_TOKEN = /\.skip|xit|xdescribe|test\.todo|@Ignore|@Disabled|pytest\.mark\.skip/;
@@ -578,11 +685,13 @@ const RULES = [
578
685
  severity: 'CRITICAL',
579
686
  gate: 'Absolute',
580
687
  action: 'block',
581
- scope: 'line',
688
+ // Source scope because formatters split chains: `test.only\n("x", ...)` is as
689
+ // focused as the one-line form, and a per-line scan never sees it.
690
+ scope: 'source',
582
691
  kinds: ['js'],
583
692
  fix: 'Remove `.only` / `fdescribe` / `fit`. A committed focus silently disables every sibling test in the file.',
584
- match(line) {
585
- return /(?:^|[^\w.])(?:fdescribe|fit|ftest)\s*\(/.test(line) || /\.only\s*[(.]/.test(line);
693
+ matchSource(stripped) {
694
+ return [...matchSpans(stripped, /(?<![\w.])(?:fdescribe|fit|ftest)\s*\(/g), ...matchSpans(stripped, /\.only\s*[(.]/g)];
586
695
  },
587
696
  },
588
697
  {
@@ -591,33 +700,39 @@ const RULES = [
591
700
  severity: 'CRITICAL',
592
701
  gate: 'Absolute',
593
702
  action: 'block',
594
- scope: 'line',
703
+ // Source scope because formatters split chains: `expect(actual)\n .toBe(actual)`
704
+ // is the same tautology as the one-line form.
705
+ scope: 'source',
595
706
  kinds: ['js', 'py', 'java', 'go'],
596
707
  fix: 'Assert the value the system under test produced against an expectation that could differ from it.',
597
- match(line, context) {
708
+ matchSource(stripped, context) {
598
709
  if (context.kind === 'js') {
599
710
  // `.not.` is excluded on purpose: `expect(x).not.toBe(x)` is a defect too,
600
711
  // but it always FAILS, so it is not the "test cannot fail" failure this row
601
712
  // is about, and blocking it would be this hook overreaching its row.
602
- return selfComparison(
603
- line,
604
- /expect\s*\(\s*([^(),]+?)\s*\)\s*\.\s*(?:to\s*\.\s*)?(?:toBe|toEqual|toStrictEqual|toBeCloseTo|equal|equals|eql|deep\s*\.\s*equal)\s*\(\s*([^(),]+?)\s*\)/g,
713
+ return selfComparisons(
714
+ stripped,
715
+ context,
716
+ /expect\s*\(([^(),]+?)\)\s*\.\s*(?:to\s*\.\s*)?(?:toBe|toEqual|toStrictEqual|toBeCloseTo|equal|equals|eql|deep\s*\.\s*equal)\s*\(([^(),]+?)\)/dg,
605
717
  );
606
718
  }
607
719
  if (context.kind === 'py') {
608
- return selfComparison(line, /assert\s+([^=<>!\s]+)\s*==\s*([^=<>!\s#]+)/g);
720
+ // Horizontal whitespace only: a Python statement does not continue onto the
721
+ // next line without a bracket or a backslash, so `\s` here would pair an
722
+ // `assert` with a `==` on a later, unrelated line.
723
+ return selfComparisons(stripped, context, /assert[ \t]+([^=<>!\s]+)[ \t]*==[ \t]*([^=<>!\s#]+)/dg);
609
724
  }
610
725
  if (context.kind === 'java') {
611
- return (
612
- /assertTrue\s*\(\s*true\s*\)/.test(line) ||
613
- /assertFalse\s*\(\s*false\s*\)/.test(line) ||
614
- selfComparison(line, /assertEquals\s*\(\s*([^,()]+?)\s*,\s*([^,()]+?)\s*\)/g)
615
- );
726
+ return [
727
+ ...matchSpans(stripped, /assertTrue\s*\(\s*true\s*\)/g),
728
+ ...matchSpans(stripped, /assertFalse\s*\(\s*false\s*\)/g),
729
+ ...selfComparisons(stripped, context, /assertEquals\s*\(([^,()]+?),([^,()]+?)\)/dg),
730
+ ];
616
731
  }
617
732
  if (context.kind === 'go') {
618
- return selfComparison(line, /assert\.(?:Equal|EqualValues)\s*\(\s*t\s*,\s*([^,()]+?)\s*,\s*([^,()]+?)\s*\)/g);
733
+ return selfComparisons(stripped, context, /assert\.(?:Equal|EqualValues)\s*\(\s*t\s*,([^,()]+?),([^,()]+?)\)/dg);
619
734
  }
620
- return false;
735
+ return [];
621
736
  },
622
737
  },
623
738
  {
@@ -746,6 +861,24 @@ function activeRules(config) {
746
861
  return RULES.filter((rule) => !disabled.has(rule.id));
747
862
  }
748
863
 
864
+ function lineStartOffsets(source) {
865
+ const starts = [0];
866
+ for (let index = source.indexOf('\n'); index !== -1; index = source.indexOf('\n', index + 1)) starts.push(index + 1);
867
+ return starts;
868
+ }
869
+
870
+ /** Zero-based line holding `offset`, by binary search over line starts. */
871
+ function lineAt(lineStarts, offset) {
872
+ let low = 0;
873
+ let high = lineStarts.length - 1;
874
+ while (low < high) {
875
+ const middle = Math.ceil((low + high) / 2);
876
+ if (lineStarts[middle] <= offset) low = middle;
877
+ else high = middle - 1;
878
+ }
879
+ return low;
880
+ }
881
+
749
882
  /**
750
883
  * Apply every open-gated rule to one file's content.
751
884
  *
@@ -769,6 +902,8 @@ function scanContent(relativePath, source, config, options) {
769
902
  const strippedLines = stripped.split('\n');
770
903
  const rawLines = source.split('\n');
771
904
  const lineCount = source.replace(/\n$/, '').split('\n').length;
905
+ const lineStarts = lineStartOffsets(stripped);
906
+ let views = null;
772
907
  const findings = [];
773
908
 
774
909
  for (const rule of activeRules(settings)) {
@@ -783,6 +918,34 @@ function scanContent(relativePath, source, config, options) {
783
918
  line: 1,
784
919
  detail: rule.describe ? rule.describe(context) : '',
785
920
  text: '',
921
+ occurrences: [''],
922
+ });
923
+ }
924
+ continue;
925
+ }
926
+
927
+ views ??= { code: stripComments(source, kind, 'keep') ?? stripped, mask: stripComments(source, kind, 'mask') ?? '' };
928
+ // What a violation IS, independent of where it sits and of the comments and
929
+ // layout around it: the code it spans, literals intact, whitespace outside
930
+ // literals dropped. `introducedFindings` compares these.
931
+ const identity = (start, end) => normalizeOperand(views.code.slice(start, end), views.mask.slice(start, end));
932
+
933
+ if (rule.scope === 'source') {
934
+ // Every match maps back to the line it starts on. Stripping preserves
935
+ // newlines, so offsets into the stripped text are offsets into the source.
936
+ // One finding per line, as the line rules report, carrying every match on it.
937
+ const byLine = new Map();
938
+ for (const [start, end] of rule.matchSource(stripped, { kind, config: settings, ...views, relativePath })) {
939
+ const index = lineAt(lineStarts, start);
940
+ byLine.set(index, [...(byLine.get(index) || []), identity(start, end)]);
941
+ }
942
+ for (const index of [...byLine.keys()].sort((a, b) => a - b)) {
943
+ findings.push({
944
+ rule,
945
+ line: index + 1,
946
+ detail: '',
947
+ text: (rawLines[index] || '').trim().slice(0, 120),
948
+ occurrences: byLine.get(index),
786
949
  });
787
950
  }
788
951
  continue;
@@ -796,6 +959,7 @@ function scanContent(relativePath, source, config, options) {
796
959
  line: index + 1,
797
960
  detail: '',
798
961
  text: (rawLines[index] || '').trim().slice(0, 120),
962
+ occurrences: [identity(lineStarts[index], lineStarts[index] + line.length)],
799
963
  });
800
964
  }
801
965
  }
@@ -899,6 +1063,86 @@ function fragmentsFromPayload(payload) {
899
1063
  return [];
900
1064
  }
901
1065
 
1066
+ /**
1067
+ * One Edit step applied to `content` the way the Edit tool applies it, or null
1068
+ * when it cannot be (the tool would reject it too).
1069
+ *
1070
+ * Index splicing on purpose: `String.prototype.replace` reads `$&` and `$1` in the
1071
+ * replacement as patterns, and test code is full of template literals.
1072
+ */
1073
+ function applyEdit(content, edit) {
1074
+ if (!edit || typeof edit.old_string !== 'string' || typeof edit.new_string !== 'string') return null;
1075
+ if (edit.old_string === '') return content === '' ? edit.new_string : null;
1076
+ if (edit.replace_all === true) {
1077
+ return content.includes(edit.old_string) ? content.split(edit.old_string).join(edit.new_string) : null;
1078
+ }
1079
+ const at = content.indexOf(edit.old_string);
1080
+ if (at === -1) return null;
1081
+ return content.slice(0, at) + edit.new_string + content.slice(at + edit.old_string.length);
1082
+ }
1083
+
1084
+ /**
1085
+ * The file as it is now and as it will be once this Edit or MultiEdit lands, or
1086
+ * null when that cannot be built.
1087
+ *
1088
+ * An Edit's `new_string` scanned on its own is scanned out of context: a fragment
1089
+ * that sits inside an existing block comment or template literal looks like code,
1090
+ * and a rule that spans the fragment's boundary is invisible. Building the
1091
+ * proposed file gives `--pre` the same view `--post` will have, and lets the
1092
+ * file-scope rules run on edits too. A missing file is an empty one, which is how
1093
+ * the Edit tool creates a file from an empty `old_string`.
1094
+ */
1095
+ function proposedEdit(payload, absolutePath) {
1096
+ const input = payload.tool_input || {};
1097
+ let edits = null;
1098
+ if (payload.tool_name === 'Edit') edits = [input];
1099
+ if (payload.tool_name === 'MultiEdit' && Array.isArray(input.edits)) edits = input.edits;
1100
+ if (!edits) return null;
1101
+
1102
+ let before = '';
1103
+ try {
1104
+ before = fs.readFileSync(absolutePath, 'utf8');
1105
+ } catch (error) {
1106
+ if (!error || error.code !== 'ENOENT') return null;
1107
+ }
1108
+
1109
+ let after = before;
1110
+ for (const edit of edits) {
1111
+ after = applyEdit(after, edit);
1112
+ if (after === null) return null;
1113
+ }
1114
+ return { before, after };
1115
+ }
1116
+
1117
+ /**
1118
+ * Findings in `after` that `before` does not already have.
1119
+ *
1120
+ * `--pre` judges the write in front of it. A violation already sitting in the
1121
+ * untouched part of the file is `--post`'s to report, and blocking an unrelated
1122
+ * edit on it would stop the agent fixing a file one edit at a time. Line numbers
1123
+ * move under an edit, so each occurrence is matched by rule and identity (the
1124
+ * code it spans, comments out, literals in), as a multiset: rewording a comment
1125
+ * beside a violation adds nothing, and a second copy of an existing violation on
1126
+ * the same line still adds one. The one trade this makes is an edit that removes
1127
+ * a violation and writes an identical one elsewhere, which `--post` reports.
1128
+ */
1129
+ function introducedFindings(before, after) {
1130
+ const key = (finding, occurrence) => `${finding.rule.id}\u0000${occurrence}`;
1131
+ const existing = new Map();
1132
+ for (const finding of before) {
1133
+ for (const occurrence of finding.occurrences) existing.set(key(finding, occurrence), (existing.get(key(finding, occurrence)) || 0) + 1);
1134
+ }
1135
+ return after.filter((finding) => {
1136
+ let introduced = false;
1137
+ for (const occurrence of finding.occurrences) {
1138
+ const remaining = existing.get(key(finding, occurrence)) || 0;
1139
+ if (remaining === 0) introduced = true;
1140
+ else existing.set(key(finding, occurrence), remaining - 1);
1141
+ }
1142
+ return introduced;
1143
+ });
1144
+ }
1145
+
902
1146
  function scanRoots(globs) {
903
1147
  const roots = new Set();
904
1148
  for (const glob of globs || []) {
@@ -1060,6 +1304,15 @@ function main(argv) {
1060
1304
  const relative = path.relative(projectRoot, absolute);
1061
1305
  if (relative.startsWith('..')) return 0;
1062
1306
 
1307
+ const proposed = proposedEdit(payload, absolute);
1308
+ if (proposed) {
1309
+ const scan = (source) => scanContent(relative, source, config, { fragmentOnly: false });
1310
+ const findings = introducedFindings(scan(proposed.before), scan(proposed.after)).map((finding) => ({ ...finding, file: relative }));
1311
+ return report(findings, 'TEA enforcement blocked this write:');
1312
+ }
1313
+
1314
+ // The proposed file could not be built (unreadable file, or an old_string the
1315
+ // Edit tool will reject anyway), so fall back to the fragments on their own.
1063
1316
  const findings = fragmentsFromPayload(payload).flatMap((fragment) =>
1064
1317
  scanContent(relative, fragment.text, config, { fragmentOnly: fragment.fragmentOnly }).map((finding) => ({
1065
1318
  ...finding,
@@ -1091,11 +1344,14 @@ module.exports = {
1091
1344
  matchesAnyGlob,
1092
1345
  kindForPath,
1093
1346
  stripNoise,
1347
+ stripComments,
1094
1348
  commentIndex,
1095
1349
  integrityWarning,
1096
1350
  scanContent,
1097
1351
  scanFile,
1098
1352
  targetsFromPayload,
1099
1353
  fragmentsFromPayload,
1354
+ proposedEdit,
1355
+ introducedFindings,
1100
1356
  main,
1101
1357
  };
@@ -162,8 +162,8 @@ Merge into `{project-root}/.claude/settings.json`. If the file already exists, *
162
162
 
163
163
  All three are required, and each one covers a hole the others cannot:
164
164
 
165
- - `--pre` blocks the write before it lands. It sees only what the tool is about to write, which is why it is not sufficient on its own.
166
- - `--post` re-reads the affected file from disk in full. This is what catches a write made through Bash (`cat > x.spec.ts`, `sed -i`, `tee`), a violation split across two edits, and a violation sitting in the part of the file the edit never touched.
165
+ - `--pre` blocks the write before it lands. For an Edit or MultiEdit it applies the edit to the file on disk and scans the result, so text inside an existing comment reads as a comment and a violation the edit completes is seen; it blocks only on violations the edit introduces. It sees only Write, Edit and MultiEdit, which is why it is not sufficient on its own.
166
+ - `--post` re-reads the affected file from disk in full. This is what catches a write made through Bash (`cat > x.spec.ts`, `sed -i`, `tee`) and a violation sitting in the part of the file the edit never touched.
167
167
  - `--stop` sweeps test files modified during the turn. This is what catches a codegen script that wrote files it never named on its command line.
168
168
 
169
169
  The hook fails open: a malformed payload, an unreadable config, or an internal error exits 0 and allows the write. A broken enforcement hook must never become an agent that cannot write files.
@@ -17,6 +17,7 @@ You will continue to operate with your given name, identity, and communication_s
17
17
  - `{skill-root}` resolves to this skill's installed directory (where `customize.toml` lives).
18
18
  - `{project-root}` is the nearest folder containing `_bmad/`, starting at the project working directory and moving up through its parents.
19
19
  - `{tea-knowledge}` is the `knowledge/` folder of the `bmod-tea` skill, installed beside this one: `{skill-root}/../bmod-tea/knowledge`. `tea-index.csv` there lists every fragment by a path relative to that folder.
20
+ - `{tea-contracts}` is the `contracts/` folder of the `bmod-tea` skill, installed beside this one: `{skill-root}/../bmod-tea/contracts`. `story-identity.md` there says how a story is resolved, read and named.
20
21
  - `{skill-name}` resolves to the skill directory's basename.
21
22
  - Resolve sibling workflow files such as `instructions.md`, `checklist.md`, `steps-c/...`, `steps-e/...`, `steps-v/...`, and templates from `{skill-root}`.
22
23
 
@@ -103,14 +103,14 @@ Every run writes its audit to a file whose name carries the run's scope, so an a
103
103
 
104
104
  - `system`: the whole project or system, or no narrower scope could be resolved.
105
105
  - `epic-{epic_num}`: one epic.
106
- - `story-{story_key}`: one story. `story_key` is the BMM story file basename without `.md` (for example `1-2-user-authentication`). Without a story file, use the story id with `.` replaced by `-` (`1.2` becomes `1-2`).
106
+ - `story-{story_key}`: one story. Resolve, read and name the story by `{tea-contracts}/story-identity.md`: `story_key` is `shop--e1-s2` for a v7 epic entry and the v6 story file basename (`1-2-user-authentication`) for a v6 story.
107
107
 
108
108
  Slug rule (used for an epic title with no number): lowercase; replace every run of characters outside `a-z` and `0-9` with a single `-`; trim leading and trailing `-`; truncate to 64 characters.
109
109
 
110
110
  Resolve the scope in this order:
111
111
 
112
112
  1. Use the scope the user named in this invocation (a story, an epic, or the whole system).
113
- 2. Otherwise take the scope carried by the artifacts loaded above: the story file name for a story, or the epic number from the epic document's metadata, H1 heading, or filename for an epic. An epic with no number uses the slug of its title in place of `epic_num`.
113
+ 2. Otherwise take the scope carried by the artifacts loaded above: the story (a v7 ticket or a v6 story file) for a story, or the epic number from the epic document's metadata, H1 heading, or filename for an epic. An epic with no number uses the slug of its title in place of `epic_num`.
114
114
  3. If several candidate scopes remain in an interactive run, list them and ask the user which one this audit covers. **Halt** until they answer. A headless or autonomous run that cannot resolve a single scope uses `system` and states that choice in the audit's output.
115
115
 
116
116
  Set `run_scope` to `story`, `epic`, or `system` to match the resolved form, and set `run_key` accordingly.
@@ -155,6 +155,8 @@ lastSaved: '{date}'
155
155
 
156
156
  Then write this step's output below the frontmatter.
157
157
 
158
+ For a story run (`run_scope` is `story`), also write `storyId`, `storyKey`, `ticketRef` and `storyFile` into this frontmatter, as `{tea-contracts}/story-identity.md` section 4 defines them. Other scopes leave them out.
159
+
158
160
  `runScope` and `runKey` are this run's identity. Later steps carry both forward unchanged, and Resume mode refuses to continue a file whose `runKey` does not match the run being resumed.
159
161
 
160
162
  **Update `inputDocuments`**: Set `inputDocuments` in the output template frontmatter to the list of artifact paths loaded in this step (e.g., knowledge fragments, test design documents, configuration files).
@@ -78,6 +78,8 @@ If `workflowStatus` is missing (legacy output document), infer it from `lastStep
78
78
 
79
79
  ---
80
80
 
81
+ For a story run, read `{tea-contracts}/story-identity.md` before continuing: a named story is resolved by its sections 1 and 4 for the identity check, `ticketRef` locates the story when `storyFile` is empty or gone, and section 5 governs every citation the checkpoint carries (read through `resolvedSources`; report, never follow, an `unresolved` one). This holds on every resume path, named or not.
82
+
81
83
  ### 3. Display Progress Dashboard
82
84
 
83
85
  Display progress with checkmark/empty indicators:
@@ -55,6 +55,8 @@ Use explicit intent if the user already indicates scope:
55
55
  - **Epic + Stories (no PRD/ADR)** → **Epic-Level Mode**
56
56
  - **Both PRD/ADR + Epic/Stories** → Prefer **System-Level Mode** first
57
57
 
58
+ An explicit system- or epic-level request decides the mode here, and section B does not run, so its preview-layout halt does not apply. When the active initiative is in the preview layout (defined in section B), mention that `bmad migrate` moves its breakdown into `tickets/`, and continue in the requested mode.
59
+
58
60
  If intent is unclear, ask:
59
61
 
60
62
  > "Should I create (A) **System-level** test design (PRD + ADR → Architecture + QA docs), or (B) **Epic-level** test design (Epic → single test plan)?"
@@ -63,11 +65,12 @@ If intent is unclear, ask:
63
65
 
64
66
  If user intent is unclear:
65
67
 
68
+ - If an initiative is active and its folder is in the preview layout (below) → tell the user to run `bmad migrate`, which moves the breakdown into `tickets/`, and to rerun Test Design afterwards. **Halt** without choosing a mode.
66
69
  - If an initiative is active and its ticket tree holds an epic → **Epic-Level Mode**
67
70
  - Otherwise, on a v6 project, if `{implementation_artifacts}/sprint-status.yaml` exists → **Epic-Level Mode**
68
71
  - Otherwise → **System-Level Mode**
69
72
 
70
- The active initiative and the output folder belong to BMad core, not TEA's config. Read them with `uv run {project-root}/_bmad/scripts/resolve_config.py --project-root {project-root} --key core.output_folder --key core.active_initiative`. When `core.active_initiative` is set, the initiative folder is `{output_folder}/{active_initiative}/`; it holds an epic when its `tickets.toml` has an `[[epic]]` table or an `epic-*/` folder sits inside it.
73
+ The active initiative and the output folder belong to BMad core, not TEA's config. Read them with `uv run {project-root}/_bmad/scripts/resolve_config.py --project-root {project-root} --key core.output_folder --key core.active_initiative`. When `core.active_initiative` is set, the initiative folder is `{output_folder}/{active_initiative}/`. It holds an epic when `tickets/tickets.toml` inside it has an `[[epic]]` table or a `tickets/epic-*/` folder exists. It is in the preview layout when a `tickets.toml`, an `epic-*/` folder, a `story-*.md`, `spike-*.md` or `bug-*.md` leaf file, or a `*-plan.md` plan sits directly in the initiative folder, with or without a `tickets/` folder beside it; BMad's ticket tools refuse that layout until it is migrated.
71
74
 
72
75
  `{implementation_artifacts}` exists only on a v6 project and is a BMM setting that TEA's config does not define. Read `modules.bmm.implementation_artifacts` with `uv run {project-root}/_bmad/scripts/resolve_config.py --project-root {project-root} --key modules.bmm.implementation_artifacts`. When it is not set, use `{output_folder}/implementation-artifacts`; a v7 project has no such key, so a missing sprint-status file there means System-Level Mode.
73
76
 
@@ -17,6 +17,7 @@ You will continue to operate with your given name, identity, and communication_s
17
17
  - `{skill-root}` resolves to this skill's installed directory (where `customize.toml` lives).
18
18
  - `{project-root}` is the nearest folder containing `_bmad/`, starting at the project working directory and moving up through its parents.
19
19
  - `{tea-knowledge}` is the `knowledge/` folder of the `bmod-tea` skill, installed beside this one: `{skill-root}/../bmod-tea/knowledge`. `tea-index.csv` there lists every fragment by a path relative to that folder.
20
+ - `{tea-contracts}` is the `contracts/` folder of the `bmod-tea` skill, installed beside this one: `{skill-root}/../bmod-tea/contracts`. `story-identity.md` there says how a story is resolved, read and named.
20
21
  - `{skill-name}` resolves to the skill directory's basename.
21
22
  - Resolve sibling workflow files such as `instructions.md`, `checklist.md`, `steps-c/...`, `steps-e/...`, `steps-v/...`, and templates from `{skill-root}`.
22
23
 
@@ -79,7 +80,7 @@ When `headless: true` is resolved (from `workflow.yaml` defaults, a `customize.t
79
80
  - Never prompt the user — resolve every input from configuration and supplied values.
80
81
  - Honor `review_files` (authoritative review set), `context_files` (read-only context set), `output_file_override` (replaces `default_output_file` for the run), and `generate_inline_comments` (inline `// TODO (TEA Review)` comments) as first-class inputs, as documented in `workflow.yaml` and `instructions.md`.
81
82
  - Resolve the run's scope without asking. The report defaults to `{test_artifacts}/test-review/test-review-{run_key}.md`; step 1 derives `run_key` from a story or epic named in the invocation or in `context_files`, else from the reviewed target, and starts over when an unfinished report for that key exists.
82
- - Never go looking for a story, PRD, or test design that `context_files` did not name. With no human to confirm what was found, an unrequested artifact is a nondeterministic input.
83
+ - Never go looking for a story, PRD, or test design that neither `context_files` nor the invocation named. With no human to confirm what was found, an unrequested artifact is a nondeterministic input. A story the invocation names explicitly is resolved and read by `{tea-contracts}/story-identity.md`.
83
84
 
84
85
  When `headless` is false (default), the interactive path below is unchanged.
85
86
 
@@ -139,6 +139,7 @@ Context is what the tests are judged _against_: the story or acceptance criteria
139
139
 
140
140
  **Resolution order:**
141
141
 
142
+ 0. **The invocation names a story** (a ticket ref, title or leaf file, or a v6 story file) → resolve and read it by `{tea-contracts}/story-identity.md` sections 1 to 3. The story and the files that contract reads for it join the context set, alongside any `context_files`. This is the only way a story the caller did not list enters a review, and it works headless too.
142
143
  1. **`context_files` is non-empty** → it IS the complete context set. Read every entry. Validate each path exists and report a missing one in the review report rather than dropping it silently.
143
144
  2. **Empty and `headless: false`** → ask the user which story, test design, or changed source applies, and offer to proceed without it.
144
145
  3. **Empty and `headless: true`** → proceed with no context. Never ask, never go hunting for a story on your own; an unrequested artifact you happened to find is exactly the nondeterminism this resolution order exists to prevent.
@@ -146,7 +147,7 @@ Context is what the tests are judged _against_: the story or acceptance criteria
146
147
  Record `{context_basis}` from what you actually read, never from what was requested:
147
148
 
148
149
  - `none` — nothing was supplied or found
149
- - `pr_diff` — the supplied context set
150
+ - `pr_diff` — the supplied context set, including a named story and what it brought in
150
151
  - `pr_diff_truncated` — the caller states the set was trimmed to a size limit
151
152
 
152
153
  Step 4 must publish this value, so persist it.
@@ -167,8 +168,8 @@ Every run writes its report to a file whose name carries the run's identity, so
167
168
 
168
169
  Apply the first rule that matches:
169
170
 
170
- 1. **The user named a story or epic in this invocation.** Use it.
171
- 2. **The context set read in section 3 carries exactly one story or epic.** A story comes from a BMM story file (a basename such as `1-2-user-authentication.md`, or an H1 such as `Story 1.2: User Authentication`). An epic comes from an epic document's metadata, H1 heading, or filename. Use only artifacts section 3 actually read. Never go looking for a story or epic to name the run.
171
+ 1. **The user named a story or epic in this invocation.** Use it. A named story was already resolved and read in section 3.
172
+ 2. **The context set read in section 3 carries exactly one story or epic.** A story comes from a v7 ticket leaf or a BMM story file (a basename such as `1-2-user-authentication.md`, or an H1 such as `Story 1.2: User Authentication`). An epic comes from an epic document's metadata, H1 heading, or filename. Use only artifacts section 3 actually read. Never go looking for a story or epic to name the run.
172
173
  3. **The context set carries several stories or epics.** Interactive runs list the candidates and ask which one this review covers. **Halt** until the user answers. Headless runs never ask: they fall through to rule 4, and step 4 states in the report that the context named several scopes, so the run was keyed to its reviewed target.
173
174
  4. **No story or epic applies.** When `review_scope` is `suite`, the scope is the whole system. Otherwise the scope is the reviewed target: the project-relative path of the reviewed file (`single`) or directory (`directory`). When `review_files` sets the review set, the target is the one file it names, or the deepest directory that contains every file it names.
174
175
 
@@ -181,7 +182,7 @@ Then set the identity from the resolved scope:
181
182
  | Whole system | `system` | `system` |
182
183
  | Reviewed target | `target` | `target-{slug}` |
183
184
 
184
- - `story_key` is the BMM story file basename without `.md` (for example `1-2-user-authentication`). Without a story file, use the story id with `.` replaced by `-` (`1.2` becomes `1-2`).
185
+ - Resolve, read and name the story by `{tea-contracts}/story-identity.md`: `story_key` is `shop--e1-s2` for a v7 epic entry and the v6 story file basename (`1-2-user-authentication`) for a v6 story.
185
186
  - `epic_num` is the epic's number. An epic with no number uses the slug of its title.
186
187
  - `{slug}` is the slug of the target path. If the slug comes out empty (the target is the project root), the scope is the whole system: `system`.
187
188
 
@@ -244,6 +245,8 @@ lastSaved: '{date}'
244
245
 
245
246
  Then write this step's output below the frontmatter.
246
247
 
248
+ For a story run (`run_scope` is `story`), also write `storyId`, `storyKey`, `ticketRef` and `storyFile` into this frontmatter, as `{tea-contracts}/story-identity.md` section 4 defines them. Other scopes leave them out.
249
+
247
250
  `runScope` and `runKey` are this run's identity. Later steps carry both forward unchanged, and Resume mode refuses to continue a report whose `runKey` does not match the run being resumed.
248
251
 
249
252
  **Update `inputDocuments`**: Set `inputDocuments` in the output template frontmatter to the list of artifact paths loaded in this step (e.g., knowledge fragments, test design documents, configuration files).
@@ -81,6 +81,8 @@ If `workflowStatus` is missing (legacy report), infer it from `lastStep`: `step-
81
81
 
82
82
  ---
83
83
 
84
+ For a story run, read `{tea-contracts}/story-identity.md` before continuing: a named story is resolved by its sections 1 and 4 for the identity check, `ticketRef` locates the story when `storyFile` is empty or gone, and section 5 governs every citation the checkpoint carries (read through `resolvedSources`; report, never follow, an `unresolved` one). This holds on every resume path, named or not.
85
+
84
86
  ### 3. Display Progress Dashboard
85
87
 
86
88
  Display progress with checkmark/empty indicators: