pi-lens 3.8.69 → 3.8.71

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 (147) hide show
  1. package/CHANGELOG.md +99 -0
  2. package/README.md +31 -13
  3. package/dist/clients/bootstrap.js +3 -1
  4. package/dist/clients/bus-events-logger.js +53 -0
  5. package/dist/clients/bus-publish.js +45 -2
  6. package/dist/clients/cache/rule-cache.js +9 -5
  7. package/dist/clients/cache-manager.js +19 -13
  8. package/dist/clients/code-quality-warnings.js +27 -0
  9. package/dist/clients/dead-code-client.js +5 -23
  10. package/dist/clients/diagnostic-dispositions.js +298 -0
  11. package/dist/clients/diagnostics-publish.js +38 -2
  12. package/dist/clients/dispatch/auxiliary-lsp.js +144 -6
  13. package/dist/clients/dispatch/dispatcher.js +6 -1
  14. package/dist/clients/dispatch/facts/function-facts.js +83 -0
  15. package/dist/clients/dispatch/integration.js +19 -4
  16. package/dist/clients/dispatch/rules/async-noise.js +1 -1
  17. package/dist/clients/dispatch/rules/async-unnecessary-wrapper.js +1 -1
  18. package/dist/clients/dispatch/rules/cors-wildcard.js +1 -1
  19. package/dist/clients/dispatch/rules/error-obscuring.js +2 -1
  20. package/dist/clients/dispatch/rules/error-swallowing.js +2 -1
  21. package/dist/clients/dispatch/rules/framework-call-noise.js +67 -0
  22. package/dist/clients/dispatch/rules/high-complexity.js +12 -1
  23. package/dist/clients/dispatch/rules/high-fan-out.js +14 -3
  24. package/dist/clients/dispatch/rules/high-import-coupling.js +1 -1
  25. package/dist/clients/dispatch/rules/missing-error-propagation.js +1 -1
  26. package/dist/clients/dispatch/rules/no-commented-credentials.js +1 -1
  27. package/dist/clients/dispatch/rules/pass-through-wrappers.js +1 -1
  28. package/dist/clients/dispatch/rules/placeholder-comments.js +1 -1
  29. package/dist/clients/dispatch/rules/unsafe-boundary.js +1 -1
  30. package/dist/clients/dispatch/runners/ast-grep-napi.js +75 -18
  31. package/dist/clients/dispatch/runners/lsp.js +23 -34
  32. package/dist/clients/dispatch/runners/oxlint.js +1 -1
  33. package/dist/clients/dispatch/suppress-writer.js +68 -0
  34. package/dist/clients/dispatch/utils/lsp-diagnostics.js +4 -1
  35. package/dist/clients/disposition-logger.js +39 -0
  36. package/dist/clients/disposition-publish.js +109 -0
  37. package/dist/clients/file-utils.js +94 -33
  38. package/dist/clients/format-events-publish.js +299 -0
  39. package/dist/clients/git-tracked-ignore.js +208 -0
  40. package/dist/clients/gitleaks-client.js +40 -5
  41. package/dist/clients/installer/index.js +123 -6
  42. package/dist/clients/instance-reaper.js +229 -2
  43. package/dist/clients/instance-registry.js +141 -2
  44. package/dist/clients/json-cache-read.js +65 -0
  45. package/dist/clients/knip-client.js +35 -38
  46. package/dist/clients/language-profile.js +11 -11
  47. package/dist/clients/lens-engine.js +12 -0
  48. package/dist/clients/lens-map.js +1079 -0
  49. package/dist/clients/log-cleanup.js +61 -19
  50. package/dist/clients/lsp/aggregation.js +69 -2
  51. package/dist/clients/lsp/cascade-tier.js +31 -19
  52. package/dist/clients/lsp/client.js +124 -14
  53. package/dist/clients/lsp/config.js +27 -1
  54. package/dist/clients/lsp/index.js +1028 -68
  55. package/dist/clients/lsp/server-strategies.js +17 -8
  56. package/dist/clients/lsp/server.js +80 -28
  57. package/dist/clients/lsp/tsserver-sync.js +145 -0
  58. package/dist/clients/lsp/workspace-diagnostics-cache.js +172 -0
  59. package/dist/clients/lsp-budget.js +148 -0
  60. package/dist/clients/mcp/session.js +9 -0
  61. package/dist/clients/middle-man-analysis.js +260 -0
  62. package/dist/clients/module-report.js +173 -11
  63. package/dist/clients/ndjson-logger.js +24 -0
  64. package/dist/clients/opengrep-client.js +217 -0
  65. package/dist/clients/opengrep-config.js +2 -10
  66. package/dist/clients/path-utils.js +66 -0
  67. package/dist/clients/pipeline.js +5 -1
  68. package/dist/clients/project-diagnostics/cache.js +5 -12
  69. package/dist/clients/project-diagnostics/extractors.js +21 -1
  70. package/dist/clients/project-diagnostics/fresh-fetch.js +275 -0
  71. package/dist/clients/project-diagnostics/runner-adapters/opengrep.js +40 -0
  72. package/dist/clients/project-diagnostics/runner-adapters/runner-findings.js +46 -0
  73. package/dist/clients/project-snapshot.js +3 -6
  74. package/dist/clients/quiet-window.js +57 -2
  75. package/dist/clients/read-expansion.js +2 -3
  76. package/dist/clients/read-guard-tool-lines.js +10 -0
  77. package/dist/clients/read-guard.js +1 -1
  78. package/dist/clients/resource-sampler.js +254 -0
  79. package/dist/clients/review-graph/builder.js +322 -42
  80. package/dist/clients/review-graph/import-resolvers.js +53 -19
  81. package/dist/clients/review-graph/symbol-id.js +57 -0
  82. package/dist/clients/runtime-agent-end.js +26 -0
  83. package/dist/clients/runtime-coordinator.js +9 -1
  84. package/dist/clients/runtime-session.js +93 -17
  85. package/dist/clients/runtime-tool-call.js +789 -0
  86. package/dist/clients/runtime-tool-result.js +15 -2
  87. package/dist/clients/runtime-turn.js +62 -13
  88. package/dist/clients/safe-spawn.js +48 -2
  89. package/dist/clients/session-state-store.js +6 -9
  90. package/dist/clients/sgconfig.js +2 -9
  91. package/dist/clients/source-filter.js +17 -25
  92. package/dist/clients/source-walker.js +66 -0
  93. package/dist/clients/startup-scan.js +105 -43
  94. package/dist/clients/symbol-containment.js +24 -0
  95. package/dist/clients/test-runner-client.js +544 -29
  96. package/dist/clients/tree-sitter-symbol-extractor.js +12 -5
  97. package/dist/clients/typos-config.js +2 -11
  98. package/dist/clients/widget-state.js +83 -1
  99. package/dist/clients/write-ordering-guard.js +58 -0
  100. package/dist/clients/zizmor-config.js +29 -10
  101. package/dist/index.js +25511 -19414
  102. package/dist/mcp/server.js +95 -19
  103. package/dist/tools/activate-tools.js +72 -0
  104. package/dist/tools/ast-dump.js +2 -8
  105. package/dist/tools/lens-diagnostic-mark.js +158 -0
  106. package/dist/tools/lens-diagnostics.js +327 -33
  107. package/dist/tools/lsp-diagnostics.js +525 -105
  108. package/dist/tools/module-report.js +18 -5
  109. package/docs/agent-tools.md +136 -0
  110. package/docs/ast-grep_rules_catalog.md +564 -0
  111. package/docs/astplayground.md +178 -0
  112. package/docs/audit1.md +177 -0
  113. package/docs/custom-rules.md +231 -0
  114. package/docs/dependencies.md +54 -0
  115. package/docs/dispositions.md +85 -0
  116. package/docs/env_variables.md +10 -0
  117. package/docs/environment-variables.md +83 -0
  118. package/docs/fable.md +140 -0
  119. package/docs/features.md +338 -0
  120. package/docs/globalconfig.md +79 -0
  121. package/docs/language-coverage.md +48 -0
  122. package/docs/lsp-capability-matrix.md +157 -0
  123. package/docs/lsp-latency-benchmark.md +169 -0
  124. package/docs/mcp.md +438 -0
  125. package/docs/module-report-read-symbol.md +258 -0
  126. package/docs/servercapabilities.md +118 -0
  127. package/docs/subagent-compat.md +281 -0
  128. package/docs/tools.md +16 -0
  129. package/docs/tools_improvement2.md +345 -0
  130. package/docs/tree-sitter_rules_catalog.md +296 -0
  131. package/docs/usage.md +129 -0
  132. package/docs/word-index.md +150 -0
  133. package/package.json +10 -1
  134. package/rules/ast-grep-rules/rule-tests/find-import-file-without-extension-test.yml +4 -0
  135. package/rules/ast-grep-rules/rule-tests/no-javascript-url-js-test.yml +5 -0
  136. package/rules/ast-grep-rules/rule-tests/no-javascript-url-test.yml +9 -0
  137. package/rules/ast-grep-rules/rules/array-callback-return-js.yml +1 -1
  138. package/rules/ast-grep-rules/rules/find-import-file-without-extension.yml +3 -1
  139. package/rules/ast-grep-rules/rules/jwt-no-verify-js.yml +1 -1
  140. package/rules/ast-grep-rules/rules/no-extra-boolean-cast-js.yml +1 -1
  141. package/rules/ast-grep-rules/rules/no-implied-eval-js.yml +1 -1
  142. package/rules/ast-grep-rules/rules/no-javascript-url-js.yml +13 -1
  143. package/rules/ast-grep-rules/rules/no-javascript-url.yml +12 -0
  144. package/rules/ast-grep-rules/rules/no-sql-in-code-js.yml +1 -1
  145. package/rules/ast-grep-rules/rules/weak-rsa-key-js.yml +1 -1
  146. package/skills/pi-lens-ast-grep/SKILL.md +3 -1
  147. package/dist/clients/production-readiness.js +0 -493
