pi-lens 3.8.71 → 3.8.73

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 (83) hide show
  1. package/CHANGELOG.md +152 -1
  2. package/README.md +31 -22
  3. package/config/markdownlint/core.json +6 -0
  4. package/dist/clients/atomic-write.js +83 -0
  5. package/dist/clients/config-enabled-shape.js +39 -0
  6. package/dist/clients/deps/js-yaml.js +1 -1
  7. package/dist/clients/diagnostic-dispositions.js +64 -2
  8. package/dist/clients/dispatch/integration.js +2 -1
  9. package/dist/clients/dispatch/runners/ast-grep-napi.js +60 -7
  10. package/dist/clients/dispatch/runners/lsp.js +54 -25
  11. package/dist/clients/dispatch/runners/markdownlint.js +7 -4
  12. package/dist/clients/dispatch/runners/pyright.js +1 -0
  13. package/dist/clients/dispatch/runners/tree-sitter.js +1 -1
  14. package/dist/clients/env-utils.js +38 -0
  15. package/dist/clients/file-utils.js +21 -3
  16. package/dist/clients/instance-registry.js +32 -21
  17. package/dist/clients/jscpd-client.js +52 -39
  18. package/dist/clients/language-profile.js +12 -19
  19. package/dist/clients/lens-config.js +106 -27
  20. package/dist/clients/lens-engine.js +129 -3
  21. package/dist/clients/lsp/cascade-tier.js +1 -38
  22. package/dist/clients/lsp/client.js +3 -1
  23. package/dist/clients/lsp/index.js +707 -109
  24. package/dist/clients/lsp/server-strategies.js +3 -224
  25. package/dist/clients/lsp/server.js +1 -1
  26. package/dist/clients/lsp/wait-policy/capability-snapshot.js +1 -0
  27. package/dist/clients/lsp/wait-policy/classification.js +63 -0
  28. package/dist/clients/lsp/wait-policy/index.js +10 -0
  29. package/dist/clients/lsp/wait-policy/strategies.js +244 -0
  30. package/dist/clients/lsp-budget.js +54 -16
  31. package/dist/clients/mcp/analyze.js +1 -1
  32. package/dist/clients/mcp/host-shim.js +12 -8
  33. package/dist/clients/mcp/ipc.js +118 -0
  34. package/dist/clients/mcp/session.js +2 -2
  35. package/dist/clients/pipeline.js +11 -6
  36. package/dist/clients/project-diagnostics/fresh-fetch.js +20 -1
  37. package/dist/clients/project-diagnostics/scanner.js +37 -6
  38. package/dist/clients/project-lens-config.js +167 -3
  39. package/dist/clients/project-report.js +627 -0
  40. package/dist/clients/project-scale.js +239 -0
  41. package/dist/clients/project-scan-policy.js +11 -1
  42. package/dist/clients/recent-touches.js +6 -11
  43. package/dist/clients/review-graph/builder.js +170 -13
  44. package/dist/clients/review-graph/import-resolvers.js +149 -13
  45. package/dist/clients/review-graph/tsconfig-paths.js +242 -0
  46. package/dist/clients/review-graph/workspace-modules.js +21 -9
  47. package/dist/clients/rules-scanner.js +15 -2
  48. package/dist/clients/runtime-agent-end.js +104 -17
  49. package/dist/clients/runtime-config.js +4 -0
  50. package/dist/clients/runtime-coordinator.js +50 -1
  51. package/dist/clients/runtime-session.js +41 -3
  52. package/dist/clients/runtime-tool-result.js +4 -3
  53. package/dist/clients/runtime-turn.js +4 -1
  54. package/dist/clients/safe-spawn.js +264 -40
  55. package/dist/clients/session-lifecycle.js +36 -0
  56. package/dist/clients/session-state-store.js +8 -3
  57. package/dist/clients/source-filter.js +136 -61
  58. package/dist/clients/source-walker.js +89 -0
  59. package/dist/clients/startup-scan.js +189 -111
  60. package/dist/clients/subagent-mode.js +14 -3
  61. package/dist/clients/todo-scanner.js +5 -1
  62. package/dist/clients/tool-policy.js +26 -4
  63. package/dist/clients/warm-attach.js +204 -0
  64. package/dist/clients/word-index.js +36 -5
  65. package/dist/clients/workspace-topology.js +266 -0
  66. package/dist/index.js +15205 -11330
  67. package/dist/mcp/server.js +125 -10
  68. package/dist/tools/ast-grep-search.js +21 -0
  69. package/dist/tools/lens-diagnostic-mark.js +198 -7
  70. package/dist/tools/lens-diagnostics.js +119 -21
  71. package/dist/tools/lsp-diagnostics.js +143 -10
  72. package/dist/tools/lsp-navigation.js +11 -2
  73. package/dist/tools/project-report.js +94 -0
  74. package/dist/tools/symbol-search.js +32 -8
  75. package/docs/environment-variables.md +10 -0
  76. package/docs/features.md +7 -1
  77. package/docs/globalconfig.md +70 -0
  78. package/docs/servercapabilities.md +1 -1
  79. package/docs/usage.md +13 -2
  80. package/package.json +8 -9
  81. package/rules/tree-sitter-queries/typescript/no-equality-in-for-condition.yml +1 -0
  82. package/rules/tree-sitter-queries/typescript/no-jump-in-finally.yml +1 -0
  83. package/scripts/download-grammars.js +1 -0
