@draht/coding-agent 2026.11.18-1 → 2026.11.19-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/bin/draht-kg.cjs +4782 -0
  3. package/bin/draht-tools.cjs +747 -47
  4. package/dist/bundle/chunks/{anthropic-messages-AFT3AY2S.js → anthropic-messages-7PTOA4ZA.js} +1 -1
  5. package/dist/bundle/chunks/{azure-openai-responses-A52AJ5P5.js → azure-openai-responses-CDW6FCMN.js} +1 -1
  6. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  7. package/dist/bundle/chunks/{chunk-5PDANNKW.js → chunk-3F4OOENR.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-YFDWS2SA.js → chunk-7HQNDYWE.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-TUIWJI22.js → chunk-B6OJ7QX4.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-2XOICIOV.js → chunk-BIXKXDGW.js} +1 -1
  11. package/dist/bundle/chunks/{chunk-JMYX7QEX.js → chunk-BQMYLQSG.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-ACQFXG5D.js → chunk-HKQ3PU5T.js} +1 -1
  13. package/dist/bundle/chunks/{chunk-HTSLUWLE.js → chunk-INKDO5TZ.js} +3 -3
  14. package/dist/bundle/chunks/{chunk-CXCOVS2M.js → chunk-JI5YDTBB.js} +1 -1
  15. package/dist/bundle/chunks/{chunk-6EVZEBYO.js → chunk-MHNW355A.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-CP35SXCN.js → chunk-WOIC265R.js} +7 -4
  17. package/dist/bundle/chunks/{chunk-LKMWSNTE.js → chunk-YOPX5URH.js} +1 -1
  18. package/dist/bundle/chunks/{cli-L6U4GJHK.js → cli-QUYXUKRF.js} +1 -1
  19. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-KYAP5L2X.js → cloudflare-workers-ai-system-one-W63EWPDW.js} +1 -1
  20. package/dist/bundle/chunks/{google-generative-ai-WR6OZ27M.js → google-generative-ai-M5WKK5CW.js} +1 -1
  21. package/dist/bundle/chunks/{google-vertex-FUYYVM54.js → google-vertex-UYNOGPMI.js} +1 -1
  22. package/dist/bundle/chunks/{llama-cpp-classify-6LLMLBUC.js → llama-cpp-classify-SAUGLDPT.js} +1 -1
  23. package/dist/bundle/chunks/{mistral-conversations-WVGS4PN2.js → mistral-conversations-VQ3J6W5K.js} +1 -1
  24. package/dist/bundle/chunks/{openai-codex-responses-CTLT3QUI.js → openai-codex-responses-JTGQLYC7.js} +1 -1
  25. package/dist/bundle/chunks/{openai-completions-V37FD5ZZ.js → openai-completions-WAW7BG4E.js} +1 -1
  26. package/dist/bundle/chunks/{openai-decisions-WTY6DQT4.js → openai-decisions-KHHHHMGW.js} +1 -1
  27. package/dist/bundle/chunks/{openai-responses-R7W5BVUV.js → openai-responses-GWADST54.js} +1 -1
  28. package/dist/bundle/chunks/{openrouter-images-7GGRYAYP.js → openrouter-images-AP626CWG.js} +1 -1
  29. package/dist/bundle/chunks/{pi-messages-O7OXMCNL.js → pi-messages-H5TYIEJT.js} +1 -1
  30. package/dist/bundle/chunks/{typesafe-system-one-FGISCLX2.js → typesafe-system-one-RLPGOT75.js} +1 -1
  31. package/dist/bundle/chunks/{virtual-modules-JL2BFG57.js → virtual-modules-5V4G5GQH.js} +1 -1
  32. package/dist/bundle/cli-runtime.js +1 -1
  33. package/dist/bundle/index.js +1 -1
  34. package/dist/bundle/rpc-entry.js +1 -1
  35. package/dist/cli/args.d.ts.map +1 -1
  36. package/dist/cli/args.js +3 -0
  37. package/dist/cli/args.js.map +1 -1
  38. package/dist/prompts/commands/map-codebase.md +3 -1
  39. package/docs/environment-variables.md +2 -0
  40. package/package.json +9 -9
  41. package/prompts/commands/map-codebase.md +3 -1
