@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
@@ -133,6 +133,263 @@ describe('extractImports', () => {
133
133
  const result = extractImports(content);
134
134
  expect(result).toEqual([{ path: './side-effect', line: 1 }]);
135
135
  });
136
+
137
+ /**
138
+ * Issue #759 — import TEXT that is not import CODE.
139
+ *
140
+ * Every case below is a shape that a real project contains on purpose (a test
141
+ * pinning a scanner's own behaviour, a doc block, a parser fixture) and that
142
+ * the scanner used to report as a violation for a path that never existed.
143
+ * Eight of these eleven were reproduced in dialog-survey, where they blocked
144
+ * pushes.
145
+ *
146
+ * The fixture strings are built with template literals so the nesting is
147
+ * visible; `BS` keeps a literal backslash unambiguous, because writing `\\'`
148
+ * inside a template literal silently yields just `'` and turns the test into
149
+ * one that passes against the bug.
150
+ */
151
+ describe('ignores import text inside strings, templates and comments (#759)', () => {
152
+ const BS = String.fromCharCode(92);
153
+ // Built from a code point so a backtick in the fixture cannot end the
154
+ // surrounding template literal by accident (same trap as `BS` above).
155
+ const BT = String.fromCharCode(96);
156
+
157
+ it('ignores import text inside a double-quoted string', () => {
158
+ const content = `const x = "import foo from './missing';";`;
159
+ expect(extractImports(content)).toEqual([]);
160
+ });
161
+
162
+ it('ignores import text inside a single-quoted string', () => {
163
+ const content = `const x = 'import foo from "./missing";';`;
164
+ expect(extractImports(content)).toEqual([]);
165
+ });
166
+
167
+ it('ignores require() text inside a string', () => {
168
+ const content = `const x = "require('./missing')";`;
169
+ expect(extractImports(content)).toEqual([]);
170
+ });
171
+
172
+ it('ignores dynamic import text inside a string', () => {
173
+ const content = `const x = "import('./missing')";`;
174
+ expect(extractImports(content)).toEqual([]);
175
+ });
176
+
177
+ it('ignores export-from text inside a string', () => {
178
+ const content = `const x = "export * from './missing'";`;
179
+ expect(extractImports(content)).toEqual([]);
180
+ });
181
+
182
+ it('ignores import text inside a single-line template literal', () => {
183
+ const content = "const x = `import foo from './missing';`;";
184
+ expect(extractImports(content)).toEqual([]);
185
+ });
186
+
187
+ it('ignores import text inside a multi-line template literal', () => {
188
+ const content = "const x = `\nimport foo from './missing';\n`;";
189
+ expect(extractImports(content)).toEqual([]);
190
+ });
191
+
192
+ it('ignores import text inside a trailing line comment', () => {
193
+ const content = `const y = 1; // import foo from './missing';`;
194
+ expect(extractImports(content)).toEqual([]);
195
+ });
196
+
197
+ it('ignores import text inside a block comment', () => {
198
+ const content = `/* import foo from './missing'; */`;
199
+ expect(extractImports(content)).toEqual([]);
200
+ });
201
+
202
+ it('ignores import text inside JSDoc', () => {
203
+ const content = `/**\n * import foo from './missing';\n */`;
204
+ expect(extractImports(content)).toEqual([]);
205
+ });
206
+
207
+ /**
208
+ * The other half of a comment: that it ENDS.
209
+ *
210
+ * The two cases above only prove text INSIDE a comment is ignored. A masker
211
+ * that never leaves block-comment mode keeps both green while swallowing
212
+ * every real import after the closing delimiter — found by mutation: making
213
+ * the closing check unreachable survived all 58 tests. These pin the resume.
214
+ */
215
+ it('resumes scanning after a block comment closes', () => {
216
+ const content = `/* import gone from './missing'; */\nimport real from './real';`;
217
+ expect(extractImports(content)).toEqual([{ path: './real', line: 2 }]);
218
+ });
219
+
220
+ it('resumes scanning after a JSDoc block closes', () => {
221
+ const content = `/**\n * import gone from './missing';\n */\nimport real from './real';`;
222
+ expect(extractImports(content)).toEqual([{ path: './real', line: 4 }]);
223
+ });
224
+
225
+ it('resumes scanning after a line comment ends at the newline', () => {
226
+ const content = `// import gone from './missing';\nimport real from './real';`;
227
+ expect(extractImports(content)).toEqual([{ path: './real', line: 2 }]);
228
+ });
229
+
230
+ it('still treats a template interpolation as code', () => {
231
+ const content = "const x = `${import('./real')}`;";
232
+ expect(extractImports(content)).toEqual([{ path: './real', line: 1 }]);
233
+ });
234
+
235
+ /**
236
+ * Nested interpolations must return to the INNER template, not to code.
237
+ *
238
+ * A single integer depth counter cannot express that: on entering the inner
239
+ * `${`, assigning (instead of pushing) made the inner `}` look like the
240
+ * close of the outer one, so the masker stayed in template mode and every
241
+ * real import after the line was masked. Measured against the counter
242
+ * version, `extractImports` returned `[]` for the case below.
243
+ */
244
+ it('stays aligned through a nested template interpolation', () => {
245
+ const Q = BT;
246
+ const content =
247
+ 'const a = ' + Q + '${' + Q + '${x}' + Q + '}' + Q + ';\n' +
248
+ "import real from './real';\n";
249
+ expect(extractImports(content)).toEqual([{ path: './real', line: 2 }]);
250
+ });
251
+
252
+ it('stays aligned through nested interpolation containing an import', () => {
253
+ const Q = BT;
254
+ const content =
255
+ 'const a = ' + Q + '${' + Q + '${import("./inner")}' + Q + '}' + Q + ';\n' +
256
+ "import real from './real';\n";
257
+ // The inner import is inside code (an interpolation), so it counts; the
258
+ // outer import must survive the nesting too.
259
+ expect(extractImports(content)).toEqual([
260
+ { path: './inner', line: 1 },
261
+ { path: './real', line: 2 },
262
+ ]);
263
+ });
264
+
265
+ /**
266
+ * A regex literal that contains `//` used to open a phantom line comment.
267
+ * The masker does not parse regex literals (documented limitation), but a
268
+ * line holding both a URL-ish regex and a real import must not lose the
269
+ * import. The `/` of `//` inside a regex is escaped in real code, and an
270
+ * unescaped `//` in a regex is a syntax error, so the remaining risk is
271
+ * confined to generated/minified text — pinned here so it stays a KNOWN
272
+ * limitation rather than an untested assumption.
273
+ */
274
+ it('keeps a real import on the same line as a regex literal', () => {
275
+ const content = 'const re = /(?:a)/; import real from "./real";\n';
276
+ expect(extractImports(content)).toEqual([{ path: './real', line: 1 }]);
277
+ });
278
+
279
+ /**
280
+ * A line that STARTS with a comment can still carry a real import.
281
+ *
282
+ * The original guard asked `trimmed.startsWith('/*')` on the raw line and
283
+ * skipped the whole line, so `/* eslint-disable */ import real from ...`
284
+ * was never scanned — a MISS, which is the one direction a compliance gate
285
+ * must not fail in. Measured before the fix: `[]`.
286
+ */
287
+ it('keeps an import that follows a leading block comment', () => {
288
+ const content = '/* eslint-disable */ import real from "./real";\n';
289
+ expect(extractImports(content)).toEqual([{ path: './real', line: 1 }]);
290
+ });
291
+
292
+ it('still ignores import text that is only a comment', () => {
293
+ const content = '/* import fake from "./fake" */\n';
294
+ expect(extractImports(content)).toEqual([]);
295
+ });
296
+
297
+ it('still ignores import text on a JSDoc continuation line', () => {
298
+ const content = ' * import fake from "./fake"\n';
299
+ expect(extractImports(content)).toEqual([]);
300
+ });
301
+
302
+ /**
303
+ * A static import whose path sits on a LATER line. Multi-line imports are
304
+ * ordinary formatting, and a strictly per-line scan misses them entirely —
305
+ * measured `[]` before joining, which is a MISS in the direction that
306
+ * matters (a real boundary violation would not be reported).
307
+ */
308
+ it('finds an import whose path is on a continuation line', () => {
309
+ const content = 'import {\n foo,\n} from "./bar";\n';
310
+ expect(extractImports(content)).toEqual([{ path: './bar', line: 1 }]);
311
+ });
312
+
313
+ it('does not double-report a multi-line import, and keeps the next line', () => {
314
+ const content = 'import {\n a,\n} from "./b";\nimport c from "./c";\n';
315
+ expect(extractImports(content)).toEqual([
316
+ { path: './b', line: 1 },
317
+ { path: './c', line: 4 },
318
+ ]);
319
+ });
320
+
321
+ it('finds a dynamic import written with a space before the paren', () => {
322
+ // `import ('./x')` is legal and appears in formatted code; the pattern
323
+ // required `import(` exactly and measured `[]`.
324
+ const content = "const m = import ('./x');\n";
325
+ expect(extractImports(content)).toEqual([{ path: './x', line: 1 }]);
326
+ });
327
+
328
+ it('does not report import.meta as a dynamic import', () => {
329
+ const content = 'const u = import.meta.url;\n';
330
+ expect(extractImports(content)).toEqual([]);
331
+ });
332
+
333
+ /**
334
+ * KNOWN LIMITATION, pinned so it cannot drift unnoticed.
335
+ *
336
+ * A quote inside a regex literal opens a phantom string. Measured output for
337
+ * the fixture below is `[{ path: './fake', line: 2 }]`: the import text
338
+ * inside the real string is reported as if it were code, and the genuine
339
+ * import on line 3 is missed. Both directions, which is why the masker's
340
+ * header no longer claims "can only cause a MISS".
341
+ *
342
+ * It is tolerable because a regex holding an unescaped quote is a SYNTAX
343
+ * ERROR — no file that parses can contain line 1. This test exists to make
344
+ * that reasoning explicit: if it ever starts failing differently, the
345
+ * limitation changed and the header comment must be re-measured.
346
+ */
347
+ it('documents the regex-quote limitation instead of pretending it cannot happen', () => {
348
+ const SQ = String.fromCharCode(39);
349
+ const DQ = String.fromCharCode(34);
350
+ const content =
351
+ 'const re = /' + SQ + '/;\n' +
352
+ 'const s = ' + DQ + 'import x from ' + SQ + './fake' + SQ + DQ + ';\n' +
353
+ 'import real from ' + DQ + './real' + DQ + ';\n';
354
+ expect(extractImports(content)).toEqual([{ path: './fake', line: 2 }]);
355
+ });
356
+
357
+ it('keeps line numbers truthful across a line continuation', () => {
358
+ // A backslash immediately followed by a newline is a legal continuation
359
+ // inside a string literal. Masking it as a plain space deleted a line, so
360
+ // an import on line 3 was reported as line 2 — measured against the
361
+ // version that emitted a space for the newline.
362
+ const NL = String.fromCharCode(10);
363
+ const content =
364
+ "const s = 'aaa" + BS + NL + "bbb';" + NL +
365
+ "import real from './real';" + NL;
366
+ expect(extractImports(content)).toEqual([{ path: './real', line: 3 }]);
367
+ });
368
+
369
+ it('resumes scanning after an unterminated-looking line comment', () => {
370
+ const content = "const u = 'http://x'; import real from './real';\n";
371
+ // The `//` sits inside a string, so it is text — the import is real code.
372
+ expect(extractImports(content)).toEqual([{ path: './real', line: 1 }]);
373
+ });
374
+
375
+ it('does not end a string early on an escaped quote', () => {
376
+ const content = `const x = 'it${BS}'s import foo from "./missing"';`;
377
+ expect(extractImports(content)).toEqual([]);
378
+ });
379
+
380
+ it('does not end a string early on an escaped double quote', () => {
381
+ const content = `const x = "say ${BS}"hi import foo from './missing'";`;
382
+ expect(extractImports(content)).toEqual([]);
383
+ });
384
+
385
+ it('reports the real import on a line that also holds import text', () => {
386
+ const content = [
387
+ `import real from './real';`,
388
+ `const doc = "import fake from './fake';";`,
389
+ ].join('\n');
390
+ expect(extractImports(content)).toEqual([{ path: './real', line: 1 }]);
391
+ });
392
+ });
136
393
  });