@@ -0,0 +1,627 @@
1
+ /**
2
+ * Project Report (#773) — the top of the discovery funnel: `project_report` →
3
+ * `module_report` → `read_symbol`. Answers "orient me in this project" from
4
+ * data the review graph already computes, so no line of output exists unless
5
+ * it changes which file the calling agent opens next (no vanity metrics —
6
+ * no file counts, LOC averages, language breakdowns as their own section).
7
+ *
8
+ * READ-ONLY over the cached review graph, mirroring module_report's #256
9
+ * no-build contract: this tool's product IS the graph, so a cold cache kicks
10
+ * off a single bounded background build (deduped per cwd, fire-and-forget)
11
+ * and returns `available: false` with an actionable retry hint — the same
12
+ * shape symbol_search's cold word-index path uses (clients/lens-engine.ts).
13
+ * The call never blocks on a build.
14
+ *
15
+ * Six sections, each capped and ranked worst/most-important first:
16
+ * 1. trust — graph freshness + coverage + edge-resolution-quality mix.
17
+ * 2. hubs — top fan-in files (the repo's contract surface).
18
+ * 3. entryPoints — near-zero fan-in, high fan-out files (activation/CLI/mains).
19
+ * 4. subsystems — directory-level import graph: cycles + layering violations.
20
+ * 5. riskHotspots — fan-in × max per-symbol cyclomatic complexity.
21
+ * 6. deadWeight — zero-importer files that aren't entry points (low-confidence
22
+ * — shipped with an explicit disclaimer; dynamic imports/runtime
23
+ * registration/test-only reachability all produce false positives here).
24
+ *
25
+ * Non-goals (v1, refs #773): no per-symbol detail (module_report's job), no
26
+ * delta/"since ref" mode (needs git integration — a follow-up), no prose
27
+ * summarization (structural facts only; the calling agent composes its own
28
+ * narrative). Middle-man detection is NOT surfaced here: the review graph
29
+ * does not currently persist that signal on symbol nodes (module_report
30
+ * computes it per-file, on demand, from raw file content — see
31
+ * middle-man-analysis.ts) and re-deriving it project-wide would mean
32
+ * re-reading and re-scanning every class-bearing file on this read-only,
33
+ * never-blocks path. A follow-up could have the builder persist the signal
34
+ * into symbol-node metadata so this path can read it for free.
35
+ */
36
+ import * as path from "node:path";
37
+ import { normalizeMapKey } from "./path-utils.js";
38
+ import { isAtOrAboveHomeDir } from "./path-utils.js";
39
+ import { loadProjectSnapshot } from "./project-snapshot.js";
40
+ const DEFAULT_LIMIT = 10;
41
+ const STALE_THRESHOLD_MS = 15 * 60_000; // 15 minutes
42
+ const LOW_COVERAGE_THRESHOLD = 0.8;
43
+ const DEAD_WEIGHT_DISCLAIMER = "Low confidence: dynamic imports, runtime registration, and test-only " +
44
+ "reachability all produce false positives here — verify with a real " +
45
+ "usage search (symbol_search/grep) before deleting anything listed.";
46
+ function clampLimit(limit) {
47
+ return Math.max(1, Math.floor(limit ?? DEFAULT_LIMIT));
48
+ }
49
+ // Same display-path convention as module-report.ts's toDisplayPath: cwd-relative
50
+ // + forward-slashed under the project root, else the absolute (slash-normalized)
51
+ // path.
52
+ function toDisplayPath(p, projectRoot) {
53
+ if (!path.isAbsolute(p))
54
+ return p.replace(/\\/g, "/");
55
+ const rel = path.relative(projectRoot, p);
56
+ return rel && !rel.startsWith("..")
57
+ ? rel.replace(/\\/g, "/")
58
+ : p.replace(/\\/g, "/");
59
+ }
60
+ function suggestedNext(displayPath) {
61
+ return { tool: "module_report", path: displayPath };
62
+ }
63
+ // --- focus re-ranking (module_report's normalizeFocus/focusScore pattern) ----
64
+ // Duplicated rather than imported: module-report.ts doesn't export these, and
65
+ // the two token sets are scored slightly differently downstream (whole
66
+ // section rankings here vs per-symbol/per-callback there), so a shared export
67
+ // would be a false abstraction for two call sites.
68
+ function normalizeFocus(focus) {
69
+ return (focus ?? "")
70
+ .toLowerCase()
71
+ .split(/[^a-z0-9_.]+/)
72
+ .map((part) => part.trim())
73
+ .filter((part) => part.length >= 3)
74
+ .slice(0, 8);
75
+ }
76
+ function focusScore(text, terms) {
77
+ if (terms.length === 0)
78
+ return 0;
79
+ const haystack = text.toLowerCase();
80
+ return terms.reduce((score, term) => score + (haystack.includes(term) ? 6 : 0), 0);
81
+ }
82
+ function buildFileDegrees(graph) {
83
+ const fanIn = new Map();
84
+ const fanOut = new Map();
85
+ for (const edge of graph.edges) {
86
+ if (edge.kind !== "imports")
87
+ continue;
88
+ if (edge.from === edge.to)
89
+ continue;
90
+ const fromNode = graph.nodes.get(edge.from);
91
+ const toNode = graph.nodes.get(edge.to);
92
+ if (!fromNode || fromNode.kind !== "file")
93
+ continue;
94
+ if (!toNode || toNode.kind !== "file")
95
+ continue; // internal files only
96
+ let outSet = fanOut.get(edge.from);
97
+ if (!outSet) {
98
+ outSet = new Set();
99
+ fanOut.set(edge.from, outSet);
100
+ }
101
+ outSet.add(edge.to);
102
+ let inSet = fanIn.get(edge.to);
103
+ if (!inSet) {
104
+ inSet = new Set();
105
+ fanIn.set(edge.to, inSet);
106
+ }
107
+ inSet.add(edge.from);
108
+ }
109
+ return { fanIn, fanOut };
110
+ }
111
+ // --- section 1: trust header --------------------------------------------------
112
+ function computeTrust(graph, cwd) {
113
+ const filesCovered = graph.fileNodes.size;
114
+ const snapshot = loadProjectSnapshot(cwd);
115
+ const snapshotFileCount = snapshot ? Object.keys(snapshot.files).length : 0;
116
+ const filesTotal = Math.max(filesCovered, snapshotFileCount);
117
+ const coverage = filesTotal > 0 ? filesCovered / filesTotal : 1;
118
+ let exact = 0;
119
+ let imp = 0;
120
+ let receiverType = 0;
121
+ let nameOnly = 0;
122
+ for (const edge of graph.edges) {
123
+ if (edge.kind !== "calls" && edge.kind !== "references")
124
+ continue;
125
+ switch (edge.resolution) {
126
+ case "exact":
127
+ exact += 1;
128
+ break;
129
+ case "import":
130
+ imp += 1;
131
+ break;
132
+ case "receiver-type":
133
+ receiverType += 1;
134
+ break;
135
+ case "name-only":
136
+ nameOnly += 1;
137
+ break;
138
+ default:
139
+ break;
140
+ }
141
+ }
142
+ const sampleSize = exact + imp + receiverType + nameOnly;
143
+ const frac = (n) => (sampleSize > 0 ? n / sampleSize : 0);
144
+ const ageMs = Date.now() - Date.parse(graph.builtAt);
145
+ const stale = Number.isFinite(ageMs) && ageMs > STALE_THRESHOLD_MS;
146
+ const lowCoverage = coverage < LOW_COVERAGE_THRESHOLD;
147
+ const notes = [];
148
+ if (stale) {
149
+ const ageMin = Math.round(ageMs / 60_000);
150
+ notes.push(`Graph is stale: built ${ageMin}m ago. Sections below may miss recent edits — run pilens_rebuild or re-analyze to refresh.`);
151
+ }
152
+ if (lowCoverage) {
153
+ notes.push(`Low coverage: only ${filesCovered}/${filesTotal} project files (${Math.round(coverage * 100)}%) are in the graph — whole subsystems may be invisible below.`);
154
+ }
155
+ return {
156
+ graphBuiltAt: graph.builtAt,
157
+ filesCovered,
158
+ filesTotal,
159
+ coverage,
160
+ resolution: {
161
+ exact: frac(exact),
162
+ import: frac(imp),
163
+ receiverType: frac(receiverType),
164
+ nameOnly: frac(nameOnly),
165
+ sampleSize,
166
+ },
167
+ stale,
168
+ lowCoverage,
169
+ notes,
170
+ };
171
+ }
172
+ // --- section 2: hubs -----------------------------------------------------------
173
+ function roleFor(graph, filePath) {
174
+ const symbolIds = graph.symbolNodesByFile.get(filePath) ?? [];
175
+ const scored = [];
176
+ for (const symbolId of symbolIds) {
177
+ const node = graph.nodes.get(symbolId);
178
+ if (!node || !node.exported || !node.symbolName)
179
+ continue;
180
+ const refs = (graph.edgesByTo.get(symbolId) ?? []).filter((e) => e.kind === "calls" || e.kind === "references").length;
181
+ scored.push({ name: node.qualifiedName ?? node.symbolName, refs });
182
+ }
183
+ scored.sort((a, b) => b.refs - a.refs);
184
+ const top = scored.slice(0, 3).filter((s) => s.refs > 0);
185
+ return top.length > 0 ? top.map((s) => s.name).join(", ") : undefined;
186
+ }
187
+ async function computeHubs(graph, degrees, cwd, limit, focusTerms) {
188
+ const { computeTransitiveImpact } = await import("./review-graph/query.js");
189
+ const ranked = [...graph.fileNodes.entries()]
190
+ .map(([filePath, fileNodeId]) => ({
191
+ filePath,
192
+ fileNodeId,
193
+ fanIn: degrees.fanIn.get(fileNodeId)?.size ?? 0,
194
+ }))
195
+ .filter((f) => f.fanIn > 0)
196
+ .sort((a, b) => {
197
+ const focusDelta = focusScore(a.filePath, focusTerms) - focusScore(b.filePath, focusTerms);
198
+ if (focusDelta !== 0)
199
+ return -focusDelta;
200
+ return b.fanIn - a.fanIn || a.filePath.localeCompare(b.filePath);
201
+ })
202
+ .slice(0, limit);
203
+ return ranked.map((f) => {
204
+ const impact = computeTransitiveImpact(graph, f.filePath, { maxDepth: 3 });
205
+ const display = toDisplayPath(f.filePath, cwd);
206
+ return {
207
+ file: display,
208
+ fanIn: f.fanIn,
209
+ blastRadius: impact.hits.length,
210
+ role: roleFor(graph, f.filePath),
211
+ suggestedNext: suggestedNext(display),
212
+ };
213
+ });
214
+ }
215
+ // --- section 3: entry points ---------------------------------------------------
216
+ function computeEntryPoints(graph, degrees, cwd, limit, focusTerms) {
217
+ const candidates = [...graph.fileNodes.entries()]
218
+ .map(([filePath, fileNodeId]) => ({
219
+ filePath,
220
+ fanIn: degrees.fanIn.get(fileNodeId)?.size ?? 0,
221
+ fanOut: degrees.fanOut.get(fileNodeId)?.size ?? 0,
222
+ }))
223
+ .filter((f) => f.fanIn === 0 && f.fanOut > 0)
224
+ .sort((a, b) => {
225
+ const focusDelta = focusScore(a.filePath, focusTerms) - focusScore(b.filePath, focusTerms);
226
+ if (focusDelta !== 0)
227
+ return -focusDelta;
228
+ return b.fanOut - a.fanOut || a.filePath.localeCompare(b.filePath);
229
+ });
230
+ // The exclusion set for dead weight is UNCAPPED (#773: "zero-importer files
231
+ // that aren't entry points") — an entry-point-like file past the display
232
+ // cap must not be reclassified as suspected dead weight.
233
+ const entryPointFiles = new Set(candidates.map((c) => c.filePath));
234
+ const entryPoints = candidates.slice(0, limit).map((f) => {
235
+ const display = toDisplayPath(f.filePath, cwd);
236
+ return {
237
+ file: display,
238
+ fanIn: f.fanIn,
239
+ fanOut: f.fanOut,
240
+ suggestedNext: suggestedNext(display),
241
+ };
242
+ });
243
+ return { entryPoints, entryPointFiles };
244
+ }
245
+ // --- section 4: subsystem map (directory-level aggregation) -------------------
246
+ // Depth heuristic (#773): first path segment under the project root by
247
+ // default; collapse to a deeper (two-segment) cluster only for files under a
248
+ // segment that dominates the covered file set (so a monorepo's one giant
249
+ // top-level dir still gets useful sub-clustering instead of one blob node).
250
+ const DOMINANCE_THRESHOLD = 0.4;
251
+ function directoryClusters(filePaths, cwd) {
252
+ const segmentsOf = (filePath) => toDisplayPath(filePath, cwd).split("/").filter(Boolean);
253
+ const topCounts = new Map();
254
+ const perFileSegments = new Map();
255
+ for (const filePath of filePaths) {
256
+ const segments = segmentsOf(filePath);
257
+ perFileSegments.set(filePath, segments);
258
+ const top = segments.length > 1 ? segments[0] : "(root)";
259
+ topCounts.set(top, (topCounts.get(top) ?? 0) + 1);
260
+ }
261
+ const total = filePaths.length || 1;
262
+ const dominant = new Set([...topCounts.entries()]
263
+ .filter(([, count]) => count / total >= DOMINANCE_THRESHOLD)
264
+ .map(([seg]) => seg));
265
+ const clusterOf = new Map();
266
+ for (const filePath of filePaths) {
267
+ const segments = perFileSegments.get(filePath) ?? [];
268
+ if (segments.length <= 1) {
269
+ clusterOf.set(filePath, "(root)");
270
+ continue;
271
+ }
272
+ const top = segments[0];
273
+ if (dominant.has(top) && segments.length > 2) {
274
+ clusterOf.set(filePath, `${segments[0]}/${segments[1]}`);
275
+ }
276
+ else {
277
+ clusterOf.set(filePath, top);
278
+ }
279
+ }
280
+ return clusterOf;
281
+ }
282
+ // Tarjan SCC over the (small, directory-granularity) cluster graph — finds
283
+ // every strongly-connected component, i.e. every directory-level import cycle.
284
+ function tarjanSCCs(nodes, adjacency) {
285
+ let index = 0;
286
+ const indices = new Map();
287
+ const lowlink = new Map();
288
+ const onStack = new Set();
289
+ const stack = [];
290
+ const sccs = [];
291
+ function strongConnect(v) {
292
+ indices.set(v, index);
293
+ lowlink.set(v, index);
294
+ index += 1;
295
+ stack.push(v);
296
+ onStack.add(v);
297
+ for (const w of adjacency.get(v) ?? []) {
298
+ if (!indices.has(w)) {
299
+ strongConnect(w);
300
+ lowlink.set(v, Math.min(lowlink.get(v), lowlink.get(w)));
301
+ }
302
+ else if (onStack.has(w)) {
303
+ lowlink.set(v, Math.min(lowlink.get(v), indices.get(w)));
304
+ }
305
+ }
306
+ if (lowlink.get(v) === indices.get(v)) {
307
+ const scc = [];
308
+ let w;
309
+ do {
310
+ w = stack.pop();
311
+ onStack.delete(w);
312
+ scc.push(w);
313
+ } while (w !== v);
314
+ sccs.push(scc);
315
+ }
316
+ }
317
+ for (const v of nodes) {
318
+ if (!indices.has(v))
319
+ strongConnect(v);
320
+ }
321
+ return sccs;
322
+ }
323
+ function computeSubsystems(graph, cwd, limit) {
324
+ const filePaths = [...graph.fileNodes.keys()];
325
+ const clusterOf = directoryClusters(filePaths, cwd);
326
+ const fileNodeIdToCluster = new Map();
327
+ for (const [filePath, nodeId] of graph.fileNodes) {
328
+ const cluster = clusterOf.get(filePath);
329
+ if (cluster)
330
+ fileNodeIdToCluster.set(nodeId, cluster);
331
+ }
332
+ const edgeCounts = new Map(); // "from|to" -> count
333
+ for (const edge of graph.edges) {
334
+ if (edge.kind !== "imports")
335
+ continue;
336
+ const fromCluster = fileNodeIdToCluster.get(edge.from);
337
+ const toCluster = fileNodeIdToCluster.get(edge.to);
338
+ if (!fromCluster || !toCluster || fromCluster === toCluster)
339
+ continue;
340
+ const key = `${fromCluster}|${toCluster}`;
341
+ edgeCounts.set(key, (edgeCounts.get(key) ?? 0) + 1);
342
+ }
343
+ const directories = [...new Set(clusterOf.values())].sort((a, b) => a.localeCompare(b));
344
+ const edges = [...edgeCounts.entries()]
345
+ .map(([key, count]) => {
346
+ const [from, to] = key.split("|");
347
+ return { from, to, count };
348
+ })
349
+ .sort((a, b) => b.count - a.count || a.from.localeCompare(b.from));
350
+ // Layering violations: for each unordered pair with edges both ways, the
351
+ // minority direction is the violation candidate (#773). Ties (equal counts,
352
+ // genuinely ambiguous "dominant direction") are skipped rather than guessed.
353
+ const seenPairs = new Set();
354
+ const violations = [];
355
+ for (const edge of edges) {
356
+ const pairKey = [edge.from, edge.to]
357
+ .sort((a, b) => a.localeCompare(b))
358
+ .join("|");
359
+ if (seenPairs.has(pairKey))
360
+ continue;
361
+ const reverseKey = `${edge.to}|${edge.from}`;
362
+ const reverseCount = edgeCounts.get(reverseKey);
363
+ if (reverseCount === undefined || reverseCount === edge.count)
364
+ continue;
365
+ seenPairs.add(pairKey);
366
+ if (edge.count < reverseCount) {
367
+ violations.push({
368
+ from: edge.from,
369
+ to: edge.to,
370
+ count: edge.count,
371
+ dominantCount: reverseCount,
372
+ });
373
+ }
374
+ else {
375
+ violations.push({
376
+ from: edge.to,
377
+ to: edge.from,
378
+ count: reverseCount,
379
+ dominantCount: edge.count,
380
+ });
381
+ }
382
+ }
383
+ violations.sort((a, b) => b.count - a.count || a.from.localeCompare(b.from));
384
+ const adjacency = new Map();
385
+ for (const dir of directories)
386
+ adjacency.set(dir, new Set());
387
+ for (const edge of edges) {
388
+ adjacency.get(edge.from)?.add(edge.to);
389
+ }
390
+ const sccs = tarjanSCCs(directories, adjacency).filter((scc) => scc.length > 1);
391
+ const cycles = sccs
392
+ .map((scc) => {
393
+ const members = new Set(scc);
394
+ let edgeCount = 0;
395
+ for (const edge of edges) {
396
+ if (members.has(edge.from) && members.has(edge.to))
397
+ edgeCount += edge.count;
398
+ }
399
+ return { dirs: [...scc].sort((a, b) => a.localeCompare(b)), edgeCount };
400
+ })
401
+ .sort((a, b) => b.edgeCount - a.edgeCount);
402
+ return {
403
+ directories,
404
+ edges: edges.slice(0, limit),
405
+ cycles: cycles.slice(0, limit),
406
+ violations: violations.slice(0, limit),
407
+ };
408
+ }
409
+ // --- section 5: risk hotspots ---------------------------------------------------
410
+ function computeRiskHotspots(graph, degrees, cwd, limit, focusTerms) {
411
+ const ranked = [...graph.fileNodes.entries()]
412
+ .map(([filePath, fileNodeId]) => {
413
+ const symbolIds = graph.symbolNodesByFile.get(filePath) ?? [];
414
+ let maxComplexity = 0;
415
+ for (const symbolId of symbolIds) {
416
+ const complexity = graph.nodes.get(symbolId)?.metadata?.cyclomaticComplexity;
417
+ if (typeof complexity === "number" && complexity > maxComplexity) {
418
+ maxComplexity = complexity;
419
+ }
420
+ }
421
+ const fanIn = degrees.fanIn.get(fileNodeId)?.size ?? 0;
422
+ return { filePath, fanIn, maxComplexity, score: fanIn * maxComplexity };
423
+ })
424
+ .filter((f) => f.score > 0)
425
+ .sort((a, b) => {
426
+ const focusDelta = focusScore(a.filePath, focusTerms) - focusScore(b.filePath, focusTerms);
427
+ if (focusDelta !== 0)
428
+ return -focusDelta;
429
+ return b.score - a.score || a.filePath.localeCompare(b.filePath);
430
+ })
431
+ .slice(0, limit);
432
+ return ranked.map((f) => {
433
+ const display = toDisplayPath(f.filePath, cwd);
434
+ return {
435
+ file: display,
436
+ fanIn: f.fanIn,
437
+ maxComplexity: f.maxComplexity,
438
+ score: f.score,
439
+ suggestedNext: suggestedNext(display),
440
+ };
441
+ });
442
+ }
443
+ // --- section 6: suspected dead weight --------------------------------------------
444
+ function computeDeadWeight(graph, degrees, entryPointFiles, cwd, limit) {
445
+ const candidates = [...graph.fileNodes.entries()]
446
+ .filter(([filePath, nodeId]) => {
447
+ if (entryPointFiles.has(filePath))
448
+ return false;
449
+ const fanIn = degrees.fanIn.get(nodeId)?.size ?? 0;
450
+ return fanIn === 0;
451
+ })
452
+ .map(([filePath, fileNodeId]) => ({
453
+ filePath,
454
+ fanOut: degrees.fanOut.get(fileNodeId)?.size ?? 0,
455
+ }))
456
+ // Truly-isolated files (zero fan-in AND zero fan-out) first — the
457
+ // highest-confidence dead weight — then rising fan-out.
458
+ .sort((a, b) => a.fanOut - b.fanOut || a.filePath.localeCompare(b.filePath))
459
+ .slice(0, limit);
460
+ return {
461
+ files: candidates.map((f) => {
462
+ const display = toDisplayPath(f.filePath, cwd);
463
+ return { file: display, suggestedNext: suggestedNext(display) };
464
+ }),
465
+ disclaimer: DEAD_WEIGHT_DISCLAIMER,
466
+ };
467
+ }
468
+ // --- cold-path background build (mirrors word-index.ts's #348 pattern) --------
469
+ const inFlightGraphBuilds = new Set();
470
+ /** Test-only: reset the in-flight-build guard between test files/cases. */
471
+ export function _resetProjectReportBuildGuardForTests() {
472
+ inFlightGraphBuilds.clear();
473
+ }
474
+ function triggerBackgroundGraphBuild(cwd) {
475
+ const key = normalizeMapKey(path.resolve(cwd));
476
+ if (isAtOrAboveHomeDir(key))
477
+ return;
478
+ if (inFlightGraphBuilds.has(key))
479
+ return;
480
+ inFlightGraphBuilds.add(key);
481
+ void (async () => {
482
+ try {
483
+ const { buildOrUpdateGraph } = await import("./review-graph/builder.js");
484
+ const { FactStore } = await import("./dispatch/fact-store.js");
485
+ await buildOrUpdateGraph(key, [], new FactStore());
486
+ }
487
+ catch {
488
+ // Best-effort warmth, not a request the caller is waiting on.
489
+ }
490
+ finally {
491
+ inFlightGraphBuilds.delete(key);
492
+ }
493
+ })();
494
+ }
495
+ // --- entry point ---------------------------------------------------------------
496
+ /**
497
+ * Project-level orientation report (#773), read-only over the cached review
498
+ * graph. Returns `available: false` on a cold cache and kicks off a background
499
+ * build (never blocking this call) — see module-level doc comment.
500
+ */
501
+ export async function projectReport(cwd, options) {
502
+ const limit = clampLimit(options?.limit);
503
+ const focusTerms = normalizeFocus(options?.focus);
504
+ const view = options?.view;
505
+ const { getCachedReviewGraph, getReviewGraphSizeSkipVerdict } = await import("./review-graph/builder.js");
506
+ let graph;
507
+ try {
508
+ graph = getCachedReviewGraph(cwd);
509
+ }
510
+ catch {
511
+ graph = undefined;
512
+ }
513
+ if (!graph) {
514
+ // #782: a fresh size-skip verdict means the graph will never build at the
515
+ // CURRENT cap — retrying "shortly" is actively wrong guidance here, so
516
+ // this branches before the generic cold-cache hint (and skips kicking off
517
+ // another background build that would just re-hit the same cap).
518
+ let sizeSkip;
519
+ try {
520
+ sizeSkip = getReviewGraphSizeSkipVerdict(cwd);
521
+ }
522
+ catch {
523
+ sizeSkip = undefined;
524
+ }
525
+ if (sizeSkip) {
526
+ return {
527
+ available: false,
528
+ hint: `review graph disabled: project has ${sizeSkip.sourceFileCount} files, ` +
529
+ `cap is ${sizeSkip.maxFileCount} — raise maxProjectFiles in .pi-lens.json ` +
530
+ "or set PI_LENS_REVIEW_GRAPH_MAX_FILES",
531
+ ...(view ? { view } : {}),
532
+ };
533
+ }
534
+ triggerBackgroundGraphBuild(cwd);
535
+ return {
536
+ available: false,
537
+ hint: "No review graph cached for this workspace yet — a build was kicked " +
538
+ "off in the background; retry this call shortly.",
539
+ ...(view ? { view } : {}),
540
+ };
541
+ }
542
+ const degrees = buildFileDegrees(graph);
543
+ const trust = computeTrust(graph, cwd);
544
+ const hubs = await computeHubs(graph, degrees, cwd, limit, focusTerms);
545
+ const { entryPoints, entryPointFiles } = computeEntryPoints(graph, degrees, cwd, limit, focusTerms);
546
+ const subsystems = computeSubsystems(graph, cwd, limit);
547
+ const riskHotspots = computeRiskHotspots(graph, degrees, cwd, limit, focusTerms);
548
+ const deadWeight = computeDeadWeight(graph, degrees, entryPointFiles, cwd, limit);
549
+ return {
550
+ available: true,
551
+ ...(view ? { view } : {}),
552
+ trust,
553
+ hubs,
554
+ entryPoints,
555
+ subsystems,
556
+ riskHotspots,
557
+ deadWeight,
558
+ };
559
+ }
560
+ // --- compact (line-oriented text) rendering -------------------------------------
561
+ function fmtPct(n) {
562
+ return `${Math.round(n * 100)}%`;
563
+ }
564
+ /**
565
+ * Render a ProjectReport as line-oriented text (mirrors
566
+ * renderCompactModuleReport's convention) — cheapest option, one line per
567
+ * ranked item instead of a repeated-keys JSON object.
568
+ */
569
+ export function renderCompactProjectReport(report) {
570
+ if (!report.available) {
571
+ return `project_report — unavailable${report.hint ? `: ${report.hint}` : ""}`;
572
+ }
573
+ const lines = [];
574
+ const t = report.trust;
575
+ if (t) {
576
+ lines.push(`TRUST: built ${t.graphBuiltAt} — ${t.filesCovered}/${t.filesTotal} files (${fmtPct(t.coverage)} coverage)` +
577
+ (t.resolution.sampleSize > 0
578
+ ? ` — resolution: exact ${fmtPct(t.resolution.exact)}, import ${fmtPct(t.resolution.import)}, receiver-type ${fmtPct(t.resolution.receiverType)}, name-only ${fmtPct(t.resolution.nameOnly)}`
579
+ : " — no resolution-tagged edges yet"));
580
+ for (const note of t.notes)
581
+ lines.push(` ! ${note}`);
582
+ }
583
+ if (report.hubs?.length) {
584
+ lines.push("HUBS:");
585
+ for (const h of report.hubs) {
586
+ const role = h.role ? ` — ${h.role}` : "";
587
+ lines.push(` ${h.file}${role}; ${h.fanIn} importer(s), blastRadius ${h.blastRadius}`);
588
+ }
589
+ }
590
+ if (report.entryPoints?.length) {
591
+ lines.push("ENTRY POINTS:");
592
+ for (const e of report.entryPoints) {
593
+ lines.push(` ${e.file}; fan-out ${e.fanOut}`);
594
+ }
595
+ }
596
+ if (report.subsystems) {
597
+ const s = report.subsystems;
598
+ lines.push(`SUBSYSTEMS: ${s.directories.length} directories, ${s.edges.length} cross-dir edge group(s)`);
599
+ if (s.cycles.length > 0) {
600
+ lines.push(" CYCLES:");
601
+ for (const c of s.cycles) {
602
+ lines.push(` ${c.dirs.join(" <-> ")} (${c.edgeCount} edges)`);
603
+ }
604
+ }
605
+ if (s.violations.length > 0) {
606
+ lines.push(" LAYERING VIOLATIONS:");
607
+ for (const v of s.violations) {
608
+ lines.push(` ${v.from} -> ${v.to} (${v.count} edge(s), against the dominant ${v.to} -> ${v.from} direction, ${v.dominantCount} edge(s))`);
609
+ }
610
+ }
611
+ }
612
+ if (report.riskHotspots?.length) {
613
+ lines.push("RISK HOTSPOTS:");
614
+ for (const r of report.riskHotspots) {
615
+ lines.push(` ${r.file}; fan-in ${r.fanIn} × max complexity ${r.maxComplexity} = ${r.score}`);
616
+ }
617
+ }
618
+ if (report.deadWeight) {
619
+ lines.push(`DEAD WEIGHT (${report.deadWeight.disclaimer}):`);
620
+ for (const d of report.deadWeight.files) {
621
+ lines.push(` ${d.file}`);
622
+ }
623
+ if (report.deadWeight.files.length === 0)
624
+ lines.push(" (none found)");
625
+ }
626
+ return lines.join("\n");
627
+ }