pi-lens 4.1.5 → 4.2.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 (219) hide show
  1. package/CHANGELOG.md +415 -0
  2. package/README.md +13 -8
  3. package/config/dependency-cruiser-eager-allowlist.json +6 -1
  4. package/dist/clients/actionable-warnings.js +30 -4
  5. package/dist/clients/agent-behavior-client.js +2 -0
  6. package/dist/clients/analysed-root.js +1 -0
  7. package/dist/clients/ast-grep-tool-logger.js +1 -1
  8. package/dist/clients/bash-file-access.js +26 -0
  9. package/dist/clients/biome-client.js +13 -2
  10. package/dist/clients/blocker-freshness.js +403 -35
  11. package/dist/clients/bootstrap.js +6 -1
  12. package/dist/clients/bounded-telemetry.js +2 -0
  13. package/dist/clients/cache-observability.js +122 -1
  14. package/dist/clients/cascade-format.js +200 -4
  15. package/dist/clients/code-quality-warnings.js +10 -2
  16. package/dist/clients/complexity-client.js +5 -0
  17. package/dist/clients/config-diagnostic-codes.js +2 -0
  18. package/dist/clients/config-resolve.js +6 -3
  19. package/dist/clients/config-schema.js +17 -0
  20. package/dist/clients/config-warn.js +2 -2
  21. package/dist/clients/dead-code-client.js +8 -1
  22. package/dist/clients/degradation-ledger.js +16 -1
  23. package/dist/clients/dependency-checker.js +5 -1
  24. package/dist/clients/diagnostic-dispositions.js +12 -1
  25. package/dist/clients/dispatch/ast-grep-catalog.js +65 -0
  26. package/dist/clients/dispatch/auxiliary-lsp.js +28 -0
  27. package/dist/clients/dispatch/dispatcher.js +47 -17
  28. package/dist/clients/dispatch/facts/function-facts.js +1 -1
  29. package/dist/clients/dispatch/facts/import-facts.js +5 -1
  30. package/dist/clients/dispatch/finding-policy.js +222 -0
  31. package/dist/clients/dispatch/indent-detect.js +389 -13
  32. package/dist/clients/dispatch/integration.js +175 -25
  33. package/dist/clients/dispatch/rule-ignores.js +62 -0
  34. package/dist/clients/dispatch/runners/actionlint.js +2 -1
  35. package/dist/clients/dispatch/runners/ast-grep-napi.js +21 -41
  36. package/dist/clients/dispatch/runners/biome-check.js +8 -4
  37. package/dist/clients/dispatch/runners/cpp-check.js +4 -3
  38. package/dist/clients/dispatch/runners/credo.js +2 -1
  39. package/dist/clients/dispatch/runners/cue-vet.js +2 -1
  40. package/dist/clients/dispatch/runners/dart-analyze.js +2 -1
  41. package/dist/clients/dispatch/runners/detekt.js +2 -1
  42. package/dist/clients/dispatch/runners/dotnet-build.js +2 -1
  43. package/dist/clients/dispatch/runners/elixir-check.js +2 -1
  44. package/dist/clients/dispatch/runners/eslint.js +2 -1
  45. package/dist/clients/dispatch/runners/fish-indent.js +2 -1
  46. package/dist/clients/dispatch/runners/gleam-check.js +2 -1
  47. package/dist/clients/dispatch/runners/go-vet.js +2 -1
  48. package/dist/clients/dispatch/runners/golangci-lint.js +2 -1
  49. package/dist/clients/dispatch/runners/hadolint.js +2 -1
  50. package/dist/clients/dispatch/runners/helm-lint.js +3 -1
  51. package/dist/clients/dispatch/runners/helm-render.js +2 -1
  52. package/dist/clients/dispatch/runners/htmlhint.js +2 -1
  53. package/dist/clients/dispatch/runners/javac.js +2 -1
  54. package/dist/clients/dispatch/runners/ktlint.js +2 -1
  55. package/dist/clients/dispatch/runners/lsp.js +19 -1
  56. package/dist/clients/dispatch/runners/markdownlint.js +3 -2
  57. package/dist/clients/dispatch/runners/mypy.js +2 -1
  58. package/dist/clients/dispatch/runners/oxlint.js +2 -1
  59. package/dist/clients/dispatch/runners/php-lint.js +2 -1
  60. package/dist/clients/dispatch/runners/phpstan.js +2 -1
  61. package/dist/clients/dispatch/runners/prisma-validate.js +2 -1
  62. package/dist/clients/dispatch/runners/psscriptanalyzer.js +12 -12
  63. package/dist/clients/dispatch/runners/pyright.js +2 -1
  64. package/dist/clients/dispatch/runners/rubocop.js +2 -1
  65. package/dist/clients/dispatch/runners/ruff.js +2 -2
  66. package/dist/clients/dispatch/runners/rust-clippy.js +12 -11
  67. package/dist/clients/dispatch/runners/shellcheck.js +2 -1
  68. package/dist/clients/dispatch/runners/shfmt.js +4 -13
  69. package/dist/clients/dispatch/runners/spellcheck.js +2 -2
  70. package/dist/clients/dispatch/runners/spotbugs.js +2 -1
  71. package/dist/clients/dispatch/runners/sqlfluff.js +3 -2
  72. package/dist/clients/dispatch/runners/stylelint.js +3 -2
  73. package/dist/clients/dispatch/runners/swiftlint.js +2 -1
  74. package/dist/clients/dispatch/runners/taplo.js +2 -1
  75. package/dist/clients/dispatch/runners/terragrunt.js +2 -1
  76. package/dist/clients/dispatch/runners/tflint.js +2 -1
  77. package/dist/clients/dispatch/runners/tree-sitter.js +2 -21
  78. package/dist/clients/dispatch/runners/trivy-config.js +2 -1
  79. package/dist/clients/dispatch/runners/utils/availability-policy.js +5 -0
  80. package/dist/clients/dispatch/runners/utils/candidate-probe.js +2 -2
  81. package/dist/clients/dispatch/runners/utils/runner-helpers.js +8 -2
  82. package/dist/clients/dispatch/runners/vale.js +2 -1
  83. package/dist/clients/dispatch/runners/yamllint.js +4 -3
  84. package/dist/clients/dispatch/runners/zig-check.js +2 -1
  85. package/dist/clients/dispatch/types.js +4 -1
  86. package/dist/clients/disposition-publish.js +1 -0
  87. package/dist/clients/effective-config.js +12 -2
  88. package/dist/clients/extension-log.js +2 -0
  89. package/dist/clients/file-kinds.js +26 -1
  90. package/dist/clients/file-role.js +23 -6
  91. package/dist/clients/file-utils.js +156 -10
  92. package/dist/clients/finding-delivery-gate.js +60 -9
  93. package/dist/clients/format-service.js +39 -21
  94. package/dist/clients/formatters.js +113 -200
  95. package/dist/clients/generation-guard.js +6 -2
  96. package/dist/clients/git-guard.js +11 -3
  97. package/dist/clients/gitleaks-client.js +42 -6
  98. package/dist/clients/govulncheck-client.js +48 -7
  99. package/dist/clients/indent-retarget.js +78 -8
  100. package/dist/clients/installer/index.js +524 -161
  101. package/dist/clients/instance-reaper-state.js +7 -0
  102. package/dist/clients/instance-reaper.js +20 -10
  103. package/dist/clients/jscpd-client.js +9 -1
  104. package/dist/clients/knip-client.js +9 -2
  105. package/dist/clients/language-profile.js +35 -3
  106. package/dist/clients/language-registry.js +5 -1
  107. package/dist/clients/latency-logger.js +6 -1
  108. package/dist/clients/lens-config.js +4 -0
  109. package/dist/clients/lens-engine.js +12 -3
  110. package/dist/clients/lens-events.js +2 -1
  111. package/dist/clients/lens-flag-registry.js +79 -0
  112. package/dist/clients/live-bus-emitter.js +2 -1
  113. package/dist/clients/lsp/client.js +25 -21
  114. package/dist/clients/lsp/config.js +36 -7
  115. package/dist/clients/lsp/diagnostic-binding.js +24 -1
  116. package/dist/clients/lsp/document-drift.js +78 -0
  117. package/dist/clients/lsp/index.js +288 -45
  118. package/dist/clients/lsp/launch.js +16 -4
  119. package/dist/clients/lsp/server.js +79 -15
  120. package/dist/clients/lsp/workspace-diagnostics-cache.js +39 -5
  121. package/dist/clients/lsp-mutation.js +5 -3
  122. package/dist/clients/map-with-concurrency.js +12 -8
  123. package/dist/clients/mcp/analyze.js +3 -0
  124. package/dist/clients/mcp/session.js +38 -4
  125. package/dist/clients/ndjson-logger.js +24 -7
  126. package/dist/clients/observed-mutation.js +40 -2
  127. package/dist/clients/opaque-mutation-scan.js +23 -3
  128. package/dist/clients/opengrep-client.js +111 -14
  129. package/dist/clients/package-manager.js +2 -1
  130. package/dist/clients/path-utils.js +123 -3
  131. package/dist/clients/performance-report.js +5 -1
  132. package/dist/clients/php-cs-fixer-config.js +8 -3
  133. package/dist/clients/pipeline.js +77 -7
  134. package/dist/clients/project-diagnostics/cache.js +37 -5
  135. package/dist/clients/project-diagnostics/fresh-fetch.js +173 -18
  136. package/dist/clients/project-diagnostics/runner-adapters/dead-code.js +4 -1
  137. package/dist/clients/project-diagnostics/runner-adapters/gitleaks.js +10 -9
  138. package/dist/clients/project-diagnostics/scanner.js +59 -3
  139. package/dist/clients/project-lens-config.js +48 -2
  140. package/dist/clients/read-guard-logger.js +2 -0
  141. package/dist/clients/read-guard.js +70 -11
  142. package/dist/clients/resource-sampler.js +147 -9
  143. package/dist/clients/review-graph-logger.js +2 -0
  144. package/dist/clients/ruff-client.js +18 -9
  145. package/dist/clients/runtime-agent-end.js +42 -5
  146. package/dist/clients/runtime-context.js +6 -2
  147. package/dist/clients/runtime-coordinator.js +82 -7
  148. package/dist/clients/runtime-session.js +33 -5
  149. package/dist/clients/runtime-tool-call.js +43 -12
  150. package/dist/clients/runtime-tool-result.js +334 -86
  151. package/dist/clients/runtime-turn.js +195 -18
  152. package/dist/clients/safe-spawn.js +258 -5
  153. package/dist/clients/scratch-tree-policy.js +6 -0
  154. package/dist/clients/security-scan-client.js +2 -2
  155. package/dist/clients/session-event-guard.js +119 -6
  156. package/dist/clients/sg-runner.js +25 -12
  157. package/dist/clients/sgconfig.js +79 -2
  158. package/dist/clients/situational-tool-telemetry.js +108 -0
  159. package/dist/clients/test-runner-client.js +258 -78
  160. package/dist/clients/test-runner-delivery.js +43 -0
  161. package/dist/clients/tool-agreement.js +423 -0
  162. package/dist/clients/tool-config.js +249 -0
  163. package/dist/clients/tool-cwd.js +270 -0
  164. package/dist/clients/tool-policy.js +163 -7
  165. package/dist/clients/tool-probe.js +53 -0
  166. package/dist/clients/tool-set-policy.js +42 -0
  167. package/dist/clients/tree-sitter-client.js +120 -0
  168. package/dist/clients/tree-sitter-query-loader.js +127 -189
  169. package/dist/clients/trivy-client.js +9 -1
  170. package/dist/clients/turn-context.js +52 -0
  171. package/dist/clients/widget-state.js +102 -3
  172. package/dist/clients/word-index.js +5 -2
  173. package/dist/clients/write-ordering-guard.js +7 -0
  174. package/dist/index.js +26968 -21741
  175. package/dist/mcp/analyze-cli.js +3 -2
  176. package/dist/mcp/server.js +140 -161
  177. package/dist/tools/activate-tools.js +10 -7
  178. package/dist/tools/ast-grep-outline.js +2 -13
  179. package/dist/tools/ast-grep-replace.js +8 -13
  180. package/dist/tools/ast-grep-search.js +83 -39
  181. package/dist/tools/effective-config.js +4 -3
  182. package/dist/tools/lens-diagnostic-mark.js +8 -11
  183. package/dist/tools/lens-diagnostics.js +516 -133
  184. package/dist/tools/lsp-diagnostics.js +265 -182
  185. package/dist/tools/lsp-navigation.js +20 -44
  186. package/dist/tools/module-report.js +5 -9
  187. package/dist/tools/project-report.js +9 -17
  188. package/dist/tools/render-compact.js +280 -1
  189. package/dist/tools/symbol-search.js +2 -2
  190. package/docs/agent-guide.md +3 -4
  191. package/docs/agent-tools.md +46 -22
  192. package/docs/audit1.md +5 -5
  193. package/docs/configuration.md +9 -0
  194. package/docs/dependencies.md +11 -0
  195. package/docs/dispositions.md +52 -0
  196. package/docs/environment-variables.md +2 -7
  197. package/docs/features.md +7 -7
  198. package/docs/globalconfig.md +14 -2
  199. package/docs/language-coverage.md +1 -0
  200. package/docs/mcp.md +13 -1
  201. package/docs/pi-lens-fixer.md +48 -18
  202. package/docs/pi-lens-investigator.md +38 -18
  203. package/docs/pi-lens-monitor.md +88 -0
  204. package/docs/pi-lens-retro.md +97 -0
  205. package/docs/pi-lens-reviewer.md +53 -31
  206. package/docs/pi-lens-subagent.md +12 -4
  207. package/docs/public-api-stability.md +1 -0
  208. package/docs/real-harness.md +46 -0
  209. package/docs/release-qa-baseline.md +27 -1
  210. package/docs/servercapabilities.md +1 -6
  211. package/docs/settings.md +44 -6
  212. package/docs/tools_improvement2.md +4 -4
  213. package/docs/usage.md +15 -3
  214. package/package.json +10 -1
  215. package/rules/tree-sitter-queries/typescript/sql-injection.yml +23 -7
  216. package/scripts/analyze-pi-lens-logs.mjs +40 -0
  217. package/skills/pi-lens-ast-grep/SKILL.md +23 -6
  218. package/skills/pi-lens-lsp-navigation/SKILL.md +26 -9
  219. package/dist/tools/ast-dump.js +0 -103