137
394
 
138
395
  /**
@@ -0,0 +1,177 @@
1
+ /**
2
+ * @test The quote/comment masker's own contract (#759)
3
+ * @intent Assert the masker's three positional invariants directly instead of
4
+ * inferring them from extractImports' output. A shorter result shifts
5
+ * every later line number, a lost newline collapses lines, and a
6
+ * surviving quote re-opens the exact hole #759 closed — each is a
7
+ * silent failure, so each is pinned here.
8
+ * @covers maskTextQuotes, maskTextQuotesForTest
9
+ */
10
+
11
+ import { describe, it, expect } from 'vitest';
12
+ import { maskTextQuotesForTest } from '../quote-masker';
13
+
14
+ /**
15
+ * Every other test drives `extractImports` and infers the masker's
16
+ * behaviour from the paths that come out. These assert the three properties the
17
+ * masker promises directly, because each is a silent-failure class on its own:
18
+ * a shorter output shifts every later line number, a lost newline collapses
19
+ * lines, and a surviving quote re-opens the exact bug #759 fixed.
20
+ */
21
+ describe('maskTextQuotes contract', () => {
22
+ const BS = String.fromCharCode(92);
23
+ const BT = String.fromCharCode(96);
24
+ const SQ = String.fromCharCode(39);
25
+ const SAMPLES: Array<[string, string]> = [
26
+ ['plain code', "import x from './x';"],
27
+ ['single-quoted string', "const a = 'hello';"],
28
+ ['double-quoted string', 'const b = "hello";'],
29
+ ['template literal', 'const c = ' + BT + 'hello' + BT + ';'],
30
+ ['nested interpolation', 'const d = ' + BT + '${' + BT + '${v}' + BT + '}' + BT + ';'],
31
+ ['line comment', "// import x from './x'"],
32
+ ['block comment', "/* import x from './x' */"],
33
+ ['escaped quote', 'const e = ' + BS + '"'],
34
+ ['line continuation', "const f = 'a" + BS + "\nb';"],
35
+ ['regex literal', 'const g = /ab+c/;'],
36
+ ['trailing backslash', 'const h = ' + BS],
37
+ // Unbalanced delimiters: the masker must never throw and never grow or
38
+ // shrink the text, even when the file simply ends mid-literal. Every one of
39
+ // these is a shape a truncated or generated file really contains.
40
+ ['unterminated single quote', "const i = 'abc"],
41
+ ['unterminated double quote', 'const j = "abc'],
42
+ ['unterminated template', 'const k = ' + BT + 'abc'],
43
+ ['unterminated block comment', 'const l = 1; /* abc'],
44
+ ['unterminated interpolation', 'const m = ' + BT + '${'],
45
+ ['regex holding a quote', 'const n = /' + SQ + '/;'],
46
+ ['empty input', ''],
47
+ ];
48
+
49
+ it.each(SAMPLES)('preserves length for %s', (_label, sample) => {
50
+ expect(maskTextQuotesForTest(sample).length).toBe(sample.length);
51
+ });
52
+
53
+ it.each(SAMPLES)('preserves the newline count for %s', (_label, sample) => {
54
+ const countNewlines = (s: string): number => s.split(String.fromCharCode(10)).length;
55
+ expect(countNewlines(maskTextQuotesForTest(sample))).toBe(countNewlines(sample));
56
+ });
57
+
58
+ it('leaves no raw quote inside masked text', () => {
59
+ // The DELIMITERS survive (they are real code); what must not survive is a
60
+ // quote INSIDE a literal or comment, which is what would let the import
61
+ // regexes see pseudo-code. Asserting "no quote anywhere" would be wrong —
62
+ // the opening quote is code.
63
+ const content = "const a = 'it\"s \"x\"'; // 'another'";
64
+ const masked = maskTextQuotesForTest(content);
65
+ // Everything from the opening delimiter to the end of the line is either
66
+ // the delimiter itself, a sentinel, or a space.
67
+ const open = masked.indexOf("'");
68
+ expect(open).toBeGreaterThan(-1);
69
+ // The doubled-quote body keeps ONE extra delimiter; every other quote inside
70
+ // the literal must be a sentinel.
71
+ const seen = new Set(masked.slice(open + 1));
72
+ expect(seen.has('"')).toBe(false);
73
+ // The comment's quote must not survive either.
74
+ expect(masked.split("'").length - 1).toBe(2);
75
+ });
76
+
77
+ it('is idempotent in length when applied twice', () => {
78
+ // The masker is not a fixed point of itself (masking a masked string masks
79
+ // its sentinels), but it must never grow or shrink the text.
80
+ const content = "const a = 'x'; import y from './y';";
81
+ const once = maskTextQuotesForTest(content);
82
+ expect(maskTextQuotesForTest(once).length).toBe(content.length);
83
+ });
84
+
85
+ it('never throws on any sample, including unbalanced delimiters', () => {
86
+ // `extractImports` runs over arbitrary real files, and a truncated file or a
87
+ // generated artefact can end mid-literal. A throw here would abort Gate 10
88
+ // for the whole file rather than mis-report one line, so this is checked
89
+ // across every sample rather than one representative case.
90
+ for (const [label, sample] of SAMPLES) {
91
+ expect(() => maskTextQuotesForTest(sample), label).not.toThrow();
92
+ }
93
+ });
94
+
95
+ it('never throws on a lone sentinel byte in the input', () => {
96
+ // QUOTE_SENTINEL is a NUL character. Source containing a literal NUL is
97
+ // unusual but legal in a string, and the masker must not treat it as
98
+ // anything special.
99
+ const NUL = String.fromCharCode(0);
100
+ const content = "const a = '" + NUL + "'; import y from './y';";
101
+ expect(() => maskTextQuotesForTest(content)).not.toThrow();
102
+ expect(maskTextQuotesForTest(content).length).toBe(content.length);
103
+ });
104
+
105
+ it('preserves CR bytes on a CRLF-terminated file', () => {
106
+ // Windows-authored sources are everywhere in this repo. A masker that
107
+ // stripped or normalised `\r` would shift nothing on its own, but the
108
+ // length/newline invariants are what line numbers are derived from, so the
109
+ // CR bytes are pinned explicitly rather than assumed to survive.
110
+ const CR = String.fromCharCode(13);
111
+ const NL = String.fromCharCode(10);
112
+ const content =
113
+ "import a from './a';" + CR + NL +
114
+ "const s = 'x';" + CR + NL +
115
+ "import b from './b';" + CR + NL;
116
+ const masked = maskTextQuotesForTest(content);
117
+ expect(masked.length).toBe(content.length);
118
+ expect(masked.split(CR).length).toBe(content.split(CR).length);
119
+ expect(masked.split(NL).length).toBe(content.split(NL).length);
120
+ });
121
+
122
+ it('treats a division operator as code, not the start of a regex', () => {
123
+ // The masker has no regex support, so `a / b` must not be mistaken for the
124
+ // start of a literal. If it were, the quote in the following comment would
125
+ // open a phantom string and mask the rest of the file.
126
+ const content = "const r = a / b; // it's a comment\nimport real from './real';\n";
127
+ const masked = maskTextQuotesForTest(content);
128
+ expect(masked.length).toBe(content.length);
129
+ // The real import's delimiters survive: they are code, not text.
130
+ expect(masked).toContain("'./real'");
131
+ });
132
+
133
+ it('keeps length when a file ends on an escape INSIDE a literal', () => {
134
+ // Regression: `stepEscape` pushed two characters but advanced past a
135
+ // one-character remainder, so this input came out LONGER than it went in
136
+ // (13 -> 14) and every line number after it would have been wrong. The
137
+ // unrelated `trailing backslash` sample above missed it because that
138
+ // backslash sits in code mode and never reaches stepEscape.
139
+ const content = "const e = 'a" + BS;
140
+ expect(maskTextQuotesForTest(content).length).toBe(content.length);
141
+ });
142
+
143
+ it('keeps length for EVERY truncation point of a tricky file', () => {
144
+ // Exhaustive rather than representative: a fixpoint over every prefix of
145
+ // several shapes is what actually proves the length invariant, because the
146
+ // escape bug above lived at exactly ONE truncation point out of many.
147
+ const DQ = String.fromCharCode(34);
148
+ const NL = String.fromCharCode(10);
149
+ const seeds = [
150
+ "const a = 'x' + " + DQ + 'y' + DQ + ';',
151
+ 'const t = ' + BT + '${a + ' + BT + '${b}' + BT + '}' + BT + ';',
152
+ '/* c */ const z = 1; // tail',
153
+ "const e = 'a" + BS + "'b';",
154
+ "const l = 'a" + BS + NL + " b';",
155
+ 'const m = ' + BT + '${' + BT + '${v}' + BT + '}' + BT + ';',
156
+ ];
157
+ for (const seed of seeds) {
158
+ for (let n = 0; n <= seed.length; n++) {
159
+ const prefix = seed.slice(0, n);
160
+ expect(
161
+ maskTextQuotesForTest(prefix).length,
162
+ 'prefix ' + n + ' of ' + JSON.stringify(seed),
163
+ ).toBe(prefix.length);
164
+ }
165
+ }
166
+ });
167
+
168
+ it('terminates on an unterminated literal instead of spinning', () => {
169
+ // A truncated file leaves `mode` non-code for the rest of the input. Each
170
+ // handler advances the cursor, so the loop is bounded by the input length —
171
+ // this test fails (by timing out) if a future handler ever forgets to.
172
+ for (const sample of ["const i = 'abc", '/* x', 'const k = ' + BT + 'abc']) {
173
+ const out = maskTextQuotesForTest(sample);
174
+ expect(out.length).toBe(sample.length);
175
+ }
176
+ });
177
+ });
@@ -3,6 +3,7 @@ import { promisify } from 'util';
3
3
  import * as fs from 'fs/promises';
