@boyingliu01/xp-gate 0.36.1 → 0.37.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 (123) hide show
  1. package/adapters/cpp.sh +78 -10
  2. package/adapters/csharp.sh +58 -3
  3. package/adapters/gate-3.sh +15 -5
  4. package/adapters/gate-8.sh +131 -9
  5. package/adapters/typescript.sh +32 -8
  6. package/build-integrity/__tests__/import-resolver.test.ts +257 -0
  7. package/build-integrity/__tests__/quote-masker.test.ts +177 -0
  8. package/build-integrity/gate-10.ts +127 -9
  9. package/build-integrity/quote-masker.ts +266 -0
  10. package/gate-10.sh +66 -0
  11. package/gate-12-file-hygiene.sh +15 -7
  12. package/gate-13-compiler-strictness.sh +81 -1
  13. package/gate-3.sh +15 -5
  14. package/gate-6-layers.sh +375 -0
  15. package/gate-8.sh +131 -9
  16. package/hooks/gate-10.sh +66 -0
  17. package/hooks/gate-12-file-hygiene.sh +15 -7
  18. package/hooks/gate-13-compiler-strictness.sh +81 -1
  19. package/hooks/gate-3.sh +15 -5
  20. package/hooks/gate-6-layers.sh +375 -0
  21. package/hooks/gate-8.sh +131 -9
  22. package/hooks/gate-registry.sh +2 -2
  23. package/hooks/hook-module-resolution.sh +1 -1
  24. package/hooks/lib/assertion-quality.sh +8 -2
  25. package/hooks/lib/ccn-ratchet.sh +10 -0
  26. package/hooks/lib/layer-baseline.cjs +88 -0
  27. package/hooks/lib/typecheck.sh +28 -5
  28. package/hooks/pre-commit +376 -53
  29. package/hooks/pre-push +46 -13
  30. package/lib/__tests__/agent-runtime-journal.test.js +1 -1
  31. package/lib/__tests__/arch.test.js +9 -0
  32. package/lib/__tests__/audit-cli-contract.test.ts +1 -1
  33. package/lib/__tests__/check-alignment-reasons.test.mjs +11 -1
  34. package/lib/__tests__/check-all-skip-accounting.test.js +1 -1
  35. package/lib/__tests__/detect-deps-gate-identity.test.js +135 -0
  36. package/lib/__tests__/detect-deps.test.js +2 -1
  37. package/lib/__tests__/doctor-469-hook-env.test.js +7 -1
  38. package/lib/__tests__/doctor-arch-tools.test.js +169 -0
  39. package/lib/__tests__/doctor-delphi.test.js +1 -1
  40. package/lib/__tests__/doctor-drift-round2.test.js +4 -1
  41. package/lib/__tests__/doctor-executed-surface.test.js +45 -24
  42. package/lib/__tests__/doctor-module-drift.test.js +13 -7
  43. package/lib/__tests__/doctor-module-resolution-parity.test.js +74 -2
  44. package/lib/__tests__/doctor-tui-skill-freshness.test.js +21 -6
  45. package/lib/__tests__/doctor.test.js +17 -0
  46. package/lib/__tests__/gate-runner-tsx-invocation.test.js +149 -0
  47. package/lib/__tests__/gate-runner.test.js +23 -7
  48. package/lib/__tests__/init-gitignore.test.js +204 -0
  49. package/lib/__tests__/init.test.js +24 -3
  50. package/lib/__tests__/language-tools-build-file-install.test.js +82 -0
  51. package/lib/__tests__/language-tools-detect.test.js +61 -0
  52. package/lib/__tests__/mirror-sync.test.js +2 -0
  53. package/lib/__tests__/phase-transition.test.js +19 -1
  54. package/lib/__tests__/sprint-status-rework.test.js +32 -12
  55. package/lib/__tests__/test-alignment-range-guard.test.ts +82 -0
  56. package/lib/__tests__/test-alignment.test.ts +13 -3
  57. package/lib/__tests__/update-skill.test.js +2 -2
  58. package/lib/detect-deps.js +7 -1
  59. package/lib/doctor.js +81 -17
  60. package/lib/gate-runner.js +101 -7
  61. package/lib/hook-module-resolution.js +18 -6
  62. package/lib/init.js +136 -1
  63. package/lib/language-tools.js +217 -1
  64. package/lib/layer-baseline.cjs +88 -0
  65. package/lib/mattpocock-license-verdict.json +1 -1
  66. package/lib/principles.js +21 -6
  67. package/lib/test-alignment.ts +452 -55
  68. package/mock-policy/AGENTS.md +1 -1
  69. package/mutation/AGENTS.md +1 -1
  70. package/package.json +2 -1
  71. package/plugins/claude-code/.claude-plugin/plugin.json +1 -1
  72. package/plugins/claude-code/skills/delphi-review/.delphi-config.json.example +34 -24
  73. package/plugins/claude-code/skills/delphi-review/AGENTS.md +1 -1
  74. package/plugins/claude-code/skills/delphi-review/INSTALL.md +29 -1
  75. package/plugins/claude-code/skills/sprint-flow/AGENTS.md +1 -1
  76. package/plugins/claude-code/skills/test-specification-alignment/AGENTS.md +1 -1
  77. package/plugins/dsh/package.json +1 -1
  78. package/plugins/dsh/skills/delphi-review/.delphi-config.json.example +34 -24
  79. package/plugins/dsh/skills/delphi-review/AGENTS.md +1 -1
  80. package/plugins/dsh/skills/delphi-review/INSTALL.md +29 -1
  81. package/plugins/dsh/skills/sprint-flow/AGENTS.md +1 -1
  82. package/plugins/dsh/skills/test-specification-alignment/AGENTS.md +1 -1
  83. package/plugins/dsh/src/client.test.ts +1 -1
  84. package/plugins/dsh/src/command.test.ts +1 -1
  85. package/plugins/dsh/src/contract.test.ts +1 -1
  86. package/plugins/dsh/src/credentials.test.ts +1 -1
  87. package/plugins/opencode/package.json +1 -1
  88. package/plugins/opencode/skills/delphi-review/.delphi-config.json.example +34 -24
  89. package/plugins/opencode/skills/delphi-review/AGENTS.md +1 -1
  90. package/plugins/opencode/skills/delphi-review/INSTALL.md +29 -1
  91. package/plugins/opencode/skills/sprint-flow/AGENTS.md +1 -1
  92. package/plugins/opencode/skills/test-specification-alignment/AGENTS.md +1 -1
  93. package/plugins/qoder/plugin.json +1 -1
  94. package/plugins/qoder/skills/delphi-review/.delphi-config.json.example +34 -24
  95. package/plugins/qoder/skills/delphi-review/AGENTS.md +1 -1
  96. package/plugins/qoder/skills/delphi-review/INSTALL.md +29 -1
  97. package/plugins/qoder/skills/sprint-flow/AGENTS.md +1 -1
  98. package/plugins/qoder/skills/test-specification-alignment/AGENTS.md +1 -1
  99. package/principles/AGENTS.md +1 -1
  100. package/principles/__tests__/config-arch-group.test.ts +106 -0
  101. package/principles/__tests__/config-enforcement.test.ts +1 -1
  102. package/principles/adapters/control-nesting.ts +572 -0
  103. package/principles/adapters/csharp.ts +73 -42
  104. package/principles/adapters/java.ts +9 -5
  105. package/principles/adapters/typescript.ts +138 -176
  106. package/principles/config.ts +37 -2
  107. package/principles/index.ts +57 -4
  108. package/principles/reporter.ts +99 -65
  109. package/principles/rules/arch/__tests__/dependency.test.ts +180 -0
  110. package/principles/rules/arch/__tests__/naming.test.ts +133 -0
  111. package/principles/rules/arch/__tests__/shared.test.ts +113 -0
  112. package/principles/rules/arch/dependency.ts +264 -0
  113. package/principles/rules/arch/naming.ts +188 -0
  114. package/principles/rules/arch/shared.ts +169 -0
  115. package/principles/rules/exports.ts +26 -0
  116. package/principles/rules/index.ts +11 -18
  117. package/scripts/__tests__/sync-package-content.test.js +23 -1
  118. package/scripts/sync-package-content.js +8 -2
  119. package/skills/delphi-review/.delphi-config.json.example +34 -24
  120. package/skills/delphi-review/AGENTS.md +1 -1
  121. package/skills/delphi-review/INSTALL.md +29 -1
  122. package/skills/sprint-flow/AGENTS.md +1 -1
  123. package/skills/test-specification-alignment/AGENTS.md +1 -1