@@ -0,0 +1,1079 @@
1
+ /**
2
+ * `/lens-map` (#679) — a human-facing, self-contained interactive HTML project
3
+ * map rendered from the existing review graph. Zero external dependencies: the
4
+ * force-directed layout is computed here in Node at generation time (a simple
5
+ * deterministic simulation), and the client side is just an embedded JSON
6
+ * payload rendered by vanilla JS into an SVG (pan/zoom/hover/click) — no CDN
7
+ * script, no npm deps, nothing fetched at view time.
8
+ *
9
+ * The review graph is symbol-level; this file aggregates it to FILE-level
10
+ * nodes (the unit humans actually want to see on a map) and file→file edges
11
+ * (deduped, weighted by how many underlying symbol edges they represent).
12
+ * "external" kind nodes (third-party/stdlib import targets) are excluded from
13
+ * the map outright — their count is surfaced in the header instead.
14
+ *
15
+ * Human-only surface: no agent tool, no MCP mirror. See index.ts's `lens-map`
16
+ * command registration.
17
+ */
18
+ import * as fs from "node:fs";
19
+ import * as path from "node:path";
20
+ import { FactStore } from "./dispatch/fact-store.js";
21
+ import { getProjectDataDir } from "./file-utils.js";
22
+ import { collectUntrackedIgnoredIds } from "./git-tracked-ignore.js";
23
+ import { normalizeMapKey } from "./path-utils.js";
24
+ import { buildOrUpdateGraph } from "./review-graph/service.js";
25
+ import { detectFileRole } from "./file-role.js";
26
+ export const DEFAULT_MAX_MAP_NODES = 500;
27
+ /**
28
+ * Aggregates a symbol-level {@link ReviewGraph} into file-level nodes/edges.
29
+ * Pure and side-effect-free — no graph build here, no filesystem access — so
30
+ * it's directly unit-testable against a synthetic graph.
31
+ */
32
+ export function aggregateGraphToFiles(graph, options) {
33
+ const maxNodes = Math.max(1, options?.maxNodes ?? DEFAULT_MAX_MAP_NODES);
34
+ const files = new Map();
35
+ let externalCount = 0;
36
+ const testFileIds = new Set();
37
+ // A node resolves to the file it belongs to: a "file" kind node IS the
38
+ // file; a "symbol" kind node belongs to its `filePath`. Anything else
39
+ // ("external" — third-party/stdlib import targets, or "module" —
40
+ // unresolved same-project import placeholders with no real file on disk)
41
+ // has no file identity and is excluded from the map. Only "external" is
42
+ // counted (per #679's spec); "module" placeholders are silently dropped —
43
+ // they're not real files and there's nothing useful to show for them.
44
+ // Test files (per `detectFileRole`) are ALSO excluded (#679 follow-up):
45
+ // they pollute the file-level map and, left in, would dominate the
46
+ // truncation ranking on test-heavy repos. Excluding at nodeToFile
47
+ // construction time means their edges are dropped for free below (an
48
+ // edge whose endpoint never resolves to a file is skipped) and they can
49
+ // never influence degree/dependents/truncation ranking, which is
50
+ // computed entirely from the (post-exclusion) nodeToFile map.
51
+ const nodeToFile = new Map();
52
+ // detectFileRole is pure on the path, and a file's many symbol nodes all
53
+ // share one path — cache per normalized id so the classification runs once
54
+ // per FILE, not once per node.
55
+ const isTestById = new Map();
56
+ function isTestFile(id, filePath) {
57
+ let isTest = isTestById.get(id);
58
+ if (isTest === undefined) {
59
+ isTest = detectFileRole(filePath) === "test";
60
+ isTestById.set(id, isTest);
61
+ }
62
+ return isTest;
63
+ }
64
+ // ── Pass 1: gather file identities (post test-exclusion) ────────────────
65
+ // Needed BEFORE aggregation because compiled-twin canonicalization (below)
66
+ // can only decide "does X.js have an X.ts sibling?" once the full set of
67
+ // file identities is known.
68
+ const allFileIds = new Set();
69
+ for (const node of graph.nodes.values()) {
70
+ if (node.kind === "external") {
71
+ externalCount += 1;
72
+ continue;
73
+ }
74
+ if ((node.kind !== "file" && node.kind !== "symbol") || !node.filePath) {
75
+ continue;
76
+ }
77
+ const id = normalizeMapKey(node.filePath);
78
+ if (isTestFile(id, node.filePath)) {
79
+ testFileIds.add(id);
80
+ continue;
81
+ }
82
+ allFileIds.add(id);
83
+ }
84
+ // ── Pass 2: canonicalize compiled twins ─────────────────────────────────
85
+ // pi-lens (and many TS projects) compile in place, so the review graph's
86
+ // import resolution frequently lands on the compiled `X.js` sibling of an
87
+ // `X.ts` source. Rendering both as separate map nodes doubles the project
88
+ // and splits each file's edges across the pair. When BOTH the compiled
89
+ // form and a source twin exist as file identities, the compiled one is
90
+ // canonicalized onto the source: its symbols and ALL its edges remap onto
91
+ // the source node (merge, never drop — the compiled twin carries most
92
+ // import edges). Deterministic sibling families: .js → .ts (preferred)
93
+ // then .tsx; .mjs → .mts; .cjs → .cts. A compiled-looking file with no
94
+ // source twin (vendored deps, pure-JS projects) is untouched.
95
+ const COMPILED_TWIN_SOURCES = [
96
+ [".js", [".ts", ".tsx"]],
97
+ [".mjs", [".mts"]],
98
+ [".cjs", [".cts"]],
99
+ ];
100
+ // Interplay with the untracked-gitignored exclusion (`excludeIds`):
101
+ // twin canonicalization takes PRECEDENCE over exclusion. An excluded
102
+ // compiled file whose source twin survives is merged onto that twin
103
+ // (edges preserved) rather than dropped — dropping it would silently
104
+ // discard the import edges the compiled twin carries, which is strictly
105
+ // worse than merging them onto the source node. Only excluded files with
106
+ // NO surviving canonical target actually vanish. Conversely an excluded
107
+ // file can never BE a canonical target — merging a survivor onto a node
108
+ // that's about to disappear would drop both.
109
+ const excludeIds = options?.excludeIds;
110
+ const canonicalOf = new Map();
111
+ for (const id of allFileIds) {
112
+ for (const [compiledExt, sourceExts] of COMPILED_TWIN_SOURCES) {
113
+ if (!id.endsWith(compiledExt))
114
+ continue;
115
+ const stem = id.slice(0, id.length - compiledExt.length);
116
+ for (const sourceExt of sourceExts) {
117
+ const candidate = stem + sourceExt;
118
+ if (allFileIds.has(candidate) && !excludeIds?.has(candidate)) {
119
+ canonicalOf.set(id, candidate);
120
+ break;
121
+ }
122
+ }
123
+ break;
124
+ }
125
+ }
126
+ const compiledTwinCount = canonicalOf.size;
127
+ // Excluded ids that actually drop: in the graph, untracked-gitignored,
128
+ // and NOT rescued by the twin merge above. Computed before pass 3 so the
129
+ // aggregation skip (and therefore edge dropping, degree/dependents/
130
+ // truncation ranking) all see the post-exclusion world.
131
+ const droppedIgnoredIds = new Set();
132
+ if (excludeIds) {
133
+ for (const id of allFileIds) {
134
+ if (excludeIds.has(id) && !canonicalOf.has(id)) {
135
+ droppedIgnoredIds.add(id);
136
+ }
137
+ }
138
+ }
139
+ const ignoredFileCount = droppedIgnoredIds.size;
140
+ // ── Pass 3: aggregate nodes under their canonical file identity ─────────
141
+ for (const node of graph.nodes.values()) {
142
+ if (node.kind === "external")
143
+ continue; // counted in pass 1
144
+ if (node.kind === "file" && node.filePath) {
145
+ const raw = normalizeMapKey(node.filePath);
146
+ if (isTestById.get(raw))
147
+ continue;
148
+ if (droppedIgnoredIds.has(raw))
149
+ continue;
150
+ const id = canonicalOf.get(raw) ?? raw;
151
+ nodeToFile.set(node.id, id);
152
+ const existing = files.get(id);
153
+ if (existing) {
154
+ // A canonicalized (compiled-twin) node must not overwrite the
155
+ // source file's language — only fill a still-empty slot.
156
+ if (raw === id) {
157
+ existing.language = node.language || existing.language;
158
+ }
159
+ else if (!existing.language) {
160
+ existing.language = node.language || "";
161
+ }
162
+ }
163
+ else {
164
+ files.set(id, { id, path: id, language: node.language || "", symbolCount: 0 });
165
+ }
166
+ continue;
167
+ }
168
+ if (node.kind === "symbol" && node.filePath) {
169
+ const raw = normalizeMapKey(node.filePath);
170
+ if (isTestById.get(raw))
171
+ continue;
172
+ if (droppedIgnoredIds.has(raw))
173
+ continue;
174
+ const id = canonicalOf.get(raw) ?? raw;
175
+ nodeToFile.set(node.id, id);
176
+ const existing = files.get(id);
177
+ if (existing) {
178
+ existing.symbolCount += 1;
179
+ }
180
+ else {
181
+ files.set(id, {
182
+ id,
183
+ path: id,
184
+ language: node.language || "",
185
+ symbolCount: 1,
186
+ });
187
+ }
188
+ continue;
189
+ }
190
+ // "module" (or any future kind) — no file identity, drop silently.
191
+ }
192
+ // Aggregate edges to file->file, deduped with a weight (#679: "keep a
193
+ // count as edge weight"). Same-file edges (a symbol's own `contains`/
194
+ // `defines` edge back to its file, or an intra-file call) are dropped —
195
+ // they're not informative at the file-map altitude. Because nodeToFile
196
+ // already maps compiled twins to their canonical source id, an edge that
197
+ // becomes self-referential only AFTER canonicalization (e.g. x.js → x.ts)
198
+ // collapses through the same fromFile === toFile check.
199
+ const edgeWeights = new Map();
200
+ for (const edge of graph.edges) {
201
+ const fromFile = nodeToFile.get(edge.from);
202
+ const toFile = nodeToFile.get(edge.to);
203
+ if (!fromFile || !toFile || fromFile === toFile)
204
+ continue;
205
+ // NUL separator (same idiom as review-graph/builder.ts): the one byte
206
+ // that can never appear in a file path, written as an escape sequence so
207
+ // this source file stays text for grep (a literal NUL makes ripgrep
208
+ // treat the file as binary).
209
+ const key = `${fromFile}\u0000${toFile}`;
210
+ edgeWeights.set(key, (edgeWeights.get(key) ?? 0) + 1);
211
+ }
212
+ function buildEdgeList(keepIds) {
213
+ const out = [];
214
+ for (const [key, weight] of edgeWeights) {
215
+ const sep = key.indexOf("\u0000");
216
+ const from = key.slice(0, sep);
217
+ const to = key.slice(sep + 1);
218
+ if (keepIds && (!keepIds.has(from) || !keepIds.has(to)))
219
+ continue;
220
+ out.push({ from, to, weight });
221
+ }
222
+ return out;
223
+ }
224
+ function degreesFor(edges) {
225
+ const inNeighbors = new Map();
226
+ const outNeighbors = new Map();
227
+ for (const edge of edges) {
228
+ if (!outNeighbors.has(edge.from))
229
+ outNeighbors.set(edge.from, new Set());
230
+ outNeighbors.get(edge.from)?.add(edge.to);
231
+ if (!inNeighbors.has(edge.to))
232
+ inNeighbors.set(edge.to, new Set());
233
+ inNeighbors.get(edge.to)?.add(edge.from);
234
+ }
235
+ return { inNeighbors, outNeighbors };
236
+ }
237
+ // Truncation (#679): keep the highest-degree files when the graph exceeds
238
+ // the cap, ranked over the FULL (pre-truncation) edge set so the ranking
239
+ // isn't self-referentially biased by an arbitrary earlier cut.
240
+ let keepIds;
241
+ let truncated = false;
242
+ if (files.size > maxNodes) {
243
+ const fullEdges = buildEdgeList(undefined);
244
+ const { inNeighbors, outNeighbors } = degreesFor(fullEdges);
245
+ const ranked = [...files.keys()].sort((a, b) => {
246
+ const degA = (inNeighbors.get(a)?.size ?? 0) + (outNeighbors.get(a)?.size ?? 0);
247
+ const degB = (inNeighbors.get(b)?.size ?? 0) + (outNeighbors.get(b)?.size ?? 0);
248
+ if (degA !== degB)
249
+ return degB - degA;
250
+ return a.localeCompare(b);
251
+ });
252
+ keepIds = new Set(ranked.slice(0, maxNodes));
253
+ truncated = true;
254
+ }
255
+ const finalEdges = buildEdgeList(keepIds);
256
+ const { inNeighbors, outNeighbors } = degreesFor(finalEdges);
257
+ // Transitive dependents (#679: "node radius scales with transitive
258
+ // dependents") — BFS over incoming (reverse) edges of the RENDERED file
259
+ // graph: "who depends on this file, directly or indirectly".
260
+ function transitiveDependents(seed) {
261
+ const visited = new Set([seed]);
262
+ let frontier = [seed];
263
+ while (frontier.length > 0) {
264
+ const next = [];
265
+ for (const id of frontier) {
266
+ for (const dependent of inNeighbors.get(id) ?? []) {
267
+ if (visited.has(dependent))
268
+ continue;
269
+ visited.add(dependent);
270
+ next.push(dependent);
271
+ }
272
+ }
273
+ frontier = next;
274
+ }
275
+ visited.delete(seed);
276
+ return visited.size;
277
+ }
278
+ const keptEntries = [...files.values()].filter((entry) => !keepIds || keepIds.has(entry.id));
279
+ const nodes = keptEntries
280
+ .map((entry) => ({
281
+ id: entry.id,
282
+ path: entry.path,
283
+ language: entry.language,
284
+ symbolCount: entry.symbolCount,
285
+ outDegree: outNeighbors.get(entry.id)?.size ?? 0,
286
+ inDegree: inNeighbors.get(entry.id)?.size ?? 0,
287
+ dependents: transitiveDependents(entry.id),
288
+ }))
289
+ .sort((a, b) => a.id.localeCompare(b.id));
290
+ return {
291
+ nodes,
292
+ edges: finalEdges,
293
+ externalCount,
294
+ testFileCount: testFileIds.size,
295
+ compiledTwinCount,
296
+ ignoredFileCount,
297
+ truncated,
298
+ };
299
+ }
300
+ const DEFAULT_LAYOUT_WIDTH = 1600;
301
+ const DEFAULT_LAYOUT_HEIGHT = 1200;
302
+ const DEFAULT_ITERATIONS = 200;
303
+ const LAYOUT_MARGIN = 40;
304
+ const GRAVITY_STRENGTH = 0.02;
305
+ const ATTRACTION_SCALE = 0.02;
306
+ // FNV-1a 32-bit — cheap, deterministic, no external dep. Used purely to seed
307
+ // initial node positions from a hash of the file path (#679: "seed initial
308
+ // positions from a hash of the file path so two runs on the same project give
309
+ // the same map") — never as a source of real randomness.
310
+ function fnv1a(input) {
311
+ let hash = 0x811c9dc5;
312
+ for (let i = 0; i < input.length; i += 1) {
313
+ hash ^= input.charCodeAt(i);
314
+ hash = Math.imul(hash, 0x01000193);
315
+ }
316
+ return hash >>> 0;
317
+ }
318
+ function seededPosition(id, width, height) {
319
+ const hx = fnv1a(id);
320
+ const hy = fnv1a(`${id}\u0000y`);
321
+ return {
322
+ x: (hx % 10000) / 10000 * width,
323
+ y: (hy % 10000) / 10000 * height,
324
+ };
325
+ }
326
+ /**
327
+ * Simple deterministic force-directed layout: pairwise repulsion + edge-spring
328
+ * attraction + center gravity, run for a fixed number of iterations with a
329
+ * linear cooling schedule. Not a physically exact Fruchterman-Reingold
330
+ * implementation — good enough for a human-facing project map, computed once
331
+ * at generation time (never re-run client-side). Pure: same nodes/edges/opts
332
+ * always produce identical output (no Math.random, no wall-clock).
333
+ */
334
+ export function computeLayout(nodes, edges, options) {
335
+ const width = Math.max(1, options?.width ?? DEFAULT_LAYOUT_WIDTH);
336
+ const height = Math.max(1, options?.height ?? DEFAULT_LAYOUT_HEIGHT);
337
+ const iterations = Math.max(1, options?.iterations ?? DEFAULT_ITERATIONS);
338
+ if (nodes.length === 0)
339
+ return [];
340
+ const ids = nodes.map((n) => n.id);
341
+ const pos = new Map();
342
+ for (const id of ids) {
343
+ const seed = seededPosition(id, width, height);
344
+ pos.set(id, { x: seed.x, y: seed.y, dx: 0, dy: 0 });
345
+ }
346
+ if (ids.length === 1) {
347
+ const only = pos.get(ids[0]);
348
+ if (only) {
349
+ only.x = width / 2;
350
+ only.y = height / 2;
351
+ }
352
+ }
353
+ const relevantEdges = edges.filter((e) => pos.has(e.from) && pos.has(e.to) && e.from !== e.to);
354
+ const area = width * height;
355
+ const k = Math.sqrt(area / Math.max(1, ids.length));
356
+ const center = { x: width / 2, y: height / 2 };
357
+ for (let iter = 0; iter < iterations; iter += 1) {
358
+ for (const id of ids) {
359
+ const p = pos.get(id);
360
+ if (p) {
361
+ p.dx = 0;
362
+ p.dy = 0;
363
+ }
364
+ }
365
+ // Pairwise repulsion (Coulomb-like: force ~ k^2 / dist).
366
+ for (let i = 0; i < ids.length; i += 1) {
367
+ const a = pos.get(ids[i]);
368
+ if (!a)
369
+ continue;
370
+ for (let j = i + 1; j < ids.length; j += 1) {
371
+ const b = pos.get(ids[j]);
372
+ if (!b)
373
+ continue;
374
+ let dx = a.x - b.x;
375
+ let dy = a.y - b.y;
376
+ let distSq = dx * dx + dy * dy;
377
+ if (distSq < 0.0001) {
378
+ dx = 0.1;
379
+ dy = 0.1;
380
+ distSq = 0.02;
381
+ }
382
+ const dist = Math.sqrt(distSq);
383
+ const force = (k * k) / dist;
384
+ const fx = (dx / dist) * force;
385
+ const fy = (dy / dist) * force;
386
+ a.dx += fx;
387
+ a.dy += fy;
388
+ b.dx -= fx;
389
+ b.dy -= fy;
390
+ }
391
+ }
392
+ // Edge-spring attraction (Hooke-like: force ~ dist^2 / k), scaled up
393
+ // slightly by edge weight so heavily-aggregated edges pull tighter.
394
+ for (const edge of relevantEdges) {
395
+ const a = pos.get(edge.from);
396
+ const b = pos.get(edge.to);
397
+ if (!a || !b)
398
+ continue;
399
+ const dx = b.x - a.x;
400
+ const dy = b.y - a.y;
401
+ const dist = Math.max(0.01, Math.sqrt(dx * dx + dy * dy));
402
+ const weightFactor = Math.min(4, 1 + Math.log2(edge.weight + 1));
403
+ const force = ((dist * dist) / k) * weightFactor * ATTRACTION_SCALE;
404
+ const fx = (dx / dist) * force;
405
+ const fy = (dy / dist) * force;
406
+ a.dx += fx;
407
+ a.dy += fy;
408
+ b.dx -= fx;
409
+ b.dy -= fy;
410
+ }
411
+ // Center gravity — keeps disconnected components from drifting off canvas.
412
+ for (const id of ids) {
413
+ const p = pos.get(id);
414
+ if (!p)
415
+ continue;
416
+ p.dx += (center.x - p.x) * GRAVITY_STRENGTH;
417
+ p.dy += (center.y - p.y) * GRAVITY_STRENGTH;
418
+ }
419
+ // Cooling schedule: max displacement per step shrinks linearly to ~0.
420
+ const temperature = Math.max(0.5, width * 0.05 * (1 - iter / iterations));
421
+ for (const id of ids) {
422
+ const p = pos.get(id);
423
+ if (!p)
424
+ continue;
425
+ const dispLen = Math.max(0.0001, Math.sqrt(p.dx * p.dx + p.dy * p.dy));
426
+ const capped = Math.min(dispLen, temperature);
427
+ p.x += (p.dx / dispLen) * capped;
428
+ p.y += (p.dy / dispLen) * capped;
429
+ p.x = Math.min(width - LAYOUT_MARGIN, Math.max(LAYOUT_MARGIN, p.x));
430
+ p.y = Math.min(height - LAYOUT_MARGIN, Math.max(LAYOUT_MARGIN, p.y));
431
+ }
432
+ }
433
+ return nodes.map((n) => {
434
+ const p = pos.get(n.id);
435
+ const x = p && Number.isFinite(p.x) ? p.x : width / 2;
436
+ const y = p && Number.isFinite(p.y) ? p.y : height / 2;
437
+ return { id: n.id, x, y };
438
+ });
439
+ }
440
+ // Escape the embedded JSON payload so it can never break out of its
441
+ // <script type="application/json"> block — #504-spike XSS-from-repo-content
442
+ // mitigation (repo file names/paths are attacker-influenceable in cloned
443
+ // repos). Replacing every `<` with its unicode escape is a strictly stronger
444
+ // guarantee than just escaping "</script": no "<" survives at all, so no
445
+ // substring of the payload can ever open a tag, script or otherwise.
446
+ function escapeJsonForScriptTag(json) {
447
+ return json
448
+ .replace(/</g, "\\u003c")
449
+ .replace(/>/g, "\\u003e")
450
+ .replace(/&/g, "\\u0026");
451
+ }
452
+ /**
453
+ * Renders the self-contained lens-map HTML page. Pure string building — the
454
+ * ONLY dynamic content that reaches the page is the JSON payload (embedded via
455
+ * `escapeJsonForScriptTag`, read back out and rendered through DOM text APIs
456
+ * client-side). No graph-derived string (file path, project label) is ever
457
+ * concatenated directly into HTML markup — see the client script below, which
458
+ * populates every visible label via `textContent`.
459
+ */
460
+ export function renderMapHtml(payload) {
461
+ const json = escapeJsonForScriptTag(JSON.stringify(payload));
462
+ return `<!doctype html>
463
+ <html lang="en">
464
+ <head>
465
+ <meta charset="utf-8" />
466
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
467
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src 'none'; connect-src 'none'; base-uri 'none'; form-action 'none'; object-src 'none'" />
468
+ <title>pi-lens project map</title>
469
+ <style>
470
+ :root {
471
+ color-scheme: light;
472
+ --font-body: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, "Inter", "Helvetica Neue", Arial, sans-serif;
473
+ --font-mono: ui-monospace, "SF Mono", "Cascadia Code", Menlo, Consolas, monospace;
474
+ --bg: #ffffff;
475
+ --panel: #ffffff;
476
+ --panel-recessed: #f4f5f7;
477
+ --fg: #0f172a;
478
+ --muted: #64748b;
479
+ --line: #e2e8f0;
480
+ --line-strong: #cbd5e1;
481
+ --accent: #2563eb;
482
+ --accent-soft: #dbeafe;
483
+ --warn: #d97706;
484
+ }
485
+ @media (prefers-color-scheme: dark) {
486
+ :root {
487
+ color-scheme: dark;
488
+ --bg: #0a0a0b; --panel: #16161a; --panel-recessed: #1f1f25;
489
+ --fg: #f1f5f9; --muted: #94a3b8; --line: #26262c; --line-strong: #36363d;
490
+ --accent: #60a5fa; --accent-soft: rgba(96, 165, 250, 0.16); --warn: #fbbf24;
491
+ }
492
+ }
493
+ * { box-sizing: border-box; }
494
+ body { margin: 0; min-height: 100vh; background: var(--bg); color: var(--fg); font-family: var(--font-body); }
495
+ header { padding: 16px 20px; border-bottom: 1px solid var(--line); display: flex; flex-wrap: wrap; gap: 10px 18px; align-items: baseline; }
496
+ header h1 { margin: 0; font-size: 1.15rem; letter-spacing: -0.01em; }
497
+ .stats { display: flex; flex-wrap: wrap; gap: 14px; color: var(--muted); font-size: 0.85rem; }
498
+ .stats strong { color: var(--fg); font-family: var(--font-mono); }
499
+ #truncation-note { width: 100%; margin-top: 4px; color: var(--warn); font-size: 0.82rem; }
500
+ #truncation-note[hidden] { display: none; }
501
+ #stage { position: relative; height: calc(100vh - 76px); overflow: hidden; }
502
+ #graph-svg { width: 100%; height: 100%; display: block; cursor: grab; background: var(--panel-recessed); }
503
+ #graph-svg:active { cursor: grabbing; }
504
+ .node-circle { stroke: var(--panel); stroke-width: 1.5px; cursor: pointer; transition: opacity 120ms ease; }
505
+ .node text { font-family: var(--font-mono); font-size: 9px; fill: var(--muted); pointer-events: none; }
506
+ .edge { stroke: var(--line-strong); stroke-opacity: 0.55; transition: opacity 120ms ease, stroke 120ms ease; }
507
+ .edge.active { stroke: var(--accent); stroke-opacity: 0.9; }
508
+ .dimmed { opacity: 0.12; }
509
+ .faded { opacity: 0.15; }
510
+ .edge.edge-hidden { display: none; }
511
+ .node.no-label text { display: none; }
512
+ .node.search-hit .node-circle { stroke: var(--accent); stroke-width: 2.5px; }
513
+ .node.selected .node-circle { stroke: var(--warn); stroke-width: 2.5px; }
514
+ .node.trace-hit .node-circle { stroke: var(--accent); stroke-width: 3px; }
515
+ #controls { position: absolute; top: 12px; left: 12px; z-index: 5; display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; max-width: min(560px, calc(100% - 24px)); padding: 8px 12px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); box-shadow: 0 6px 18px rgba(0,0,0,0.12); font-size: 0.8rem; color: var(--muted); }
516
+ #search-input { width: 170px; padding: 4px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--panel-recessed); color: var(--fg); font-family: var(--font-mono); font-size: 0.8rem; }
517
+ #weight-label { display: flex; align-items: center; gap: 6px; white-space: nowrap; }
518
+ #weight-slider { width: 100px; }
519
+ #trace-toggle { border: 1px solid var(--line); border-radius: 6px; background: var(--panel-recessed); color: var(--fg); padding: 4px 10px; cursor: pointer; font-size: 0.78rem; }
520
+ #trace-toggle[aria-pressed="true"] { background: var(--accent-soft); border-color: var(--accent); }
521
+ #help-note { flex-basis: 100%; font-size: 0.72rem; line-height: 1.4; }
522
+ #trace-status { margin: 0 0 8px; color: var(--warn); }
523
+ #trace-status[hidden] { display: none; }
524
+ #detail-panel { position: fixed; right: 16px; bottom: 16px; width: 300px; max-width: calc(100% - 32px); border: 1px solid var(--line); border-radius: 12px; background: var(--panel); box-shadow: 0 12px 34px rgba(0,0,0,0.18); padding: 14px 16px; font-size: 0.85rem; }
525
+ #detail-panel[hidden] { display: none; }
526
+ #detail-panel h2 { margin: 0 0 8px; font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); }
527
+ #detail-path { display: block; word-break: break-word; font-family: var(--font-mono); color: var(--fg); margin-bottom: 10px; }
528
+ #detail-panel dl { margin: 0; display: grid; grid-template-columns: auto 1fr; gap: 4px 10px; }
529
+ #detail-panel dt { color: var(--muted); }
530
+ #detail-panel dd { margin: 0; font-family: var(--font-mono); text-align: right; }
531
+ #detail-close { position: absolute; top: 8px; right: 10px; border: 0; background: none; color: var(--muted); cursor: pointer; font-size: 0.95rem; }
532
+ #detail-close:hover { color: var(--fg); }
533
+ #empty-note { padding: 40px 20px; color: var(--muted); }
534
+ noscript { display: block; padding: 20px; color: var(--muted); }
535
+ </style>
536
+ </head>
537
+ <body>
538
+ <noscript>This project map needs JavaScript to render the interactive graph.</noscript>
539
+ <header>
540
+ <h1>pi-lens project map</h1>
541
+ <div class="stats">
542
+ <span><strong id="stat-files">-</strong> files</span>
543
+ <span><strong id="stat-edges">-</strong> edges</span>
544
+ <span><strong id="stat-external">-</strong> external deps (excluded)</span>
545
+ <span id="stat-testfiles-wrap" hidden><strong id="stat-testfiles">-</strong> test files (excluded)</span>
546
+ <span id="stat-twins-wrap" hidden><strong id="stat-twins">-</strong> compiled twins (merged into sources)</span>
547
+ <span id="stat-ignored-wrap" hidden><strong id="stat-ignored">-</strong> gitignored files (excluded)</span>
548
+ <span>generated <strong id="stat-generated">-</strong></span>
549
+ <span id="stat-project"></span>
550
+ </div>
551
+ <p id="truncation-note" hidden></p>
552
+ </header>
553
+ <div id="stage">
554
+ <div id="controls">
555
+ <input id="search-input" type="search" placeholder="search files" autocomplete="off" spellcheck="false" aria-label="Search files" />
556
+ <label id="weight-label">min edge weight
557
+ <input id="weight-slider" type="range" min="1" max="1" step="1" value="1" />
558
+ <span id="weight-value">1</span> (<span id="visible-edges">0</span> edges)
559
+ </label>
560
+ <button id="trace-toggle" type="button" aria-pressed="false">trace path</button>
561
+ <span id="help-note">hover: neighbors &middot; click: select + details &middot; shift+click a 2nd node (or arm &quot;trace path&quot;, then click another node): trace their connection &middot; Esc or background click: clear</span>
562
+ </div>
563
+ <svg id="graph-svg" xmlns="http://www.w3.org/2000/svg"></svg>
564
+ <div id="detail-panel" hidden>
565
+ <button id="detail-close" type="button" aria-label="Close">&times;</button>
566
+ <h2>File</h2>
567
+ <p id="trace-status" hidden></p>
568
+ <span id="detail-path"></span>
569
+ <dl>
570
+ <dt>Symbols</dt><dd id="detail-symbols"></dd>
571
+ <dt>In-degree</dt><dd id="detail-in"></dd>
572
+ <dt>Out-degree</dt><dd id="detail-out"></dd>
573
+ <dt>Dependents</dt><dd id="detail-dependents"></dd>
574
+ </dl>
575
+ </div>
576
+ </div>
577
+ <script type="application/json" id="lens-map-payload">${json}</script>
578
+ <script>
579
+ (function () {
580
+ "use strict";
581
+ var payloadEl = document.getElementById("lens-map-payload");
582
+ var payload = JSON.parse(payloadEl.textContent || "{}");
583
+ var nodes = payload.nodes || [];
584
+ var edges = payload.edges || [];
585
+
586
+ function setText(id, value) {
587
+ var el = document.getElementById(id);
588
+ if (el) el.textContent = value;
589
+ }
590
+
591
+ setText("stat-files", String(payload.fileCount || 0));
592
+ setText("stat-edges", String(payload.edgeCount || 0));
593
+ setText("stat-external", String(payload.externalCount || 0));
594
+ // The review graph itself excludes test files by role since #260, so this
595
+ // count is normally 0 — only show the stat when the exclusion actually did
596
+ // something (belt-and-braces against a future graph-scope change).
597
+ if (payload.testFileCount > 0) {
598
+ setText("stat-testfiles", String(payload.testFileCount));
599
+ var tfWrap = document.getElementById("stat-testfiles-wrap");
600
+ if (tfWrap) tfWrap.hidden = false;
601
+ }
602
+ // Compiled twins (X.js merged into its X.ts source) only occur in
603
+ // compile-in-place projects — hide the stat when nothing was merged.
604
+ if (payload.compiledTwinCount > 0) {
605
+ setText("stat-twins", String(payload.compiledTwinCount));
606
+ var twWrap = document.getElementById("stat-twins-wrap");
607
+ if (twWrap) twWrap.hidden = false;
608
+ }
609
+ // Untracked-gitignored files dropped from the map (0 when the project is
610
+ // not a git repo — the filter degrades to a no-op there): hide when zero.
611
+ if (payload.ignoredFileCount > 0) {
612
+ setText("stat-ignored", String(payload.ignoredFileCount));
613
+ var igWrap = document.getElementById("stat-ignored-wrap");
614
+ if (igWrap) igWrap.hidden = false;
615
+ }
616
+ setText("stat-generated", payload.generatedAt || "");
617
+ setText("stat-project", payload.projectLabel || "");
618
+
619
+ var truncationNote = document.getElementById("truncation-note");
620
+ if (payload.truncated) {
621
+ truncationNote.textContent =
622
+ "Showing the " + payload.fileCount + " highest-degree files " +
623
+ "(project exceeds the " + payload.maxNodes + "-file map cap).";
624
+ truncationNote.hidden = false;
625
+ }
626
+
627
+ var svg = document.getElementById("graph-svg");
628
+ if (nodes.length === 0) {
629
+ var stage = document.getElementById("stage");
630
+ var empty = document.createElement("div");
631
+ empty.id = "empty-note";
632
+ empty.textContent = "No files to map yet.";
633
+ stage.replaceChild(empty, svg);
634
+ return;
635
+ }
636
+
637
+ var svgNS = "http://www.w3.org/2000/svg";
638
+ var width = payload.width || 1600;
639
+ var height = payload.height || 1200;
640
+ svg.setAttribute("viewBox", "0 0 " + width + " " + height);
641
+
642
+ var world = document.createElementNS(svgNS, "g");
643
+ world.setAttribute("id", "world");
644
+ svg.appendChild(world);
645
+ var edgeGroup = document.createElementNS(svgNS, "g");
646
+ world.appendChild(edgeGroup);
647
+ var nodeGroup = document.createElementNS(svgNS, "g");
648
+ world.appendChild(nodeGroup);
649
+
650
+ var nodeById = {};
651
+ nodes.forEach(function (n) { nodeById[n.id] = n; });
652
+
653
+ var neighbors = {};
654
+ nodes.forEach(function (n) { neighbors[n.id] = {}; });
655
+ edges.forEach(function (e) {
656
+ if (neighbors[e.from]) neighbors[e.from][e.to] = true;
657
+ if (neighbors[e.to]) neighbors[e.to][e.from] = true;
658
+ });
659
+
660
+ // Edge records keep from/to/weight alongside the element so the single
661
+ // visibility pass below can filter without re-reading DOM attributes.
662
+ var edgeEls = [];
663
+ edges.forEach(function (e) {
664
+ var a = nodeById[e.from];
665
+ var b = nodeById[e.to];
666
+ if (!a || !b) return;
667
+ var line = document.createElementNS(svgNS, "line");
668
+ line.setAttribute("x1", String(a.x));
669
+ line.setAttribute("y1", String(a.y));
670
+ line.setAttribute("x2", String(b.x));
671
+ line.setAttribute("y2", String(b.y));
672
+ line.setAttribute("class", "edge");
673
+ line.setAttribute("stroke-width", String(Math.min(4, 0.6 + Math.log2(e.weight + 1))));
674
+ edgeGroup.appendChild(line);
675
+ edgeEls.push({ el: line, from: e.from, to: e.to, weight: e.weight || 1 });
676
+ });
677
+
678
+ // Node fill: neutral brand-blue intensity scale by transitive dependents
679
+ // ONLY (light #2563eb family / dark #60a5fa family) — NOT complexity-based.
680
+ // Calibrated complexity-aware coloring is deferred to #306; wiring a second
681
+ // color dimension here would guess at a scale nobody has validated yet.
682
+ var isDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
683
+ var loStop = isDark ? [30, 41, 59] : [219, 234, 254];
684
+ var hiStop = isDark ? [96, 165, 250] : [37, 99, 235];
685
+ function blueForRatio(ratio) {
686
+ var t = Math.max(0, Math.min(1, ratio));
687
+ var r = Math.round(loStop[0] + (hiStop[0] - loStop[0]) * t);
688
+ var g = Math.round(loStop[1] + (hiStop[1] - loStop[1]) * t);
689
+ var b = Math.round(loStop[2] + (hiStop[2] - loStop[2]) * t);
690
+ return "rgb(" + r + "," + g + "," + b + ")";
691
+ }
692
+
693
+ var maxDependents = nodes.reduce(function (m, n) { return Math.max(m, n.dependents || 0); }, 0) || 1;
694
+ var minRadius = 5, maxRadius = 22;
695
+
696
+ // Label culling: a label renders only when (zoomed in past LABEL_ZOOM) OR
697
+ // (the node is in the top-25 by transitive dependents — the structurally
698
+ // load-bearing files a viewer wants named at any zoom). Safe on tiny
699
+ // graphs: slice(0, 25) of a 3-node list is just those 3.
700
+ var LABEL_ZOOM = 1.5;
701
+ var labelAlways = {};
702
+ nodes.slice()
703
+ .sort(function (a, b) { return (b.dependents || 0) - (a.dependents || 0); })
704
+ .slice(0, 25)
705
+ .forEach(function (n) { labelAlways[n.id] = true; });
706
+
707
+ var nodeEls = {};
708
+ nodes.forEach(function (n) {
709
+ var g = document.createElementNS(svgNS, "g");
710
+ g.setAttribute("class", "node");
711
+ g.setAttribute("transform", "translate(" + n.x + "," + n.y + ")");
712
+ g.dataset.id = n.id;
713
+
714
+ var ratio = (n.dependents || 0) / maxDependents;
715
+ var radius = minRadius + (maxRadius - minRadius) * Math.sqrt(ratio);
716
+
717
+ var circle = document.createElementNS(svgNS, "circle");
718
+ circle.setAttribute("r", String(radius));
719
+ circle.setAttribute("fill", blueForRatio(ratio));
720
+ circle.setAttribute("class", "node-circle");
721
+ g.appendChild(circle);
722
+
723
+ var title = document.createElementNS(svgNS, "title");
724
+ title.textContent = n.path + " — " + n.symbolCount + " symbols, " + n.dependents + " dependents";
725
+ g.appendChild(title);
726
+
727
+ // Repo-derived string → textContent only, never markup (the #504-spike
728
+ // discipline): the label is the path's last segment.
729
+ var label = document.createElementNS(svgNS, "text");
730
+ label.setAttribute("y", String(radius + 10));
731
+ label.setAttribute("text-anchor", "middle");
732
+ label.textContent = (n.path || "").split("/").pop() || n.path;
733
+ g.appendChild(label);
734
+
735
+ g.addEventListener("mouseenter", function () { hoverId = n.id; recomputeVisibility(); });
736
+ g.addEventListener("mouseleave", function () { hoverId = null; recomputeVisibility(); });
737
+ g.addEventListener("click", function (ev) { ev.stopPropagation(); onNodeClick(n, ev); });
738
+
739
+ nodeGroup.appendChild(g);
740
+ nodeEls[n.id] = g;
741
+ });
742
+
743
+ // ── Interaction state — composed by ONE visibility pass ───────────────────
744
+ var hoverId = null;
745
+ var searchTerm = "";
746
+ var weightThreshold = 1;
747
+ var selectedId = null;
748
+ var traceArmed = false;
749
+ var trace = null; // { found, nodeSet, edgeKeys } while a trace is displayed
750
+
751
+ // Undirected edge identity (order-independent): NUL can never appear in a
752
+ // file path, same idiom as the aggregation layer.
753
+ function edgeKey(a, b) { return a < b ? a + "\\u0000" + b : b + "\\u0000" + a; }
754
+
755
+ // The four interactions (search, weight filter, trace, label culling) all
756
+ // funnel through this single pass instead of four fighting inline style
757
+ // writers. Precedence for node/edge OPACITY: trace active > search filter
758
+ // > weight-isolation fade (hover only narrows within what the winning
759
+ // filter allows). The weight filter is a DISPLAY axis — edges below the
760
+ // threshold hide entirely — with one exception: a traced-path edge always
761
+ // shows, or the trace visual would have holes. Label culling only ever
762
+ // affects labels, never circles or edges.
763
+ function recomputeVisibility() {
764
+ var searching = searchTerm.length > 0;
765
+ var matches = {};
766
+ if (searching) {
767
+ nodes.forEach(function (n) {
768
+ if ((n.path || "").toLowerCase().indexOf(searchTerm) !== -1) matches[n.id] = true;
769
+ });
770
+ }
771
+
772
+ var tracing = trace !== null && trace.found;
773
+ var visibleEdgeCount = 0;
774
+ var touchedByVisibleEdge = {};
775
+ edgeEls.forEach(function (e) {
776
+ var passesWeight = e.weight >= weightThreshold;
777
+ if (passesWeight) {
778
+ visibleEdgeCount += 1;
779
+ touchedByVisibleEdge[e.from] = true;
780
+ touchedByVisibleEdge[e.to] = true;
781
+ }
782
+ var onTracePath = tracing && trace.edgeKeys[edgeKey(e.from, e.to)];
783
+ var dimmed, active;
784
+ if (trace !== null) {
785
+ active = !!onTracePath;
786
+ dimmed = !onTracePath;
787
+ } else {
788
+ active = hoverId !== null && (e.from === hoverId || e.to === hoverId);
789
+ if (searching) {
790
+ dimmed = !(matches[e.from] && matches[e.to]);
791
+ if (!dimmed && hoverId !== null) dimmed = !active;
792
+ } else {
793
+ dimmed = hoverId !== null ? !active : false;
794
+ }
795
+ }
796
+ e.el.classList.toggle("edge-hidden", !passesWeight && !onTracePath);
797
+ e.el.classList.toggle("active", !!active);
798
+ e.el.classList.toggle("dimmed", dimmed);
799
+ });
800
+ setText("weight-value", String(weightThreshold));
801
+ setText("visible-edges", String(visibleEdgeCount));
802
+
803
+ nodes.forEach(function (n) {
804
+ var el = nodeEls[n.id];
805
+ if (!el) return;
806
+ var dimmed;
807
+ var faded = false;
808
+ if (trace !== null) {
809
+ dimmed = !(tracing && trace.nodeSet[n.id]);
810
+ } else if (searching) {
811
+ dimmed = !matches[n.id];
812
+ if (!dimmed && hoverId !== null) {
813
+ dimmed = !(n.id === hoverId || (neighbors[hoverId] || {})[n.id]);
814
+ }
815
+ } else {
816
+ dimmed = hoverId !== null
817
+ ? !(n.id === hoverId || (neighbors[hoverId] || {})[n.id])
818
+ : false;
819
+ // Weight-isolation fade — lowest precedence, and a fade rather than
820
+ // a removal: layout position stability matters more than reclaiming
821
+ // the pixels.
822
+ if (!dimmed && weightThreshold > 1 && !touchedByVisibleEdge[n.id]) faded = true;
823
+ }
824
+ el.classList.toggle("dimmed", dimmed);
825
+ el.classList.toggle("faded", faded);
826
+ el.classList.toggle("search-hit", searching && trace === null && !!matches[n.id]);
827
+ el.classList.toggle("selected", n.id === selectedId);
828
+ el.classList.toggle("trace-hit", tracing && !!trace.nodeSet[n.id]);
829
+ var labelOn = !dimmed && !faded && (view.scale > LABEL_ZOOM || !!labelAlways[n.id]);
830
+ el.classList.toggle("no-label", !labelOn);
831
+ });
832
+ }
833
+
834
+ // Path tracing: BFS treating edges as UNDIRECTED — for "how are these two
835
+ // files related", connectivity matters more than dependency direction
836
+ // (whether A imports B or B imports A, a human tracing the map wants the
837
+ // chain shown either way).
838
+ function runTrace(fromId, toId) {
839
+ var parent = {};
840
+ parent[fromId] = fromId;
841
+ var queue = [fromId];
842
+ var found = false;
843
+ while (queue.length > 0 && !found) {
844
+ var next = [];
845
+ for (var i = 0; i < queue.length && !found; i += 1) {
846
+ var adj = neighbors[queue[i]] || {};
847
+ for (var nid in adj) {
848
+ if (parent[nid] !== undefined) continue;
849
+ parent[nid] = queue[i];
850
+ if (nid === toId) { found = true; break; }
851
+ next.push(nid);
852
+ }
853
+ }
854
+ queue = next;
855
+ }
856
+ var nodeSet = {};
857
+ var edgeKeys = {};
858
+ var hops = 0;
859
+ if (found) {
860
+ var cur = toId;
861
+ nodeSet[cur] = true;
862
+ while (cur !== fromId) {
863
+ var p = parent[cur];
864
+ edgeKeys[edgeKey(p, cur)] = true;
865
+ nodeSet[p] = true;
866
+ cur = p;
867
+ hops += 1;
868
+ }
869
+ }
870
+ trace = { found: found, nodeSet: nodeSet, edgeKeys: edgeKeys };
871
+ var status = document.getElementById("trace-status");
872
+ if (status) {
873
+ status.textContent = found
874
+ ? "Path: " + (hops + 1) + " files, " + hops + " hops."
875
+ : "No path between the selected files.";
876
+ status.hidden = false;
877
+ }
878
+ detailPanel.hidden = false;
879
+ }
880
+
881
+ function hideTraceStatus() {
882
+ var status = document.getElementById("trace-status");
883
+ if (status) status.hidden = true;
884
+ }
885
+
886
+ function onNodeClick(n, ev) {
887
+ var wantsTrace = (ev.shiftKey || traceArmed) && selectedId !== null && selectedId !== n.id;
888
+ if (wantsTrace) {
889
+ runTrace(selectedId, n.id);
890
+ } else {
891
+ trace = null;
892
+ hideTraceStatus();
893
+ selectedId = n.id;
894
+ showDetail(n);
895
+ }
896
+ recomputeVisibility();
897
+ }
898
+
899
+ function clearTraceAndSelection() {
900
+ trace = null;
901
+ selectedId = null;
902
+ hideTraceStatus();
903
+ detailPanel.hidden = true;
904
+ recomputeVisibility();
905
+ }
906
+
907
+ var detailPanel = document.getElementById("detail-panel");
908
+ function showDetail(n) {
909
+ setText("detail-path", n.path);
910
+ setText("detail-symbols", String(n.symbolCount));
911
+ setText("detail-in", String(n.inDegree));
912
+ setText("detail-out", String(n.outDegree));
913
+ setText("detail-dependents", String(n.dependents));
914
+ detailPanel.hidden = false;
915
+ }
916
+ document.getElementById("detail-close").addEventListener("click", function () {
917
+ detailPanel.hidden = true;
918
+ });
919
+ svg.addEventListener("click", clearTraceAndSelection);
920
+ document.addEventListener("keydown", function (ev) {
921
+ if (ev.key === "Escape") clearTraceAndSelection();
922
+ });
923
+
924
+ // ── Controls wiring ───────────────────────────────────────────────────────
925
+ var searchInput = document.getElementById("search-input");
926
+ if (searchInput) {
927
+ // No debounce: recomputeVisibility is a single O(nodes+edges) pass and
928
+ // the map caps at PI_LENS_MAP_MAX_NODES (500 default) — cheap per input.
929
+ searchInput.addEventListener("input", function () {
930
+ searchTerm = searchInput.value.trim().toLowerCase();
931
+ recomputeVisibility();
932
+ });
933
+ }
934
+ var maxWeight = edges.reduce(function (m, e) { return Math.max(m, e.weight || 1); }, 1);
935
+ var slider = document.getElementById("weight-slider");
936
+ if (slider) {
937
+ slider.max = String(maxWeight);
938
+ slider.addEventListener("input", function () {
939
+ weightThreshold = Number(slider.value) || 1;
940
+ recomputeVisibility();
941
+ });
942
+ }
943
+ var traceToggle = document.getElementById("trace-toggle");
944
+ if (traceToggle) {
945
+ traceToggle.addEventListener("click", function () {
946
+ traceArmed = !traceArmed;
947
+ traceToggle.setAttribute("aria-pressed", traceArmed ? "true" : "false");
948
+ });
949
+ }
950
+
951
+ // Pan (drag background) + zoom (wheel).
952
+ var view = { x: 0, y: 0, scale: 1 };
953
+ var dragging = false, lastX = 0, lastY = 0;
954
+ function applyTransform() {
955
+ world.setAttribute("transform", "translate(" + view.x + "," + view.y + ") scale(" + view.scale + ")");
956
+ }
957
+ svg.addEventListener("pointerdown", function (ev) {
958
+ dragging = true;
959
+ lastX = ev.clientX;
960
+ lastY = ev.clientY;
961
+ svg.setPointerCapture(ev.pointerId);
962
+ });
963
+ svg.addEventListener("pointermove", function (ev) {
964
+ if (!dragging) return;
965
+ view.x += ev.clientX - lastX;
966
+ view.y += ev.clientY - lastY;
967
+ lastX = ev.clientX;
968
+ lastY = ev.clientY;
969
+ applyTransform();
970
+ });
971
+ svg.addEventListener("pointerup", function () { dragging = false; });
972
+ svg.addEventListener("pointercancel", function () { dragging = false; });
973
+ svg.addEventListener("wheel", function (ev) {
974
+ ev.preventDefault();
975
+ var delta = ev.deltaY > 0 ? 0.9 : 1.1;
976
+ view.scale = Math.max(0.15, Math.min(6, view.scale * delta));
977
+ applyTransform();
978
+ // Zoom crossing LABEL_ZOOM changes which labels render.
979
+ recomputeVisibility();
980
+ }, { passive: false });
981
+ applyTransform();
982
+ recomputeVisibility();
983
+ })();
984
+ </script>
985
+ </body>
986
+ </html>
987
+ `;
988
+ }
989
+ function resolveMaxNodes() {
990
+ const raw = process.env.PI_LENS_MAP_MAX_NODES?.trim();
991
+ if (!raw)
992
+ return DEFAULT_MAX_MAP_NODES;
993
+ const parsed = Number(raw);
994
+ return Number.isFinite(parsed) && parsed > 0
995
+ ? Math.floor(parsed)
996
+ : DEFAULT_MAX_MAP_NODES;
997
+ }
998
+ // #694: the untracked-AND-ignored id computation (parse + git spawn + the
999
+ // tracked-file semantic) now lives in git-tracked-ignore.ts, shared with the
1000
+ // review-graph builder's ignore-gated node creation. Re-exported here so
1001
+ // existing imports of `parseUntrackedIgnoredOutput` from this module keep
1002
+ // working unchanged.
1003
+ export { parseUntrackedIgnoredOutput } from "./git-tracked-ignore.js";
1004
+ // Human-facing display path: cwd-relative + forward-slashed when the file
1005
+ // sits under the project root, else the absolute (slash-normalized) path.
1006
+ // Mirrors module-report.ts's toDisplayPath convention.
1007
+ function toDisplayPath(p, projectRoot) {
1008
+ if (!path.isAbsolute(p))
1009
+ return p.replace(/\\/g, "/");
1010
+ const rel = path.relative(projectRoot, p);
1011
+ return rel && !rel.startsWith("..")
1012
+ ? rel.replace(/\\/g, "/")
1013
+ : p.replace(/\\/g, "/");
1014
+ }
1015
+ /**
1016
+ * Builds (or refreshes) the review graph, aggregates it to a file-level map,
1017
+ * lays it out, renders the self-contained HTML page, and writes it to disk
1018
+ * under `<project data dir>/reports/lens-map.html`. Unlike module_report's
1019
+ * read-only #256 contract, this path DOES build the graph on a cold cache —
1020
+ * the user explicitly asked for a map via `/lens-map`, so taking a few seconds
1021
+ * to build is an acceptable, expected cost (this is not a hot per-edit path).
1022
+ */
1023
+ export async function generateLensMap(cwd) {
1024
+ const facts = new FactStore();
1025
+ // Kick off the git ignored-file listing concurrently with the (much
1026
+ // slower) graph build — both are bounded (10s spawn timeout + the ambient
1027
+ // turn abort signal safeSpawnAsync applies by default).
1028
+ const excludeIdsPromise = collectUntrackedIgnoredIds(cwd);
1029
+ const graph = await buildOrUpdateGraph(cwd, [], facts);
1030
+ const excludeIds = await excludeIdsPromise;
1031
+ const maxNodes = resolveMaxNodes();
1032
+ const aggregated = aggregateGraphToFiles(graph, { maxNodes, excludeIds });
1033
+ const displayNodes = aggregated.nodes.map((node) => ({
1034
+ ...node,
1035
+ path: toDisplayPath(node.path, cwd),
1036
+ }));
1037
+ const width = DEFAULT_LAYOUT_WIDTH;
1038
+ const height = DEFAULT_LAYOUT_HEIGHT;
1039
+ const layout = computeLayout(displayNodes, aggregated.edges, {
1040
+ width,
1041
+ height,
1042
+ });
1043
+ const positionById = new Map(layout.map((p) => [p.id, p]));
1044
+ const payloadNodes = displayNodes.map((node) => {
1045
+ const point = positionById.get(node.id);
1046
+ return { ...node, x: point?.x ?? width / 2, y: point?.y ?? height / 2 };
1047
+ });
1048
+ const payload = {
1049
+ generatedAt: new Date().toISOString(),
1050
+ projectLabel: path.basename(path.resolve(cwd)),
1051
+ fileCount: aggregated.nodes.length,
1052
+ edgeCount: aggregated.edges.length,
1053
+ externalCount: aggregated.externalCount,
1054
+ testFileCount: aggregated.testFileCount,
1055
+ compiledTwinCount: aggregated.compiledTwinCount,
1056
+ ignoredFileCount: aggregated.ignoredFileCount,
1057
+ truncated: aggregated.truncated,
1058
+ maxNodes,
1059
+ width,
1060
+ height,
1061
+ nodes: payloadNodes,
1062
+ edges: aggregated.edges,
1063
+ };
1064
+ const html = renderMapHtml(payload);
1065
+ const outDir = path.join(getProjectDataDir(cwd), "reports");
1066
+ fs.mkdirSync(outDir, { recursive: true });
1067
+ const filePath = path.join(outDir, "lens-map.html");
1068
+ fs.writeFileSync(filePath, html, "utf-8");
1069
+ return {
1070
+ filePath,
1071
+ fileCount: aggregated.nodes.length,
1072
+ edgeCount: aggregated.edges.length,
1073
+ truncated: aggregated.truncated,
1074
+ externalCount: aggregated.externalCount,
1075
+ testFileCount: aggregated.testFileCount,
1076
+ compiledTwinCount: aggregated.compiledTwinCount,
1077
+ ignoredFileCount: aggregated.ignoredFileCount,
1078
+ };
1079
+ }