@@ -1,11 +1,13 @@
1
1
  const DEFAULT_INDENTATION = { style: "space", width: 2 };
2
2
  /**
3
3
  * Infer the prevailing indentation convention from lines that are indented.
4
- * The detector deliberately has no language knowledge: formatter callers use
5
- * it only as a conservative fallback when the repository has no config.
4
+ * Formatter callers use it only as a conservative fallback when the repository
5
+ * has no config. It has two pieces of lexical knowledge: the `/* … *\/` block
6
+ * comment and the multi-line template literal, whose interior lines are
7
+ * alignment rather than nesting; everything else is counted as written.
6
8
  */
7
9
  export function detectIndentation(content) {
8
- const lines = content.split(/\r?\n/);
10
+ const lines = structuralLines(content.split(/\r?\n/));
9
11
  const tabs = lines.filter((line) => /^\t+\S/.test(line)).length;
10
12
  const spaceCounts = lines
11
13
  .map((line) => line.match(/^ +(?=\S)/)?.[0].length ?? 0)
@@ -15,20 +17,394 @@ export function detectIndentation(content) {
15
17
  if (tabs > spaceCounts.length)
16
18
  return { style: "tab", width: 1 };
17
19
  if (spaceCounts.length > tabs) {
18
- const counts = new Map();
19
- for (const count of spaceCounts) {
20
- for (const other of spaceCounts) {
21
- if (other > count) {
22
- const delta = other - count;
23
- counts.set(delta, (counts.get(delta) ?? 0) + 1);
24
- }
25
- }
20
+ const minimum = Math.min(...spaceCounts);
21
+ // 0 is GCD's identity, so seeding the fold both satisfies "reduce needs an
22
+ // initial value" and leaves every result unchanged.
23
+ const gcd = spaceCounts.reduce((unit, count) => greatestCommonDivisor(unit, count), 0);
24
+ const nonBlank = lines
25
+ .map((line) => line.match(/^( *)\S/)?.[1]?.length)
26
+ .filter((count) => count !== undefined);
27
+ const hasStructuralBoundary = nonBlank.some((count, index) => {
28
+ const previous = nonBlank[index - 1];
29
+ return count === minimum && previous !== undefined && previous < minimum;
30
+ });
31
+ if (hasStructuralBoundary && minimum <= 8) {
32
+ return { style: "space", width: minimum };
33
+ }
34
+ // A continuation line can be the shallowest observed line even though it
35
+ // is not one indentation unit from the surrounding structure. GCD gives
36
+ // those aligned runs their structural unit (for example 4/6 -> 2).
37
+ if (gcd < minimum && gcd <= 8) {
38
+ return { style: "space", width: gcd };
26
39
  }
27
- const inferredWidth = [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0]?.[0] ?? Math.min(...spaceCounts);
28
- return { style: "space", width: inferredWidth <= 8 ? inferredWidth : 2 };
40
+ // A file containing only nested runs (for example 6/12 spaces) has no
41
+ // evidence that its first run is one unit rather than three or six. Do
42
+ // not impose a formatter style on that ambiguous evidence.
43
+ return undefined;
29
44
  }
30
45
  return DEFAULT_INDENTATION;
31
46
  }
47
+ /**
48
+ * Whether the line opens a block comment that it does not also close. A `/*`
49
+ * that follows a `//` on the same line is inside a line comment, not an
50
+ * opener; a `//` that follows the `/*` (a URL in a banner) is not.
51
+ */
52
+ function opensBlockComment(line) {
53
+ const blockAt = line.indexOf("/*");
54
+ if (blockAt < 0)
55
+ return false;
56
+ const lineAt = line.indexOf("//");
57
+ if (lineAt >= 0 && lineAt < blockAt)
58
+ return false;
59
+ return line.indexOf("*/", blockAt + 2) < 0;
60
+ }
61
+ /**
62
+ * One boolean per line: true when the line sits *inside* a terminated block
63
+ * comment, so its leading space is alignment on the opener's `*` column, not
64
+ * a nesting unit. The opener line itself is false (its own indentation *is*
65
+ * structural). An opener that never closes was a `/*` inside a string or a
66
+ * regex, so its lines are left false rather than silently swallowed.
67
+ *
68
+ * Shared by {@link structuralLines} (drops the lines from indentation
69
+ * detection's own evidence — a top-level JSDoc otherwise contributes a run
70
+ * of 1-space lines, so a 2- or 4-space file with doc comments reads as width
71
+ * 1 and a tab file with a top-level JSDoc reads as spaces, #3039 F1/F2) and
72
+ * by `clients/indent-retarget.ts`'s `retargetReplacementIndentation`, which
73
+ * must not pick its base nesting unit from a comment's alignment column
74
+ * either (#3052) — one lexer for "which lines carry structure", not two.
75
+ */
76
+ export function blockCommentInteriorMask(lines) {
77
+ const mask = Array.from({ length: lines.length }, () => false);
78
+ let pendingStart = -1;
79
+ for (const [i, line] of lines.entries()) {
80
+ if (pendingStart >= 0) {
81
+ mask[i] = true;
82
+ if (line.includes("*/"))
83
+ pendingStart = -1;
84
+ continue;
85
+ }
86
+ if (opensBlockComment(line))
87
+ pendingStart = i;
88
+ }
89
+ if (pendingStart >= 0) {
90
+ for (let i = pendingStart + 1; i < lines.length; i += 1)
91
+ mask[i] = false;
92
+ }
93
+ return mask;
94
+ }
95
+ /** Whether `stack` holds a frame the mask (or its fail-safe) must treat as
96
+ * "inside a template" — every frame except `"block"`. A `/* … *\/` comment
97
+ * nested in the tracked span (plain code, or inside a `${ … }` substitution)
98
+ * is not itself template evidence; {@link blockCommentInteriorMask} already
99
+ * excludes a top-level block comment's own lines. */
100
+ function hasLiveFrame(stack) {
101
+ return stack.some((frame) => frame.kind !== "block");
102
+ }
103
+ /**
104
+ * Advance a lexical stack over one line of source, mutating it in place.
105
+ * Shared by {@link templateLiteralInteriorMask}'s per-line pass. `stack`
106
+ * empty means plain code; a `"template"` frame means raw template text; an
107
+ * `"expr"` frame means code inside a `${ … }` substitution, with its own
108
+ * brace-depth counter so a nested `{`/`}` (an object literal, a block) does
109
+ * not close the substitution early — only the brace that returns the counter
110
+ * to 0, the one that matches the `${`, does; a `"block"` frame means a
111
+ * `/* … *\/` comment, so a JSDoc's own backtick (a fenced code sample, an
112
+ * inline `` `x` ``) never opens a tracked template that then swallows real
113
+ * code up to whatever later backtick happens to close it (#3059 review F1,
114
+ * AGENTS.md shape 43 — prose mistaken for executable structure).
115
+ *
116
+ * A backtick, `//`, `/*`, or quote character means nothing while `//` has
117
+ * already started a line comment, a `/* … *\/` comment is open, or a quoted
118
+ * string is open, so all three states resolve before the general
119
+ * per-character switch (line comments run to EOL; quoted strings skip
120
+ * everything up to their own unescaped terminator, taking a backtick inside
121
+ * them out of consideration the same way; a block comment skips everything,
122
+ * backticks included, up to its own `*\/`, possibly spanning lines).
123
+ *
124
+ * A regex literal (`` /pattern/flags ``) has its own resolution: the same
125
+ * class of problem as a `/* … *\/` comment or a quoted string, since a
126
+ * backtick or `/*` inside one must not be read as a real opener either
127
+ * (#3120). Disambiguating `/` from division in general needs a real
128
+ * tokenizer with full grammar context — a first-pass heuristic tried here
129
+ * over-declined the corpus 54 files vs 5 for a real fix, so {@link
130
+ * isRegexOpenerPosition} only recognises `/` as an opener in positions
131
+ * where JS grammar makes a value expression, never a divisor: immediately
132
+ * after `(`, `,`, `=`, `:`, `[`, `!`, `&`, `|`, `?`, a `return`/`typeof`/
133
+ * `case` keyword, or at line start. (`{`, `}`, and `;` were tried too —
134
+ * dropped, not just unused: `}` is grammatically unsound on its own
135
+ * (`x = {a:1} / 2` is division, not a regex opener, and both sibling
136
+ * lexers in this tree — `tests/support/sweep-kit.ts`,
137
+ * `scripts/check-pr-body.mjs`'s `blankCommentsAndStrings` — exclude it for
138
+ * that reason), and measurement showed `{`/`}`/`;` firing 10/0/6 times
139
+ * across a 25,553-file corpus (own tree plus `node_modules`, every
140
+ * extension biome/prettier/ruff/shfmt format) with zero verdict
141
+ * differences either way — see #3120 PR round 2.) Anywhere else (after an
142
+ * identifier, a digit, `)`, `]`, a string, or a template) is left alone
143
+ * exactly as before this state existed — division stays division, so the
144
+ * gate can only ever add masking correctness, never remove it, MODULO the
145
+ * closing-scan's own correctness (see {@link skipRegexLiteral}'s doc
146
+ * comment: the position gate alone is not sufficient — a misfired skip
147
+ * that swallows an odd number of backticks can still invert parity for
148
+ * the rest of the file; measured against the same corpus, this changed
149
+ * 0 files' verdicts, but 158 of 181 gate firings on the corpus's 882
150
+ * Markdown files alone accepted a false close before the closing-scan's
151
+ * own tightening below cut that to 19). A recognised opener is skipped to its own
152
+ * closing `/` (honouring `[...]` character classes and `\` escapes) by
153
+ * {@link skipRegexLiteral} the same way `skipQuoted` skips a string;
154
+ * everything inside — backticks, `/*`, quotes — is consumed without
155
+ * touching `stack`. A regex literal cannot itself contain a literal
156
+ * newline, so this resolves entirely within one line; the position gate
157
+ * fires on every `/` that starts a line (for instance a Markdown path
158
+ * like `/src`), not only on shapes that can actually close as a regex —
159
+ * it is the closing scan's own `-1` fallback, not the gate, that makes an
160
+ * unclosed or wrongly-shaped match safe.
161
+ */
162
+ function advanceTemplateState(line, stack) {
163
+ let j = 0;
164
+ while (j < line.length) {
165
+ const top = stack[stack.length - 1];
166
+ if (top?.kind === "template") {
167
+ if (line[j] === "\\") {
168
+ j += 2; // an escaped character, including an escaped backtick, \`
169
+ continue;
170
+ }
171
+ if (line.startsWith("${", j)) {
172
+ stack.push({ kind: "expr", braceDepth: 1 });
173
+ j += 2;
174
+ continue;
175
+ }
176
+ if (line[j] === "`") {
177
+ stack.pop();
178
+ j += 1;
179
+ continue;
180
+ }
181
+ j += 1;
182
+ continue;
183
+ }
184
+ if (top?.kind === "block") {
185
+ const closeAt = line.indexOf("*/", j);
186
+ if (closeAt < 0)
187
+ return; // still inside the comment at EOL
188
+ stack.pop();
189
+ j = closeAt + 2;
190
+ continue;
191
+ }
192
+ // Plain code, at the top level or inside a `${ … }` substitution.
193
+ if (line.startsWith("//", j))
194
+ return; // rest of line is a line comment
195
+ if (line.startsWith("/*", j)) {
196
+ stack.push({ kind: "block" });
197
+ j += 2;
198
+ continue;
199
+ }
200
+ if (line[j] === "/" && isRegexOpenerPosition(line, j)) {
201
+ const after = skipRegexLiteral(line, j);
202
+ if (after >= 0) {
203
+ j = after;
204
+ continue;
205
+ }
206
+ // No closing `/` before EOL: not actually a regex literal at this
207
+ // position (the heuristic misfired, or the line just ends mid-token).
208
+ // Fall through and scan `/` as an ordinary character, unchanged from
209
+ // before this state existed.
210
+ }
211
+ const ch = line[j];
212
+ if (ch === '"' || ch === "'") {
213
+ j = skipQuoted(line, j, ch);
214
+ continue;
215
+ }
216
+ if (ch === "`") {
217
+ stack.push({ kind: "template" });
218
+ j += 1;
219
+ continue;
220
+ }
221
+ if (top?.kind === "expr") {
222
+ if (ch === "{") {
223
+ top.braceDepth += 1;
224
+ j += 1;
225
+ continue;
226
+ }
227
+ if (ch === "}") {
228
+ top.braceDepth -= 1;
229
+ j += 1;
230
+ if (top.braceDepth === 0)
231
+ stack.pop();
232
+ continue;
233
+ }
234
+ }
235
+ j += 1;
236
+ }
237
+ }
238
+ /** Skip a single- or double-quoted string starting at `quote`, honoring `\`
239
+ * escapes, so a backtick (or anything else) inside it is never inspected. */
240
+ function skipQuoted(line, start, quote) {
241
+ let j = start + 1;
242
+ while (j < line.length) {
243
+ if (line[j] === "\\") {
244
+ j += 2;
245
+ continue;
246
+ }
247
+ if (line[j] === quote)
248
+ return j + 1;
249
+ j += 1;
250
+ }
251
+ return line.length; // unterminated on this line; nothing more to find
252
+ }
253
+ /** The set of characters that make a following `/` unambiguous — JS grammar
254
+ * only accepts a value expression there, never a divisor. */
255
+ const REGEX_OPENER_PUNCTUATION = new Set([
256
+ "(",
257
+ ",",
258
+ "=",
259
+ ":",
260
+ "[",
261
+ "!",
262
+ "&",
263
+ "|",
264
+ "?",
265
+ ]);
266
+ /** A `return`, `typeof`, or `case` keyword, word-bounded, immediately before
267
+ * (modulo trailing whitespace) the position under test. */
268
+ const REGEX_OPENER_KEYWORD = /(?:^|[^A-Za-z0-9_$])(?:return|typeof|case)$/;
269
+ /**
270
+ * Whether `line[at]` (a `/`) sits in a position where JS grammar makes it a
271
+ * regex-literal opener rather than division: immediately after one of
272
+ * {@link REGEX_OPENER_PUNCTUATION}, a `return`/`typeof`/`case` keyword, or
273
+ * at the start of the line (#3120). Deliberately narrower than every legal
274
+ * regex position (an arrow function's `=>`, for instance, is not
275
+ * recognised) — a missed opener leaves `/` division-shaped exactly like
276
+ * before this state existed, so under-recognition is inert while
277
+ * over-recognition would corrupt real code.
278
+ */
279
+ function isRegexOpenerPosition(line, at) {
280
+ const before = line.slice(0, at).replace(/[ \t]+$/, "");
281
+ if (before === "")
282
+ return true; // line start (modulo leading whitespace)
283
+ if (REGEX_OPENER_KEYWORD.test(before))
284
+ return true;
285
+ return REGEX_OPENER_PUNCTUATION.has(before.at(-1) ?? "");
286
+ }
287
+ /** Regex flag letters JS accepts after a literal's closing `/`. */
288
+ const REGEX_FLAG_CHARS = "dgimsuvy";
289
+ /**
290
+ * Skip a regex literal starting at its opening `/` (`start`), honoring
291
+ * `[...]` character classes (a `/` or unescaped `]` inside one closes
292
+ * nothing) and `\` escapes, mirroring {@link skipQuoted}. Returns the index
293
+ * just past the closing `/`, or -1 if none is found before EOL — a regex
294
+ * literal cannot contain a literal newline, so an unclosed scan means this
295
+ * was not actually one.
296
+ *
297
+ * The position gate ({@link isRegexOpenerPosition}) alone is not enough:
298
+ * it fires on every `/` that starts a value-expression position, including
299
+ * prose that merely looks like one — a Markdown line like `` Layout: /src
300
+ * `bin/cli` and friends. `` gates on the `:` before `/src`, and the first
301
+ * `/` found afterward (inside the backticked `` `bin/cli` ``) would
302
+ * otherwise read as a valid close, swallowing the backtick and inverting
303
+ * template-tracking parity for the rest of the file. A closing `/` is
304
+ * accepted only when it is followed by zero or more regex flag letters
305
+ * ({@link REGEX_FLAG_CHARS}) and then a NON-IDENTIFIER character (or
306
+ * EOL) — `/src/cli` and friends` has an identifier character (`c`) right
307
+ * after the candidate close, which a real regex literal's own syntax
308
+ * forbids (flags must be immediately followed by a statement terminator,
309
+ * not more identifier text), so it is rejected and the scan returns -1
310
+ * instead.
311
+ *
312
+ * This narrows the false-close family, it does not close it: when what
313
+ * follows the false close is instead a NON-identifier character (a
314
+ * backtick, a space, `)`, `.` — anything outside `[A-Za-z0-9_$]`), this
315
+ * check does not fire either, and the same corruption is still possible
316
+ * in principle. Round 3 F2 measured the residual directly rather than
317
+ * asserting it away: of the 19 regex-shaped matches that still survive
318
+ * in the corpus's Markdown files after this check (round 2's own count),
319
+ * NONE has a backtick inside its matched span — every survivor is either
320
+ * a genuine regex literal in a fenced code sample or ASCII-art/prose that
321
+ * happens to satisfy the grammar without ever touching a `` ` `` — so the
322
+ * residual is 0 of 25,553 corpus files and 0 of those 19 matches, not
323
+ * merely untested. The only check that closes the family completely is
324
+ * counting backticks in the consumed span and rejecting an odd count —
325
+ * which is exactly the shape a real `` /`foo`/ `` regex literal (a
326
+ * pattern that legitimately contains backticks) also has, so rejecting
327
+ * it would re-introduce the over-decline this PR's own first-pass
328
+ * heuristic was rejected for (#3120's own history). Left as a measured,
329
+ * documented limit rather than tightened further.
330
+ */
331
+ function skipRegexLiteral(line, start) {
332
+ let j = start + 1;
333
+ let inClass = false;
334
+ while (j < line.length) {
335
+ const c = line[j];
336
+ if (c === "\\") {
337
+ j += 2;
338
+ continue;
339
+ }
340
+ if (inClass) {
341
+ if (c === "]")
342
+ inClass = false;
343
+ j += 1;
344
+ continue;
345
+ }
346
+ if (c === "[") {
347
+ inClass = true;
348
+ j += 1;
349
+ continue;
350
+ }
351
+ if (c === "/") {
352
+ let k = j + 1;
353
+ while (k < line.length && REGEX_FLAG_CHARS.includes(line[k] ?? ""))
354
+ k += 1;
355
+ if (k < line.length && /[A-Za-z0-9_$]/.test(line[k] ?? ""))
356
+ return -1;
357
+ return j + 1;
358
+ }
359
+ j += 1;
360
+ }
361
+ return -1; // unterminated on this line; not a regex literal after all
362
+ }
363
+ /**
364
+ * One boolean per line: true when the line sits *inside* a multi-line
365
+ * template literal (or a `${ … }` substitution nested in one), so its leading
366
+ * space is alignment on the surrounding text or expression, not a nesting
367
+ * unit — the same shape as {@link blockCommentInteriorMask} for `/* … *\/`
368
+ * (#3059, a fourth member of AGENTS.md defect 49). The opener line itself is
369
+ * false (its own indentation *is* structural); a backtick inside a `//` line
370
+ * comment or a quoted string must not open a template (`advanceTemplateState`
371
+ * resolves both before treating a backtick as an opener); `${ … }` nesting
372
+ * and escaped backticks are tracked through the frame stack so neither an
373
+ * object literal inside a substitution nor an escaped backtick in template
374
+ * text closes anything early. A template that never closes by EOF was
375
+ * (like an unterminated block comment) something this lexer misread — a
376
+ * backtick inside a regex literal, say — so its lines are left false rather
377
+ * than silently swallowed.
378
+ */
379
+ export function templateLiteralInteriorMask(lines) {
380
+ const mask = Array.from({ length: lines.length }, () => false);
381
+ const stack = [];
382
+ let openLine = -1;
383
+ for (const [i, line] of lines.entries()) {
384
+ if (hasLiveFrame(stack)) {
385
+ mask[i] = true;
386
+ }
387
+ else {
388
+ openLine = i;
389
+ }
390
+ advanceTemplateState(line, stack);
391
+ }
392
+ if (hasLiveFrame(stack)) {
393
+ for (let i = openLine + 1; i < lines.length; i += 1)
394
+ mask[i] = false;
395
+ }
396
+ return mask;
397
+ }
398
+ function structuralLines(lines) {
399
+ const blockCommentMask = blockCommentInteriorMask(lines);
400
+ const templateMask = templateLiteralInteriorMask(lines);
401
+ return lines.filter((_, index) => !blockCommentMask[index] && !templateMask[index]);
402
+ }
403
+ function greatestCommonDivisor(left, right) {
404
+ while (right !== 0)
405
+ [left, right] = [right, left % right];
406
+ return left;
407
+ }
32
408
  /** Whether the content supplied evidence from which a style can be inferred. */
33
409
  export function hasDetectableIndentation(content) {
34
410
  return /^(?:\t+| {1,})\S/m.test(content);