codefactory-cli 0.20.1__py3-none-any.whl

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 (61) hide show
  1. codefactory/__init__.py +3 -0
  2. codefactory/__main__.py +5 -0
  3. codefactory/accept.py +68 -0
  4. codefactory/analyzers/__init__.py +55 -0
  5. codefactory/analyzers/generic.py +392 -0
  6. codefactory/analyzers/parallel.py +113 -0
  7. codefactory/analyzers/python.py +279 -0
  8. codefactory/analyzers/python_parse.py +402 -0
  9. codefactory/analyzers/treewalk.py +299 -0
  10. codefactory/analyzers/ts_helper.js +483 -0
  11. codefactory/analyzers/typescript.py +118 -0
  12. codefactory/apple.py +80 -0
  13. codefactory/audit.py +227 -0
  14. codefactory/baseline.py +58 -0
  15. codefactory/brief.py +330 -0
  16. codefactory/cache.py +93 -0
  17. codefactory/checks.py +608 -0
  18. codefactory/cli.py +782 -0
  19. codefactory/config.py +157 -0
  20. codefactory/coverage.py +104 -0
  21. codefactory/deps.py +182 -0
  22. codefactory/diff.py +197 -0
  23. codefactory/efficiency.py +250 -0
  24. codefactory/flags.py +263 -0
  25. codefactory/graph.py +95 -0
  26. codefactory/hotspots.py +344 -0
  27. codefactory/infra.py +242 -0
  28. codefactory/intent.py +106 -0
  29. codefactory/layers.py +143 -0
  30. codefactory/org.py +131 -0
  31. codefactory/owners.py +72 -0
  32. codefactory/patch.py +81 -0
  33. codefactory/paths.py +93 -0
  34. codefactory/plan.py +476 -0
  35. codefactory/privacy.py +221 -0
  36. codefactory/profile.py +667 -0
  37. codefactory/rerank.py +161 -0
  38. codefactory/review.py +1504 -0
  39. codefactory/rules.py +50 -0
  40. codefactory/sarif.py +661 -0
  41. codefactory/sbom.py +78 -0
  42. codefactory/security.py +537 -0
  43. codefactory/similar.py +199 -0
  44. codefactory/skill.py +144 -0
  45. codefactory/skill_template/SKILL.md +68 -0
  46. codefactory/skill_template/__init__.py +0 -0
  47. codefactory/sqlgraph.py +109 -0
  48. codefactory/suppress.py +92 -0
  49. codefactory/taint.py +439 -0
  50. codefactory/trace.py +72 -0
  51. codefactory/viewer/__init__.py +19 -0
  52. codefactory/viewer/dashboard.html +43 -0
  53. codefactory/viewer/factory.css +61 -0
  54. codefactory/viewer/factory.js +665 -0
  55. codefactory/viewer/template.html +47 -0
  56. codefactory_cli-0.20.1.dist-info/METADATA +250 -0
  57. codefactory_cli-0.20.1.dist-info/RECORD +61 -0
  58. codefactory_cli-0.20.1.dist-info/WHEEL +5 -0
  59. codefactory_cli-0.20.1.dist-info/entry_points.txt +2 -0
  60. codefactory_cli-0.20.1.dist-info/licenses/LICENSE +21 -0
  61. codefactory_cli-0.20.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,665 @@