@@ -1345,8 +1345,11 @@ function visParseImports(content, language) {
1345
1345
  while ((m = reqRe.exec(content)) !== null) {
1346
1346
  out.push({ specifier: m[1], default: null, namespace: null, names: [] });
1347
1347
  }
1348
- // re-exports: export { foo } from "./x"
1349
- const reExportRe = /export\s+\{([^}]+)\}\s+from\s+["']([^"']+)["']/g;
1348
+ // re-exports: export { foo } from "./x" | export type { Foo } from "./x"
1349
+ // (per-specifier `export { type Foo }` is stripped in the map below). Without the optional
1350
+ // `type`, a type-only re-export got no link, fell back to its barrel as origin, and made a
1351
+ // sibling `export *` of the real definer look like a clash.
1352
+ const reExportRe = /export\s+(?:type\s+)?\{([^}]+)\}\s+from\s+["']([^"']+)["']/g;
1350
1353
  while ((m = reExportRe.exec(content)) !== null) {
1351
1354
  const names = m[1].split(",").map((s) => {
1352
1355
  const t = s.trim().replace(/^type\s+/, "");
@@ -1359,7 +1362,9 @@ function visParseImports(content, language) {
1359
1362
  // star re-exports: export * from "./x" or export * as Foo from "./x"
1360
1363
  const starReExportRe = /export\s+\*(?:\s+as\s+([A-Za-z_$][\w$]*))?\s+from\s+["']([^"']+)["']/g;
1361
1364
  while ((m = starReExportRe.exec(content)) !== null) {
1362
- out.push({ specifier: m[2], default: null, namespace: m[1] || "*", names: [], reExport: true });
1365
+ let line = 1;
1366
+ for (let i = 0; i < m.index; i++) if (content.charCodeAt(i) === 10) line++;
1367
+ out.push({ specifier: m[2], default: null, namespace: m[1] || "*", names: [], reExport: true, line });
1363
1368
  }
1364
1369
  return out;
1365
1370
  }
@@ -1388,6 +1393,132 @@ function visExtractRawImports(content, language) {
1388
1393
  return imports;
1389
1394
  }
1390
1395
 
1396
+ // A regex literal longer than this is not treated as one (see visMaskNonCode).
1397
+ const VIS_REGEX_SCAN_LIMIT = 4096;
1398
+ // Keywords after which a `/` starts a regex literal rather than a division.
1399
+ const VIS_REGEX_AFTER_KEYWORDS = new Set([
1400
+ "return", "typeof", "instanceof", "in", "of", "new", "delete", "void", "throw", "case", "do", "else", "yield", "await",
1401
+ ]);
1402
+
1403
+ // Single-pass, length- and newline-preserving masker for JS/TS source: comments are blanked
1404
+ // entirely, string and regex-literal contents are blanked with their delimiters kept, and
1405
+ // template literals keep their `${ … }` expression code (nested) while the literal text is
1406
+ // blanked. Content-level pattern passes (named export lists, `export * as`) run on the result so
1407
+ // that neither a commented-out example nor an export list inside a string can become a fake
1408
+ // export — and a `/*` inside a string (`"packages/*/src"`) can no longer swallow real code up to
1409
+ // the next `*/`. Only "\n" is preserved: line numbers are derived by splitting on it.
1410
+ // Lockstep with Go parse.MaskNonCode — change both together.
1411
+ function visMaskNonCode(src) {
1412
+ const n = src.length;
1413
+ const parts = [];
1414
+ let keep = 0; // start of the pending unmasked run
1415
+ const mask = (a, b) => {
1416
+ if (b <= a) return;
1417
+ if (a > keep) parts.push(src.slice(keep, a));
1418
+ parts.push(src.slice(a, b).replace(/[^\n]/g, " "));
1419
+ keep = b;
1420
+ };
1421
+ const isWordChar = (c) => (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 95 || c === 36 || c >= 128;
1422
+ const exprDepth = []; // open `${` expressions: brace depth inside each
1423
+ let inTemplate = false;
1424
+ let regexOk = true; // may an expression (hence a regex literal) start here?
1425
+ let i = 0;
1426
+ while (i < n) {
1427
+ if (inTemplate) {
1428
+ const start = i;
1429
+ while (i < n) {
1430
+ const c = src.charCodeAt(i);
1431
+ if (c === 92) { i += 2; continue; } // backslash escape
1432
+ if (c === 96 || (c === 36 && src.charCodeAt(i + 1) === 123)) break; // ` or ${
1433
+ i++;
1434
+ }
1435
+ if (i > n) i = n;
1436
+ mask(start, i);
1437
+ if (i >= n) break;
1438
+ inTemplate = false;
1439
+ if (src.charCodeAt(i) === 96) { i++; regexOk = false; } else { i += 2; exprDepth.push(0); regexOk = true; }
1440
+ continue;
1441
+ }
1442
+ const c = src.charCodeAt(i);
1443
+ if (c === 47) { // /
1444
+ const next = src.charCodeAt(i + 1);
1445
+ if (next === 47) { // line comment
1446
+ let j = src.indexOf("\n", i);
1447
+ if (j < 0) j = n;
1448
+ mask(i, j);
1449
+ i = j;
1450
+ continue;
1451
+ }
1452
+ if (next === 42) { // block comment
1453
+ const j = src.indexOf("*/", i + 2);
1454
+ const end = j < 0 ? n : j + 2;
1455
+ mask(i, end);
1456
+ i = end;
1457
+ continue;
1458
+ }
1459
+ if (regexOk) {
1460
+ // A regex literal never spans lines; `/` inside a [...] class does not end it. The scan is
1461
+ // bounded so a stray `/` in a huge minified line cannot make masking quadratic.
1462
+ let k = i + 1, inClass = false, close = -1;
1463
+ for (; k < n && k - i <= VIS_REGEX_SCAN_LIMIT; k++) {
1464
+ const d = src.charCodeAt(k);
1465
+ if (d === 10) break;
1466
+ if (d === 92) { k++; continue; }
1467
+ if (d === 91) inClass = true;
1468
+ else if (d === 93) inClass = false;
1469
+ else if (d === 47 && !inClass) { close = k; break; }
1470
+ }
1471
+ if (close >= 0) {
1472
+ mask(i + 1, close);
1473
+ i = close + 1;
1474
+ while (i < n && isWordChar(src.charCodeAt(i))) i++; // flags
1475
+ regexOk = false;
1476
+ continue;
1477
+ }
1478
+ }
1479
+ i++;
1480
+ regexOk = true;
1481
+ continue;
1482
+ }
1483
+ if (c === 39 || c === 34) { // ' or " — unterminated strings end at the line break
1484
+ let k = i + 1;
1485
+ while (k < n) {
1486
+ const d = src.charCodeAt(k);
1487
+ if (d === c || d === 10) break;
1488
+ k += d === 92 ? 2 : 1;
1489
+ }
1490
+ if (k > n) k = n;
1491
+ mask(i + 1, k);
1492
+ i = k < n && src.charCodeAt(k) === c ? k + 1 : k;
1493
+ regexOk = false;
1494
+ continue;
1495
+ }
1496
+ if (c === 96) { i++; inTemplate = true; continue; } // `
1497
+ if (c === 123) { if (exprDepth.length) exprDepth[exprDepth.length - 1]++; i++; regexOk = true; continue; } // {
1498
+ if (c === 125) { // }
1499
+ i++;
1500
+ if (exprDepth.length) {
1501
+ if (exprDepth[exprDepth.length - 1] === 0) { exprDepth.pop(); inTemplate = true; continue; }
1502
+ exprDepth[exprDepth.length - 1]--;
1503
+ }
1504
+ regexOk = true;
1505
+ continue;
1506
+ }
1507
+ if (isWordChar(c)) {
1508
+ const start = i;
1509
+ while (i < n && isWordChar(src.charCodeAt(i))) i++;
1510
+ regexOk = VIS_REGEX_AFTER_KEYWORDS.has(src.slice(start, i));
1511
+ continue;
1512
+ }
1513
+ if (c === 41 || c === 93) { i++; regexOk = false; continue; } // ) ]
1514
+ if (c !== 32 && c !== 9 && c !== 10 && c !== 13) regexOk = true;
1515
+ i++;
1516
+ }
1517
+ if (keep === 0) return src;
1518
+ if (keep < n) parts.push(src.slice(keep));
1519
+ return parts.join("");
1520
+ }
1521
+
1391
1522
  // Extract exports — distinguish exported names so we can build a real call graph
1392
1523
  function visExtractExports(rawContent, language) {
1393
1524
  const out = [];
@@ -1425,20 +1556,19 @@ function visExtractExports(rawContent, language) {
1425
1556
  };
1426
1557
 
1427
1558
  if (language === "typescript" || language === "javascript") {
1428
- const exportRe = /^\s*export\s+(?:default\s+)?(?:async\s+)?(class|interface|type|function|const|let|enum|var)\s+([A-Za-z_$][\w$]*)/;
1429
- const namedExportRe = /^\s*export\s*\{([^}]+)\}(?!\s+from)/;
1559
+ const exportRe = /^\s*export\s+(default\s+)?(?:async\s+)?(class|interface|type|function|const|let|enum|var)\s+([A-Za-z_$][\w$]*)/;
1430
1560
  const defaultRe = /^\s*export\s+default\s/;
1431
1561
  const commandRe = /^\s*commands\s*\[\s*["']([^"']+)["']\s*\]\s*=/;
1432
1562
  for (let i = 0; i < lines.length; i++) {
1433
1563
  let m;
1434
1564
  if ((m = exportRe.exec(lines[i]))) {
1435
- out.push({ name: m[2], kind: m[1], line: i + 1, doc: findLeadingDoc(i) });
1436
- } else if ((m = namedExportRe.exec(lines[i]))) {
1437
- const doc = findLeadingDoc(i);
1438
- for (const part of m[1].split(",")) {
1439
- const t = part.trim().replace(/^type\s+/, "");
1440
- const asMatch = t.match(/^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/);
1441
- if (asMatch) out.push({ name: asMatch[2] || asMatch[1], kind: "named", line: i + 1, doc });
1565
+ // `export default class Widget {}` exports ONLY `default` — the
1566
+ // name binds locally, never as an exported binding (ES spec), so
1567
+ // star expansion must not forward it under its local name.
1568
+ if (m[1]) {
1569
+ if (!out.some((e) => e.name === "default")) out.push({ name: "default", kind: "default", line: i + 1, doc: findLeadingDoc(i) });
1570
+ } else {
1571
+ out.push({ name: m[3], kind: m[2], line: i + 1, doc: findLeadingDoc(i) });
1442
1572
  }
1443
1573
  } else if (defaultRe.test(lines[i]) && !out.some((e) => e.name === "default")) {
1444
1574
  out.push({ name: "default", kind: "default", line: i + 1, doc: findLeadingDoc(i) });
@@ -1447,6 +1577,49 @@ function visExtractExports(rawContent, language) {
1447
1577
  }
1448
1578
  if (out.length > 200) break;
1449
1579
  }
1580
+ // Named export lists — content-level so multi-line `export {\n a,\n b\n}` blocks (with or
1581
+ // without `from`) are captured. Barrels are pure re-export lists; without this every
1582
+ // package index.ts reports exports(0) and its public API is invisible to graph-query.
1583
+ const lineOf = (charIdx) => {
1584
+ let pos = 0;
1585
+ for (let i = 0; i < lines.length; i++) {
1586
+ if (pos + lines[i].length + 1 > charIdx) return i + 1;
1587
+ pos += lines[i].length + 1;
1588
+ }
1589
+ return lines.length;
1590
+ };
1591
+ // The content-level passes match against a comment- and string-MASKED copy
1592
+ // (see visMaskNonCode; offsets and lines still map to the raw source): a
1593
+ // commented-out `// export { Admin } from "./x"` example, or an export list
1594
+ // inside a string/template literal, must not become a public export.
1595
+ // Docs still read from the raw lines.
1596
+ const maskedContent = visMaskNonCode(rawContent);
1597
+ const namedBlockRe = /export\s+(?:type\s+)?\{([^}]*)\}(\s*from\s*["'][^"']+["'])?/g;
1598
+ let nb;
1599
+ while ((nb = namedBlockRe.exec(maskedContent)) !== null && out.length <= 200) {
1600
+ const isReExport = Boolean(nb[2]);
1601
+ const line = lineOf(nb.index);
1602
+ const doc = findLeadingDoc(line - 1);
1603
+ for (const part of nb[1].split(",")) {
1604
+ const t = part.trim().replace(/^type\s+/, "");
1605
+ if (!t) continue;
1606
+ const asMatch = t.match(/^([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?$/);
1607
+ if (asMatch) {
1608
+ const entry = { name: asMatch[2] || asMatch[1], kind: isReExport ? "re-export" : "named", line, doc };
1609
+ // A LOCAL alias (`export { a as b }`, no `from`) exposes one binding
1610
+ // under two names: keep the local name so origin keys compare the
1611
+ // BINDING (`b` ≡ `a`), not the export name.
1612
+ if (!isReExport && asMatch[2] && asMatch[2] !== asMatch[1]) entry.viaName = asMatch[1];
1613
+ out.push(entry);
1614
+ }
1615
+ }
1616
+ }
1617
+ // `export * as NS from "./x"` exposes NS as a named export of this module.
1618
+ const starAsRe = /export\s+\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s*["'][^"']+["']/g;
1619
+ let sa;
1620
+ while ((sa = starAsRe.exec(maskedContent)) !== null && out.length <= 200) {
1621
+ out.push({ name: sa[1], kind: "re-export", line: lineOf(sa.index), doc: null });
1622
+ }
1450
1623
  } else if (language === "python") {
1451
1624
  const re = /^(class|def)\s+([A-Za-z_][A-Za-z0-9_]*)/;
1452
1625
  for (let i = 0; i < lines.length; i++) {
@@ -1833,6 +2006,10 @@ function visBuildSymbols(exportsArr, content, language) {
1833
2006
  };
1834
2007
  if (language === "typescript" || language === "javascript") {
1835
2008
  addDecl(/^(?:async\s+)?(?:function|class)\s+([A-Za-z_$][\w$]*)|^(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/, (l) => /^\s*(?:async\s+)?class\b/.test(l) ? "class" : /^\s*(?:async\s+)?function\b/.test(l) ? "function" : "const");
2009
+ // `export default class Widget {}` exports only `default`; the name binds
2010
+ // locally. Record it as a non-exported symbol so search still finds the
2011
+ // defining file by its real name.
2012
+ if (syms.length < 60) addDecl(/^export\s+default\s+(?:async\s+)?(?:function(?:\s*\*\s*|\s+)|(?:abstract\s+)?class\s+)([A-Za-z_$][\w$]*)/, (l) => /\bclass\b/.test(l) ? "class" : "function");
1836
2013
  } else if (language === "python") {
1837
2014
  addDecl(/^(?:class|def)\s+([A-Za-z_][\w]*)/, (l) => /^class\b/.test(l) ? "class" : "def");
1838
2015
  } else if (language === "go") {
@@ -1987,6 +2164,22 @@ function visComputeClusters(modules, edges, moduleByRel, containerOf) {
1987
2164
  const fallbackOrdinal = new Map();
1988
2165
  const clusters = [];
1989
2166
  const clusterOf = new Map();
2167
+ const packageKeyOf = (m) => m.package || containerOf(m).replace(/^(pkg|dir):/, "");
2168
+ // Container directories: top-level dirs holding modules of two or more packages (`packages/`,
2169
+ // `apps/` style parents). Only these are renamed after their package below; a plain root dir
2170
+ // (`src`, `scripts`) is the most informative label there is.
2171
+ const containerDirs = new Set();
2172
+ {
2173
+ const packagesByTopDir = new Map();
2174
+ for (const m of modules) {
2175
+ const slash = m.path.indexOf("/");
2176
+ if (slash < 0) continue;
2177
+ const top = m.path.slice(0, slash);
2178
+ if (!packagesByTopDir.has(top)) packagesByTopDir.set(top, new Set());
2179
+ packagesByTopDir.get(top).add(packageKeyOf(m));
2180
+ }
2181
+ for (const [top, keys] of packagesByTopDir) if (keys.size > 1) containerDirs.add(top);
2182
+ }
1990
2183
  const sortedGroups = finalGroups
1991
2184
  .map((members) => members.slice().sort())
1992
2185
  .sort((a, b) => b.length - a.length || (a[0] < b[0] ? -1 : 1));
@@ -1994,7 +2187,7 @@ function visComputeClusters(modules, edges, moduleByRel, containerOf) {
1994
2187
  const pkgCount = {}, layerCount = {};
1995
2188
  for (const id of sorted) {
1996
2189
  const m = moduleByRel.get(id);
1997
- const p = m.package || containerOf(m).replace(/^(pkg|dir):/, "");
2190
+ const p = packageKeyOf(m);
1998
2191
  pkgCount[p] = (pkgCount[p] || 0) + 1;
1999
2192
  layerCount[m.layer] = (layerCount[m.layer] || 0) + 1;
2000
2193
  }
@@ -2007,6 +2200,10 @@ function visComputeClusters(modules, edges, moduleByRel, containerOf) {
2007
2200
  if (prefix) {
2008
2201
  cid = "cluster:" + prefix;
2009
2202
  clabel = prefix.split("/").slice(-2).join("/");
2203
+ // A bare container dir ("packages") says nothing — prefer the package name when unambiguous.
2204
+ if (!prefix.includes("/") && containerDirs.has(prefix) && dominantPackage && packages.length === 1) {
2205
+ clabel = String(dominantPackage).replace(/^@[^/]+\//, "");
2206
+ }
2010
2207
  } else {
2011
2208
  const base = "cluster:" + (dominantPackage || "root");
2012
2209
  const n = (fallbackOrdinal.get(base) || 0) + 1;
@@ -2025,6 +2222,29 @@ function visComputeClusters(modules, edges, moduleByRel, containerOf) {
2025
2222
  clusters.push({ id: cid, label: clabel, size: sorted.length, members: sorted, dominantPackage, dominantLayer, packages });
2026
2223
  }
2027
2224
  clusters.sort((a, b) => b.size - a.size || (a.id < b.id ? -1 : 1));
2225
+ // Disambiguate duplicate labels: recursive splitting of oversized communities yields several
2226
+ // groups sharing one directory prefix, so graph-clusters printed six indistinguishable
2227
+ // "packages/ai" rows. Append the dominant layer, then a stable ordinal. Iteration order is
2228
+ // the sorted clusters array, so the suffixes are deterministic across rebuilds.
2229
+ {
2230
+ const dupes = new Set();
2231
+ const seenOnce = new Set();
2232
+ for (const c of clusters) {
2233
+ if (seenOnce.has(c.label)) dupes.add(c.label);
2234
+ seenOnce.add(c.label);
2235
+ }
2236
+ const used = new Set();
2237
+ for (const c of clusters) {
2238
+ let label = dupes.has(c.label) ? c.label + " · " + c.dominantLayer : c.label;
2239
+ if (used.has(label)) {
2240
+ let n = 2;
2241
+ while (used.has(label + " · " + n)) n++;
2242
+ label = label + " · " + n;
2243
+ }
2244
+ used.add(label);
2245
+ c.label = label;
2246
+ }
2247
+ }
2028
2248
  return { clusters, clusterOf };
2029
2249
  }
2030
2250
 
@@ -2060,7 +2280,7 @@ function visComputeSurprising(edges, callEdges, moduleByRel, clusterOf, groupOfC
2060
2280
  if (score <= 0) continue;
2061
2281
  out.push({ from: e.from, to: e.to, score, reason: reasons.join(", "), sampleSymbols: callSym.get(e.from + "|" + e.to) || [] });
2062
2282
  }
2063
- out.sort((x, y) => y.score - x.score || (x.from < y.from ? -1 : x.from > y.from ? 1 : 0));
2283
+ out.sort((x, y) => y.score - x.score || (x.from < y.from ? -1 : x.from > y.from ? 1 : 0) || (x.to < y.to ? -1 : x.to > y.to ? 1 : 0));
2064
2284
  return out.slice(0, 20);
2065
2285
  }
2066
2286
 
@@ -2144,11 +2364,19 @@ function visBuildMap(root) {
2144
2364
  loc = content.split("\n").length;
2145
2365
  if (VIS_CODE_LANGS.has(lang)) {
2146
2366
  totalLoc.value += loc; // WP2: LOC rollup tracks code modules only, matching stats.files
2147
- // Use raw content for export/JSDoc extraction (need comments) and stripped for sink/import detection
2367
+ // Use raw content for export/JSDoc extraction (need comments) and stripped for sink/import detection.
2148
2368
  const stripped = content
2149
2369
  .replace(/\/\*[\s\S]*?\*\//g, "")
2150
2370
  .replace(/(^|[^:])\/\/.*$/gm, "$1");
2151
- parsedImports = visParseImports(stripped, lang);
2371
+ // Import parsing gets a NEWLINE-PRESERVING strip so Import line numbers
2372
+ // (star re-export expansion feeds them into exports/symbols) stay aligned
2373
+ // with the raw source even when a multiline block comment precedes the
2374
+ // statement. Sinks/routes keep the fully-deleting strip (lockstep with
2375
+ // the Go engine's StripComments / StripCommentsPreserveLines pair).
2376
+ const importStripped = content
2377
+ .replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ""))
2378
+ .replace(/(^|[^:])\/\/.*$/gm, "$1");
2379
+ parsedImports = visParseImports(importStripped, lang);
2152
2380
  exports = visExtractExports(content, lang);
2153
2381
  sinks = visDetectSinks(stripped);
2154
2382
  sinkSites = visFindSinkSites(content, lang);
@@ -2181,7 +2409,7 @@ function visBuildMap(root) {
2181
2409
  loc,
2182
2410
  isTest,
2183
2411
  package: pkg,
2184
- exports: exports.slice(0, 30),
2412
+ exports: exports.slice(0, 60),
2185
2413
  symbols,
2186
2414
  sinks,
2187
2415
  sinkSites: sinkSites.slice(0, 10),
@@ -2255,6 +2483,10 @@ function visBuildMap(root) {
2255
2483
  } catch { /* empty */ }
2256
2484
  }
2257
2485
 
2486
+ const starReExports = new Map(); // barrel module id -> [{ target, line }] for `export * from`
2487
+ const namedReExports = new Map(); // module id -> Map(exported name -> { target, imported }) for `export { x } from`
2488
+ const importedLocals = new Map(); // module id -> Map(local name -> { resolved, importedName }) for plain imports
2489
+
2258
2490
  const resolveSpec = (fromDir, spec) => {
2259
2491
  // Relative path
2260
2492
  if (spec.startsWith(".") || spec.startsWith("/")) {
@@ -2301,13 +2533,26 @@ function visBuildMap(root) {
2301
2533
  edges.push({ from: m.id, to: resolved, kind: imp.reExport ? "re-export" : "import", confidence: "EXTRACTED" });
2302
2534
  // Re-exports don't introduce local usage — they pass the symbol through to the
2303
2535
  // importer of THIS module. We capture them separately for re-export traversal in flow BFS.
2304
- if (imp.reExport) continue;
2536
+ if (imp.reExport) {
2537
+ if (imp.namespace === "*") {
2538
+ if (!starReExports.has(m.id)) starReExports.set(m.id, []);
2539
+ starReExports.get(m.id).push({ target: resolved, line: imp.line || 1 });
2540
+ } else if (!imp.namespace) {
2541
+ if (!namedReExports.has(m.id)) namedReExports.set(m.id, new Map());
2542
+ const links = namedReExports.get(m.id);
2543
+ for (const n of imp.names || []) {
2544
+ if (!links.has(n.local)) links.set(n.local, { target: resolved, imported: n.imported });
2545
+ }
2546
+ }
2547
+ continue;
2548
+ }
2305
2549
  if (imp.default) usedLocals.set(imp.default, { resolved, importedName: "default" });
2306
2550
  if (imp.namespace) usedLocals.set(imp.namespace, { resolved, importedName: "*" });
2307
2551
  for (const n of imp.names || []) {
2308
2552
  usedLocals.set(n.local, { resolved, importedName: n.imported });
2309
2553
  }
2310
2554
  }
2555
+ importedLocals.set(m.id, usedLocals);
2311
2556
  // For each imported local, scan for call sites: `localName(` or `localName.x(` (member call)
2312
2557
  if (usedLocals.size > 0) {
2313
2558
  const text = file.content || "";
@@ -2327,6 +2572,233 @@ function visBuildMap(root) {
2327
2572
  }
2328
2573
  }
2329
2574
 
2575
+ // Re-export resolution. The ORIGIN of a module's export `name` is the binding that ultimately
2576
+ // DEFINES it: { mod, name there }. Same-binding routes are ONE export (a barrel starring both the
2577
+ // definer and a named re-exporter of the same binding keeps the name; a local alias
2578
+ // `export { a as b }` stands for the binding `a`). Everything is computed from the modules' OWN
2579
+ // declared exports (snapshotted below, before any star copy exists), so the answer is a pure
2580
+ // function of the module graph and never depends on file names or iteration order:
2581
+ // - an own export (local, alias, `export * as NS`) is its own binding, unless it exports a
2582
+ // name the module imported (`import { x } from './y'; export { x }`): that is y's binding; a named re-export
2583
+ // (`export { x } from './y'`) takes the binding resolved at its target, and a target that
2584
+ // never exports the name (CommonJS: no extracted exports) is itself the origin;
2585
+ // - otherwise `export *` resolves the name at every star target (never `default`): one distinct
2586
+ // binding → exported; several → ambiguous, NOT exported (ES ResolveExport);
2587
+ // - ambiguity propagates (ES ResolveExport step "if resolution is ambiguous, return ambiguous"):
2588
+ // a barrel starring a target where the name is ambiguous does not export it either, however
2589
+ // its other targets resolve; a target where the name is merely absent contributes nothing;
2590
+ // - modules that only reach a name through each other (a cycle) resolve it to the same thing,
2591
+ // from what enters the cycle from outside, never from a stale half-computed state.
2592
+ // Resolution runs Tarjan over lazily discovered (module, name) nodes: every strongly connected
2593
+ // component is closed once and its status is final, so work stays polynomial even on dense
2594
+ // barrel cycles. Lockstep with Go graph.exportResolver — change both together.
2595
+ const baseExports = new Map(modules.map((m) => [m.id, new Map(m.exports.map((e) => [e.name, e]))]));
2596
+ const AMBIGUOUS = { ambiguous: true };
2597
+ const exportKey = (modId, name) => modId + "\u0000" + name;
2598
+ const sameBinding = (a, b) => a.mod === b.mod && a.name === b.name;
2599
+ const describeExport = (mod, name) => {
2600
+ const own = baseExports.get(mod.id).get(name);
2601
+ if (own) {
2602
+ const link = own.kind === "re-export" && namedReExports.has(mod.id) ? namedReExports.get(mod.id).get(name) : null;
2603
+ const target = link ? moduleByRel.get(link.target) : null;
2604
+ if (!target) {
2605
+ // `import { foo } from './x'; export { foo }` exports x's binding, not a new one:
2606
+ // a barrel starring both files reaches ONE `foo`, not an ambiguous pair.
2607
+ const binding = own.viaName || name;
2608
+ const imported = own.kind === "named" && importedLocals.has(mod.id) ? importedLocals.get(mod.id).get(binding) : null;
2609
+ const source = imported && imported.importedName !== "*" ? moduleByRel.get(imported.resolved) : null;
2610
+ if (source && source !== mod) return { named: true, edges: [{ mod: source, name: imported.importedName }] };
2611
+ return { terminal: { mod: mod.id, name: binding }, edges: [] };
2612
+ }
2613
+ return { named: true, edges: [{ mod: target, name: link.imported }] };
2614
+ }
2615
+ const edges = [];
2616
+ if (name !== "default") { // a bare `export *` never forwards default (ES spec)
2617
+ for (const star of starReExports.get(mod.id) || []) {
2618
+ const target = moduleByRel.get(star.target);
2619
+ if (target) edges.push({ mod: target, name });
2620
+ }
2621
+ }
2622
+ return { edges };
2623
+ };
2624
+ const resolvedExport = new Map(); // exportKey -> null (not exported) | AMBIGUOUS | { mod, name }
2625
+ const tarjanIndex = new Map();
2626
+ const tarjanLow = new Map();
2627
+ const tarjanNodes = new Map();
2628
+ const tarjanStack = [];
2629
+ let tarjanCounter = 0;
2630
+ // Closes the strongly connected component rooted at `key`: every member gets the same final status.
2631
+ const closeComponent = (key) => {
2632
+ const members = new Set();
2633
+ for (;;) {
2634
+ const k = tarjanStack.pop();
2635
+ members.add(k);
2636
+ if (k === key) break;
2637
+ }
2638
+ const found = [];
2639
+ let ambiguous = false;
2640
+ const add = (b) => { if (!found.some((f) => sameBinding(f, b))) found.push(b); };
2641
+ for (const k of members) {
2642
+ const member = tarjanNodes.get(k);
2643
+ if (member.terminal) add(member.terminal);
2644
+ for (const edge of member.edges) {
2645
+ const childKey = exportKey(edge.mod.id, edge.name);
2646
+ if (members.has(childKey)) continue;
2647
+ const child = resolvedExport.get(childKey);
2648
+ if (child === AMBIGUOUS) ambiguous = true;
2649
+ else if (child) add(child);
2650
+ else if (member.named) add({ mod: edge.mod.id, name: edge.name });
2651
+ }
2652
+ }
2653
+ const status = ambiguous || found.length > 1 ? AMBIGUOUS : found.length === 1 ? found[0] : null;
2654
+ for (const k of members) { resolvedExport.set(k, status); tarjanNodes.delete(k); }
2655
+ };
2656
+ // Iterative (explicit frame stack): barrel chains can be thousands deep.
2657
+ const strongConnect = (rootMod, rootName, rootKey) => {
2658
+ const frames = [];
2659
+ const open = (mod, name, key) => {
2660
+ tarjanNodes.set(key, describeExport(mod, name));
2661
+ tarjanIndex.set(key, tarjanCounter);
2662
+ tarjanLow.set(key, tarjanCounter);
2663
+ tarjanCounter++;
2664
+ tarjanStack.push(key);
2665
+ frames.push({ key, edges: tarjanNodes.get(key).edges, i: 0 });
2666
+ };
2667
+ open(rootMod, rootName, rootKey);
2668
+ while (frames.length) {
2669
+ const frame = frames[frames.length - 1];
2670
+ if (frame.i < frame.edges.length) {
2671
+ const edge = frame.edges[frame.i++];
2672
+ const childKey = exportKey(edge.mod.id, edge.name);
2673
+ if (resolvedExport.has(childKey)) continue;
2674
+ if (!tarjanIndex.has(childKey)) open(edge.mod, edge.name, childKey);
2675
+ else tarjanLow.set(frame.key, Math.min(tarjanLow.get(frame.key), tarjanIndex.get(childKey)));
2676
+ continue;
2677
+ }
2678
+ frames.pop();
2679
+ if (tarjanLow.get(frame.key) === tarjanIndex.get(frame.key)) closeComponent(frame.key);
2680
+ if (frames.length) {
2681
+ const parent = frames[frames.length - 1];
2682
+ tarjanLow.set(parent.key, Math.min(tarjanLow.get(parent.key), tarjanLow.get(frame.key)));
2683
+ }
2684
+ }
2685
+ };
2686
+ const resolveExport = (mod, name) => {
2687
+ const key = exportKey(mod.id, name);
2688
+ if (!resolvedExport.has(key)) strongConnect(mod, name, key);
2689
+ return resolvedExport.get(key);
2690
+ };
2691
+ const isBinding = (r) => r !== null && r !== AMBIGUOUS;
2692
+ // ES GetExportedNames: the module's own names, then every star target's (depth-first in source
2693
+ // order, each module once), never `default` through a star; first occurrence wins.
2694
+ const exportedNames = (root) => {
2695
+ const names = [];
2696
+ const seen = new Set();
2697
+ const visited = new Set();
2698
+ const pending = [root];
2699
+ while (pending.length) {
2700
+ const mod = pending.pop();
2701
+ if (visited.has(mod.id)) continue;
2702
+ visited.add(mod.id);
2703
+ for (const n of baseExports.get(mod.id).keys()) {
2704
+ if ((mod !== root && n === "default") || seen.has(n)) continue;
2705
+ seen.add(n);
2706
+ names.push(n);
2707
+ }
2708
+ const stars = starReExports.get(mod.id) || [];
2709
+ for (let i = stars.length - 1; i >= 0; i--) {
2710
+ const target = moduleByRel.get(stars[i].target);
2711
+ if (target) pending.push(target);
2712
+ }
2713
+ }
2714
+ return names;
2715
+ };
2716
+ // Doc of the nearest entry providing `binding` for `name`: the module's own entry, else the first
2717
+ // star target (depth-first in source order) that provides it. undefined = no provider found.
2718
+ const exportDocOf = (start, name, binding) => {
2719
+ const seen = new Set();
2720
+ const frames = [];
2721
+ const enter = (mod) => {
2722
+ const own = baseExports.get(mod.id).get(name);
2723
+ if (own) return own.doc;
2724
+ const key = exportKey(mod.id, name);
2725
+ if (!seen.has(key)) { seen.add(key); frames.push({ mod, i: 0 }); }
2726
+ return undefined;
2727
+ };
2728
+ let doc = enter(start);
2729
+ while (doc === undefined && frames.length) {
2730
+ const frame = frames[frames.length - 1];
2731
+ const stars = starReExports.get(frame.mod.id) || [];
2732
+ if (frame.i >= stars.length) { frames.pop(); continue; }
2733
+ const target = moduleByRel.get(stars[frame.i++].target);
2734
+ const r = target ? resolveExport(target, name) : null;
2735
+ if (isBinding(r) && sameBinding(r, binding)) doc = enter(target);
2736
+ }
2737
+ return doc;
2738
+ };
2739
+
2740
+ // Star re-export expansion: `export * from './x'` declares no names, so without this pass
2741
+ // a star barrel's public API is invisible to graph-context/graph-query/MAP.html search.
2742
+ // Copy each resolved name in as kind "re-export" (with `via` = the real defining module), in
2743
+ // GetExportedNames order; the 60-per-module cap (own exports included) bounds MAP.json growth
2744
+ // and is applied after resolution, so which names survive it is deterministic.
2745
+ if (starReExports.size > 0) {
2746
+ const EXPANSION_CAP = 60;
2747
+ const sortedBarrels = [...starReExports.keys()].sort();
2748
+ for (const barrelId of sortedBarrels) {
2749
+ const barrel = moduleByRel.get(barrelId);
2750
+ if (!barrel) continue;
2751
+ const stars = starReExports.get(barrelId);
2752
+ const own = baseExports.get(barrelId);
2753
+ for (const name of exportedNames(barrel)) {
2754
+ if (own.has(name)) continue; // an explicit export shadows the star
2755
+ if (barrel.exports.length >= EXPANSION_CAP) break;
2756
+ const origin = resolveExport(barrel, name);
2757
+ if (!isBinding(origin)) continue;
2758
+ // line/doc come from the first star statement whose target provides the binding.
2759
+ let line = 1, doc = null;
2760
+ for (const star of stars) {
2761
+ const target = moduleByRel.get(star.target);
2762
+ const r = target ? resolveExport(target, name) : null;
2763
+ if (!isBinding(r) || !sameBinding(r, origin)) continue;
2764
+ line = star.line;
2765
+ doc = exportDocOf(target, name, origin) ?? null;
2766
+ break;
2767
+ }
2768
+ const copy = { name, kind: "re-export", line, doc, via: origin.mod };
2769
+ if (origin.name !== name) copy.viaName = origin.name;
2770
+ barrel.exports.push(copy);
2771
+ }
2772
+ }
2773
+ // Mirror expanded names into symbols so graph-query and the HTML viewer see them.
2774
+ for (const barrelId of sortedBarrels) {
2775
+ const barrel = moduleByRel.get(barrelId);
2776
+ if (!barrel) continue;
2777
+ const seen = new Set(barrel.symbols.map((s) => s.name));
2778
+ for (const e of barrel.exports) {
2779
+ if (barrel.symbols.length >= EXPANSION_CAP) break;
2780
+ if (seen.has(e.name)) continue;
2781
+ seen.add(e.name);
2782
+ barrel.symbols.push({ name: e.name, kind: "re-export", line: e.line, exported: true });
2783
+ }
2784
+ }
2785
+ }
2786
+
2787
+ // Record each named re-export entry's origin as `via`. The origin BINDING matters too:
2788
+ // `export { b as a } from './x'` exposes x's `b` under the name `a` (viaName "b") — a star
2789
+ // sibling exposing x's own `a` is a different binding, hence ambiguous. An entry whose target
2790
+ // gains the name through its own `export *` names the defining module, not that intermediate
2791
+ // barrel.
2792
+ for (const m of modules) {
2793
+ for (const e of m.exports) {
2794
+ if (e.kind !== "re-export" || e.via) continue;
2795
+ const origin = resolveExport(m, e.name);
2796
+ if (!isBinding(origin) || origin.mod === m.id) continue;
2797
+ e.via = origin.mod;
2798
+ if (origin.name !== e.name) e.viaName = origin.name;
2799
+ }
2800
+ }
2801
+
2330
2802
  // Containers: prefer packages; fall back to top-level dirs
2331
2803
  const containers = [];
2332
2804
  if (pkgs.length > 1) {
@@ -2889,17 +3361,20 @@ function visBuildMap(root) {
2889
3361
 
2890
3362
  // Symbol index for agents (the searchable identifier glossary). Defect 25: rank exporting
2891
3363
  // modules by import in-degree (most-depended-on first) BEFORE cutting, so a hard cap doesn't
2892
- // arbitrarily amputate whichever modules happened to sort last by file-walk order.
3364
+ // arbitrarily amputate whichever modules happened to sort last by file-walk order. Re-export
3365
+ // entries (`via`: barrel and star copies of a name defined elsewhere) are left out: the defining
3366
+ // module already indexes the name, and ~1k duplicates would crowd real definitions out of the cap.
2893
3367
  const SYMBOL_INDEX_CAP = 5000;
2894
3368
  let symbolIndexTruncated = false;
2895
3369
  const exportingModulesRanked = modules
2896
- .filter((m) => m.exports && m.exports.length > 0)
3370
+ .filter((m) => m.exports && m.exports.some((e) => !e.via))
2897
3371
  .slice()
2898
3372
  .sort((a, b) => (inDeg.get(b.id) || 0) - (inDeg.get(a.id) || 0) || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
2899
3373
  const symbolIndex = [];
2900
3374
  for (const m of exportingModulesRanked) {
2901
3375
  if (symbolIndex.length >= SYMBOL_INDEX_CAP) { symbolIndexTruncated = true; break; }
2902
3376
  for (const e of m.exports) {
3377
+ if (e.via) continue;
2903
3378
  if (symbolIndex.length >= SYMBOL_INDEX_CAP) { symbolIndexTruncated = true; break; }
2904
3379
  symbolIndex.push({ name: e.name, kind: e.kind, line: e.line, file: m.path, package: m.package, exported: true });
2905
3380
  }
@@ -2938,7 +3413,7 @@ function visBuildMap(root) {
2938
3413
  .slice(0, 600);
2939
3414
 
2940
3415
  return {
2941
- schemaVersion: 5,
3416
+ schemaVersion: 6,
2942
3417
  generatedAt: new Date().toISOString(),
2943
3418
  buildMs: Date.now() - startedAt,
2944
3419
  root: path.basename(root),
@@ -3194,6 +3669,16 @@ svg, canvas { display:block; user-select:none; position:absolute; inset:0; width
3194
3669
  .ctrl-checkbox { display:inline-flex; align-items:center; gap:5px; color:var(--muted);
3195
3670
  font-size:11px; cursor:pointer; padding:4px 8px; border:1px solid var(--border); border-radius:6px; background:var(--panel); }
3196
3671
  .ctrl-checkbox input { margin:0; cursor:pointer; }
3672
+ #insights { position:absolute; inset:0; overflow:auto; padding:18px 24px; background:var(--bg); }
3673
+ #insights h2 { font-size:13px; text-transform:uppercase; letter-spacing:0.08em; color:var(--muted); margin:18px 0 8px; }
3674
+ #insights table { border-collapse:collapse; width:100%; max-width:1100px; font-size:12px; }
3675
+ #insights th { text-align:left; color:var(--muted); font-weight:500; padding:4px 10px 4px 0; border-bottom:1px solid var(--border); }
3676
+ #insights td { padding:4px 10px 4px 0; border-bottom:1px solid var(--border); vertical-align:top; }
3677
+ #insights .num { text-align:right; font-variant-numeric:tabular-nums; }
3678
+ #insights .tag { display:inline-block; padding:1px 6px; border-radius:4px; font-size:10px; background:var(--panel); border:1px solid var(--border); color:var(--muted); margin-right:6px; }
3679
+ #insights .tag.hot { color:#f85149; border-color:#f85149; }
3680
+ #insights .ins-link { cursor:pointer; color:#58a6ff; }
3681
+ #insights .ins-link:hover { text-decoration:underline; }
3197
3682
  </style>
3198
3683
  </head>
3199
3684
  <body>
@@ -3204,6 +3689,7 @@ svg, canvas { display:block; user-select:none; position:absolute; inset:0; width
3204
3689
  <button id="tab-graph" class="active">Graph</button>
3205
3690
  <button id="tab-architecture">Architecture</button>
3206
3691
  <button id="tab-flows">Flows</button>
3692
+ <button id="tab-insights">Insights</button>
3207
3693
  </div>
3208
3694
  <div class="live dead" id="live-indicator">● static snapshot</div>
3209
3695
  </header>
@@ -3234,6 +3720,7 @@ svg, canvas { display:block; user-select:none; position:absolute; inset:0; width
3234
3720
  <div id="error-banner"></div>
3235
3721
  <svg id="svg" width="100%" height="100%" style="display:none"></svg>
3236
3722
  <canvas id="canvas"></canvas>
3723
+ <div id="insights" style="display:none"></div>
3237
3724
  <div id="overlay-left">
3238
3725
  <div id="graph-controls">
3239
3726
  <label class="ctrl-checkbox"><input type="checkbox" id="show-tests-cb"/> show tests</label>
@@ -3461,13 +3948,19 @@ function connectLive() {
3461
3948
  // ====================== view routing ======================
3462
3949
  function setView(v) {
3463
3950
  state.view = v;
3464
- ["tab-graph","tab-architecture","tab-flows"].forEach(function (id) {
3951
+ ["tab-graph","tab-architecture","tab-flows","tab-insights"].forEach(function (id) {
3465
3952
  $(id).classList.toggle("active", id === "tab-" + v);
3466
3953
  });
3467
3954
  svg.style.display = (v === "architecture" || v === "flows") ? "block" : "none";
3468
3955
  canvas.style.display = (v === "graph") ? "block" : "none";
3956
+ $("insights").style.display = (v === "insights") ? "block" : "none";
3469
3957
  $("graph-controls").style.display = (v === "graph") ? "flex" : "none";
3470
3958
  $("flows-sidebar").style.display = (v === "flows") ? "block" : "none";
3959
+ // Insights is a document, not a canvas — the legend/camera/export overlays don't apply.
3960
+ // Clear the inline style (not "block"/"flex") so the stylesheet layout returns intact.
3961
+ $("overlay-left").style.display = (v === "insights") ? "none" : "";
3962
+ var ctrls = document.querySelector(".controls");
3963
+ if (ctrls) ctrls.style.display = (v === "insights") ? "none" : "";
3471
3964
  // B3: re-measure the canvas's backing-store size whenever it becomes visible. A resize while
3472
3965
  // the Graph tab was hidden left canvas.width/height stale (clientWidth/height reflow correctly
3473
3966
  // even for display:none, but resizeCanvas() only ran on the debounced window "resize" handler
@@ -3483,6 +3976,8 @@ function render() {
3483
3976
  if (state.view === "graph") {
3484
3977
  ensureGraphModel();
3485
3978
  requestDraw();
3979
+ } else if (state.view === "insights") {
3980
+ renderInsights();
3486
3981
  } else {
3487
3982
  var W = svg.clientWidth, H = svg.clientHeight;
3488
3983
  svg.innerHTML = "";
@@ -3736,6 +4231,66 @@ function svgToWorld(ev) {
3736
4231
  return { x: (sx - state.pan.x) / state.zoom, y: (sy - state.pan.y) / state.zoom };
3737
4232
  }
3738
4233
 
4234
+ // ====================== Insights view ======================
4235
+ // Skimmable clusters / hotspots / surprising-connections / rationale panel (the graphify-style
4236
+ // "read this first" view). All map fields are optional (|| []) so a stale pre-v6 MAP.json served
4237
+ // by map-serve still renders the other tabs without breaking this one.
4238
+ function renderInsights() {
4239
+ var map = state.map;
4240
+ var box = $("insights");
4241
+ var h = "";
4242
+ var mod = function (id) { return linkBtn(id.split("/").slice(-2).join("/"), "module", id); };
4243
+
4244
+ var clusters = (map.clusters || []).slice().sort(function (a, b) { return b.size - a.size; });
4245
+ h += "<h2>Clusters (" + clusters.length + ") — structural import neighborhoods</h2>";
4246
+ if (clusters.length) {
4247
+ h += '<table><tr><th>label</th><th class="num">modules</th><th>layer</th><th>packages</th><th>sample members</th></tr>';
4248
+ clusters.slice(0, 30).forEach(function (c) {
4249
+ var sample = (c.members || []).slice(0, 3).map(mod).join(", ");
4250
+ h += "<tr><td>" + linkBtn(c.label, "cluster", c.id) + '</td><td class="num">' + c.size + "</td><td>" + escapeHtml(c.dominantLayer || "-") + "</td><td>" + escapeHtml((c.packages || []).slice(0, 3).join(", ")) + "</td><td>" + sample + "</td></tr>";
4251
+ });
4252
+ h += "</table>";
4253
+ if (clusters.length > 30) h += '<div class="tag">+' + (clusters.length - 30) + " more</div>";
4254
+ } else h += '<div class="tag">no cluster data — rebuild with map-graph</div>';
4255
+
4256
+ var hs = map.hotspots || {};
4257
+ var hsSection = function (title, arr) {
4258
+ h += "<h2>" + title + "</h2>";
4259
+ if (!arr || !arr.length) { h += '<div class="tag">none</div>'; return; }
4260
+ h += '<table><tr><th>module</th><th class="num">in</th><th class="num">out</th><th class="num">loc</th><th>why</th></tr>';
4261
+ arr.slice(0, 10).forEach(function (g) {
4262
+ h += "<tr><td>" + linkBtn(g.path, "module", g.id || g.path) + '</td><td class="num">' + g.inDegree + '</td><td class="num">' + g.outDegree + '</td><td class="num">' + g.loc + "</td><td>" + escapeHtml(g.reason || "") + "</td></tr>";
4263
+ });
4264
+ h += "</table>";
4265
+ };
4266
+ hsSection("God nodes (most connected)", hs.godNodes);
4267
+ hsSection("Most depended-on", hs.mostDependedOn);
4268
+ hsSection("Orchestrators (most dependencies)", hs.orchestrators);
4269
+
4270
+ var sc = map.surprisingConnections || [];
4271
+ h += "<h2>Surprising connections (" + sc.length + ") — bridges, cross-group and layer-violating edges</h2>";
4272
+ if (sc.length) {
4273
+ h += '<table><tr><th>from</th><th>to</th><th>reason</th><th class="num">score</th><th>symbols</th></tr>';
4274
+ sc.slice(0, 20).forEach(function (x) {
4275
+ h += "<tr><td>" + mod(x.from) + "</td><td>" + mod(x.to) + "</td><td>" + escapeHtml(x.reason || "") + '</td><td class="num">' + x.score + "</td><td>" + escapeHtml((x.sampleSymbols || []).slice(0, 3).join(", ")) + "</td></tr>";
4276
+ });
4277
+ h += "</table>";
4278
+ } else h += '<div class="tag">none detected</div>';
4279
+
4280
+ var rat = (map.rationaleIndex || []).filter(function (r) { return ["SECURITY", "BUG", "FIXME", "HACK"].indexOf(r.tag) !== -1; });
4281
+ h += "<h2>Rationale highlights (" + rat.length + ") — SECURITY / BUG / FIXME / HACK notes in source</h2>";
4282
+ if (rat.length) {
4283
+ h += '<table><tr><th>tag</th><th>where</th><th>note</th></tr>';
4284
+ rat.slice(0, 25).forEach(function (r) {
4285
+ var hot = r.tag === "SECURITY" || r.tag === "BUG";
4286
+ h += '<tr><td><span class="tag' + (hot ? " hot" : "") + '">' + escapeHtml(r.tag) + "</span></td><td>" + linkBtn(r.file + ":" + r.line, "module", r.file) + "</td><td>" + escapeHtml(r.text || "") + "</td></tr>";
4287
+ });
4288
+ h += "</table>";
4289
+ } else h += '<div class="tag">none</div>';
4290
+
4291
+ box.innerHTML = h;
4292
+ }
4293
+
3739
4294
  function renderArchitecture(g, W, H) {
3740
4295
  var map = state.map;
3741
4296
  var layout = layoutArchitecture(map, W, H);
@@ -4795,7 +5350,13 @@ function applySearch(q) {
4795
5350
  var needle = q.toLowerCase();
4796
5351
  var set = new Set();
4797
5352
  (state.map.modules || []).forEach(function (m) {
4798
- if (m.path.toLowerCase().indexOf(needle) !== -1) set.add(m.id);
5353
+ if (m.path.toLowerCase().indexOf(needle) !== -1) { set.add(m.id); return; }
5354
+ // modules[*].symbols covers non-exported decls and barrel re-exports that the
5355
+ // exported-only symbolIndex misses.
5356
+ (m.symbols || []).some(function (s) {
5357
+ if (s.name.toLowerCase().indexOf(needle) !== -1) { set.add(m.id); return true; }
5358
+ return false;
5359
+ });
4799
5360
  });
4800
5361
  (state.map.symbolIndex || []).forEach(function (s) {
4801
5362
  if (s.name.toLowerCase().indexOf(needle) !== -1) set.add(s.file);
@@ -4948,11 +5509,13 @@ window.addEventListener("keydown", function (e) {
4948
5509
  if (e.key === "g") setView("graph");
4949
5510
  if (e.key === "a") setView("architecture");
4950
5511
  if (e.key === "F") setView("flows");
5512
+ if (e.key === "i") setView("insights");
4951
5513
  });
4952
5514
 
4953
5515
  $("tab-graph").onclick = function () { setView("graph"); };
4954
5516
  $("tab-architecture").onclick = function () { setView("architecture"); };
4955
5517
  $("tab-flows").onclick = function () { setView("flows"); };
5518
+ $("tab-insights").onclick = function () { setView("insights"); };
4956
5519
  $("fit").onclick = fit;
4957
5520
  $("clear").onclick = function () { clearFlow(); state.collapsedGroups = {}; render(); };
4958
5521
  $("reload").onclick = function () { refreshFromServer(); };
@@ -5109,20 +5672,20 @@ function visRenderReport(map) {
5109
5672
  const GRAPH_GO_COMMANDS = new Set([
5110
5673
  "map-graph", "map-serve", "graph-context", "graph-impact", "graph-callers",
5111
5674
  "graph-callees", "graph-path", "graph-query", "graph-hotspots",
5112
- "graph-clusters", "graph-hook",
5675
+ "graph-clusters", "graph-hook", "kg",
5113
5676
  ]);
5114
5677
 
5115
5678
  // Deliberately NOT "draht-tools": the $PATH scan below would otherwise find the
5116
5679
  // npm shim for THIS file and spawn it forever. See also DRAHT_GRAPH_DELEGATED.
5117
5680
  const GRAPH_BIN_NAME = process.platform === "win32" ? "draht-graph.exe" : "draht-graph";
5118
5681
 
5119
- // Must equal visBuildMap()'s schemaVersion (see the `schemaVersion: 5` literal
5682
+ // Must equal visBuildMap()'s schemaVersion (see the `schemaVersion: 6` literal
5120
5683
  // above). A stamped binary built for another schema is rejected rather than
5121
5684
  // silently producing an incompatible MAP.json.
5122
- const GRAPH_SCHEMA_VERSION = 5;
5685
+ const GRAPH_SCHEMA_VERSION = 6;
5123
5686
 
5124
5687
  // Flip to true only when every gate in SPEC.md § "Requiring the Go engine" is
5125
- // green. Until then a missing binary is a silent JS fallback, not an error.
5688
+ // green. Until then a missing binary is a JS fallback (see graphEngineHint), not an error.
5126
5689
  const GRAPH_REQUIRE_GO = false;
5127
5690
 
5128
5691
  function graphEngineMode() {
@@ -5256,6 +5819,34 @@ function graphMissingMessage() {
5256
5819
  ].join("\n");
5257
5820
  }
5258
5821
 
5822
+ // The Go engine stays an opt-in download (an unsigned native binary), so the
5823
+ // JavaScript fallback says once a day that it exists. Stderr only: stdout stays
5824
+ // byte-identical between the engines. Silent with --quiet, in CI, with
5825
+ // DRAHT_GRAPH_HINT=0, when the engine was chosen explicitly, and whenever the
5826
+ // once-a-day stamp cannot be written (better no hint than one on every run).
5827
+ const GRAPH_HINT_INTERVAL_MS = 24 * 60 * 60 * 1000;
5828
+ function graphEngineHint(args, outdated) {
5829
+ if (process.env.DRAHT_GRAPH_HINT === "0" || process.env.CI) return;
5830
+ if (args.some((a) => a === "--quiet" || a === "-q")) return;
5831
+ let stamp;
5832
+ try {
5833
+ stamp = path.join(os.homedir(), ".draht", ".graph-engine-hint");
5834
+ if (Date.now() - fs.statSync(stamp).mtimeMs < GRAPH_HINT_INTERVAL_MS) return;
5835
+ } catch (err) {
5836
+ if (!stamp || err.code !== "ENOENT") return;
5837
+ }
5838
+ try {
5839
+ fs.mkdirSync(path.dirname(stamp), { recursive: true });
5840
+ fs.writeFileSync(stamp, "");
5841
+ } catch {
5842
+ return;
5843
+ }
5844
+ const what = outdated
5845
+ ? "the installed `draht-graph` binary predates the Go `kg` engine, so `kg` ran on the built-in JavaScript engine. Update it:"
5846
+ : "running the built-in JavaScript graph engine. The optional Go engine gives the same output faster:";
5847
+ console.error(`draht-tools: ${what} npx draht-claude install-graph-engine (or npx draht-codex install-graph-engine). Shown once a day; DRAHT_GRAPH_HINT=0 turns this off.`);
5848
+ }
5849
+
5259
5850
  // Delegates and EXITS the process on success; returns normally to fall through to JS.
5260
5851
  // Value-taking Go-only flags (accepted by the Go engine's own CLI, meaningless to
5261
5852
  // the JS engine's arg parsers) vs. boolean ones. graphParseArgs/map-graph's own
@@ -5304,6 +5895,19 @@ function graphSignatureFallbackWarning() {
5304
5895
  return "draht-tools: --symbol-signatures requires the Go graph engine, but no usable `draht-graph` binary is available; continuing with the JavaScript engine without symbol signatures.";
5305
5896
  }
5306
5897
 
5898
+ // `kg` reached the Go engine later than the map commands: a binary built before
5899
+ // it answers "Unknown command: kg". Such a binary keeps serving the commands it
5900
+ // has, and `kg` stays on the JavaScript engine (same graph.json, same output).
5901
+ function graphBinHasKg(bin) {
5902
+ const res = spawnSync(bin, ["kg", "help"], {
5903
+ stdio: ["ignore", "pipe", "ignore"],
5904
+ encoding: "utf-8",
5905
+ windowsHide: true,
5906
+ env: { ...process.env, DRAHT_GRAPH_DELEGATED: "1" },
5907
+ });
5908
+ return !res.error && res.status === 0 && String(res.stdout).startsWith("draht-kg");
5909
+ }
5910
+
5307
5911
  function graphMaybeDelegate(cmd, args) {
5308
5912
  if (!GRAPH_GO_COMMANDS.has(cmd)) return;
5309
5913
  if (process.env.DRAHT_GRAPH_DELEGATED) return; // recursion guard, belt and braces
@@ -5316,7 +5920,16 @@ function graphMaybeDelegate(cmd, args) {
5316
5920
  process.exit(127);
5317
5921
  }
5318
5922
  if (graphWantsSymbolSignatures(cmd, args)) console.error(graphSignatureFallbackWarning());
5319
- return; // auto: silent JS fallback
5923
+ graphEngineHint(args, false);
5924
+ return; // auto: JS fallback
5925
+ }
5926
+ if (cmd === "kg" && !graphBinHasKg(bin)) {
5927
+ if (mode === "go" || GRAPH_REQUIRE_GO) {
5928
+ console.error(`draht-tools: ${bin} does not implement \`kg\` (it predates the Go kg engine); reinstall it or unset DRAHT_GRAPH_ENGINE.`);
5929
+ process.exit(127);
5930
+ }
5931
+ graphEngineHint(args, true);
5932
+ return; // auto: JS fallback
5320
5933
  }
5321
5934
  const res = spawnSync(bin, [cmd, ...graphPinRegexParser(cmd, args)], {
5322
5935
  stdio: "inherit", // byte-identical stdout/stderr, TTY preserved
@@ -5349,6 +5962,7 @@ function graphBuildOutputs(root, opts = {}) {
5349
5962
  console.error(graphMissingMessage());
5350
5963
  process.exit(127);
5351
5964
  }
5965
+ if (mode !== "js") graphEngineHint(opts.quiet ? ["--quiet"] : [], false);
5352
5966
  return visWriteOutputs(root, opts);
5353
5967
  }
5354
5968
  const argv = ["map-graph", "--parser", "regex"]; // see graphPinRegexParser's doc comment
@@ -5855,7 +6469,15 @@ commands["graph-impact"] = function (...args) {
5855
6469
  const epLabel = (e) => e.kind === "cli" ? "cli:" + (e.name || "") : e.kind === "http" ? "http:" + ((e.routes && e.routes[0] && (e.routes[0].method + " " + e.routes[0].path)) || "") : "lib:" + (e.name || e.path.split("/").pop());
5856
6470
  const L = [];
5857
6471
  if (notes.length) L.push(...notes);
5858
- L.push(`impact ${targets.map((t) => t.split("/").pop()).join(", ")} — ${impacted.length} modules · ${Object.keys(byPkg).length} packages · ${eps.length} entry points · sinks: ${[...sinkKinds].join(", ") || "none"}`);
6472
+ L.push(`impact ${targets.join(", ")} — ${impacted.length} modules · ${Object.keys(byPkg).length} packages · ${eps.length} entry points · sinks: ${[...sinkKinds].join(", ") || "none"}`);
6473
+ // A barrel with no importers still fronts a public API — say so instead of a bare zero.
6474
+ if (!impacted.length) {
6475
+ for (const t of targets) {
6476
+ const tm = modById.get(t);
6477
+ const reexp = (tm.exports || []).filter((e) => e.kind === "re-export");
6478
+ if (reexp.length) L.push(`note: ${t} is a barrel (re-exports ${reexp.length} symbols) with no direct importers — changes only affect external consumers of ${tm.package || "this package"}`);
6479
+ }
6480
+ }
5859
6481
  if (eps.length) L.push(`entry points reaching it (${eps.length}): ${eps.slice(0, 8).map(epLabel).join(", ")}${eps.length > 8 ? " …" : ""}`);
5860
6482
  const pkgs = Object.entries(byPkg).sort((a, b) => b[1].length - a[1].length || (a[0] < b[0] ? -1 : 1));
5861
6483
  if (pkgs.length) L.push("by package:");
@@ -5890,7 +6512,7 @@ function graphCallDir(args, direction) {
5890
6512
  const arr = byHop[d] || []; if (!arr.length) continue;
5891
6513
  console.log(` hop ${d}:`);
5892
6514
  const seen = new Set();
5893
- for (const h of arr) { const node = direction === "callers" ? h.to : h.to; if (seen.has(node)) continue; seen.add(node); const syms = arr.filter((x) => x.to === node && x.symbol).map((x) => x.symbol); console.log(` ${node}${syms.length ? " [" + [...new Set(syms)].slice(0, 4).join(", ") + "]" : ""}`); }
6515
+ for (const h of arr) { const node = h.to; if (seen.has(node)) continue; seen.add(node); const syms = arr.filter((x) => x.to === node && x.symbol).map((x) => x.symbol); console.log(` ${node}${syms.length ? " [" + [...new Set(syms)].slice(0, 4).join(", ") + "]" : ""}`); }
5894
6516
  }
5895
6517
  };
5896
6518
  commands["graph-callers"] = function (...args) { return graphCallDir(args, "callers"); };
@@ -5924,34 +6546,83 @@ commands["graph-query"] = function (...args) {
5924
6546
  if (!terms.length) { console.log("usage: graph-query <term...> [--json] (terms ≥3 chars)"); return; }
5925
6547
  const stem = (s) => s.replace(/(ing|tion|ed|s)$/, "");
5926
6548
  const clusterLabel = new Map((map.clusters || []).map((c) => [c.id, (c.label || "").toLowerCase()]));
5927
- const deg = new Map(); for (const e of map.edges) { if (e.kind !== "import") continue; deg.set(e.from, (deg.get(e.from) || 0) + 1); deg.set(e.to, (deg.get(e.to) || 0) + 1); }
6549
+ const deg = new Map(); for (const e of map.edges) { if (e.kind !== "import" && e.kind !== "re-export") continue; deg.set(e.from, (deg.get(e.from) || 0) + 1); deg.set(e.to, (deg.get(e.to) || 0) + 1); }
6550
+ // Term coverage is satisfied at the MODULE level (any symbol/path/doc/cluster hit), scaled by
6551
+ // coverage² — graphify's scheme. The old per-symbol AND required every term to hit the same
6552
+ // symbol, so "auth session" only matched files that packed both words into one identifier.
5928
6553
  const cands = [];
5929
6554
  for (const m of map.modules) {
5930
6555
  const expDoc = new Map((m.exports || []).map((e) => [e.name, e.doc || ""]));
5931
6556
  const baseLow = m.path.split("/").pop().toLowerCase();
6557
+ const pathLow = m.path.toLowerCase();
5932
6558
  const clab = clusterLabel.get(m.cluster) || "";
5933
- for (const s of (m.symbols || [])) {
5934
- const nameLow = s.name.toLowerCase(), doc = expDoc.get(s.name) || "", docLow = doc.toLowerCase();
5935
- let total = 0, ok = true;
5936
- for (const t of terms) {
6559
+ const allDocsLow = (m.exports || []).map((e) => e.doc || "").filter(Boolean).join(" ").toLowerCase();
6560
+ const symScores = new Map(); // symbol name -> summed per-term score, for display pick
6561
+ let matched = 0, sum = 0;
6562
+ for (const t of terms) {
6563
+ let best = 0;
6564
+ for (const s of (m.symbols || [])) {
6565
+ // Re-export symbols are the barrel's copies of names defined elsewhere: the defining
6566
+ // module matches them, so scoring them here ranked barrels above the real definition.
6567
+ // Barrels still match through path, doc and cluster below.
6568
+ if (s.kind === "re-export") continue;
6569
+ const nameLow = s.name.toLowerCase();
5937
6570
  let sc = 0;
5938
6571
  if (nameLow === t) sc = 400; else if (nameLow.startsWith(t)) sc = 200; else if (nameLow.includes(t)) sc = 100;
5939
- if (sc < 60 && baseLow.includes(t)) sc = 60;
5940
- if (sc < 40 && (docLow.includes(t) || docLow.includes(stem(t)))) sc = 40;
5941
- if (sc < 30 && clab.includes(t)) sc = 30;
5942
- if (sc === 0) { ok = false; break; }
5943
- total += sc;
6572
+ if (sc < 40) {
6573
+ const dl = (expDoc.get(s.name) || "").toLowerCase();
6574
+ if (dl && (dl.includes(t) || dl.includes(stem(t)))) sc = 40;
6575
+ }
6576
+ if (sc > 0) symScores.set(s.name, (symScores.get(s.name) || 0) + sc);
6577
+ if (sc > best) best = sc;
5944
6578
  }
5945
- if (!ok) continue;
5946
- let mult = 1; if (s.exported) mult *= 1.5; if (m.entryPoint) mult *= 1.3;
5947
- cands.push({ score: +(total * mult).toFixed(1), deg: deg.get(m.id) || 0, path: m.path, line: s.line, kind: s.kind, name: s.name, exported: !!s.exported, doc });
6579
+ if (best < 60 && baseLow.includes(t)) best = 60;
6580
+ if (best < 50 && pathLow.includes(t)) best = 50;
6581
+ if (best < 40 && allDocsLow && (allDocsLow.includes(t) || allDocsLow.includes(stem(t)))) best = 40;
6582
+ if (best < 30 && clab.includes(t)) best = 30;
6583
+ if (best > 0) matched++;
6584
+ sum += best;
6585
+ }
6586
+ if (!matched) continue;
6587
+ const coverage = matched / terms.length;
6588
+ let mult = coverage * coverage;
6589
+ if (m.entryPoint) mult *= 1.3;
6590
+ if (m.isTest) mult *= 0.7; // tests match everything; keep them below the code they test
6591
+ // Display anchor: best-scoring symbol (exported preferred, first-in-file on ties), else the module itself.
6592
+ let bestSym = null, bestVal = 0;
6593
+ for (const s of (m.symbols || [])) {
6594
+ if (s.kind === "re-export") continue;
6595
+ const v = (symScores.get(s.name) || 0) * (s.exported ? 1.5 : 1);
6596
+ if (v > bestVal) { bestVal = v; bestSym = s; }
5948
6597
  }
6598
+ if (bestSym && bestSym.exported) mult *= 1.5;
6599
+ // A multi-term query that one declared symbol's name satisfies in full ("session token" ->
6600
+ // SessionToken) is a definition lookup: prefer it over modules that merely cover the terms.
6601
+ if (terms.length > 1 && (m.symbols || []).some((s) => {
6602
+ if (s.kind === "re-export") return false;
6603
+ const low = s.name.toLowerCase();
6604
+ return terms.every((t) => low.includes(t));
6605
+ })) mult *= 2;
6606
+ cands.push({
6607
+ score: +(sum * mult).toFixed(1),
6608
+ matched, terms: terms.length,
6609
+ deg: deg.get(m.id) || 0,
6610
+ path: m.path,
6611
+ line: bestSym ? bestSym.line : 1,
6612
+ kind: bestSym ? bestSym.kind : "module",
6613
+ name: bestSym ? bestSym.name : m.path.split("/").pop(),
6614
+ exported: !!(bestSym && bestSym.exported),
6615
+ doc: bestSym ? (expDoc.get(bestSym.name) || "") : "",
6616
+ });
5949
6617
  }
5950
6618
  cands.sort((a, b) => b.score - a.score || b.deg - a.deg || a.path.length - b.path.length || (a.path < b.path ? -1 : 1));
5951
6619
  const top = cands.slice(0, 15);
5952
6620
  if (flags.json) { console.log(JSON.stringify(top, null, 2)); return; }
5953
6621
  console.log(`query "${terms.join(" ")}" — ${top.length}/${cands.length} hits`);
5954
- for (const c of top) console.log(`${c.path}:${c.line} ${c.kind} ${c.name}${c.doc ? " — " + c.doc.slice(0, 60) : ""}${c.exported ? " [exported]" : ""}`);
6622
+ for (const c of top) {
6623
+ const partial = c.matched < c.terms ? ` (${c.matched}/${c.terms} terms)` : "";
6624
+ console.log(`${c.path}:${c.line} ${c.kind} ${c.name}${c.doc ? " — " + c.doc.slice(0, 60) : ""}${c.exported ? " [exported]" : ""}${partial}`);
6625
+ }
5955
6626
  if (cands.length > 15) console.log(`(${cands.length - 15} more: --json for all)`);
5956
6627
  };
5957
6628
 
@@ -5985,6 +6656,23 @@ commands["graph-clusters"] = function (...args) {
5985
6656
  };
5986
6657
 
5987
6658
  // graph-hook — install/uninstall a git post-commit hook that refreshes MAP.json (graphify-style).
6659
+ // --- kg — graphify-parity symbol-level knowledge graph (second engine, draht-kg.cjs) ---
6660
+ // Runs in the Go binary when one is installed that has it (graphMaybeDelegate); this is
6661
+ // the JavaScript engine, which writes the same graph.json and prints the same output.
6662
+ // Nodes are symbols (files/classes/functions/methods/types) with graphify's relation set
6663
+ // and confidence rubric; graph.json is node-link format loadable by graphify's own tools.
6664
+ commands.kg = function (...args) {
6665
+ let kg;
6666
+ try {
6667
+ kg = require(path.join(__dirname, "draht-kg.cjs"));
6668
+ } catch (err) {
6669
+ console.error(`kg engine not found next to draht-tools.cjs (${err.message}) — reinstall the package.`);
6670
+ process.exit(1);
6671
+ }
6672
+ const code = kg.kgMain(args);
6673
+ if (code) process.exitCode = code;
6674
+ };
6675
+
5988
6676
  commands["graph-hook"] = function (...args) {
5989
6677
  const sub = args[0] || "status";
5990
6678
  const gitDir = path.join(process.cwd(), ".git");
@@ -6058,8 +6746,19 @@ Knowledge Graph (query MAP.json instead of grepping — run map-graph first):
6058
6746
  (--jobs, --parser, --cache-dir, --out, --ast-max-bytes, --verbose) are recognized
6059
6747
  and forwarded when the Go binary handles the command, and are stripped (not
6060
6748
  passed through, not an error) when the JS engine handles it instead — so a
6061
- script using them works either way. Install the binary with
6062
- \`npx draht-claude install-graph-engine\` (or draht-codex).
6749
+ script using them works either way. The binary is an opt-in download: install
6750
+ it with \`npx draht-claude install-graph-engine\` (or draht-codex). Without it
6751
+ a one-line reminder goes to stderr once a day (DRAHT_GRAPH_HINT=0 turns it off).
6752
+
6753
+ Symbol-level knowledge graph (graphify-parity engine; nodes = functions/classes/types):
6754
+ kg build [--quiet] Deterministic symbol graph → .planning/codebase/graph.json + KG_REPORT.md
6755
+ kg query "<question>" BFS/DFS subgraph traversal from scored seeds (NODE/EDGE output)
6756
+ [--dfs] [--depth N] [--budget N] [--context call|import]
6757
+ kg explain "<node>" Node dump: id, source, community, degree, top connections
6758
+ kg path "<a>" "<b>" Shortest path with directed relation arrows + confidence
6759
+ kg affected "<node>" Reverse blast-radius over calls/imports/inherits/… [--depth N]
6760
+ kg stats | report Counts / regenerate KG_REPORT.md
6761
+ kg export tree|wiki|graphml GRAPH_TREE.html / kg-wiki/ articles / graph.graphml
6063
6762
  create-project [name] Create PROJECT.md
6064
6763
  create-requirements Create REQUIREMENTS.md
6065
6764
  create-domain-model Generate DOMAIN-MODEL.md from PROJECT.md
@@ -6117,7 +6816,8 @@ const [cmd, ...args] = process.argv.slice(2);
6117
6816
  // mean nothing to the JS engine and, left in, corrupt its own arg parsing (an
6118
6817
  // unconsumed value token gets read as a positional file/dir — finding #4). Strip
6119
6818
  // them here so the two engines accept the same command line.
6120
- const jsArgs = GRAPH_GO_COMMANDS.has(cmd) ? graphStripGoOnlyFlags(args) : args;
6819
+ // (`kg` takes none of them, and its arguments are free text: left as typed.)
6820
+ const jsArgs = GRAPH_GO_COMMANDS.has(cmd) && cmd !== "kg" ? graphStripGoOnlyFlags(args) : args;
6121
6821
  await commands[cmd](...jsArgs);
6122
6822
  } else {
6123
6823
  console.error(`Unknown command: ${cmd}\nRun: draht-tools help`);