@@ -94,7 +94,7 @@ export interface TestMap {
94
94
  * the contract the branches are checked against.
95
95
  */
96
96
  export const SUPPORTED_TEST_EXTENSIONS: readonly string[] = [
97
- '.ts', '.tsx', '.js', '.jsx', '.py', '.go', '.java',
97
+ '.ts', '.tsx', '.js', '.jsx', '.cjs', '.mjs', '.py', '.go', '.java', '.bats',
98
98
  ];
99
99
 
100
100
  /**
@@ -163,6 +163,22 @@ export interface TestAlignmentReportFile {
163
163
 
164
164
 
165
165
  // ============================================================================
166
+ /**
167
+ * Directories never worth walking when discovering test files. `node_modules`
168
+ * and build output cannot contain this repo's tests; `.worktrees` holds full
169
+ * copies of the repo, so walking it would double-count every test and report
170
+ * phantom duplications.
171
+ */
172
+ const SKIP_DIRS = new Set([
173
+ 'node_modules',
174
+ 'dist',
175
+ 'coverage',
176
+ '.git',
177
+ '.worktrees',
178
+ '.stryker-tmp',
179
+ '.sprint-history',
180
+ ]);
181
+
166
182
  // parseSpecification() — regex-based extraction for specification.yaml
167
183
  // ============================================================================
168
184
 
@@ -232,18 +248,129 @@ export function parseSpecification(specPath: string): SpecificationMap {
232
248
  // Step 2: parseTestFiles()
233
249
  // ============================================================================
234
250
 
251
+ const AC_ID = /^AC-[A-Z0-9]+-(?:[A-Z0-9]+-)?\d+[a-z]?$/;
252
+
253
+ /**
254
+ * Ceiling for `AC-X-01 through AC-X-N` expansion.
255
+ *
256
+ * Why 200: this repo's largest AC block is 19 criteria (REQ-670), and the spec
257
+ * has never exceeded two digits per requirement. 200 is ~10x the observed
258
+ * maximum, so no genuine annotation can reach it, while a mistyped bound
259
+ * (`AC-X-1 through AC-X-999999999`) is rejected in constant time instead of
260
+ * allocating until the worker dies. Deliberately NOT configurable: the value
261
+ * only needs to separate "a real range" from "a typo", and a per-project knob
262
+ * would be one more thing to get wrong. Widen it only with evidence of a real
263
+ * requirement block approaching it.
264
+ */
265
+ const MAX_AC_RANGE_SPAN = 200;
266
+
267
+ /**
268
+ * Normalise a raw `@covers` token list into concrete AC ids.
269
+ *
270
+ * Two things happen here:
271
+ * - Non-AC tokens are dropped. Some headers list a function or module name
272
+ * (`@covers mock-policy-config-loader`) instead of criteria ids.
273
+ * - Range notation is expanded. Eight files in this repo write
274
+ * `AC-TDD-001-01 through AC-TDD-001-14`; reading only the two endpoints
275
+ * reported the twelve criteria in between as uncovered even though the file
276
+ * was explicitly annotated for all of them.
277
+ */
278
+ function expandAcCovers(tokens: string[]): string[] {
279
+ const out: string[] = [];
280
+ for (let i = 0; i < tokens.length; i++) {
281
+ const token = tokens[i]!;
282
+ const rangeMatch = tokens[i + 1] === 'through' && AC_ID.test(token) && AC_ID.test(tokens[i + 2] || '');
283
+ if (!rangeMatch) {
284
+ if (AC_ID.test(token)) out.push(token);
285
+ continue;
286
+ }
287
+ const from = token;
288
+ const to = tokens[i + 2]!;
289
+ const prefix = from.slice(0, from.lastIndexOf('-') + 1);
290
+ const startNum = Number(from.slice(prefix.length).replace(/[a-z]$/, ''));
291
+ const endNum = Number(to.slice(prefix.length).replace(/[a-z]$/, ''));
292
+ if (!to.startsWith(prefix) || Number.isNaN(startNum) || Number.isNaN(endNum) || endNum < startNum) {
293
+ out.push(from, to);
294
+ i += 2;
295
+ continue;
296
+ }
297
+ // A range is a convenience, not a data-transport format: real annotations
298
+ // span a handful of criteria. Without a ceiling, one mistyped digit
299
+ // (`AC-X-1 through AC-X-999999999`) allocates until the worker dies with
300
+ // ERR_WORKER_OUT_OF_MEMORY -- measured, not hypothetical. Past the ceiling
301
+ // keep only the two literal endpoints: they are genuine references, and
302
+ // silently dropping them would lose the only real signal in the line.
303
+ const span = endNum - startNum + 1;
304
+ if (span > MAX_AC_RANGE_SPAN) {
305
+ // Report the refusal. Returning quietly would present "two ACs" as the
306
+ // whole annotation, and a reader comparing that against the report has no
307
+ // way to tell a deliberate ceiling from an annotation that lists two ids.
308
+ console.warn(
309
+ `[test-alignment] refused to expand a ${span}-criterion range ` +
310
+ `(${from} through ${to}); keeping only the endpoints. ` +
311
+ `If this is a real range it is too wide to be an AC annotation -- check for a typo.`,
312
+ );
313
+ out.push(from, to);
314
+ i += 2;
315
+ continue;
316
+ }
317
+ for (let n = startNum; n <= endNum; n++) {
318
+ out.push(prefix + String(n).padStart(from.slice(prefix.length).length, '0'));
319
+ }
320
+ i += 2;
321
+ }
322
+ return out;
323
+ }
324
+
235
325
  function extractAllTags(text: string, tag: string): string[] {
236
326
  const escapedTag = tag.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
237
- const regex = new RegExp('@' + escapedTag + '\\s+(.+?)(?:\\n|\\*\\/)', 'gs');
327
+ // A tag's value runs until the NEXT tag or the end of the block -- not merely
328
+ // to the first newline. JSDoc in this repo wraps long `@covers` lists across
329
+ // lines, and stopping at the first newline read only line one, so every AC on
330
+ // a continuation line was reported uncovered.
331
+ const regex = new RegExp('@' + escapedTag + '\\s+([\\s\\S]*?)(?=\\n\\s*\\*\\s*@|\\n\\s*\\*\\/|$)', 'g');
238
332
  const results: string[] = [];
239
333
  let match: RegExpExecArray | null;
240
334
  while ((match = regex.exec(text)) !== null) {
241
- const items1 = match[1]!.split(',').map(s => s.trim()).filter(Boolean);
335
+ // Split on commas AND whitespace: this repo uses both `@covers A, B` and
336
+ // `@covers A B`, and commas alone dropped every id in the spaced form.
337
+ const items1 = match[1]!
338
+ .replace(/\n\s*\*?/g, ' ')
339
+ .split(/[,\s]+/)
340
+ .map(s => s.trim())
341
+ .filter(Boolean);
242
342
  results.push(...items1);
243
343
  }
244
344
  return results;
245
345
  }
246
346
 
347
+ /**
348
+ * Count assertions in a shell/BATS file.
349
+ *
350
+ * Shell has no `expect()`, so the JS patterns all report zero -- and a parsed
351
+ * test with zero assertions drags the data-validity dimension down as if the
352
+ * suite were empty. These are the constructs that actually fail a BATS test.
353
+ */
354
+ function countBashAssertions(content: string): number {
355
+ const patterns = [
356
+ // `[ ... ]` as a statement OR as a guard (`[ x ] || { ... }`, `[ x ] && ...`).
357
+ // Requiring the bracket to be the last thing on the line counted zero for
358
+ // every `[ ... ] || { echo ...; return 1; }` guard, which is how most BATS
359
+ // assertions in this repo are written — those files then looked assertion-
360
+ // free and were reported as low-quality tests.
361
+ /^[ \t]*\[[^\]\n]*\](?:[ \t]*(?:\|\||&&).*)?$/gm,
362
+ /^[ \t]*\[\[[^\]\n]*\]\](?:[ \t]*(?:\|\||&&).*)?$/gm,
363
+ /assert_(?:success|failure|output|line|equal|not_equal|regex|file_exists)/g,
364
+ /grep\s+-[qa-z]*q/g,
365
+ ];
366
+ let count = 0;
367
+ for (const pattern of patterns) {
368
+ const matches = content.match(pattern);
369
+ if (matches) count += matches.length;
370
+ }
371
+ return count;
372
+ }
373
+
247
374
  function countAssertions(content: string): number {
248
375
  // Count common assertion patterns.
249
376
  //
@@ -266,6 +393,11 @@ function countAssertions(content: string): number {
266
393
  /\bassert[A-Z]\w*\s*\(/g,
267
394
  // AssertJ fluent style, common in the same test suites.
268
395
  /\bassertThat\s*\(/g,
396
+ // Node's own `assert` module and assert-like guards. `throw new Error` is how
397
+ // the script-style suites under plugins/*/skills signal a failed expectation;
398
+ // counting only framework assertions made those suites look assertion-free.
399
+ /\bassert\.(?:ok|equal|strictEqual|deepEqual|notEqual|throws|fail)\s*\(/g,
400
+ /throw\s+new\s+(?:Error|AssertionError)\s*\(/g,
269
401
  ];
270
402
  let count = 0;
271
403
  for (const pattern of patterns) {
@@ -371,45 +503,219 @@ function extractCallbackBody(content: string, callbackStart: number): string {
371
503
  * driven by `@covers` tags, so this only affects the avg-assertions data-validity
372
504
  * heuristic, never AC coverage. Tracked separately from #392.
373
505
  */
374
- function extractJSDocBeforeTest(content: string): Array<{ jsdoc: string; testBody: string; testName: string }> {
375
- const results: Array<{ jsdoc: string; testBody: string; testName: string }> = [];
506
+ /**
507
+ * A JSDoc block counts as a per-test annotation only when it carries `@test`.
508
+ *
509
+ * Without this guard any doc comment above an `it()` was treated as a test
510
+ * record -- including blocks whose `@covers` lists plain function names. Those
511
+ * records then suppressed the file-level fallback below, so the file's real
512
+ * annotation never got read and every case looked like it was missing
513
+ * `@intent`. Only `@test` makes a block a test annotation.
514
+ */
515
+ const ANNOTATED_JSDOC = /@test\s+REQ-/;
376
516
 
377
- // Match: /** JSDOC */ (test|it|describe)[.modifier]( [args], )'name', ( [params] ) => {
378
- // `.each` variants have an extra `()` before the test name string.
379
- // Group 4 (bodyStart) points at the callback open paren so we can brace-match
380
- // the real function body.
381
- const testPattern = /\/\*\*([\s\S]*?)\*\/(?:[\s\n]*)(?:test|it|describe)(?:\.(?:each|skip|todo|only))?\s*\([^)]*\)\s*,\s*\(\s*(?:['"]([^'"]+)['"]|`([^`]*)`)\s*\)?\s*,?\s*(?:\([^)]*\)\s*=>)?\s*/g;
517
+ /** The `@test REQ-...` tag of a JSDoc block, or undefined when absent. */
518
+ const REQ_TAG = /@test\s+(REQ-[A-Z0-9]+(?:-[A-Z0-9]+)*)/;
382
519
 
383
- let match: RegExpExecArray | null;
384
- while ((match = testPattern.exec(content)) !== null) {
520
+ /**
521
+ * First annotation pass: a declaration that carries an extra argument list
522
+ * before the name string.
523
+ *
524
+ * Measured caveat: this pattern currently matches NOTHING in this repo, and
525
+ * neither did the `testPattern` it is copied from -- the `.each([...])('name')`
526
+ * shape it targets does not satisfy the `\([^)]*\)\s*,` requirement. It is kept
527
+ * because it is byte-identical to the inherited behaviour and dropping it would
528
+ * be an unrequested semantic change, not because it is known to fire. The TODO
529
+ * on AC-002-02 tracks actually supporting `.each`.
530
+ */
531
+ const TEST_PATTERN_WITH_ARGS = /\/\*\*((?:(?!\*\/)[\s\S])*)\*\/(?:[\s\n]*)(?:test|it|describe)(?:\.(?:each|skip|todo|only))?\s*\([^)]*\)\s*,\s*\(\s*(?:['"]([^'"]+)['"]|`([^`]*)`)\s*\)?\s*,?\s*(?:\([^)]*\)\s*=>)?\s*/g;
532
+
533
+ /**
534
+ * Second annotation pass: plain `test('name', () => { ... })` and `.skip` /
535
+ * `.todo` / `.only` forms, which have no preceding argument list.
536
+ */
537
+ const TEST_PATTERN_PLAIN = /\/\*\*((?:(?!\*\/)[\s\S])*)\*\/(?:[\s\n]*)(?:test|it|describe)(?:\.(?:skip|todo|only))?\s*\(\s*(?:['"]([^'"]+)['"]|`([^`]*)`)\s*\)?\s*,?\s*(?:\([^)]*\)\s*=>)?\s*/g;
538
+
539
+ /** A test record recovered from one JSDoc block. */
540
+ interface TestAnnotation {
541
+ jsdoc: string;
542
+ testBody: string;
543
+ testName: string;
544
+ }
545
+
546
+ /**
547
+ * Run one annotation-scanning pass and append every annotated match to
548
+ * `results`.
549
+ *
550
+ * `dedupe` is required rather than always-on because the two passes have
551
+ * different contracts: the first pass must not drop a legitimate second test
552
+ * that repeats an identical doc block, while the second pass re-finds everything
553
+ * the first pass already matched. Only the second pass may skip.
554
+ */
555
+ function collectAnnotatedTests(
556
+ content: string,
557
+ pattern: RegExp,
558
+ results: TestAnnotation[],
559
+ dedupe: boolean,
560
+ ): void {
561
+ // `matchAll` clones the regex internally, so no `lastIndex` is read or
562
+ // written: the scan cannot leave state behind for the next caller, and a
563
+ // caller cannot inherit state from a previous one. The patterns stay
564
+ // module-level constants (they are byte-identical to the inherited inline
565
+ // literals), but their mutable state is no longer reachable from here.
566
+ for (const match of content.matchAll(pattern)) {
385
567
  const jsdoc = match[1]!;
386
568
  const testName = match[2] || match[3] || '';
387
- if (testName) {
388
- const body = extractCallbackBody(content, match.index + match[0].length);
389
- // JSDoc + declaration + function body gives a self-contained test body.
390
- const testBody = content.slice(match.index, match.index + match[0].length) + body;
391
- results.push({ jsdoc, testBody, testName });
392
- }
569
+ if (!testName || !ANNOTATED_JSDOC.test(jsdoc)) continue;
570
+ if (dedupe && results.some(r => r.jsdoc === jsdoc)) continue;
571
+ const declaration = content.slice(match.index, match.index + match[0].length);
572
+ // JSDoc + declaration + function body gives a self-contained test body.
573
+ const testBody = declaration + extractCallbackBody(content, match.index + match[0].length);
574
+ results.push({ jsdoc, testBody, testName });
575
+ }
576
+ }
577
+
578
+ /**
579
+ * Decide whether the file-level block adds something the per-test records do
580
+ * not already say.
581
+ *
582
+ * The header is redundant only when a per-test record already carries BOTH its
583
+ * REQ and every AC it lists. Comparing the REQ alone was wrong: a file whose
584
+ * header covers AC-1..AC-5 while one case below happens to name the same REQ for
585
+ * its own AC-9 lost the header, and AC-1..AC-5 were reported uncovered even
586
+ * though the file is annotated for them.
587
+ */
588
+ function needsFileLevelRecord(header: string, results: TestAnnotation[]): boolean {
589
+ const headerReq = header.match(REQ_TAG)?.[1];
590
+ const headerAcs = expandAcCovers(extractAllTags(header, 'covers'));
591
+ const coveredReqs = new Set(results.map(r => r.jsdoc.match(REQ_TAG)?.[1]).filter(Boolean));
592
+ const coveredAcs = new Set(results.flatMap(r => expandAcCovers(extractAllTags(r.jsdoc, 'covers'))));
593
+ const reqMissing = !headerReq || !coveredReqs.has(headerReq);
594
+ const acsMissing = headerAcs.some(ac => !coveredAcs.has(ac));
595
+ return results.length === 0 || reqMissing || acsMissing;
596
+ }
597
+
598
+ function extractJSDocBeforeTest(content: string, sourcePath?: string): TestAnnotation[] {
599
+ const results: TestAnnotation[] = [];
600
+
601
+ collectAnnotatedTests(content, TEST_PATTERN_WITH_ARGS, results, false);
602
+ collectAnnotatedTests(content, TEST_PATTERN_PLAIN, results, true);
603
+
604
+ // File-level block: the dominant convention in this repo is ONE `@test` /
605
+ // `@covers` block at the top of the file with plain `it('...')` calls below
606
+ // it. The passes above only see an annotation that sits immediately before a
607
+ // test, so such a file would yield nothing there.
608
+ //
609
+ // The block is added in TWO situations, and the difference matters:
610
+ // - no per-test annotation was found at all -> the block is the only record
611
+ // for this file;
612
+ // - per-test annotations exist, but the block's own `@test` names a REQ none
613
+ // of them carry -> the block covers something the cases do not (e.g. a
614
+ // module-level REQ plus per-case ACs). Dropping it reported that REQ as
615
+ // having no test even though the file is annotated for it.
616
+ const fileLevelJsdoc = extractFileLevelJsdoc(content);
617
+ if (fileLevelJsdoc && needsFileLevelRecord(fileLevelJsdoc, results)) {
618
+ // One record for the whole file, NOT one per `it()`. The block annotates
619
+ // the file rather than each case; a record per test made every case
620
+ // without its own `@intent` look unannotated (2448 false findings).
621
+ results.push({
622
+ jsdoc: fileLevelJsdoc,
623
+ testBody: content,
624
+ testName: sourcePath || 'file-level',
625
+ });
393
626
  }
394
627
 
395
- // Second pass: match standard test/it/describe without .each
396
- const simplePattern = /\/\*\*([\s\S]*?)\*\/(?:[\s\n]*)(?:test|it|describe)(?:\.(?:skip|todo|only))?\s*\(\s*(?:['"]([^'"]+)['"]|`([^`]*)`)\s*\)?\s*,?\s*(?:\([^)]*\)\s*=>)?\s*/g;
628
+ return results;
629
+ }
397
630
 
398
- while ((match = simplePattern.exec(content)) !== null) {
399
- const jsdoc = match[1]!;
400
- const testName = match[2] || match[3] || '';
401
- if (testName) {
402
- // Don't duplicate if already found in first pass
403
- const alreadyFound = results.some(r => r.jsdoc === jsdoc);
404
- if (!alreadyFound) {
405
- const body = extractCallbackBody(content, match.index + match[0].length);
406
- const testBody = content.slice(match.index, match.index + match[0].length) + body;
407
- results.push({ jsdoc, testBody, testName });
408
- }
631
+ /**
632
+ * The leading JSDoc block of a file, if it carries an @test tag.
633
+ *
634
+ * Only a block that appears before any executable code counts as file-level:
635
+ * a trailing doc comment must not retroactively annotate the whole file.
636
+ *
637
+ * @param content - Full file contents
638
+ * @returns The block's inner text, or null when there is no leading annotated block
639
+ */
640
+ /**
641
+ * Matches the leading JSDoc block, skipping any preceding `//` lines.
642
+ *
643
+ * The pattern is assembled as a string rather than a regex literal: the
644
+ * literal form puts `*` + `/` next to each other in the source, which any
645
+ * doc-comment scanner (including this module) reads as a comment terminator.
646
+ * One of the seven defects found here was exactly that confusion, so the
647
+ * source is written to be unambiguous to a reader.
648
+ */
649
+ const FILE_LEVEL_JSDOC = new RegExp(
650
+ '^(?:#![^\\n]*\\n)?(?:(?:[ \\t]*\\/\\/[^\\n]*\\n)|(?:[ \\t]*\\n))*[ \\t]*\\/\\*\\*([\\s\\S]*?)\\*\\/',
651
+ );
652
+
653
+ /**
654
+ * A leading JS import block, which a file-level annotation may follow.
655
+ *
656
+ * Several files put `import ...` first and the `@test` / `@covers` block after
657
+ * it. Requiring the block to be line 1 made those files parse as unannotated.
658
+ * Only `import`/`from`/`require` lines are tolerated -- an annotation must still
659
+ * precede any executable statement, otherwise a doc comment further down would
660
+ * retroactively annotate the whole file.
661
+ */
662
+ const IMPORT_PRELUDE_LINE = /^(?:import\b[^;]*?;|import\b[^;]*?from\s*['"][^'"]*['"];?|const\s+\w+\s*=\s*require\([^)]*\);?|from\s+\w+\s+import\b.*?)$/;
663
+
664
+ /**
665
+ * Drop a leading run of import / require statements (and blank lines between
666
+ * them), leaving the rest of the file untouched.
667
+ *
668
+ * Used only to let a file-level annotation follow the imports; anything other
669
+ * than an import line stops the strip, so the annotation can never move past an
670
+ * executable statement.
671
+ */
672
+ function stripLeadingImports(content: string): string {
673
+ const lines = content.split('\n');
674
+ let i = 0;
675
+ while (i < lines.length) {
676
+ const line = lines[i]!.trim();
677
+ if (line === '') {
678
+ i++;
679
+ continue;
409
680
  }
681
+ if (IMPORT_PRELUDE_LINE.test(line)) {
682
+ i++;
683
+ continue;
684
+ }
685
+ break;
410
686
  }
687
+ return lines.slice(i).join('\n');
688
+ }
411
689
 
412
- return results;
690
+
691
+ function extractFileLevelJsdoc(content: string): string | null {
692
+ // Leading `//` lines are skipped: .cjs files in this repo often open with
693
+ // `// vitest globals: true` before the annotation block.
694
+ const jsdoc = content.match(FILE_LEVEL_JSDOC);
695
+ if (jsdoc && /@test\s+REQ-/.test(jsdoc[1] || '')) return jsdoc[1] || null;
696
+
697
+ // An annotation that follows a leading import block still describes the file:
698
+ // the imports are not executable statements in the sense that matters here.
699
+ const afterImports = stripLeadingImports(content);
700
+ if (afterImports !== content) {
701
+ const shifted = afterImports.match(FILE_LEVEL_JSDOC);
702
+ if (shifted && /@test\s+REQ-/.test(shifted[1] || '')) return shifted[1] || null;
703
+ }
704
+
705
+ // Shell-family files (.bats, .sh) annotate with leading `#` comments rather
706
+ // than a JSDoc block. Without this arm every BATS test file -- 177 of them
707
+ // carrying 119 distinct REQ tags -- was invisible, and its requirements were
708
+ // reported as having no test at all.
709
+ // Blank lines are allowed INSIDE the block: these headers carry a long
710
+ // `@intent` with paragraph breaks before `@covers`, and stopping at the
711
+ // first blank line dropped the `@covers` for every such file.
712
+ const hashHeader = content.match(/^(?:#![^\n]*\n)?(?:[ \t]*#[^\n]*\n|[ \t]*\n)+/);
713
+ if (hashHeader) {
714
+ const block = hashHeader[0].replace(/^#![^\n]*\n/, '');
715
+ if (/@test\s+REQ-/.test(block)) return block;
716
+ }
717
+
718
+ return null;
413
719
  }
414
720
 
415
721
  /**
@@ -464,7 +770,9 @@ function pushTestWithCovers(
464
770
  const covers: string[] = [];
465
771
  let coversMatch: RegExpExecArray | null;
466
772
  while ((coversMatch = coversRegex.exec(fileContent)) !== null) {
467
- covers.push(...coversMatch[1]!.split(',').map(s => s.trim()).filter(c => /^AC-[A-Z0-9]+-\d+-\d+$/.test(c)));
773
+ // Trailing lowercase letter is legal: the spec carries ids like
774
+ // `AC-670-19b`, added when an AC was split without renumbering.
775
+ covers.push(...expandAcCovers(coversMatch[1]!.split(',').map(s => s.trim())));
468
776
  }
469
777
 
470
778
  // Count assertions against the *per-test body*, not the whole file, so
@@ -491,41 +799,63 @@ export function parseTestFiles(testPaths: string[]): TestMap {
491
799
  for (const testPath of testPaths) {
492
800
  if (!fs.existsSync(testPath)) continue;
493
801
 
494
- const content = fs.readFileSync(testPath, 'utf8');
802
+ // Normalise CRLF before parsing. This repo checks out with `core.autocrlf`
803
+ // on Windows, so a `.bats` header ends its lines with `\r\n`; the `#`-block
804
+ // matcher then stopped after the shebang and every such file parsed as
805
+ // unannotated. Line-oriented regexes must see one line ending, not two.
806
+ const content = fs.readFileSync(testPath, 'utf8').replace(/\r\n/g, '\n');
495
807
  const ext = path.extname(testPath);
496
808
 
497
- if (ext === '.ts' || ext === '.tsx' || ext === '.js' || ext === '.jsx') {
498
- const matches = extractJSDocBeforeTest(content);
809
+ // `.cjs` / `.mjs` carry the same syntax as `.js` and are used by this
810
+ // repo's own script tests (44 and 2 files). They were in neither the
811
+ // supported nor the unsupported list, so those files were dropped without a
812
+ // trace -- a test file the checker cannot see is indistinguishable from a
813
+ // test that does not exist.
814
+ const isJSLike = ['.ts', '.tsx', '.js', '.jsx', '.cjs', '.mjs'].includes(ext);
815
+ if (isJSLike) {
816
+ const matches = extractJSDocBeforeTest(content, testPath);
499
817
 
500
818
  for (const m of matches) {
501
- const reqMatch = m.jsdoc.match(/@test\s+(REQ-[A-Z0-9]+-[A-Z0-9]+)/);
502
- const intentMatch = m.jsdoc.match(/@intent\s+(.+?)(?:\n\s*\*)/s);
819
+ // Five files in this repo fold the rationale into the `@test` line as
820
+ // `@test REQ-X intent: ...` instead of using a separate `@intent` tag.
821
+ // Without this fallback they were reported as having no intent at all.
822
+ const inlineIntent = m.jsdoc.match(/@test[^\n]*?\bintent:\s*([^\n]*(?:\n[ \t]*[^\n*@][^\n]*)*)/);
823
+ const intentValue = extractAllTags(m.jsdoc, 'intent').join(' ').trim()
824
+ || (inlineIntent ? inlineIntent[1]!.replace(/\s*\n\s*/g, ' ').trim() : '');
503
825
  const coversRaw = extractAllTags(m.jsdoc, 'covers');
504
- // Filter: only valid AC IDs (AC-XXX-NNN-NN pattern)
505
- const covers = coversRaw.filter(c => /^AC-[A-Z0-9]+-\d+-\d+$/.test(c));
826
+ const covers = expandAcCovers(coversRaw);
827
+
828
+ // A block may name several requirements (`@test REQ-705, REQ-707`).
829
+ // Taking only the first left every other REQ in the list looking
830
+ // untested even though the same code was covered by the same tests.
831
+ const reqIds = Array.from(
832
+ new Set((m.jsdoc.match(/@test\s+([^\n*]+)/)?.[1] || '').match(/REQ-[A-Z0-9]+(?:-[A-Z0-9]+)*/g) || []),
833
+ );
506
834
 
507
835
  const assertions = countAssertions(m.testBody);
508
836
  totalAssertionsObj.value += assertions;
509
837
 
510
- tests.push({
511
- name: m.testName,
512
- file: testPath,
513
- requirementId: reqMatch ? reqMatch[1] : undefined,
514
- intent: intentMatch ? intentMatch[1]!.trim() : undefined,
515
- covers,
516
- edgeCases: [],
517
- assertions,
518
- });
838
+ for (const reqId of reqIds.length ? reqIds : [undefined]) {
839
+ tests.push({
840
+ name: m.testName,
841
+ file: testPath,
842
+ requirementId: reqId,
843
+ intent: intentValue || undefined,
844
+ covers,
845
+ edgeCases: [],
846
+ assertions,
847
+ });
848
+ }
519
849
  }
520
850
  } else if (ext === '.py') {
521
- const pyTestPattern = /(# @test\s+(REQ-[A-Z0-9]+-[A-Z0-9]+)[\s\S]*?)(?:# @intent\s+(.+?)\n)?def\s+(test_\w+)/g;
851
+ const pyTestPattern = /(# @test\s+(REQ-[A-Z0-9]+(?:-[A-Z0-9]+)*)[\s\S]*?)(?:# @intent\s+(.+?)\n)?def\s+(test_\w+)/g;
522
852
  let m: RegExpExecArray | null;
523
853
  while ((m = pyTestPattern.exec(content)) !== null) {
524
854
  const body = extractPythonTestBody(content, m.index + m[0].lastIndexOf('def '));
525
855
  pushTestWithCovers(tests, testPath, m[4]!, m[2]!, m[3]?.trim(), content, body, totalAssertionsObj);
526
856
  }
527
857
  } else if (ext === '.go') {
528
- const goTestPattern = /(\/\/ @test\s+(REQ-[A-Z0-9]+-[A-Z0-9]+))\s*[\s\S]*?func\s+(Test_\w+)/g;
858
+ const goTestPattern = /(\/\/ @test\s+(REQ-[A-Z0-9]+(?:-[A-Z0-9]+)*))\s*[\s\S]*?func\s+(Test_\w+)/g;
529
859
  let m: RegExpExecArray | null;
530
860
  while ((m = goTestPattern.exec(content)) !== null) {
531
861
  const block = content.slice(Math.max(0, m.index - 500), m.index);
@@ -548,7 +878,7 @@ export function parseTestFiles(testPaths: string[]): TestMap {
548
878
  let docMatch: RegExpExecArray | null;
549
879
  while ((docMatch = javaDocPattern.exec(content)) !== null) {
550
880
  const docBlock = docMatch[1]!;
551
- const reqMatch = docBlock.match(/@test\s+(REQ-[A-Z0-9]+-[A-Z0-9]+)/);
881
+ const reqMatch = docBlock.match(/@test\s+(REQ-[A-Z0-9]+(?:-[A-Z0-9]+)*)/);
552
882
  // Without a requirement tag this is not an annotated test in this
553
883
  // project's sense; skip it rather than inventing a TestCase.
554
884
  if (!reqMatch) continue;
@@ -571,6 +901,35 @@ export function parseTestFiles(testPaths: string[]): TestMap {
571
901
  content, body, totalAssertionsObj,
572
902
  );
573
903
  }
904
+ } else if (ext === '.bats' || ext === '.sh') {
905
+ // BATS bodies are shell; the annotation contract is the same `# @test` /
906
+ // `# @intent` / `# @covers` header used everywhere else in this repo.
907
+ const batsDoc = extractFileLevelJsdoc(content);
908
+ if (batsDoc) {
909
+ const header = batsDoc;
910
+ const reqMatch = header.match(/@test\s+(REQ-[A-Z0-9]+(?:-[A-Z0-9]+)*)/);
911
+ const intentMatch = header.match(/@intent\s+([\s\S]*?)(?=\n[ \t]*#?[ \t]*@|$)/);
912
+ // Same inline form as the JS branch: `# @test REQ-X intent: ...`.
913
+ const inlineIntent = header.match(/@test[^\n]*?\bintent:\s*([\s\S]*?)(?=\n[ \t]*#?[ \t]*@|\n[ \t]*#\s*$|$)/);
914
+ const intentValue = (intentMatch ? intentMatch[1]!.replace(/\n[ \t]*#?/g, ' ').trim() : '')
915
+ || (inlineIntent ? inlineIntent[1]!.replace(/\n[ \t]*#?/g, ' ').trim() : '');
916
+ const coversRaw = extractAllTags(header, 'covers');
917
+
918
+ if (reqMatch) {
919
+ const covers = expandAcCovers(coversRaw);
920
+ const assertions = countBashAssertions(content);
921
+ totalAssertionsObj.value += assertions;
922
+ tests.push({
923
+ name: testPath,
924
+ file: testPath,
925
+ requirementId: reqMatch[1],
926
+ intent: intentValue || undefined,
927
+ covers,
928
+ edgeCases: [],
929
+ assertions,
930
+ });
931
+ }
932
+ }
574
933
  } else if (UNSUPPORTED_TEST_EXTENSIONS.includes(ext)) {
575
934
  // Recognised as a test file, but no parser exists. Recording it is the
576
935
  // whole point: previously this arm did not exist, so the file vanished
@@ -602,6 +961,14 @@ export function verifyAlignment(
602
961
  const coveredAcIds = new Set<string>();
603
962
  let testsWithIntent = 0;
604
963
 
964
+ // The file-level intent, so per-group blocks can inherit it (see Rule 3).
965
+ const intentByFile = new Map<string, string>();
966
+ for (const test of testMap.tests) {
967
+ if (test.intent && !intentByFile.has(test.file)) {
968
+ intentByFile.set(test.file, test.intent);
969
+ }
970
+ }
971
+
605
972
  for (const test of testMap.tests) {
606
973
  if (test.requirementId) {
607
974
  coveredReqIds.add(test.requirementId);
@@ -627,8 +994,20 @@ export function verifyAlignment(
627
994
  }
628
995
 
629
996
  // Rule 1: Each REQ must have a test (Critical)
997
+ //
998
+ // "Has a test" is satisfied either by naming the REQ in `@test` OR by covering
999
+ // one of its acceptance criteria. A file that pins AC-718-01..03 under a
1000
+ // broader `@test REQ-439` really does test REQ-718; reporting the requirement
1001
+ // as untested while its criteria are covered is contradictory, and it punished
1002
+ // exactly the annotation style this repo uses for follow-up issues.
1003
+ const reqsWithCoveredAc = new Set<string>();
1004
+ for (const req of specMap.requirements) {
1005
+ if (req.acceptanceCriteria.some(ac => coveredAcIds.has(ac))) {
1006
+ reqsWithCoveredAc.add(req.id);
1007
+ }
1008
+ }
630
1009
  for (const reqId of allReqIds) {
631
- if (!coveredReqIds.has(reqId)) {
1010
+ if (!coveredReqIds.has(reqId) && !reqsWithCoveredAc.has(reqId)) {
632
1011
  issues.push({
633
1012
  type: 'MISSING_REQUIREMENT_TEST',
634
1013
  severity: 'critical',
@@ -654,8 +1033,15 @@ export function verifyAlignment(
654
1033
  }
655
1034
 
656
1035
  // Rule 3: Each test must have @intent (Major)
1036
+ //
1037
+ // A per-group `@test` / `@covers` block inside a file whose HEADER already
1038
+ // states the intent is not a missing annotation: the header annotates the
1039
+ // file, and the inner blocks only narrow the AC. Reporting those cases
1040
+ // demanded the same sentence be repeated on every `describe`.
657
1041
  for (const test of testMap.tests) {
658
1042
  if (!test.intent || test.intent.trim().length === 0) {
1043
+ const inherited = intentByFile.get(test.file);
1044
+ if (inherited && inherited.trim().length > 0) continue;
659
1045
  issues.push({
660
1046
  type: 'MISSING_INTENT',
661
1047
  severity: 'major',
@@ -827,6 +1213,10 @@ export function writeReport(report: TestAlignmentReportFile, outputPath: string)
827
1213
  */
828
1214
  function isTestFileName(name: string): boolean {
829
1215
  const ext = path.extname(name);
1216
+ // `.bats` files ARE tests by definition -- BATS only runs test suites. Many in
1217
+ // this repo use a descriptive name (`issue-602-gate6-java-architecture.bats`)
1218
+ // with no `.test.` infix, and requiring the infix silently excluded them.
1219
+ if (ext === '.bats') return true;
830
1220
  const knownExt = SUPPORTED_TEST_EXTENSIONS.includes(ext) || UNSUPPORTED_TEST_EXTENSIONS.includes(ext);
831
1221
  if (!knownExt) return false;
832
1222
  if (/\.(test|spec)\.[^.]+$/.test(name)) return true;
@@ -842,7 +1232,14 @@ export interface AlignmentOptions {
842
1232
  }
843
1233
 
844
1234
  export function runFullAlignment(options: AlignmentOptions): TestAlignmentReportFile {
845
- const { specPath, testDirs = ['tests', 'test', '__tests__', 'src/__tests__'], headCommit, outputPath } = options;
1235
+ // Default to the repo root rather than a hard-coded list of top-level test
1236
+ // directories. The old list (`tests`, `test`, `__tests__`, `src/__tests__`)
1237
+ // matched NONE of this repo's test files -- they live in per-module
1238
+ // `__tests__` folders such as `src/principles/__tests__/` and
1239
+ // `src/npm-package/lib/__tests__/`. With no test files discovered, every REQ
1240
+ // and AC was reported as uncovered (854 findings), which read as 854 missing
1241
+ // tests but was really one wrong default.
1242
+ const { specPath, testDirs = ['.'], headCommit, outputPath } = options;
846
1243
 
847
1244
  // Step 1: Parse spec
848
1245
  let spec: SpecificationMap;
@@ -873,7 +1270,7 @@ export function runFullAlignment(options: AlignmentOptions): TestAlignmentReport
873
1270
  const entries = fs.readdirSync(d, { withFileTypes: true });
874
1271
  for (const entry of entries) {
875
1272
  const fullPath = path.join(d, entry.name);
876
- if (entry.isDirectory() && entry.name !== 'node_modules') {
1273
+ if (entry.isDirectory() && !SKIP_DIRS.has(entry.name)) {
877
1274
  walkDir(fullPath);
878
1275
  } else if (entry.isFile() && isTestFileName(entry.name)) {
879
1276
  testFiles.push(fullPath);
@@ -3,7 +3,7 @@
3
3
  **Generated:** 2026-11-04
4
4
  **Commit:** eb2097b0
5
5
  **Branch:** sprint/2026-11-03-02
6
- **Version:** 0.36.1.0
6
+ **Version:** 0.37.1.0
7
7
 
8
8
  ## OVERVIEW
9
9
  Mock layering policy enforcement — Gate M3 of pre-push hook. Ensures integration tests use real implementations for internal dependencies, mock external dependencies, and annotate pending mocks with removal plans. Combines project scope scanning, mock decision engine, and per-file validation into a single pipeline.