1
+ // codefactory: ignore-file raw_html — every value from the graph goes through esc() before it's inserted
2
+ // The factory floor: layers are zones (left = depends on the others, right = depended on), files are machines
3
+ // (size = lines), calls or imports are belts (thickness = how many), and flags are lights on the machines.
4
+ (function () {
5
+ "use strict";
6
+ const D = window.FACTORY;
7
+ const css = (n) => getComputedStyle(document.documentElement).getPropertyValue(n).trim();
8
+ const $ = (s) => document.querySelector(s);
9
+ const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
10
+ const SEV = { high: 0, warn: 1, info: 2 };
11
+ const reduceMotion = matchMedia("(prefers-reduced-motion: reduce)").matches;
12
+
13
+ // ---- model -------------------------------------------------------------------------------------------
14
+ const fnById = new Map(D.functions.map((f) => [f.id, f]));
15
+ const files = D.files.map((f) => ({ ...f, fns: [], flags: [], inn: new Map(), out: new Map(), worst: null }));
16
+ const fileById = new Map(files.map((f) => [f.id, f]));
17
+ for (const fn of D.functions) if (fn.kind !== "module") fileById.get(fn.file)?.fns.push(fn);
18
+ const fileOf = (target) => fileById.get(target) || fileById.get(fnById.get(target)?.file);
19
+ for (const fl of D.flags) {
20
+ const f = fileOf(fl.target);
21
+ if (!f) continue;
22
+ f.flags.push(fl);
23
+ if (f.worst === null || SEV[fl.severity] < SEV[f.worst]) f.worst = fl.severity;
24
+ }
25
+ // Lenses: duplication (copies and near-copies), efficiency (I/O, searches and awaits inside loops), size.
26
+ const DUP = new Set(["duplicate", "similar"]), SLOW = new Set(["io_in_loop", "quadratic_scan", "sequential_await"]);
27
+ const LENS_KINDS = { duplication: DUP, efficiency: SLOW, size: new Set(["large_file", "long_function"]) };
28
+ for (const f of files) {
29
+ const copied = new Set(f.flags.filter((x) => DUP.has(x.kind)).map((x) => x.target));
30
+ f.dupFns = copied.size;
31
+ f.dupLoc = [...copied].reduce((t, id) => t + (fnById.get(id)?.loc || 0), 0);
32
+ f.slow = f.flags.filter((x) => SLOW.has(x.kind)).reduce((t, x) => t + (x.severity === "warn" ? 3 : 1), 0);
33
+ f.ioFns = f.fns.filter((fn) => fn.io && fn.io.length).length;
34
+ f.longFns = f.flags.filter((x) => x.kind === "long_function").length;
35
+ }
36
+ const twins = new Map(); // "a|b" -> { a, b, score }: two files holding copies of each other's code
37
+ for (const fl of D.flags) {
38
+ if (!DUP.has(fl.kind)) continue;
39
+ const a = fileOf(fl.target);
40
+ for (const r of fl.related || []) {
41
+ const b = fileOf(r);
42
+ if (!a || !b || a === b) continue;
43
+ const [x, y] = a.id < b.id ? [a, b] : [b, a], k = x.id + "|" + y.id;
44
+ const score = fl.kind === "duplicate" ? 1 : fl.score || 0.8;
45
+ const t = twins.get(k);
46
+ if (!t || t.score < score) twins.set(k, { a: x, b: y, score, n: (t?.n || 0) + 1 });
47
+ else t.n++;
48
+ }
49
+ }
50
+ const hot = new Set(); // "src>dst" file pairs where a loop calls into code that does I/O
51
+ for (const fl of D.flags) {
52
+ if (fl.kind !== "io_in_loop") continue;
53
+ const a = fileOf(fl.target), b = fl.related && fl.related[0] ? fileOf(fl.related[0]) : a;
54
+ if (a && b) hot.add(a.id + ">" + b.id);
55
+ }
56
+ const lensMetric = { issues: () => 0, duplication: (f) => f.dupLoc, efficiency: (f) => f.slow, size: (f) => f.loc };
57
+ const lensMax = {};
58
+ for (const k of Object.keys(lensMetric)) lensMax[k] = Math.max(1, ...files.map(lensMetric[k]));
59
+ let lens = "issues";
60
+ const fnCallers = new Map(), fnCallees = new Map();
61
+ function beltsFor(kind) {
62
+ const agg = new Map();
63
+ for (const e of D.edges) {
64
+ if (kind === "call" ? e.kind !== "call" : e.kind !== "import") continue;
65
+ const a = fileOf(e.src), b = fileOf(e.dst);
66
+ if (!a || !b || a === b || a.hidden || b.hidden) continue;
67
+ const k = a.id + "\u0000" + b.id;
68
+ agg.set(k, (agg.get(k) || 0) + e.count);
69
+ }
70
+ return [...agg].map(([k, count]) => { const [s, d] = k.split("\u0000"); return { src: fileById.get(s), dst: fileById.get(d), count }; });
71
+ }
72
+ for (const e of D.edges) {
73
+ if (e.kind === "import") continue;
74
+ if (!fnCallers.has(e.dst)) fnCallers.set(e.dst, []);
75
+ if (!fnCallees.has(e.src)) fnCallees.set(e.src, []);
76
+ fnCallers.get(e.dst).push(e); fnCallees.get(e.src).push(e);
77
+ }
78
+
79
+ // EXPLAIN for a function: everything it eventually calls, each at its shortest depth.
80
+ function traceFrom(start) {
81
+ const depth = new Map([[start, 0]]), order = [];
82
+ const q = [start];
83
+ let loop = false;
84
+ while (q.length) {
85
+ const cur = q.shift();
86
+ for (const e of fnCallees.get(cur) || []) {
87
+ if (e.kind !== "call") continue;
88
+ if (e.dst === start) loop = true;
89
+ if (!depth.has(e.dst) && fnById.has(e.dst)) { depth.set(e.dst, depth.get(cur) + 1); order.push(e.dst); q.push(e.dst); }
90
+ }
91
+ }
92
+ const fns = order.map((id) => ({ fn: fnById.get(id), depth: depth.get(id) }));
93
+ return { start: fnById.get(start), fns, loop, files: new Set([fnById.get(start).file, ...fns.map((x) => x.fn.file)]),
94
+ maxDepth: Math.max(0, ...fns.map((x) => x.depth)), loc: fns.reduce((t, x) => t + x.fn.loc, 0) };
95
+ }
96
+
97
+ // ---- layout -------------------------------------------------------------------------------------------
98
+ const GAP = 140, PAD = 40, TOP = 110;
99
+ const size = (f) => Math.round(Math.min(150, Math.max(36, 26 + Math.sqrt(f.loc) * 2.6)) / 10) * 10;
100
+ const layers = D.layers.length ? D.layers : [...new Set(files.map((f) => f.layer))];
101
+ const hasTests = files.some((f) => f.layer === "tests");
102
+ let showTests = !hasTests || files.filter((f) => f.layer === "tests").length < files.length * 0.1;
103
+ let zones = [], worldW = 0, worldH = 0;
104
+ files.forEach((f) => { f.s = size(f); });
105
+ // Zones are halls of one shared height, each as wide as its machines need, so the whole floor has about the
106
+ // screen's shape: a big codebase fits on screen instead of becoming a long thin strip.
107
+ function layout() {
108
+ zones = [];
109
+ files.forEach((f) => { f.hidden = f.layer === "tests" && !showTests; f.zone = -1; });
110
+ const groups = layers.map((name) => files.filter((f) => f.layer === name && !f.hidden)).filter((m) => m.length);
111
+ const areaOf = (m) => m.reduce((t, f) => t + (f.s + PAD) ** 2, 0) * 1.15;
112
+ const total = groups.reduce((t, m) => t + areaOf(m), 0);
113
+ const aspect = Math.max(1, (innerWidth - 360) / Math.max(300, innerHeight));
114
+ const hall = Math.max(240, Math.sqrt(total / aspect));
115
+ let x = 0;
116
+ for (const members of groups) {
117
+ members.sort((a, b) => b.s - a.s || a.id.localeCompare(b.id));
118
+ // never a sliver: even a hall of one file is wide enough for its summary card when zoomed out
119
+ const width = Math.max(members[0].s + PAD, hall * 0.22, Math.ceil(areaOf(members) / hall / 10) * 10);
120
+ let cx = 0, cy = 0, rowH = 0;
121
+ for (const f of members) {
122
+ if (cx > 0 && cx + f.s > width) { cx = 0; cy += rowH + PAD; rowH = 0; }
123
+ f.x = x + PAD + cx; f.y = TOP + cy; cx += f.s + PAD; rowH = Math.max(rowH, f.s);
124
+ f.zone = zones.length;
125
+ }
126
+ zones.push({ name: members[0].layer, x, w: width + PAD * 2, h: cy + rowH + PAD * 2 + 30, count: members.length });
127
+ x += width + PAD * 2 + GAP;
128
+ }
129
+ const h = Math.max(...zones.map((z) => z.h), 200);
130
+ zones.forEach((z) => { z.h = h; });
131
+ worldW = x - GAP; worldH = h + TOP;
132
+ }
133
+ layout();
134
+
135
+ let mode = "call", belts = [];
136
+ function buildBelts() {
137
+ belts = beltsFor(mode).map((b, i) => {
138
+ const back = b.dst.zone < b.src.zone; // flows against the zone order
139
+ const over = b.dst.zone <= b.src.zone; // routed over the top: backwards, or within one zone
140
+ const x1 = b.src.x + b.src.s, y1 = b.src.y + b.src.s / 2, x2 = b.dst.x, y2 = b.dst.y + b.dst.s / 2;
141
+ let pts;
142
+ if (!over) {
143
+ const z = zones[b.src.zone];
144
+ const mx = z.x + z.w + 12 + (i * 7) % (GAP - 24);
145
+ pts = [[x1, y1], [mx, y1], [mx, y2], [x2, y2]];
146
+ } else { // up and over the top of the floor
147
+ const lane = 16 + (i * 5) % 44;
148
+ pts = [[b.src.x + b.src.s / 2, b.src.y], [b.src.x + b.src.s / 2, lane], [b.dst.x + b.dst.s / 2, lane], [b.dst.x + b.dst.s / 2, b.dst.y]];
149
+ }
150
+ let len = 0; const segs = [];
151
+ for (let k = 1; k < pts.length; k++) { const l = Math.abs(pts[k][0] - pts[k - 1][0]) + Math.abs(pts[k][1] - pts[k - 1][1]); segs.push(l); len += l; }
152
+ return { ...b, back, pts, segs, len, w: 1 + Math.min(5, Math.log2(b.count + 1)), dots: Math.min(6, 1 + Math.floor(Math.log2(b.count + 1))) };
153
+ });
154
+ for (const f of files) { f.inn = new Map(); f.out = new Map(); }
155
+ for (const b of belts) { b.src.out.set(b.dst, b.count); b.dst.inn.set(b.src, b.count); }
156
+ // The overview: one conveyor per pair of halls, and a summary card per hall.
157
+ const agg = new Map();
158
+ for (const b of belts) {
159
+ if (b.src.zone === b.dst.zone) continue;
160
+ const k = b.src.zone + ">" + b.dst.zone;
161
+ const l = agg.get(k) || { a: b.src.zone, b: b.dst.zone, count: 0, links: 0 };
162
+ l.count += b.count; l.links++; agg.set(k, l);
163
+ }
164
+ zoneLinks = [...agg.values()].sort((x, y) => x.count - y.count);
165
+ zones.forEach((z, i) => {
166
+ const members = files.filter((f) => f.zone === i);
167
+ z.loc = members.reduce((t, f) => t + f.loc, 0);
168
+ z.fns = members.reduce((t, f) => t + f.fns.length, 0);
169
+ z.sev = { high: 0, warn: 0, info: 0 };
170
+ for (const f of members) for (const fl of f.flags) z.sev[fl.severity]++;
171
+ z.top = members.filter((f) => f.inn.size).sort((p, q) => q.inn.size - p.inn.size).slice(0, 3);
172
+ z.dupFns = members.reduce((t, f) => t + f.dupFns, 0);
173
+ z.slowWarn = members.reduce((t, f) => t + f.flags.filter((x) => SLOW.has(x.kind) && x.severity === "warn").length, 0);
174
+ z.slowAll = members.reduce((t, f) => t + f.flags.filter((x) => SLOW.has(x.kind)).length, 0);
175
+ z.ioFns = members.reduce((t, f) => t + f.ioFns, 0);
176
+ z.longFns = members.reduce((t, f) => t + f.longFns, 0);
177
+ z.metric = members.reduce((t, f) => t + lensMetric[lens](f), 0);
178
+ });
179
+ }
180
+ let zoneLinks = [];
181
+ buildBelts();
182
+
183
+ // ---- view ---------------------------------------------------------------------------------------------
184
+ const canvas = $("#floor"), ctx = canvas.getContext("2d");
185
+ let scale = 1, ox = 0, oy = 0, hover = null, selected = null, flagFilter = null, query = "", traced = null, spot = null;
186
+ function resize() {
187
+ const r = canvas.getBoundingClientRect(), dpr = devicePixelRatio || 1;
188
+ canvas.width = r.width * dpr; canvas.height = r.height * dpr; ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
189
+ }
190
+ function fit() {
191
+ const r = canvas.getBoundingClientRect();
192
+ scale = Math.min(2, Math.max(0.02, Math.min((r.width - 40) / worldW, (r.height - 40) / worldH)));
193
+ ox = (r.width - worldW * scale) / 2; oy = Math.max(20, (r.height - worldH * scale) / 2);
194
+ }
195
+ // Zoom to show these machines together (a trace), close enough to see them as machines.
196
+ // If they're too far apart to show as machines together, centre on `primary` (the function being traced).
197
+ function fitFiles(list, primary) {
198
+ const shown = list.filter((f) => f && !f.hidden);
199
+ if (!shown.length) return;
200
+ const r = canvas.getBoundingClientRect();
201
+ const x0 = Math.min(...shown.map((f) => f.x)), y0 = Math.min(...shown.map((f) => f.y));
202
+ const x1 = Math.max(...shown.map((f) => f.x + f.s)), y1 = Math.max(...shown.map((f) => f.y + f.s));
203
+ const fitScale = Math.min((r.width - 80) / Math.max(1, x1 - x0), (r.height - 80) / Math.max(1, y1 - y0));
204
+ if (fitScale < NEAR + 0.06 && primary && !primary.hidden) {
205
+ scale = Math.max(scale, NEAR + 0.2);
206
+ ox = r.width / 2 - (primary.x + primary.s / 2) * scale; oy = r.height / 2 - (primary.y + primary.s / 2) * scale;
207
+ return;
208
+ }
209
+ scale = Math.min(1.4, fitScale);
210
+ ox = r.width / 2 - ((x0 + x1) / 2) * scale; oy = r.height / 2 - ((y0 + y1) / 2) * scale;
211
+ }
212
+ function focusOn(f) {
213
+ if (f.hidden) { showTests = true; testsBtn.setAttribute("aria-pressed", true); layout(); buildBelts(); }
214
+ const r = canvas.getBoundingClientRect();
215
+ scale = Math.max(scale, 1);
216
+ ox = r.width / 2 - (f.x + f.s / 2) * scale; oy = r.height / 2 - (f.y + f.s / 2) * scale;
217
+ }
218
+ const toWorld = (px, py) => [(px - ox) / scale, (py - oy) / scale];
219
+ const hit = (wx, wy) => files.find((f) => !f.hidden && wx >= f.x && wx <= f.x + f.s && wy >= f.y && wy <= f.y + f.s) || null;
220
+ const matches = (f) => (!query || f.id.toLowerCase().includes(query)) && (!flagFilter || f.flags.some((fl) => fl.kind === flagFilter));
221
+
222
+ function pointAt(b, d) {
223
+ for (let k = 0; k < b.segs.length; k++) {
224
+ if (d <= b.segs[k]) {
225
+ const [ax, ay] = b.pts[k], [bx, by] = b.pts[k + 1], t = b.segs[k] ? d / b.segs[k] : 0;
226
+ return [ax + (bx - ax) * t, ay + (by - ay) * t];
227
+ }
228
+ d -= b.segs[k];
229
+ }
230
+ return b.pts[b.pts.length - 1];
231
+ }
232
+
233
+ // Semantic zoom: below FAR the floor is shown as halls with summary cards and one conveyor per hall pair;
234
+ // above NEAR, the machines. In between, one fades into the other.
235
+ const FAR = 0.26, NEAR = 0.46;
236
+ const detailLevel = () => Math.min(1, Math.max(0, (scale - FAR) / (NEAR - FAR)));
237
+ const overview = () => detailLevel() < 0.5;
238
+ let hoverZone = -1;
239
+ const hallRect = (z) => ({ x: ox + z.x * scale, y: oy + (TOP - 30) * scale, w: z.w * scale, h: z.h * scale });
240
+ function zoneAt(px, py) {
241
+ return zones.findIndex((z) => { const h = hallRect(z); return px >= h.x && px <= h.x + h.w && py >= h.y && py <= h.y + h.h; });
242
+ }
243
+ function zoomToZone(i) {
244
+ const z = zones[i], r = canvas.getBoundingClientRect();
245
+ scale = Math.min(1.4, Math.max(NEAR + 0.04, Math.min((r.width - 60) / z.w, (r.height - 60) / (z.h + 40))));
246
+ ox = r.width / 2 - (z.x + z.w / 2) * scale; oy = r.height / 2 - (TOP - 30 + z.h / 2) * scale;
247
+ }
248
+ const fmt = (n) => n.toLocaleString("en-US");
249
+ function fitText(text, max) {
250
+ if (ctx.measureText(text).width <= max) return text;
251
+ let t = text;
252
+ while (t.length > 1 && ctx.measureText(t + "…").width > max) t = t.slice(0, -1);
253
+ return t + "…";
254
+ }
255
+ function drawOverview(C, a, lensColor) {
256
+ const zMax = Math.max(1, ...zones.map((z) => z.metric || 0));
257
+ const max = Math.max(1, ...zoneLinks.map((l) => l.count));
258
+ ctx.save(); ctx.globalAlpha = a;
259
+ // halls
260
+ zones.forEach((z, i) => {
261
+ const h = hallRect(z);
262
+ ctx.fillStyle = C.panel; ctx.globalAlpha = a * 0.88; ctx.fillRect(h.x, h.y, h.w, h.h); ctx.globalAlpha = a;
263
+ if (lensColor && z.metric > 0) {
264
+ ctx.fillStyle = lensColor; ctx.globalAlpha = a * (0.08 + 0.32 * Math.sqrt(z.metric / zMax)); ctx.fillRect(h.x, h.y, h.w, h.h); ctx.globalAlpha = a;
265
+ }
266
+ ctx.strokeStyle = i === hoverZone ? C.sel : C.edge; ctx.lineWidth = i === hoverZone ? 2.5 : 1.2; ctx.strokeRect(h.x, h.y, h.w, h.h);
267
+ });
268
+ // conveyors: forward ones arch over the top, backward ones (a lower layer reaching up) under the floor
269
+ const top = Math.min(...zones.map((z) => hallRect(z).y)), bottom = Math.max(...zones.map((z) => { const h = hallRect(z); return h.y + h.h; }));
270
+ const labels = [];
271
+ for (const l of zoneLinks) {
272
+ const A = hallRect(zones[l.a]), B = hallRect(zones[l.b]), back = l.b < l.a;
273
+ const on = hoverZone < 0 || l.a === hoverZone || l.b === hoverZone;
274
+ const share = l.count / max, w = 1.5 + 7 * Math.sqrt(share);
275
+ const x1 = A.x + A.w * (back ? 0.35 : 0.65), x2 = B.x + B.w * (back ? 0.65 : 0.35);
276
+ const span = Math.abs(l.b - l.a);
277
+ const y0 = back ? bottom : top, lift = (back ? 1 : -1) * (18 + span * 16);
278
+ ctx.globalAlpha = a * (on ? 0.35 + 0.6 * Math.sqrt(share) : 0.06);
279
+ ctx.strokeStyle = back ? C.back : C.belt; ctx.lineWidth = w; ctx.setLineDash(back ? [10, 6] : []);
280
+ ctx.beginPath(); ctx.moveTo(x1, y0); ctx.bezierCurveTo(x1, y0 + lift * 1.6, x2, y0 + lift * 1.6, x2, y0); ctx.stroke();
281
+ ctx.setLineDash([]);
282
+ // arrowhead at the receiving hall
283
+ ctx.fillStyle = ctx.strokeStyle; ctx.beginPath();
284
+ const d = back ? -1 : 1;
285
+ ctx.moveTo(x2, y0); ctx.lineTo(x2 - w - 3, y0 - d * (w + 7)); ctx.lineTo(x2 + w + 3, y0 - d * (w + 7)); ctx.fill();
286
+ if (on && (share >= 0.12 || hoverZone >= 0)) labels.push({ x: (x1 + x2) / 2, y: y0 + lift * 1.2, text: `${fmt(l.count)} ${mode === "call" ? "calls" : "imports"}` });
287
+ }
288
+ ctx.globalAlpha = a; ctx.font = "600 12px Inter, system-ui, sans-serif"; ctx.textAlign = "center"; ctx.textBaseline = "middle";
289
+ for (const lb of labels) {
290
+ const w = ctx.measureText(lb.text).width + 10;
291
+ ctx.fillStyle = C.floor; ctx.fillRect(lb.x - w / 2, lb.y - 9, w, 18);
292
+ ctx.fillStyle = C.muted; ctx.fillText(lb.text, lb.x, lb.y);
293
+ }
294
+ // cards
295
+ ctx.textAlign = "left"; ctx.textBaseline = "alphabetic";
296
+ zones.forEach((z) => {
297
+ const h = hallRect(z), pad = Math.max(6, Math.min(16, h.w * 0.06)), room = h.w - pad * 2;
298
+ if (room < 46) { // too narrow for a card: the name, written up the hall
299
+ ctx.save(); ctx.translate(h.x + h.w / 2 + 4, h.y + h.h - 10); ctx.rotate(-Math.PI / 2);
300
+ ctx.fillStyle = C.ink; ctx.font = "700 12px Inter, system-ui, sans-serif";
301
+ ctx.fillText(fitText(`${z.name.toUpperCase()} · ${z.count}`, h.h - 20), 0, 0); ctx.restore();
302
+ return;
303
+ }
304
+ const big = Math.max(11, Math.min(22, room / 6.5));
305
+ let y = h.y + pad + big;
306
+ ctx.fillStyle = C.ink; ctx.font = `700 ${big}px Inter, system-ui, sans-serif`;
307
+ ctx.fillText(fitText(z.name.toUpperCase(), room), h.x + pad, y);
308
+ const small = Math.max(10, Math.min(13, room / 11));
309
+ ctx.font = `400 ${small}px Inter, system-ui, sans-serif`; ctx.fillStyle = C.muted;
310
+ for (const line of [`${fmt(z.count)} files`, `${fmt(z.fns)} functions`, `${fmt(z.loc)} lines`]) {
311
+ y += small * 1.5; ctx.fillText(fitText(line, room), h.x + pad, y);
312
+ }
313
+ // issue pills
314
+ y += small * 1.2;
315
+ let px = h.x + pad;
316
+ ctx.font = `600 ${small}px Inter, system-ui, sans-serif`;
317
+ for (const sv of ["high", "warn", "info"]) {
318
+ if (!z.sev[sv]) continue;
319
+ const t = `${z.sev[sv]} ${sv}`, w = ctx.measureText(t).width + 12;
320
+ if (px + w > h.x + h.w - pad) { px = h.x + pad; y += small * 1.9; }
321
+ ctx.fillStyle = C[sv]; ctx.globalAlpha = a * 0.16; ctx.fillRect(px, y, w, small * 1.6);
322
+ ctx.globalAlpha = a; ctx.fillStyle = C[sv]; ctx.fillText(t, px + 6, y + small * 1.15);
323
+ px += w + 5;
324
+ }
325
+ // what the lens is about, in words
326
+ const lensLine = lens === "duplication" ? (z.dupFns ? `${z.dupFns} copied functions` : "no copies")
327
+ : lens === "efficiency" ? `${z.slowWarn} N+1 loops · ${z.slowAll - z.slowWarn} minor loop notes · ${z.ioFns} functions do I/O`
328
+ : lens === "size" ? `${z.longFns} long functions` : "";
329
+ if (lensLine) {
330
+ y += small * 2.6; ctx.font = `700 ${small}px Inter, system-ui, sans-serif`; ctx.fillStyle = lensColor;
331
+ const words = lensLine.split(" · ");
332
+ for (const w of words) { ctx.fillText(fitText(w, room), h.x + pad, y); y += small * 1.4; }
333
+ y -= small * 1.4;
334
+ }
335
+ // most-used files
336
+ if (z.top.length && y + small * 7 < h.y + h.h) {
337
+ y += small * 3.2; ctx.fillStyle = C.muted; ctx.font = `600 ${small}px Inter, system-ui, sans-serif`;
338
+ ctx.fillText(fitText("MOST USED", room), h.x + pad, y);
339
+ ctx.font = `400 ${small}px JetBrains Mono, ui-monospace, monospace`; ctx.fillStyle = C.ink;
340
+ for (const f of z.top) { y += small * 1.5; ctx.fillText(fitText(`${f.id.split("/").pop()} · ${f.inn.size}`, room), h.x + pad, y); }
341
+ }
342
+ });
343
+ // hint
344
+ ctx.font = "12px Inter, system-ui, sans-serif"; ctx.fillStyle = C.muted; ctx.textAlign = "center";
345
+ const r = canvas.getBoundingClientRect();
346
+ ctx.fillText("Click a hall or zoom in to see its files", r.width / 2, Math.min(r.height - 60, bottom + 120));
347
+ ctx.textAlign = "left";
348
+ ctx.restore();
349
+ }
350
+
351
+ function draw(now) {
352
+ const r = canvas.getBoundingClientRect();
353
+ const C = { floor: css("--floor"), grid: css("--grid"), machine: css("--machine"), edge: css("--machine-edge"),
354
+ belt: css("--belt"), dot: css("--belt-dot"), back: css("--back"), ink: css("--ink"), muted: css("--muted"),
355
+ idle: css("--idle"), sel: css("--sel"), high: css("--high"), warn: css("--warn"), info: css("--info"), line: css("--line"),
356
+ panel: css("--panel"), dup: css("--dup"), slow: css("--slow"), size: css("--size") };
357
+ const lensColor = { duplication: C.dup, efficiency: C.slow, size: C.size }[lens];
358
+ const detail = detailLevel();
359
+ ctx.fillStyle = C.floor; ctx.fillRect(0, 0, r.width, r.height);
360
+ ctx.save(); ctx.translate(ox, oy); ctx.scale(scale, scale);
361
+ // floor grid
362
+ const step = 20, [x0, y0] = toWorld(0, 0), [x1, y1] = toWorld(r.width, r.height);
363
+ if (scale > 0.35) {
364
+ ctx.fillStyle = C.grid;
365
+ for (let gx = Math.floor(x0 / step) * step; gx < x1; gx += step)
366
+ for (let gy = Math.floor(y0 / step) * step; gy < y1; gy += step) ctx.fillRect(gx, gy, 1.2, 1.2);
367
+ }
368
+ // zones
369
+ for (const z of zones) {
370
+ ctx.globalAlpha = detail;
371
+ ctx.strokeStyle = C.line; ctx.lineWidth = 1.5; ctx.setLineDash([6, 6]);
372
+ ctx.strokeRect(z.x, TOP - 30, z.w, z.h); ctx.setLineDash([]);
373
+ ctx.fillStyle = C.muted; ctx.font = "600 13px Inter, system-ui, sans-serif";
374
+ ctx.fillText(`${z.name.toUpperCase()} · ${z.count}`, z.x + 10, TOP - 12);
375
+ }
376
+ const focus = hover || selected;
377
+ const linked = (b) => traced ? traced.files.has(b.src.id) && traced.files.has(b.dst.id) : !focus || b.src === focus || b.dst === focus;
378
+ // belts
379
+ for (const b of belts) {
380
+ const on = linked(b), visible = matches(b.src) || matches(b.dst);
381
+ // with no machine in focus, a big floor's belts stay faint so the machines read first
382
+ const isHot = lens === "efficiency" && hot.has(b.src.id + ">" + b.dst.id);
383
+ const rest = focus || traced ? 0.9 : belts.length > 300 ? 0.28 : 0.8;
384
+ const lensDim = lens === "issues" || isHot ? 1 : lens === "efficiency" ? 0.25 : 0.35;
385
+ ctx.globalAlpha = (!visible ? 0.06 : on ? (isHot ? 1 : rest) : 0.1) * detail * lensDim;
386
+ if (detail === 0) continue;
387
+ ctx.strokeStyle = isHot ? C.slow : b.back ? C.back : C.belt; ctx.lineWidth = isHot ? b.w + 2.5 : b.w;
388
+ ctx.setLineDash(b.back ? [8, 5] : []);
389
+ ctx.beginPath(); ctx.moveTo(...b.pts[0]); for (const p of b.pts.slice(1)) ctx.lineTo(...p); ctx.stroke();
390
+ ctx.setLineDash([]);
391
+ if (on && visible && !reduceMotion && detail > 0.5) {
392
+ ctx.fillStyle = C.dot;
393
+ for (let k = 0; k < b.dots; k++) {
394
+ const d = ((now / 1000) * 60 + (k * b.len) / b.dots) % b.len, [px, py] = pointAt(b, d);
395
+ ctx.fillRect(px - 2, py - 2, 4, 4);
396
+ }
397
+ }
398
+ }
399
+ ctx.globalAlpha = 1;
400
+ // machines
401
+ for (const f of files) {
402
+ if (f.hidden) continue;
403
+ const dim = !matches(f) || (spot ? !spot.has(f.id) : traced ? !traced.files.has(f.id) : focus && f !== focus && !focus.inn.has(f) && !focus.out.has(f));
404
+ ctx.globalAlpha = (dim ? 0.25 : 1) * (0.3 + 0.7 * detail);
405
+ const idle = f.inn.size === 0 && f.out.size === 0;
406
+ ctx.fillStyle = idle ? C.idle : C.machine; ctx.fillRect(f.x, f.y, f.s, f.s);
407
+ if (lensColor) { // heat: how much of this lens's problem the machine holds
408
+ const m = lensMetric[lens](f);
409
+ if (m > 0) {
410
+ const a0 = ctx.globalAlpha;
411
+ ctx.globalAlpha = a0 * (0.18 + 0.67 * Math.sqrt(m / lensMax[lens]));
412
+ ctx.fillStyle = lensColor; ctx.fillRect(f.x, f.y, f.s, f.s); ctx.globalAlpha = a0;
413
+ }
414
+ }
415
+ ctx.strokeStyle = f === selected ? C.sel : C.edge; ctx.lineWidth = f === selected ? 3 : 1.5;
416
+ ctx.strokeRect(f.x, f.y, f.s, f.s);
417
+ if (lens === "efficiency" && f.ioFns) { // a drum: this file talks to a database, files or the network itself
418
+ const cx = f.x + 10, cy = f.y + 10;
419
+ ctx.fillStyle = C.slow; ctx.strokeStyle = C.slow; ctx.lineWidth = 1.2;
420
+ ctx.beginPath(); ctx.ellipse(cx, cy - 3, 5, 2, 0, 0, Math.PI * 2); ctx.fill();
421
+ ctx.beginPath(); ctx.moveTo(cx - 5, cy - 3); ctx.lineTo(cx - 5, cy + 3); ctx.ellipse(cx, cy + 3, 5, 2, 0, Math.PI, 0, true);
422
+ ctx.lineTo(cx + 5, cy - 3); ctx.stroke();
423
+ }
424
+ // function bars: one tick per function, height by its size
425
+ const n = Math.min(f.fns.length, Math.floor((f.s - 10) / 4));
426
+ ctx.fillStyle = C.muted;
427
+ for (let k = 0; k < n; k++) {
428
+ const h = Math.min(f.s * 0.45, 3 + Math.sqrt(f.fns[k].loc) * 1.6);
429
+ ctx.fillRect(f.x + 6 + k * 4, f.y + f.s - 6 - h, 2.5, h);
430
+ }
431
+ // ports
432
+ ctx.fillStyle = C.edge;
433
+ if (f.inn.size) ctx.fillRect(f.x - 3, f.y + f.s / 2 - 4, 3, 8);
434
+ if (f.out.size) ctx.fillRect(f.x + f.s, f.y + f.s / 2 - 4, 3, 8);
435
+ // status light
436
+ if (f.worst) {
437
+ ctx.fillStyle = C[f.worst]; ctx.beginPath(); ctx.arc(f.x + f.s - 8, f.y + 8, 5, 0, Math.PI * 2); ctx.fill();
438
+ }
439
+ if (scale > 0.45) {
440
+ ctx.fillStyle = C.ink; ctx.font = "11px JetBrains Mono, ui-monospace, monospace";
441
+ let name = f.id.split("/").pop();
442
+ const room = f.s + PAD - 8;
443
+ while (name.length > 4 && ctx.measureText(name).width > room) name = name.slice(0, -2) + "…";
444
+ ctx.fillText(name, f.x, f.y + f.s + 14);
445
+ }
446
+ }
447
+ if (lens === "duplication" && detail > 0) { // arcs joining files that hold copies of each other's code
448
+ ctx.font = "600 11px Inter, system-ui, sans-serif"; ctx.textAlign = "center";
449
+ for (const t of twins.values()) {
450
+ if (t.a.hidden || t.b.hidden) continue;
451
+ const on = !(hover || selected || spot) || [hover, selected].includes(t.a) || [hover, selected].includes(t.b) || (spot && spot.has(t.a.id) && spot.has(t.b.id));
452
+ const x1 = t.a.x + t.a.s / 2, y1 = t.a.y + t.a.s / 2, x2 = t.b.x + t.b.s / 2, y2 = t.b.y + t.b.s / 2;
453
+ const mx = (x1 + x2) / 2, my = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, len = Math.hypot(dx, dy) || 1;
454
+ const cx = mx - (dy / len) * Math.min(160, len * 0.3), cy = my + (dx / len) * Math.min(160, len * 0.3);
455
+ ctx.globalAlpha = detail * (on ? 0.95 : 0.12);
456
+ ctx.strokeStyle = C.dup; ctx.lineWidth = 1.5 + 2.5 * t.score; ctx.setLineDash([7, 4]);
457
+ ctx.beginPath(); ctx.moveTo(x1, y1); ctx.quadraticCurveTo(cx, cy, x2, y2); ctx.stroke(); ctx.setLineDash([]);
458
+ if (on && scale > 0.3) {
459
+ const lx = 0.25 * x1 + 0.5 * cx + 0.25 * x2, ly = 0.25 * y1 + 0.5 * cy + 0.25 * y2, label = `${Math.round(t.score * 100)}%`;
460
+ const w = ctx.measureText(label).width + 8;
461
+ ctx.fillStyle = C.floor; ctx.fillRect(lx - w / 2, ly - 8, w, 16);
462
+ ctx.fillStyle = C.dup; ctx.fillText(label, lx, ly + 4);
463
+ }
464
+ }
465
+ ctx.textAlign = "left";
466
+ }
467
+ ctx.globalAlpha = 1; ctx.restore();
468
+ if (detail < 1) drawOverview(C, 1 - detail, lensColor);
469
+ requestAnimationFrame(draw);
470
+ }
471
+
472
+ // ---- input --------------------------------------------------------------------------------------------
473
+ let drag = null;
474
+ canvas.addEventListener("pointerdown", (e) => { drag = { x: e.clientX, y: e.clientY, ox, oy, moved: false }; canvas.setPointerCapture(e.pointerId); });
475
+ canvas.addEventListener("pointermove", (e) => {
476
+ const r = canvas.getBoundingClientRect();
477
+ if (drag) {
478
+ const dx = e.clientX - drag.x, dy = e.clientY - drag.y;
479
+ if (Math.abs(dx) + Math.abs(dy) > 3) { drag.moved = true; canvas.classList.add("drag"); }
480
+ ox = drag.ox + dx; oy = drag.oy + dy; return;
481
+ }
482
+ const tip = $("#tip");
483
+ if (overview()) {
484
+ hover = null;
485
+ hoverZone = zoneAt(e.clientX - r.left, e.clientY - r.top);
486
+ const z = zones[hoverZone];
487
+ if (z) {
488
+ const out = zoneLinks.filter((l) => l.a === hoverZone).reduce((t, l) => t + l.count, 0);
489
+ const inn = zoneLinks.filter((l) => l.b === hoverZone).reduce((t, l) => t + l.count, 0);
490
+ tip.innerHTML = `${esc(z.name)} · ${fmt(z.count)} files<br>${fmt(inn)} ${mode === "call" ? "calls" : "imports"} in · ${fmt(out)} out` +
491
+ `<br>${z.sev.high} high · ${z.sev.warn} warn · ${z.sev.info} info<br>click to open`;
492
+ tip.style.display = "block"; tip.style.left = e.clientX - r.left + 14 + "px"; tip.style.top = e.clientY - r.top + 14 + "px";
493
+ } else tip.style.display = "none";
494
+ return;
495
+ }
496
+ hoverZone = -1;
497
+ hover = hit(...toWorld(e.clientX - r.left, e.clientY - r.top));
498
+ if (hover) {
499
+ const lights = ["high", "warn", "info"].map((s) => [s, hover.flags.filter((f) => f.severity === s).length]).filter(([, c]) => c);
500
+ tip.innerHTML = `${esc(hover.id)}<br>${hover.loc} lines · ${hover.fns.length} functions · in ${hover.inn.size} · out ${hover.out.size}` +
501
+ (lights.length ? `<br>${lights.map(([s, c]) => `${c} ${s}`).join(" · ")}` : "");
502
+ tip.style.display = "block"; tip.style.left = e.clientX - r.left + 14 + "px"; tip.style.top = e.clientY - r.top + 14 + "px";
503
+ } else tip.style.display = "none";
504
+ });
505
+ canvas.addEventListener("pointerup", (e) => {
506
+ canvas.classList.remove("drag");
507
+ if (drag && !drag.moved) {
508
+ const r = canvas.getBoundingClientRect(), px = e.clientX - r.left, py = e.clientY - r.top;
509
+ if (overview()) { const i = zoneAt(px, py); if (i >= 0) { zoomToZone(i); hoverZone = -1; $("#tip").style.display = "none"; } }
510
+ else select(hit(...toWorld(px, py)));
511
+ }
512
+ drag = null;
513
+ });
514
+ canvas.addEventListener("pointerleave", () => { hover = null; hoverZone = -1; $("#tip").style.display = "none"; });
515
+ canvas.addEventListener("wheel", (e) => {
516
+ e.preventDefault();
517
+ const r = canvas.getBoundingClientRect(), px = e.clientX - r.left, py = e.clientY - r.top;
518
+ const k = Math.exp(-e.deltaY * 0.0015), next = Math.min(4, Math.max(0.02, scale * k));
519
+ ox = px - (px - ox) * (next / scale); oy = py - (py - oy) * (next / scale); scale = next;
520
+ }, { passive: false });
521
+ addEventListener("resize", resize);
522
+ addEventListener("keydown", (e) => { if (e.target.tagName !== "INPUT" && e.key === "f") fit(); if (e.key === "Escape") { traced = null; select(null); } });
523
+
524
+ // ---- fix prompts ---------------------------------------------------------------------------------------
525
+ // Every issue belongs to a task of `codefactory plan`; its prompt is ready to paste into Claude Code.
526
+ const taskOfFlag = new Map();
527
+ for (const t of D.tasks || []) for (const i of t.flags) taskOfFlag.set(i, t);
528
+ function copyText(text) {
529
+ const done = () => toast("Prompt copied. Paste it into Claude Code.");
530
+ if (navigator.clipboard && window.isSecureContext !== false) {
531
+ navigator.clipboard.writeText(text).then(done, () => fallback());
532
+ } else fallback();
533
+ function fallback() {
534
+ const ta = document.createElement("textarea");
535
+ ta.value = text; ta.style.position = "fixed"; ta.style.opacity = "0"; document.body.appendChild(ta); ta.select();
536
+ try { document.execCommand("copy"); done(); } catch { toast("Couldn't copy: select the prompt text instead."); }
537
+ ta.remove();
538
+ }
539
+ }
540
+ let toastTimer = 0;
541
+ function toast(msg) {
542
+ const el = $("#toast"); el.textContent = msg; el.hidden = false;
543
+ clearTimeout(toastTimer); toastTimer = setTimeout(() => { el.hidden = true; }, 2600);
544
+ }
545
+ const promptButton = (i) => taskOfFlag.has(i)
546
+ ? `<button class="fixbtn" data-fix="${i}" title="${esc(taskOfFlag.get(i).title)}">Copy fix prompt</button>` : "";
547
+ function wireFix(root) {
548
+ root.querySelectorAll("[data-fix]").forEach((b) => b.onclick = (e) => { e.stopPropagation(); copyText(taskOfFlag.get(+b.dataset.fix).prompt); });
549
+ }
550
+
551
+ // ---- panels -------------------------------------------------------------------------------------------
552
+ const KIND = { taint: "Request data in dangerous calls", custom: "Custom rules", cycle: "Import loops", layer_violation: "Layer violations", io_in_loop: "Calls in loops",
553
+ duplicate: "Duplicates", similar: "Near-duplicates", unused: "Unused", quadratic_scan: "Searches in loops",
554
+ sequential_await: "Awaits in loops", test_only: "Test only", hub: "Hubs", large_file: "Large files", long_function: "Long functions" };
555
+ const shortTarget = (t) => t.includes("::") ? t.split("::")[1] + " · " + t.split("::")[0] : t;
556
+ function renderIssues() {
557
+ const counts = {};
558
+ for (const fl of D.flags) counts[fl.kind] = (counts[fl.kind] || 0) + 1;
559
+ const kinds = Object.keys(counts).sort((a, b) => Object.keys(KIND).indexOf(a) - Object.keys(KIND).indexOf(b));
560
+ const lensSet = LENS_KINDS[lens];
561
+ const list = D.flags.filter((fl) => flagFilter ? fl.kind === flagFilter : !lensSet || lensSet.has(fl.kind)).slice(0, 400);
562
+ $("#issues").innerHTML = (kinds.length ? `<div class="chips">${kinds.map((k) =>
563
+ `<button class="chip" data-kind="${k}" aria-pressed="${flagFilter === k}">${KIND[k] || k} ${counts[k]}</button>`).join("")}</div>` :
564
+ `<p class="empty">No issues found.</p>`) +
565
+ list.map((fl) => { const i = D.flags.indexOf(fl); return `<div class="flag ${fl.severity}" tabindex="0" data-i="${i}"><b>${esc(KIND[fl.kind] || fl.kind)}</b> · ${esc(fl.message)}
566
+ <div class="where">${esc(shortTarget(fl.target))}${fl.line ? ":" + fl.line : ""}</div>${promptButton(i)}</div>`; }).join("");
567
+ wireFix($("#issues"));
568
+ $("#issues").querySelectorAll(".chip").forEach((b) => b.onclick = () => { flagFilter = flagFilter === b.dataset.kind ? null : b.dataset.kind; renderIssues(); });
569
+ $("#issues").querySelectorAll(".flag").forEach((el) => {
570
+ const go = () => {
571
+ const fl = D.flags[+el.dataset.i], f = fileOf(fl.target);
572
+ if (!f) return;
573
+ select(f); focusOn(f);
574
+ // a copy or a loop calling elsewhere: light up every file involved
575
+ if (fl.related && fl.related.length) spot = new Set([f.id, ...fl.related.map((r) => fileOf(r)?.id).filter(Boolean)]);
576
+ };
577
+ el.onclick = go; el.onkeydown = (e) => { if (e.key === "Enter") go(); };
578
+ });
579
+ }
580
+ function fnRows(f) {
581
+ return f.fns.slice().sort((a, b) => a.line - b.line).map((fn) => {
582
+ const inn = (fnCallers.get(fn.id) || []).length, out = (fnCallees.get(fn.id) || []).length;
583
+ const fl = D.flags.filter((x) => x.target === fn.id).map((x) => KIND[x.kind] || x.kind).join(", ");
584
+ return `<tr><td><span class="link" data-trace="${esc(fn.id)}" title="Trace what it calls">${esc(fn.qualname)}</span><div class="where" style="color:var(--muted)">line ${fn.line}${fl ? " · " + esc(fl) : ""}</div></td>
585
+ <td class="n">${fn.loc}</td><td class="n">${inn}</td><td class="n">${out}</td></tr>`;
586
+ }).join("");
587
+ }
588
+ function neighbours(map, label) {
589
+ const rows = [...map].sort((a, b) => b[1] - a[1]).map(([g, c]) => `<tr><td><span class="link" data-file="${esc(g.id)}">${esc(g.id)}</span></td><td class="n">${c}</td></tr>`).join("");
590
+ return `<h2>${label}</h2>` + (rows ? `<table>${rows}</table>` : `<p class="empty">None.</p>`);
591
+ }
592
+ function select(f) {
593
+ selected = f; traced = null; spot = null;
594
+ const pane = $("#selected");
595
+ pane.scrollTop = 0;
596
+ if (!f) { pane.innerHTML = `<p class="empty">Click a machine to see its functions, belts and issues.</p>`; return; }
597
+ pane.innerHTML = `<h2>Machine</h2><div style="font:13px var(--mono);word-break:break-all">${esc(f.id)}</div>
598
+ <div class="sub">layer ${esc(f.layer)} · ${f.loc} lines · ${f.fns.length} functions</div>` +
599
+ (f.flags.length ? `<h2>Issues</h2>` + f.flags.map((fl) => `<div class="flag ${fl.severity}"><b>${esc(KIND[fl.kind] || fl.kind)}</b> · ${esc(fl.message)}${promptButton(D.flags.indexOf(fl))}</div>`).join("") : "") +
600
+ `<h2>Functions</h2>` + (f.fns.length ? `<table><tr><th>Name</th><th class="n">Lines</th><th class="n">In</th><th class="n">Out</th></tr>${fnRows(f)}</table>` : `<p class="empty">None.</p>`) +
601
+ neighbours(f.inn, `Belts in (${mode === "call" ? "calls" : "imports"})`) + neighbours(f.out, `Belts out (${mode === "call" ? "calls" : "imports"})`);
602
+ pane.querySelectorAll("[data-file]").forEach((el) => el.onclick = () => { const g = fileById.get(el.dataset.file); select(g); focusOn(g); });
603
+ pane.querySelectorAll("[data-trace]").forEach((el) => el.onclick = () => showTrace(el.dataset.trace));
604
+ wireFix(pane);
605
+ tab("selected");
606
+ }
607
+ function showTrace(id) {
608
+ traced = traceFrom(id);
609
+ const t = traced, pane = $("#selected");
610
+ pane.scrollTop = 0;
611
+ fitFiles([...t.files].map((fid) => fileById.get(fid)), fileById.get(t.start.file));
612
+ pane.innerHTML = `<h2>Trace</h2><div style="font:13px var(--mono);word-break:break-all">${esc(t.start.qualname)}</div>
613
+ <div class="sub">${esc(t.start.file)}:${t.start.line}</div>
614
+ <p>Reaches <b>${t.fns.length}</b> ${t.fns.length === 1 ? "function" : "functions"} in <b>${t.files.size - 1}</b> other ${t.files.size === 2 ? "file" : "files"}, <b>${t.maxDepth}</b> ${t.maxDepth === 1 ? "call" : "calls"} deep,
615
+ <b>${t.loc}</b> lines of code.${t.loop ? ` <span style="color:var(--warn)">Calls back into itself (a call loop).</span>` : ""}</p>
616
+ <button class="chip" id="untrace">Clear trace</button>
617
+ <h2>Calls, by depth</h2>` + (t.fns.length ? `<table>${t.fns.map((x) => `<tr><td style="padding-left:${6 + (x.depth - 1) * 14}px">
618
+ <span class="link" data-trace="${esc(x.fn.id)}">${esc(x.fn.qualname)}</span>
619
+ <div style="color:var(--muted);font:11.5px var(--mono)">${esc(x.fn.file)}:${x.fn.line}</div></td>
620
+ <td class="n">${x.fn.loc}</td></tr>`).join("")}</table>` : `<p class="empty">It calls nothing the analyzer could resolve.</p>`);
621
+ pane.querySelectorAll("[data-trace]").forEach((el) => el.onclick = () => showTrace(el.dataset.trace));
622
+ $("#untrace").onclick = () => { const f = fileById.get(t.start.file); traced = null; select(f); };
623
+ tab("selected");
624
+ }
625
+ function tab(name) {
626
+ document.querySelectorAll(".tabs button").forEach((b) => b.setAttribute("aria-selected", b.dataset.tab === name));
627
+ $("#issues").hidden = name !== "issues"; $("#selected").hidden = name !== "selected";
628
+ }
629
+ document.querySelectorAll(".tabs button").forEach((b) => b.onclick = () => tab(b.dataset.tab));
630
+ document.querySelectorAll("[data-mode]").forEach((b) => b.onclick = () => {
631
+ mode = b.dataset.mode; buildBelts();
632
+ document.querySelectorAll("[data-mode]").forEach((x) => x.setAttribute("aria-pressed", x === b));
633
+ if (selected) select(selected);
634
+ });
635
+ $("#fit").onclick = fit;
636
+ const LEGEND = {
637
+ issues: $("#legend").innerHTML,
638
+ duplication: `<span><i style="background:var(--dup)"></i>tint = lines in copied functions</span><span><i style="background:var(--dup);border-radius:0"></i>dashed arc = files holding copies, with similarity</span>`,
639
+ efficiency: `<span><i style="background:var(--slow)"></i>tint = loop problems</span><span><i style="background:var(--slow);border-radius:0"></i>red belt = a loop calling into I/O</span><span>drum = does database, file or network I/O</span>`,
640
+ size: `<span><i style="background:var(--size)"></i>tint = lines of code</span>`,
641
+ };
642
+ $("#lens").onchange = (e) => {
643
+ lens = e.target.value; flagFilter = null;
644
+ zones.forEach((z, i) => { z.metric = files.filter((f) => f.zone === i).reduce((t, f) => t + lensMetric[lens](f), 0); });
645
+ $("#legend").innerHTML = LEGEND[lens];
646
+ renderIssues(); tab("issues");
647
+ };
648
+ const testsBtn = $("#tests");
649
+ testsBtn.hidden = !hasTests;
650
+ testsBtn.setAttribute("aria-pressed", showTests);
651
+ testsBtn.onclick = () => {
652
+ showTests = !showTests; testsBtn.setAttribute("aria-pressed", showTests);
653
+ if (selected && selected.layer === "tests" && !showTests) select(null);
654
+ traced = null; layout(); buildBelts(); fit();
655
+ };
656
+ $("#search").oninput = (e) => { query = e.target.value.trim().toLowerCase(); };
657
+ $("#search").onkeydown = (e) => { if (e.key === "Enter") { const f = files.find(matches); if (f) { select(f); focusOn(f); } } };
658
+
659
+ const sev = { high: 0, warn: 0, info: 0 };
660
+ for (const fl of D.flags) sev[fl.severity]++;
661
+ $("#title").textContent = D.root.split(/[\\/]/).filter(Boolean).pop() || D.root;
662
+ const quiet = (D.silenced || []).length;
663
+ $("#meta").textContent = `${D.language} · ${files.length} files · ${D.functions.filter((f) => f.kind !== "module").length} functions · ${sev.high} high · ${sev.warn} warn · ${sev.info} info${quiet ? ` · ${quiet} silenced` : ""}`;
664
+ resize(); fit(); renderIssues(); select(null); tab("issues"); requestAnimationFrame(draw);
665
+ })();