4
4
  import * as fsNative from 'fs';
5
5
  import path from 'path';
6
+ import { maskTextQuotes } from './quote-masker';
6
7
  import { fileURLToPath } from 'url';
7
8
  import type {
8
9
  CheckResult,
@@ -209,16 +210,35 @@ export async function runTscCheck(
209
210
  * import('./foo')
210
211
  * export { x } from './foo'
211
212
  * export * from './foo'
213
+ *
214
+ * Import TEXT inside a string, template literal or comment is not an import and
215
+ * must not be reported (issue #759). Projects legitimately contain such text — a
216
+ * test pinning a scanner's own behaviour, a doc block showing the syntax, a
217
+ * parser fixture — and before this was handled, the regexes below matched them
218
+ * and reported violations for paths that never existed.
212
219
  */
213
220
  export function extractImports(content: string): Array<{ path: string; line: number }> {
214
221
  const results: Array<{ path: string; line: number }> = [];
215
- const lines = content.split('\n');
216
222
  const push = (path: string, line: number) => { results.push({ path, line }); };
217
223
 
218
224
  const staticImportExportRe =
219
225
  /(?:import|export)\s+(?:(?:[^'"]*?\s+from\s+)?['"]([^'"]+)['"]|['"]([^'"]+)['"])/g;
220
226
  const requireRe = /require\(\s*['"]([^'"]+)['"]\s*\)/g;
221
- const dynamicImportRe = /(?<!\w)import\(\s*['"]([^'"]+)['"]\s*\)/g;
227
+ const dynamicImportRe = /(?<!\w)import\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
228
+
229
+ // The scanner runs over a version of the source in which every quote that is
230
+ // NOT a code-level delimiter has been replaced by a sentinel. Length and line
231
+ // breaks are preserved, so the line numbers reported below stay truthful.
232
+ //
233
+ // The distinction that matters is not "inside a string" but "is this quote a
234
+ // delimiter". A real import's path quotes are code-level (depth 0) and must
235
+ // stay visible — the path is the thing we extract. A quote nested inside an
236
+ // outer string is text and must not be. Framing it as nesting depth rather
237
+ // than as "mask all string content" is what keeps `import x from './bar'`
238
+ // working while `const s = "import x from './bar'"` is ignored.
239
+ const scanSource = maskTextQuotes(content);
240
+ const lines = scanSource.split('\n');
241
+ const originalLines = content.split('\n');
222
242
 
223
243
  // LINE-major order is the contract (import-resolver.test pins it): one pass
224
244
  // over the lines, three patterns per line in static → require → dynamic
@@ -226,20 +246,118 @@ export function extractImports(content: string): Array<{ path: string; line: num
226
246
  // pattern-major passes; a line containing both a require and an import
227
247
  // would then swap positions.
228
248
  for (let i = 0; i < lines.length; i++) {
229
- const line = lines[i];
230
- // Skip comment lines (// or leading * in JSDoc blocks)
231
- const trimmed = line.trim();
232
- if (trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('/*')) {
249
+ // Scan unless everything on the line is comment; see
250
+ // `hasCodeAfterLeadingComment` for why a raw-prefix test was not enough.
251
+ if (!hasCodeAfterLeadingComment(originalLines[i])) {
233
252
  continue;
234
253
  }
235
- scanLine(line, i + 1, staticImportExportRe, (m) => m[1] ?? m[2], push);
236
- scanLine(line, i + 1, requireRe, (m) => m[1], push);
237
- scanLine(line, i + 1, dynamicImportRe, (m) => m[1], push);
254
+ i += scanImportAt(lines, i, { staticImportExportRe, requireRe, dynamicImportRe }, push);
238
255
  }
239
256
 
240
257
  return results;
241
258
  }
242
259
 
260
+ /** The three patterns, grouped so the per-line scanner takes one argument. */
261
+ interface ImportPatterns {
262
+ staticImportExportRe: RegExp;
263
+ requireRe: RegExp;
264
+ dynamicImportRe: RegExp;
265
+ }
266
+
267
+ /**
268
+ * Scan one line for imports and return how many FOLLOWING lines it consumed.
269
+ *
270
+ * Returns 0 for the ordinary single-line case and >0 when the line opens a
271
+ * static statement whose path sits further down, which the caller adds to its
272
+ * cursor. Extracted from `extractImports` to stay under Gate 4's 50-line limit.
273
+ */
274
+ function scanImportAt(
275
+ lines: string[],
276
+ i: number,
277
+ patterns: ImportPatterns,
278
+ push: (path: string, line: number) => void,
279
+ ): number {
280
+ const line = lines[i];
281
+ scanLine(line, i + 1, patterns.requireRe, (m) => m[1], push);
282
+ scanLine(line, i + 1, patterns.dynamicImportRe, (m) => m[1], push);
283
+ // A static import that fits on ONE line is scanned in place, so the common
284
+ // case reports the import's own line. Only a line that OPENS a statement
285
+ // whose path sits further down needs joining:
286
+ // `import {\n foo,\n} from './bar';` is ordinary formatting, and a per-line
287
+ // pattern misses it entirely (measured: `[]` before this).
288
+ const statement = joinImportStatement(lines, i);
289
+ if (!statement) {
290
+ scanLine(line, i + 1, patterns.staticImportExportRe, (m) => m[1] ?? m[2], push);
291
+ return 0;
292
+ }
293
+ scanLine(statement.text, i + 1, patterns.staticImportExportRe, (m) => m[1] ?? m[2], push);
294
+ // Skip the continuation lines: they hold no import of their own, and
295
+ // re-scanning them would let the static pattern match a fragment and report
296
+ // the import twice at the wrong line.
297
+ return statement.consumed;
298
+ }
299
+
300
+ /**
301
+ * Assemble a multi-line `import`/`export ... from '...'` statement starting at
302
+ * `start`, or return null when that line does not open one.
303
+ *
304
+ * Returns the joined text and how many FOLLOWING lines were consumed, so the
305
+ * caller can advance past them. The joining character is a space, which keeps
306
+ * `from` adjacent to its quotes without disturbing `['"]` matching; the text is
307
+ * only used for matching, never for the reported line number, so collapsing
308
+ * newlines cannot shift a position that is reported.
309
+ */
310
+ function joinImportStatement(
311
+ lines: string[],
312
+ start: number,
313
+ ): { text: string; consumed: number } | null {
314
+ const first = lines[start];
315
+ // Only a line that BEGINS a static import/export can open a statement, and
316
+ // only a statement without its path yet needs joining.
317
+ if (!/^\s*(?:import|export)\b/.test(first)) return null;
318
+ if (/\bfrom\s*['"]|^\s*(?:import|export)\s*['"]/.test(first)) return null; // already complete
319
+ const parts: string[] = [first];
320
+ for (let k = start + 1; k < lines.length && parts.length <= 40; k++) {
321
+ parts.push(lines[k]);
322
+ if (/\bfrom\s*['"]|^\s*(?:import|export)\s*['"]/.test(lines[k])) {
323
+ return { text: parts.join(' '), consumed: k - start };
324
+ }
325
+ }
326
+ return null; // not a statement after all (or absurdly long): leave it alone
327
+ }
328
+
329
+ /**
330
+ * Does any CODE follow the comment that starts this line?
331
+ *
332
+ * Returns true when the line does not start with a comment at all, so callers
333
+ * can treat it as the single "should this line be scanned?" question. Only
334
+ * three prefixes can begin a comment line and each closes in exactly one way,
335
+ * so this needs no lexer — the masker has already established that the line is
336
+ * not inside a literal or template.
337
+ *
338
+ * Skipping on the raw prefix alone was a real MISS: `/* eslint-disable *&#47;
339
+ * import real from './real';` starts with `/*`, so the whole line was dropped
340
+ * and the genuine import on it was never checked — the one direction a
341
+ * compliance gate must not fail in. Measured before this fix: `[]`.
342
+ *
343
+ * `//...` -> nothing can follow on the same line
344
+ * `/* ... *&#47;` -> whatever follows the first `*&#47;` is code
345
+ * `* ...` -> a JSDoc continuation; `*&#47;` ends it, else nothing follows
346
+ */
347
+ function hasCodeAfterLeadingComment(originalLine: string): boolean {
348
+ const trimmed = originalLine.trim();
349
+ if (trimmed.startsWith('//')) return false; // nothing can follow on this line
350
+ if (trimmed.startsWith('/*') || trimmed.startsWith('*')) {
351
+ // A `/*` opener and a JSDoc `*` continuation both end at the first `*/`.
352
+ const close = trimmed.indexOf('*/');
353
+ // An unterminated block comment runs to the end of the file: no code here.
354
+ if (close === -1) return false;
355
+ const rest = trimmed.slice(close + 2).trim();
356
+ return rest.length > 0 && !rest.startsWith('//');
357
+ }
358
+ return true;
359
+ }
360
+
243
361
  /** Apply one pattern to a single line; every relative hit is pushed with its line number. */
244
362
  function scanLine(
245
363
  line: string,