@herbertgao/pi-extensions 2026.11.7 → 2026.11.8

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 (123) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +5 -5
  3. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +6 -0
  4. package/node_modules/@herbertgao/pi-subagents/README.md +2 -2
  5. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  6. package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +10 -6
  7. package/node_modules/@herbertgao/pi-subagents/src/ui/viewer-keys.ts +47 -4
  8. package/node_modules/@narumitw/pi-btw/CHANGELOG.md +12 -0
  9. package/node_modules/@narumitw/pi-btw/dist/chunks/{main-tree-picker-WHRN26NJ.ts → main-tree-picker-3PXJARQW.ts} +59 -53
  10. package/node_modules/@narumitw/pi-btw/dist/chunks/main-tree-picker-3PXJARQW.ts.map +7 -0
  11. package/node_modules/@narumitw/pi-btw/dist/index.ts +1 -1
  12. package/node_modules/@narumitw/pi-btw/docs/main-tree-snapshots.md +39 -0
  13. package/node_modules/@narumitw/pi-btw/docs/workflows.md +1 -0
  14. package/node_modules/@narumitw/pi-btw/package.json +1 -1
  15. package/node_modules/@narumitw/pi-btw/src/main-tree-picker.ts +73 -63
  16. package/node_modules/pi-lens/CHANGELOG-USER.md +6 -6
  17. package/node_modules/pi-lens/CHANGELOG.md +30 -0
  18. package/node_modules/pi-lens/README.md +1 -0
  19. package/node_modules/pi-lens/dist/{chunk-KDGKKK7A.js → chunk-2HWVG3IM.js} +1 -1
  20. package/node_modules/pi-lens/dist/{chunk-3QCI3V6C.js → chunk-3EIZMRXI.js} +5 -5
  21. package/node_modules/pi-lens/dist/{chunk-NWK7KKNO.js → chunk-3MHY4BQY.js} +2 -2
  22. package/node_modules/pi-lens/dist/{chunk-3NVGBFJS.js → chunk-3PMLYGJN.js} +2 -2
  23. package/node_modules/pi-lens/dist/{chunk-OP5BMZKK.js → chunk-3QMLB4TI.js} +1 -1
  24. package/node_modules/pi-lens/dist/{chunk-V7IPIAE5.js → chunk-3VWEZ6H2.js} +24 -26
  25. package/node_modules/pi-lens/dist/{chunk-NLRKB32C.js → chunk-5EEWCJG7.js} +1 -1
  26. package/node_modules/pi-lens/dist/{chunk-VDMF7Q2P.js → chunk-5FDUKJZO.js} +4 -4
  27. package/node_modules/pi-lens/dist/{chunk-KBSC5Z3G.js → chunk-5KLRCUDT.js} +2 -2
  28. package/node_modules/pi-lens/dist/{chunk-GL6J5R34.js → chunk-6EXGCXM5.js} +3 -3
  29. package/node_modules/pi-lens/dist/{chunk-OC4ZGVMH.js → chunk-6GWCYEP7.js} +5 -7
  30. package/node_modules/pi-lens/dist/{chunk-LXE7JAMV.js → chunk-6JLNZ6DP.js} +4 -4
  31. package/node_modules/pi-lens/dist/{chunk-TTGDTNSN.js → chunk-75TVYCQW.js} +3 -3
  32. package/node_modules/pi-lens/dist/{chunk-QAM2Q3VO.js → chunk-7BEADGAZ.js} +2 -2
  33. package/node_modules/pi-lens/dist/{chunk-R5BNSOIV.js → chunk-7KWI5UHL.js} +7 -8
  34. package/node_modules/pi-lens/dist/{chunk-5YTDZ5WP.js → chunk-7M64NTAK.js} +1 -1
  35. package/node_modules/pi-lens/dist/{chunk-B4K6OSLL.js → chunk-7T64QA5D.js} +25 -27
  36. package/node_modules/pi-lens/dist/{chunk-KDMJ2DJD.js → chunk-7ZVEFWOE.js} +5 -5
  37. package/node_modules/pi-lens/dist/{chunk-D5L7Q57Z.js → chunk-AAIVSSUU.js} +1 -1
  38. package/node_modules/pi-lens/dist/{chunk-LIDFFCZZ.js → chunk-AD7JDEI6.js} +9 -9
  39. package/node_modules/pi-lens/dist/{chunk-WBXCIRVI.js → chunk-AVBEPUCD.js} +1 -1
  40. package/node_modules/pi-lens/dist/{chunk-VTXJAO5R.js → chunk-AZXTLZHE.js} +9 -9
  41. package/node_modules/pi-lens/dist/{chunk-UELHWF5I.js → chunk-BEIPWPVR.js} +10 -10
  42. package/node_modules/pi-lens/dist/{chunk-SQBDX6IO.js → chunk-C6V2DSZZ.js} +6 -6
  43. package/node_modules/pi-lens/dist/{chunk-ZD4KVFXI.js → chunk-D2ZYRI7M.js} +172 -3
  44. package/node_modules/pi-lens/dist/{chunk-HIUVHRLM.js → chunk-D6ANA6YU.js} +20 -22
  45. package/node_modules/pi-lens/dist/{chunk-YUF4DRYB.js → chunk-D7OEGXDX.js} +1 -1
  46. package/node_modules/pi-lens/dist/{chunk-AOQKQWZU.js → chunk-DFAY7JUN.js} +1 -1
  47. package/node_modules/pi-lens/dist/{chunk-QUZYRDT6.js → chunk-DIIDMDZU.js} +6 -6
  48. package/node_modules/pi-lens/dist/{chunk-QBUSONNE.js → chunk-DZSQXG66.js} +45 -27
  49. package/node_modules/pi-lens/dist/{chunk-UY3WWW5R.js → chunk-E5SSUV2A.js} +3 -3
  50. package/node_modules/pi-lens/dist/{chunk-DNB4ZQGN.js → chunk-ET3DSSFZ.js} +1 -1
  51. package/node_modules/pi-lens/dist/{chunk-4WWPDMRA.js → chunk-F7AMFFVK.js} +4 -4
  52. package/node_modules/pi-lens/dist/{chunk-LHCDWFDB.js → chunk-FDLGJFAE.js} +1 -1
  53. package/node_modules/pi-lens/dist/{chunk-C4ICGFEO.js → chunk-FVQKX5KI.js} +12 -12
  54. package/node_modules/pi-lens/dist/{chunk-TRYOYWWU.js → chunk-G3LR6V6N.js} +4 -4
  55. package/node_modules/pi-lens/dist/{chunk-AVOUHMCS.js → chunk-GHATCG2A.js} +10 -10
  56. package/node_modules/pi-lens/dist/{chunk-R2UF54ON.js → chunk-HJWF7CGW.js} +9 -9
  57. package/node_modules/pi-lens/dist/chunk-HRQTYU2T.js +355 -0
  58. package/node_modules/pi-lens/dist/{chunk-NR4KQOXZ.js → chunk-HSTN27NR.js} +1 -1
  59. package/node_modules/pi-lens/dist/{chunk-YVPB5YGO.js → chunk-HWMNTQBJ.js} +1 -1
  60. package/node_modules/pi-lens/dist/{chunk-6XNVY3FW.js → chunk-HYDJUVOE.js} +1 -1
  61. package/node_modules/pi-lens/dist/{chunk-WXMUGUZV.js → chunk-HYR25MV3.js} +4 -4
  62. package/node_modules/pi-lens/dist/{chunk-AJ62EQIQ.js → chunk-IC4L65U7.js} +12 -9
  63. package/node_modules/pi-lens/dist/{chunk-R2VUZZPJ.js → chunk-ILC2B7IJ.js} +4 -4
  64. package/node_modules/pi-lens/dist/{chunk-E6Z3CJT2.js → chunk-IZ36G463.js} +5 -5
  65. package/node_modules/pi-lens/dist/{chunk-IBEYUBCM.js → chunk-JKAVKTMY.js} +6 -6
  66. package/node_modules/pi-lens/dist/{chunk-LHU6NG5Z.js → chunk-JLMS7EMD.js} +8 -8
  67. package/node_modules/pi-lens/dist/{chunk-6RXMQYNU.js → chunk-JRSS6KM4.js} +1 -1
  68. package/node_modules/pi-lens/dist/{chunk-HASJPQBC.js → chunk-K2LD6YNH.js} +4 -4
  69. package/node_modules/pi-lens/dist/{chunk-UQ6OZYTO.js → chunk-KUDUKKQE.js} +43 -45
  70. package/node_modules/pi-lens/dist/{chunk-34RXPR7M.js → chunk-KXDQD34C.js} +1 -1
  71. package/node_modules/pi-lens/dist/{chunk-QDZ3ZZMY.js → chunk-LD7SXICE.js} +3 -3
  72. package/node_modules/pi-lens/dist/{chunk-NQFXN5U7.js → chunk-MOEWCPMC.js} +1 -1
  73. package/node_modules/pi-lens/dist/{chunk-IJ55MYO6.js → chunk-MV6ST2KT.js} +4 -4
  74. package/node_modules/pi-lens/dist/{chunk-532X3OCZ.js → chunk-NCDH2JB7.js} +7 -9
  75. package/node_modules/pi-lens/dist/{chunk-ITAPXBIB.js → chunk-NRVWLTOY.js} +9 -9
  76. package/node_modules/pi-lens/dist/{chunk-DPDA3ILA.js → chunk-NZINZCHB.js} +1 -1
  77. package/node_modules/pi-lens/dist/{chunk-A4HKPAEN.js → chunk-OEPWTSUG.js} +6 -6
  78. package/node_modules/pi-lens/dist/{chunk-TBE4OLPA.js → chunk-OF2YGDUE.js} +21 -23
  79. package/node_modules/pi-lens/dist/{chunk-BLL4VYGZ.js → chunk-OHEUOWYT.js} +1 -1
  80. package/node_modules/pi-lens/dist/{chunk-PSUXESQ5.js → chunk-ORYQGVC3.js} +1 -1
  81. package/node_modules/pi-lens/dist/{chunk-FVEEEEIM.js → chunk-OVPR3GQ6.js} +4 -4
  82. package/node_modules/pi-lens/dist/{chunk-BN36MQW5.js → chunk-PCREZ4HJ.js} +20 -22
  83. package/node_modules/pi-lens/dist/{chunk-KNP4ENFT.js → chunk-PK3GDU4M.js} +1 -1
  84. package/node_modules/pi-lens/dist/{chunk-2SD2CGVH.js → chunk-PPYUBO6Y.js} +1 -1
  85. package/node_modules/pi-lens/dist/{chunk-4HNBY7S7.js → chunk-PTJXMYRY.js} +7 -9
  86. package/node_modules/pi-lens/dist/{chunk-VI3BJMZO.js → chunk-PXGVB2CY.js} +14 -18
  87. package/node_modules/pi-lens/dist/{chunk-3C6ZZAB2.js → chunk-QY6J2FTK.js} +10 -12
  88. package/node_modules/pi-lens/dist/{chunk-5RLEDUUE.js → chunk-R67WQ5RY.js} +3 -3
  89. package/node_modules/pi-lens/dist/{chunk-WMCAEP2K.js → chunk-S6ZQFPOX.js} +2 -2
  90. package/node_modules/pi-lens/dist/{chunk-LPM6NKVI.js → chunk-SF7KSXB5.js} +2 -2
  91. package/node_modules/pi-lens/dist/{chunk-ECYUBKYX.js → chunk-T6PPK3T6.js} +40 -37
  92. package/node_modules/pi-lens/dist/{chunk-RV5VX2XW.js → chunk-TM3A3K7T.js} +8 -9
  93. package/node_modules/pi-lens/dist/{chunk-AFNPNHJV.js → chunk-TOOXNL6M.js} +3 -3
  94. package/node_modules/pi-lens/dist/{chunk-BJDB7PXU.js → chunk-TS5EIWEF.js} +6 -6
  95. package/node_modules/pi-lens/dist/{chunk-UG4YLCJ5.js → chunk-VD7MQFEV.js} +21 -23
  96. package/node_modules/pi-lens/dist/{chunk-BBJXIZ3X.js → chunk-VU2PRGRI.js} +5 -34
  97. package/node_modules/pi-lens/dist/{chunk-GTNO6F6K.js → chunk-WTSQKJAR.js} +4 -4
  98. package/node_modules/pi-lens/dist/{chunk-TPMBNWHO.js → chunk-Y7XMKBFP.js} +16 -16
  99. package/node_modules/pi-lens/dist/{chunk-JSQK5DH3.js → chunk-YLHJWAQS.js} +2 -2
  100. package/node_modules/pi-lens/dist/{chunk-HTUG7ZFK.js → chunk-YLW26OHX.js} +3 -3
  101. package/node_modules/pi-lens/dist/{chunk-C2REOMPO.js → chunk-YTXFNCVN.js} +1 -1
  102. package/node_modules/pi-lens/dist/{chunk-F37CCZUA.js → chunk-YULIERZW.js} +8 -8
  103. package/node_modules/pi-lens/dist/{chunk-KX4DF6XX.js → chunk-Z2W5YJBW.js} +6 -6
  104. package/node_modules/pi-lens/dist/{chunk-DBAHJFBU.js → chunk-Z6WTLVUL.js} +13 -18
  105. package/node_modules/pi-lens/dist/{chunk-6K4X7IIF.js → chunk-ZWZD4TJ5.js} +23 -25
  106. package/node_modules/pi-lens/dist/index.js +1134 -618
  107. package/node_modules/pi-lens/dist/mcp/analyze-cli.js +5 -7
  108. package/node_modules/pi-lens/dist/mcp/cli.js +25 -27
  109. package/node_modules/pi-lens/dist/mcp/server.js +101 -100
  110. package/node_modules/pi-lens/dist/mcp/worker.js +43 -45
  111. package/node_modules/pi-lens/dist/probes/installer.js +11 -11
  112. package/node_modules/pi-lens/docs/agent-tools.md +54 -12
  113. package/node_modules/pi-lens/docs/configuration.md +3 -3
  114. package/node_modules/pi-lens/docs/globalconfig.md +8 -1
  115. package/node_modules/pi-lens/docs/invariants/lsp-trust-exec.md +7 -0
  116. package/node_modules/pi-lens/docs/mcp.md +2 -1
  117. package/node_modules/pi-lens/docs/usage.md +1 -1
  118. package/node_modules/pi-lens/package.json +1 -1
  119. package/package.json +4 -4
  120. package/node_modules/@narumitw/pi-btw/dist/chunks/main-tree-picker-WHRN26NJ.ts.map +0 -7
  121. package/node_modules/pi-lens/dist/chunk-3HZ6MNB2.js +0 -140
  122. package/node_modules/pi-lens/dist/chunk-43KD3PPM.js +0 -162
  123. package/node_modules/pi-lens/dist/chunk-CKEQFGLT.js +0 -32
@@ -1624,33 +1624,33 @@ var init_esm4 = __esm({
1624
1624
  return h !== -1 && host2 !== void 0 && host2 !== "" && host2 !== GLOBSTAR && share !== void 0 && share !== "" && share !== GLOBSTAR ? h : -1;
1625
1625
  };
1626
1626
  walkable = (p, dot) => !isDots(p) && (dot || !p.startsWith("."));
1627
- dotPortion = (f, start, end, dot, sep12) => {
1627
+ dotPortion = (f, start, end, dot, sep13) => {
1628
1628
  for (let k = start; k < end; ) {
1629
1629
  if (f.charCodeAt(k) === 46) {
1630
1630
  if (!dot)
1631
1631
  return true;
1632
1632
  const n = f.charCodeAt(k + 1) === 46 ? k + 2 : k + 1;
1633
- if (n >= end || isSep(f.charCodeAt(n), sep12))
1633
+ if (n >= end || isSep(f.charCodeAt(n), sep13))
1634
1634
  return true;
1635
1635
  }
1636
- const s = nextSep(f, k, sep12);
1636
+ const s = nextSep(f, k, sep13);
1637
1637
  if (s === -1)
1638
1638
  return false;
1639
1639
  k = s + 1;
1640
- while (k < end && isSep(f.charCodeAt(k), sep12))
1640
+ while (k < end && isSep(f.charCodeAt(k), sep13))
1641
1641
  k++;
1642
1642
  }
1643
1643
  return false;
1644
1644
  };
1645
- isSep = (c, sep12) => sep12 === "/" ? c === 47 : sep12 === "\\" ? c === 92 : c === 47 || c === 92;
1646
- nextSep = (f, from, sep12) => {
1647
- if (sep12 !== "both")
1648
- return f.indexOf(sep12, from);
1645
+ isSep = (c, sep13) => sep13 === "/" ? c === 47 : sep13 === "\\" ? c === 92 : c === 47 || c === 92;
1646
+ nextSep = (f, from, sep13) => {
1647
+ if (sep13 !== "both")
1648
+ return f.indexOf(sep13, from);
1649
1649
  const s = f.indexOf("/", from);
1650
1650
  const b = f.indexOf("\\", from);
1651
1651
  return s === -1 ? b : b === -1 ? s : Math.min(s, b);
1652
1652
  };
1653
- lastSep = (f, from, sep12) => sep12 !== "both" ? f.lastIndexOf(sep12, from) : Math.max(f.lastIndexOf("/", from), f.lastIndexOf("\\", from));
1653
+ lastSep = (f, from, sep13) => sep13 !== "both" ? f.lastIndexOf(sep13, from) : Math.max(f.lastIndexOf("/", from), f.lastIndexOf("\\", from));
1654
1654
  PENDING = {};
1655
1655
  Minimatch = class {
1656
1656
  options;
@@ -1974,7 +1974,7 @@ var init_esm4 = __esm({
1974
1974
  // level 2, this is only known if none of them are `.` or `..`, so
1975
1975
  // that the path does not change when it is resolved.
1976
1976
  #canMatch(f) {
1977
- const sep12 = !this.isWindows || !f.includes("\\") ? "/" : f.includes("/") ? "both" : "\\";
1977
+ const sep13 = !this.isWindows || !f.includes("\\") ? "/" : f.includes("/") ? "both" : "\\";
1978
1978
  let ends = this.#endCheck ? 0 : -1;
1979
1979
  let last = "";
1980
1980
  let lastStart = 0;
@@ -1986,14 +1986,14 @@ var init_esm4 = __esm({
1986
1986
  const p = row[row.length - 1];
1987
1987
  let end = ends !== -1 && this.#endRows[r] && p !== GLOBSTAR;
1988
1988
  if (end && ends === 0) {
1989
- const i = lastSep(f, f.length, sep12);
1989
+ const i = lastSep(f, f.length, sep13);
1990
1990
  lastStart = i + 1;
1991
1991
  last = f.slice(lastStart);
1992
1992
  if (last === "" && i >= 0) {
1993
1993
  let j = i;
1994
- while (j > 0 && isSep(f.charCodeAt(j - 1), sep12))
1994
+ while (j > 0 && isSep(f.charCodeAt(j - 1), sep13))
1995
1995
  j--;
1996
- prevStart = j === 0 ? 0 : lastSep(f, j - 1, sep12) + 1;
1996
+ prevStart = j === 0 ? 0 : lastSep(f, j - 1, sep13) + 1;
1997
1997
  prev = f.slice(prevStart, j);
1998
1998
  }
1999
1999
  const resolves = this.#level2 && (isDots(last) || last === "" && prev !== void 0 && isDots(prev));
@@ -2021,15 +2021,15 @@ var init_esm4 = __esm({
2021
2021
  if (shape === "base" && end)
2022
2022
  return "yes";
2023
2023
  if (shape === "tail" && end) {
2024
- if (this.#level2 && dotPortion(f, 0, tailStart, true, sep12)) {
2024
+ if (this.#level2 && dotPortion(f, 0, tailStart, true, sep13)) {
2025
2025
  return "maybe";
2026
2026
  }
2027
- if (!dotPortion(f, 0, tailStart, dot, sep12))
2027
+ if (!dotPortion(f, 0, tailStart, dot, sep13))
2028
2028
  return "yes";
2029
2029
  continue;
2030
2030
  }
2031
2031
  if (shape === "mid" || shape === "head") {
2032
- const m = this.#walk(f, row, shape === "head", dot, sep12);
2032
+ const m = this.#walk(f, row, shape === "head", dot, sep13);
2033
2033
  if (m !== "no")
2034
2034
  return m;
2035
2035
  continue;
@@ -2085,19 +2085,19 @@ var init_esm4 = __esm({
2085
2085
  // it must be able to walk the portions before that one, and there
2086
2086
  // must be a portion after it, which the ** after it can walk. At
2087
2087
  // level 2, this is only known if no portion is `.` or `..`.
2088
- #walk(f, row, head, dot, sep12) {
2089
- if (this.#level2 && dotPortion(f, 0, f.length, true, sep12))
2088
+ #walk(f, row, head, dot, sep13) {
2089
+ if (this.#level2 && dotPortion(f, 0, f.length, true, sep13))
2090
2090
  return "maybe";
2091
2091
  const x = row[head ? 0 : 1];
2092
2092
  let s = 0;
2093
- for (let e = nextSep(f, s, sep12); e !== -1; e = nextSep(f, s, sep12)) {
2093
+ for (let e = nextSep(f, s, sep13); e !== -1; e = nextSep(f, s, sep13)) {
2094
2094
  let next = e + 1;
2095
- while (next < f.length && isSep(f.charCodeAt(next), sep12))
2095
+ while (next < f.length && isSep(f.charCodeAt(next), sep13))
2096
2096
  next++;
2097
2097
  const hit = typeof x === "string" ? e - s === x.length && f.startsWith(x, s) : e > s && x.testUnchecked(f.slice(s, e));
2098
- if (hit && !dotPortion(f, next, f.length, dot, sep12))
2098
+ if (hit && !dotPortion(f, next, f.length, dot, sep13))
2099
2099
  return "yes";
2100
- if (head || dotPortion(f, s, next, dot, sep12))
2100
+ if (head || dotPortion(f, s, next, dot, sep13))
2101
2101
  return "no";
2102
2102
  s = next;
2103
2103
  }
@@ -2886,8 +2886,8 @@ function normalizeMapKey(filePath) {
2886
2886
  return normalizeFilePath(filePath);
2887
2887
  }
2888
2888
  function relativeInside(root, file, pathImpl = path2) {
2889
- const relative27 = pathImpl.relative(pathImpl.resolve(root), file);
2890
- return relative27 !== ".." && !relative27.startsWith(`..${pathImpl.sep}`) && !pathImpl.isAbsolute(relative27) ? relative27.replace(/\\/g, "/") : void 0;
2889
+ const relative28 = pathImpl.relative(pathImpl.resolve(root), file);
2890
+ return relative28 !== ".." && !relative28.startsWith(`..${pathImpl.sep}`) && !pathImpl.isAbsolute(relative28) ? relative28.replace(/\\/g, "/") : void 0;
2891
2891
  }
2892
2892
  function toProjectRelativePath(filePath, projectRoot) {
2893
2893
  return relativeToProjectRoot(filePath, projectRoot, () => normalizeFilePath(projectRoot));
@@ -5368,8 +5368,8 @@ function untilAborted(work, signal, aborted) {
5368
5368
  if (signal.aborted)
5369
5369
  return Promise.race([work, Promise.resolve(aborted)]);
5370
5370
  let onAbort;
5371
- const abortedPromise = new Promise((resolve153) => {
5372
- onAbort = () => resolve153(aborted);
5371
+ const abortedPromise = new Promise((resolve154) => {
5372
+ onAbort = () => resolve154(aborted);
5373
5373
  signal.addEventListener("abort", onAbort, { once: true });
5374
5374
  });
5375
5375
  return Promise.race([work, abortedPromise]).finally(() => {
@@ -5391,10 +5391,10 @@ function withDeadline(promise, options) {
5391
5391
  promise.catch(() => {
5392
5392
  });
5393
5393
  let timer;
5394
- const timeoutPromise = new Promise((resolve153, reject) => {
5394
+ const timeoutPromise = new Promise((resolve154, reject) => {
5395
5395
  timer = setTimeout(() => {
5396
5396
  if (onTimeout === "undefined")
5397
- resolve153(void 0);
5397
+ resolve154(void 0);
5398
5398
  else
5399
5399
  reject(new Error(`Timeout after ${ms}ms`));
5400
5400
  }, ms);
@@ -5428,10 +5428,10 @@ async function bounded(promise, options) {
5428
5428
  let timer;
5429
5429
  let onCallerAbort;
5430
5430
  let onShutdownAbort;
5431
- const abandoned = new Promise((resolve153) => {
5431
+ const abandoned = new Promise((resolve154) => {
5432
5432
  const fire = (reason) => {
5433
5433
  cause ??= reason;
5434
- resolve153(BOUND_ABORTED);
5434
+ resolve154(BOUND_ABORTED);
5435
5435
  };
5436
5436
  if (signal?.aborted)
5437
5437
  return fire("caller-abort");
@@ -6329,10 +6329,44 @@ function isLspSpawnAllowedByTrust() {
6329
6329
  function projectTrustDenialReason() {
6330
6330
  return trustState === "untrusted" ? "project is not trusted (host isProjectTrusted() === false)" : void 0;
6331
6331
  }
6332
- var trustState, installRefusalWarnings, INSTALL_REFUSAL_WARNING_CAP, trustGeneration;
6332
+ function setHostProjectTrustLoader(loader) {
6333
+ loadProjectTrustSdk = loader;
6334
+ }
6335
+ async function readAdoptedProjectTrust(root, shutdownSignal) {
6336
+ if (!loadProjectTrustSdk)
6337
+ return getProjectTrustState();
6338
+ try {
6339
+ const sdk = await bounded(loadProjectTrustSdk(), {
6340
+ ms: HOOK_WALL_BUDGET_MS.tool_result_read_only,
6341
+ signal: void 0,
6342
+ ...shutdownSignal ? { shutdownSignal } : {},
6343
+ hook: "off_hook",
6344
+ label: "adopted-project-trust-sdk"
6345
+ });
6346
+ if (!sdk?.ProjectTrustStore || !sdk.getAgentDir || !sdk.hasTrustRequiringProjectResources || !sdk.SettingsManager) {
6347
+ throw new Error("host SDK lacks adopted project trust exports");
6348
+ }
6349
+ const agentDir = sdk.getAgentDir();
6350
+ const saved = new sdk.ProjectTrustStore(agentDir).get(root);
6351
+ const trusted = !sdk.hasTrustRequiringProjectResources(root) ? saved ?? true : saved ?? sdk.SettingsManager.create(agentDir, agentDir, {
6352
+ projectTrusted: false
6353
+ }).getGlobalSettings().defaultProjectTrust === "always";
6354
+ return trusted ? "trusted" : "untrusted";
6355
+ } catch (trustErr) {
6356
+ recordDegradationOnce({
6357
+ kind: "lsp-registry-decision",
6358
+ subject: `adopted-trust:${root}`,
6359
+ reason: `adopted project trust unavailable: ${String(trustErr)}`
6360
+ });
6361
+ return "untrusted";
6362
+ }
6363
+ }
6364
+ var trustState, installRefusalWarnings, INSTALL_REFUSAL_WARNING_CAP, trustGeneration, loadProjectTrustSdk;
6333
6365
  var init_project_trust = __esm({
6334
6366
  "dist/clients/project-trust.js"() {
6335
6367
  "use strict";
6368
+ init_deadline_utils();
6369
+ init_hook_budgets();
6336
6370
  init_extension_log();
6337
6371
  init_degradation_ledger();
6338
6372
  trustState = "unknown";
@@ -8617,10 +8651,10 @@ function writeFlowMapping(state9, level, node) {
8617
8651
  const keyRender = writeNode(state9, level, key4, node, { iskey: true });
8618
8652
  const keyText = keyRender.text;
8619
8653
  const valueText = writeNode(state9, level, value, node, {}).text;
8620
- const sep12 = state9.flowSkipColonSpace || valueText === "" ? "" : " ";
8654
+ const sep13 = state9.flowSkipColonSpace || valueText === "" ? "" : " ";
8621
8655
  const keyIsBareProps = key4.kind === "scalar" && keyRender.noBody && (key4.tagged || key4.anchor !== void 0);
8622
8656
  const keyColonSep = key4.kind === "alias" || keyIsBareProps ? " " : "";
8623
- pairBuffer += `${keyText}${keyColonSep}:${sep12}${valueText}`;
8657
+ pairBuffer += `${keyText}${keyColonSep}:${sep13}${valueText}`;
8624
8658
  result += pairBuffer;
8625
8659
  }
8626
8660
  const pad = state9.flowBracketPadding && result !== "" ? " " : "";
@@ -8716,8 +8750,8 @@ function writeNode(state9, level, node, parent, ctx) {
8716
8750
  if (anchor !== null) props.push(anchor);
8717
8751
  if (tag !== null) props.push(tag);
8718
8752
  }
8719
- const sep12 = body === "" || body.charCodeAt(0) === CHAR_LINE_FEED ? "" : " ";
8720
- text = `${props.join(" ")}${sep12}${body}`;
8753
+ const sep13 = body === "" || body.charCodeAt(0) === CHAR_LINE_FEED ? "" : " ";
8754
+ text = `${props.join(" ")}${sep13}${body}`;
8721
8755
  }
8722
8756
  return {
8723
8757
  text,
@@ -8759,8 +8793,8 @@ function present(documents, options) {
8759
8793
  block: true,
8760
8794
  compact: true
8761
8795
  }).text;
8762
- const sep12 = body === "" ? "" : hasDirectives || rootStartsOwnLine(doc.contents) ? "\n" : " ";
8763
- result += `---${sep12}${body}
8796
+ const sep13 = body === "" ? "" : hasDirectives || rootStartsOwnLine(doc.contents) ? "\n" : " ";
8797
+ result += `---${sep13}${body}
8764
8798
  `;
8765
8799
  } else result += writeNode(state9, 0, doc.contents, null, {
8766
8800
  block: true,
@@ -10533,7 +10567,7 @@ function unrefChildAndPipes(child) {
10533
10567
  }
10534
10568
  }
10535
10569
  function spawnCollectStdoutResult(command, args, options, collectOptions = {}) {
10536
- return new Promise((resolve153) => {
10570
+ return new Promise((resolve154) => {
10537
10571
  let settled = false;
10538
10572
  let timer;
10539
10573
  const settle = (result) => {
@@ -10542,7 +10576,7 @@ function spawnCollectStdoutResult(command, args, options, collectOptions = {}) {
10542
10576
  settled = true;
10543
10577
  if (timer)
10544
10578
  clearTimeout(timer);
10545
- resolve153(result);
10579
+ resolve154(result);
10546
10580
  };
10547
10581
  try {
10548
10582
  const child = nodeSpawn(command, args, options);
@@ -11304,7 +11338,7 @@ var require_parallel = __commonJS({
11304
11338
  var require_cpu = __commonJS({
11305
11339
  "node_modules/pidusage/lib/helpers/cpu.js"(exports, module) {
11306
11340
  var os42 = __require("os");
11307
- var fs151 = __require("fs");
11341
+ var fs152 = __require("fs");
11308
11342
  var exec = __require("child_process").exec;
11309
11343
  var parallel = require_parallel();
11310
11344
  function updateCpu(cpu, next) {
@@ -11331,7 +11365,7 @@ var require_cpu = __commonJS({
11331
11365
  }
11332
11366
  module.exports = updateCpu;
11333
11367
  function getRealUptime(next) {
11334
- fs151.readFile("/proc/uptime", "utf8", function(err, uptime) {
11368
+ fs152.readFile("/proc/uptime", "utf8", function(err, uptime) {
11335
11369
  if (err || uptime === void 0) {
11336
11370
  if (!process.env.PIDUSAGE_SILENT) {
11337
11371
  console.warn("[pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value");
@@ -11379,7 +11413,7 @@ var require_cpu = __commonJS({
11379
11413
  // node_modules/pidusage/lib/procfile.js
11380
11414
  var require_procfile = __commonJS({
11381
11415
  "node_modules/pidusage/lib/procfile.js"(exports, module) {
11382
- var fs151 = __require("fs");
11416
+ var fs152 = __require("fs");
11383
11417
  var path239 = __require("path");
11384
11418
  var updateCpu = require_cpu();
11385
11419
  var parallel = require_parallel();
@@ -11392,11 +11426,11 @@ var require_procfile = __commonJS({
11392
11426
  if (history2.fd) {
11393
11427
  return cb(null, history2.fd);
11394
11428
  }
11395
- fs151.open(path240, "r", cb);
11429
+ fs152.open(path240, "r", cb);
11396
11430
  }
11397
11431
  function close(history2) {
11398
11432
  if (history2.fd) {
11399
- fs151.close(history2.fd, noop2);
11433
+ fs152.close(history2.fd, noop2);
11400
11434
  }
11401
11435
  }
11402
11436
  function readUntilEnd(fd, buf, cb) {
@@ -11406,7 +11440,7 @@ var require_procfile = __commonJS({
11406
11440
  buf = Buffer.alloc(SIZE);
11407
11441
  firstRead = true;
11408
11442
  }
11409
- fs151.read(fd, buf, 0, SIZE, 0, function(err, bytesRead, buffer) {
11443
+ fs152.read(fd, buf, 0, SIZE, 0, function(err, bytesRead, buffer) {
11410
11444
  if (err) {
11411
11445
  cb(err);
11412
11446
  return;
@@ -11689,7 +11723,7 @@ var require_gwmi = __commonJS({
11689
11723
  var require_stats = __commonJS({
11690
11724
  "node_modules/pidusage/lib/stats.js"(exports, module) {
11691
11725
  "use strict";
11692
- var fs151 = __require("fs");
11726
+ var fs152 = __require("fs");
11693
11727
  var os42 = __require("os");
11694
11728
  var path239 = __require("path");
11695
11729
  var requireMap = {
@@ -11713,7 +11747,7 @@ var require_stats = __commonJS({
11713
11747
  win: "wmic"
11714
11748
  };
11715
11749
  var platform = os42.platform();
11716
- if (fs151.existsSync("/etc/alpine-release")) {
11750
+ if (fs152.existsSync("/etc/alpine-release")) {
11717
11751
  platform = "alpine";
11718
11752
  }
11719
11753
  if (platform.match(/^win/)) {
@@ -11727,7 +11761,7 @@ var require_stats = __commonJS({
11727
11761
  var wmicAvailable;
11728
11762
  function hasWmic() {
11729
11763
  if (wmicAvailable === void 0) {
11730
- wmicAvailable = fs151.existsSync(path239.join(process.env.SystemRoot || "C:\\Windows", "System32", "wbem", "WMIC.exe"));
11764
+ wmicAvailable = fs152.existsSync(path239.join(process.env.SystemRoot || "C:\\Windows", "System32", "wbem", "WMIC.exe"));
11731
11765
  }
11732
11766
  return wmicAvailable;
11733
11767
  }
@@ -11792,10 +11826,10 @@ var require_pidusage = __commonJS({
11792
11826
  stats(pids, options, callback);
11793
11827
  return;
11794
11828
  }
11795
- return new Promise(function(resolve153, reject) {
11829
+ return new Promise(function(resolve154, reject) {
11796
11830
  stats(pids, options, function(err, data) {
11797
11831
  if (err) return reject(err);
11798
- resolve153(data);
11832
+ resolve154(data);
11799
11833
  });
11800
11834
  });
11801
11835
  }
@@ -12173,7 +12207,7 @@ async function releaseQuarantineLock(lockPath, token) {
12173
12207
  } catch (error) {
12174
12208
  if (error.code !== "ENOENT" || attempt === 2)
12175
12209
  return;
12176
- await new Promise((resolve153) => setImmediate(resolve153));
12210
+ await new Promise((resolve154) => setImmediate(resolve154));
12177
12211
  }
12178
12212
  }
12179
12213
  if (!renamed)
@@ -12300,7 +12334,7 @@ async function acquireQuarantinePidFileLock(lockPath, options) {
12300
12334
  }
12301
12335
  throw new Error(options.timeoutMessage);
12302
12336
  }
12303
- await new Promise((resolve153) => setTimeout(resolve153, Math.min(options.retryMs, remaining)));
12337
+ await new Promise((resolve154) => setTimeout(resolve154, Math.min(options.retryMs, remaining)));
12304
12338
  }
12305
12339
  }
12306
12340
  function createLegacyBoundedLock(lockPath, token) {
@@ -12694,7 +12728,7 @@ async function withInstanceRegistryLock(target, op, waitMs = LOCK_WAIT_MS) {
12694
12728
  return void 0;
12695
12729
  if (hold === "busy") {
12696
12730
  if (Date.now() <= deadline)
12697
- await new Promise((resolve153) => setTimeout(resolve153, backoffMs()));
12731
+ await new Promise((resolve154) => setTimeout(resolve154, backoffMs()));
12698
12732
  continue;
12699
12733
  }
12700
12734
  const holds = ownAsyncHolds();
@@ -13598,8 +13632,8 @@ function buildIdentityMatcher(identities) {
13598
13632
  };
13599
13633
  }
13600
13634
  function sleepUnref(ms) {
13601
- return new Promise((resolve153) => {
13602
- const timer = setTimeout(resolve153, ms);
13635
+ return new Promise((resolve154) => {
13636
+ const timer = setTimeout(resolve154, ms);
13603
13637
  timer.unref();
13604
13638
  });
13605
13639
  }
@@ -13617,9 +13651,9 @@ async function killPidTree(pid, options = {}) {
13617
13651
  stdio: "ignore"
13618
13652
  });
13619
13653
  unrefChildAndPipes(killer);
13620
- await new Promise((resolve153) => {
13621
- killer.once("close", () => resolve153());
13622
- killer.once("error", () => resolve153());
13654
+ await new Promise((resolve154) => {
13655
+ killer.once("close", () => resolve154());
13656
+ killer.once("error", () => resolve154());
13623
13657
  });
13624
13658
  } catch {
13625
13659
  }
@@ -14341,9 +14375,9 @@ async function sampleProcessTreeCpuPercent(pid, windowMs = 1200, floorPercent =
14341
14375
  }
14342
14376
  };
14343
14377
  const first = await readOnce();
14344
- const second = await new Promise((resolve153) => {
14378
+ const second = await new Promise((resolve154) => {
14345
14379
  const timer = setTimeout(() => {
14346
- void readOnce().then(resolve153);
14380
+ void readOnce().then(resolve154);
14347
14381
  }, windowMs);
14348
14382
  timer.unref?.();
14349
14383
  });
@@ -15179,10 +15213,10 @@ async function safeSpawnAsync(command, args, options) {
15179
15213
  const scopedSignal = options?.ignoreAmbientSignal ? void 0 : spawnAbortScope.getStore();
15180
15214
  const abortSignal = scopedSignal && callerSignal ? AbortSignal.any([scopedSignal, callerSignal]) : scopedSignal ?? callerSignal;
15181
15215
  const cooldown = options?.cooldown ?? (options?.ignoreAmbientSignal ? void 0 : spawnCooldownScope.getStore());
15182
- const result = await new Promise((resolve153) => {
15216
+ const result = await new Promise((resolve154) => {
15183
15217
  if (abortSignal?.aborted) {
15184
15218
  const cause = new Error("Spawn aborted before start");
15185
- resolve153({
15219
+ resolve154({
15186
15220
  stdout: "",
15187
15221
  stderr: "",
15188
15222
  status: null,
@@ -15194,7 +15228,7 @@ async function safeSpawnAsync(command, args, options) {
15194
15228
  }
15195
15229
  if (timeout <= 0) {
15196
15230
  const cause = new Error(`Process timed out after ${timeout}ms`);
15197
- resolve153({
15231
+ resolve154({
15198
15232
  stdout: "",
15199
15233
  stderr: "",
15200
15234
  status: null,
@@ -15327,7 +15361,7 @@ async function safeSpawnAsync(command, args, options) {
15327
15361
  const isWindows3 = process.platform === "win32";
15328
15362
  const admission = admitSpawn(command, options?.cwd, getSpawnEnvironment(command, options?.env, options?.stripNpmConfig));
15329
15363
  if (!admission.admitted) {
15330
- resolve153(trustRefusalResult(command, admission.executable));
15364
+ resolve154(trustRefusalResult(command, admission.executable));
15331
15365
  return;
15332
15366
  }
15333
15367
  const spawnEnv = admission.env;
@@ -15364,7 +15398,7 @@ async function safeSpawnAsync(command, args, options) {
15364
15398
  void classifySpawnFailure(resolutionError, {
15365
15399
  command,
15366
15400
  cwd: options?.cwd
15367
- }).then((spawnFailure) => resolve153({
15401
+ }).then((spawnFailure) => resolve154({
15368
15402
  stdout: "",
15369
15403
  stderr: "",
15370
15404
  status: null,
@@ -15387,7 +15421,7 @@ async function safeSpawnAsync(command, args, options) {
15387
15421
  });
15388
15422
  } catch (err) {
15389
15423
  const cause = toError(err);
15390
- void classifySpawnFailure(cause, { command, cwd: options?.cwd }).then((spawnFailure) => resolve153({
15424
+ void classifySpawnFailure(cause, { command, cwd: options?.cwd }).then((spawnFailure) => resolve154({
15391
15425
  stdout: "",
15392
15426
  stderr: "",
15393
15427
  status: null,
@@ -15680,7 +15714,7 @@ async function safeSpawnAsync(command, args, options) {
15680
15714
  deathObservedAtMs: closedAtMs,
15681
15715
  escalated: teardownEscalated
15682
15716
  });
15683
- resolve153({
15717
+ resolve154({
15684
15718
  stdout,
15685
15719
  stderr,
15686
15720
  status: null,
@@ -15695,7 +15729,7 @@ async function safeSpawnAsync(command, args, options) {
15695
15729
  });
15696
15730
  } else if (aborted) {
15697
15731
  const cause = new Error("Spawn aborted");
15698
- resolve153({
15732
+ resolve154({
15699
15733
  stdout,
15700
15734
  stderr,
15701
15735
  status: null,
@@ -15709,7 +15743,7 @@ async function safeSpawnAsync(command, args, options) {
15709
15743
  });
15710
15744
  } else if (signal) {
15711
15745
  const cause = new Error(`Process killed by signal: ${signal}`);
15712
- resolve153({
15746
+ resolve154({
15713
15747
  stdout,
15714
15748
  stderr,
15715
15749
  status: null,
@@ -15727,7 +15761,7 @@ async function safeSpawnAsync(command, args, options) {
15727
15761
  command,
15728
15762
  cwd: options?.cwd
15729
15763
  });
15730
- resolve153({
15764
+ resolve154({
15731
15765
  stdout,
15732
15766
  stderr,
15733
15767
  status: code,
@@ -15739,7 +15773,7 @@ async function safeSpawnAsync(command, args, options) {
15739
15773
  resourceUsage
15740
15774
  });
15741
15775
  } else {
15742
- resolve153({
15776
+ resolve154({
15743
15777
  stdout,
15744
15778
  stderr,
15745
15779
  status: code,
@@ -15771,7 +15805,7 @@ async function safeSpawnAsync(command, args, options) {
15771
15805
  else if (timedOut)
15772
15806
  failure = "timeout";
15773
15807
  const controlFailure = aborted ? new SpawnFailureError("killed", err.message, err) : timedOut ? new SpawnFailureError("timeout", err.message, err) : void 0;
15774
- const finish = (spawnFailure) => resolve153({
15808
+ const finish = (spawnFailure) => resolve154({
15775
15809
  stdout,
15776
15810
  stderr,
15777
15811
  status: null,
@@ -19225,10 +19259,10 @@ function isPiOwnedTempPath(filePath) {
19225
19259
  const real = realpathOrResolve(filePath);
19226
19260
  if (!isUnderDir(real, tmpRoot))
19227
19261
  return false;
19228
- const relative27 = path26.relative(tmpRoot, real);
19229
- if (relative27.length === 0 || path26.isAbsolute(relative27))
19262
+ const relative28 = path26.relative(tmpRoot, real);
19263
+ if (relative28.length === 0 || path26.isAbsolute(relative28))
19230
19264
  return false;
19231
- const segments = relative27.split(path26.sep);
19265
+ const segments = relative28.split(path26.sep);
19232
19266
  return segments.length === 1 || /^pi-/i.test(segments[0] ?? "");
19233
19267
  }
19234
19268
  function isEphemeralCheckoutRoot(dir) {
@@ -19504,9 +19538,9 @@ function drainProjectDataDirMigrations() {
19504
19538
  function displayProjectDataPath(cwd, ...segments) {
19505
19539
  const absolute = path27.resolve(getProjectDataDir(cwd), ...segments);
19506
19540
  const absolutePosix = toPosix(absolute);
19507
- const relative27 = toProjectRelativePath(absolute, cwd);
19508
- if (relative27 !== absolutePosix) {
19509
- return relative27;
19541
+ const relative28 = toProjectRelativePath(absolute, cwd);
19542
+ if (relative28 !== absolutePosix) {
19543
+ return relative28;
19510
19544
  }
19511
19545
  return homeRelativePath(absolutePosix);
19512
19546
  }
@@ -19652,10 +19686,10 @@ function createExpandedGlobMatcher() {
19652
19686
  };
19653
19687
  }
19654
19688
  function isIgnoredByGitignoreLines(lines, baseDir, filePath, isDirectory2 = false) {
19655
- const relative27 = relativeInside(baseDir, filePath);
19656
- if (relative27 === void 0)
19689
+ const relative28 = relativeInside(baseDir, filePath);
19690
+ if (relative28 === void 0)
19657
19691
  return false;
19658
- const winner = lastMatchingPattern(parseGitignoreContent(lines.join("\n"), "pilens"), normalizeIgnorePath(relative27), isDirectory2, createExpandedGlobMatcher());
19692
+ const winner = lastMatchingPattern(parseGitignoreContent(lines.join("\n"), "pilens"), normalizeIgnorePath(relative28), isDirectory2, createExpandedGlobMatcher());
19659
19693
  return winner !== void 0 && !winner.negated;
19660
19694
  }
19661
19695
  function readGitignorePatterns(rootDir, layer = "gitignore") {
@@ -19675,12 +19709,12 @@ function isWithinPathForm(child, parent) {
19675
19709
  function ancestorDirsBetween(rootDir, targetDir) {
19676
19710
  if (!isWithinPathForm(targetDir, rootDir))
19677
19711
  return [];
19678
- const relative27 = path27.relative(rootDir, targetDir);
19712
+ const relative28 = path27.relative(rootDir, targetDir);
19679
19713
  const dirs = [rootDir];
19680
- if (!relative27)
19714
+ if (!relative28)
19681
19715
  return dirs;
19682
19716
  let current = rootDir;
19683
- for (const segment of relative27.split(path27.sep).filter(Boolean)) {
19717
+ for (const segment of relative28.split(path27.sep).filter(Boolean)) {
19684
19718
  current = path27.join(current, segment);
19685
19719
  dirs.push(current);
19686
19720
  }
@@ -19804,8 +19838,8 @@ function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
19804
19838
  const dirPatterns = patternsForDir(dir);
19805
19839
  if (dirPatterns.length === 0)
19806
19840
  continue;
19807
- const relative27 = path27.relative(dir, resolved2);
19808
- const normalized2 = normalizeIgnorePath(relative27);
19841
+ const relative28 = path27.relative(dir, resolved2);
19842
+ const normalized2 = normalizeIgnorePath(relative28);
19809
19843
  const winner = lastMatchingPattern(dirPatterns, normalized2, isDirectory2, matchExpanded);
19810
19844
  if (winner) {
19811
19845
  ignored = !winner.negated;
@@ -22911,7 +22945,7 @@ function createDeadline(budgetMs) {
22911
22945
  async function yieldIfOverBudget(deadline) {
22912
22946
  if (!deadline.expired())
22913
22947
  return false;
22914
- await new Promise((resolve153) => setImmediate(resolve153));
22948
+ await new Promise((resolve154) => setImmediate(resolve154));
22915
22949
  deadline.reset();
22916
22950
  return true;
22917
22951
  }
@@ -28897,8 +28931,8 @@ function createSingleFlight(options = {}) {
28897
28931
  }
28898
28932
  let settle;
28899
28933
  let fail;
28900
- const promise = new Promise((resolve153, reject) => {
28901
- settle = resolve153;
28934
+ const promise = new Promise((resolve154, reject) => {
28935
+ settle = resolve154;
28902
28936
  fail = reject;
28903
28937
  });
28904
28938
  const flight = {
@@ -32225,7 +32259,7 @@ async function collectSourceFilesForWarmup(rootDir, maxFiles = MAX_WARMUP_SOURCE
32225
32259
  }
32226
32260
  }
32227
32261
  if (++processedSinceYield % yieldEvery === 0) {
32228
- await new Promise((resolve153) => setImmediate(resolve153));
32262
+ await new Promise((resolve154) => setImmediate(resolve154));
32229
32263
  }
32230
32264
  }
32231
32265
  }
@@ -34900,7 +34934,7 @@ async function acquireInstallLock() {
34900
34934
  ownsLock: () => ownsTopGeneration(hold.generation)
34901
34935
  };
34902
34936
  }
34903
- await new Promise((resolve153) => setTimeout(resolve153, 100));
34937
+ await new Promise((resolve154) => setTimeout(resolve154, 100));
34904
34938
  }
34905
34939
  return {
34906
34940
  reason: `timed out after ${timeoutMs}ms waiting for shared tools install lock (${installLockOwner()})`
@@ -35868,7 +35902,7 @@ function sameHost(a, b) {
35868
35902
  }
35869
35903
  }
35870
35904
  function httpsGetWithMeta(url, maxRedirects = 5, headers = {}) {
35871
- return new Promise((resolve153, reject) => {
35905
+ return new Promise((resolve154, reject) => {
35872
35906
  https.get(url, { headers: { "User-Agent": "pi-lens/1.0", ...headers } }, (res) => {
35873
35907
  if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
35874
35908
  if (maxRedirects === 0)
@@ -35878,12 +35912,12 @@ function httpsGetWithMeta(url, maxRedirects = 5, headers = {}) {
35878
35912
  const { Authorization: _drop, ...rest } = headers;
35879
35913
  return rest;
35880
35914
  })();
35881
- return resolve153(httpsGetWithMeta(location, maxRedirects - 1, nextHeaders));
35915
+ return resolve154(httpsGetWithMeta(location, maxRedirects - 1, nextHeaders));
35882
35916
  }
35883
35917
  const etag = typeof res.headers.etag === "string" ? res.headers.etag : void 0;
35884
35918
  if (res.statusCode === 304) {
35885
35919
  res.resume();
35886
- return resolve153({ statusCode: 304, body: Buffer.alloc(0), etag });
35920
+ return resolve154({ statusCode: 304, body: Buffer.alloc(0), etag });
35887
35921
  }
35888
35922
  if (res.statusCode !== 200) {
35889
35923
  res.resume();
@@ -35891,7 +35925,7 @@ function httpsGetWithMeta(url, maxRedirects = 5, headers = {}) {
35891
35925
  }
35892
35926
  const chunks = [];
35893
35927
  res.on("data", (chunk) => chunks.push(chunk));
35894
- res.on("end", () => resolve153({ statusCode: 200, body: Buffer.concat(chunks), etag }));
35928
+ res.on("end", () => resolve154({ statusCode: 200, body: Buffer.concat(chunks), etag }));
35895
35929
  res.on("error", reject);
35896
35930
  }).on("error", reject);
35897
35931
  });
@@ -36000,11 +36034,11 @@ exec ${launcherRuntime} "$(dirname "$0")/${runtimeTarget}" "$@"
36000
36034
  mode: isWindows3 ? void 0 : 488
36001
36035
  });
36002
36036
  } else if (assetName.endsWith(".gz") && !assetName.endsWith(".tar.gz")) {
36003
- const decompressed = await new Promise((resolve153, reject) => {
36037
+ const decompressed = await new Promise((resolve154, reject) => {
36004
36038
  const gunzip = createGunzip();
36005
36039
  const chunks = [];
36006
36040
  gunzip.on("data", (chunk) => chunks.push(chunk));
36007
- gunzip.on("end", () => resolve153(Buffer.concat(chunks)));
36041
+ gunzip.on("end", () => resolve154(Buffer.concat(chunks)));
36008
36042
  gunzip.on("error", reject);
36009
36043
  gunzip.end(assetBuffer);
36010
36044
  });
@@ -39260,8 +39294,7 @@ function recordUntrustedLspExecution(request, trust) {
39260
39294
  });
39261
39295
  }
39262
39296
  }
39263
- function refuseUntrustedLspExecution(request) {
39264
- const trust = getProjectTrustState();
39297
+ function refuseUntrustedLspExecution(request, trust = getProjectTrustState()) {
39265
39298
  const needsTrust = request.kind === "project-code-server" ? trust !== "trusted" : !admitProjectSuppliedTsserver(request.resolvedCommand, request.cwd, true);
39266
39299
  if (!needsTrust)
39267
39300
  return;
@@ -39504,7 +39537,7 @@ async function launchLSP(command, args = [], options = {}) {
39504
39537
  };
39505
39538
  proc.stderr?.on("data", onStartupStderr);
39506
39539
  try {
39507
- await new Promise((resolve153, reject) => {
39540
+ await new Promise((resolve154, reject) => {
39508
39541
  let settled = false;
39509
39542
  proc.on("error", (err) => {
39510
39543
  if (!settled) {
@@ -39541,7 +39574,7 @@ async function launchLSP(command, args = [], options = {}) {
39541
39574
  setTimeout(() => {
39542
39575
  if (!settled) {
39543
39576
  settled = true;
39544
- resolve153();
39577
+ resolve154();
39545
39578
  }
39546
39579
  }, startupFailureWindowMs);
39547
39580
  });
@@ -40625,10 +40658,10 @@ async function findUvWorkspace(startDir, homeDir) {
40625
40658
  } : void 0;
40626
40659
  }
40627
40660
  function isUvWorkspaceMember(workspace, projectRoot) {
40628
- const relative27 = relativeInside(workspace.root, projectRoot);
40629
- if (!relative27)
40661
+ const relative28 = relativeInside(workspace.root, projectRoot);
40662
+ if (!relative28)
40630
40663
  return false;
40631
- const matches = (dialect) => (pattern) => matchesWorkspaceMemberPattern(pattern, relative27, dialect, () => recordDegradationOnce({
40664
+ const matches = (dialect) => (pattern) => matchesWorkspaceMemberPattern(pattern, relative28, dialect, () => recordDegradationOnce({
40632
40665
  kind: "workspace-glob-cap",
40633
40666
  subject: String(pattern.length),
40634
40667
  reason: "workspace glob matcher exceeded its memo-table cell cap"
@@ -42907,8 +42940,8 @@ function createInteractiveServer(spec) {
42907
42940
  function PriorityRoot(markerGroups, excludePatterns, stopDir) {
42908
42941
  const resolvers = markerGroups.map((markers) => NearestRoot(markers, excludePatterns, stopDir));
42909
42942
  return withRootMarkers(async (file) => {
42910
- for (const resolve153 of resolvers) {
42911
- const root = await resolve153(file);
42943
+ for (const resolve154 of resolvers) {
42944
+ const root = await resolve154(file);
42912
42945
  if (root)
42913
42946
  return root;
42914
42947
  }
@@ -43083,7 +43116,7 @@ async function findAncestorFile(startDir, ...relativeSegments) {
43083
43116
  return findAncestorFileAmong(startDir, [relativeSegments]);
43084
43117
  }
43085
43118
  async function findAncestorFileAmong(startDir, candidateSegmentLists) {
43086
- const fs151 = await import("node:fs/promises");
43119
+ const fs152 = await import("node:fs/promises");
43087
43120
  const home = realpathOrResolve(os22.homedir());
43088
43121
  for (const currentDir of walkUpDirs(startDir, { spelling: true })) {
43089
43122
  if (isAtOrAboveHomeDir(realpathOrResolve(currentDir), home))
@@ -43091,7 +43124,7 @@ async function findAncestorFileAmong(startDir, candidateSegmentLists) {
43091
43124
  for (const segments of candidateSegmentLists) {
43092
43125
  const candidate = path63.join(currentDir, ...segments);
43093
43126
  try {
43094
- await fs151.access(candidate);
43127
+ await fs152.access(candidate);
43095
43128
  return candidate;
43096
43129
  } catch {
43097
43130
  }
@@ -43156,14 +43189,14 @@ async function absoluteCommandPath(command) {
43156
43189
  return found ? realpath(found).catch(() => void 0) : void 0;
43157
43190
  }
43158
43191
  async function findTsserverPath(root, allowInstall, options) {
43159
- const fs151 = await import("node:fs/promises");
43160
- const projectRoots = await Promise.all([root, options?.sessionRoot ?? process.cwd(), process.cwd()].map((dir) => fs151.realpath(dir).catch(() => path63.resolve(dir))));
43192
+ const fs152 = await import("node:fs/promises");
43193
+ const projectRoots = await Promise.all([root, options?.sessionRoot ?? process.cwd(), process.cwd()].map((dir) => fs152.realpath(dir).catch(() => path63.resolve(dir))));
43161
43194
  const admitCandidate = async (candidate, projectSupplied) => {
43162
43195
  try {
43163
- const real = await fs151.realpath(candidate);
43164
- if (path63.basename(real) !== "tsserver.js" || !(await fs151.stat(real)).isFile())
43196
+ const real = await fs152.realpath(candidate);
43197
+ if (path63.basename(real) !== "tsserver.js" || !(await fs152.stat(real)).isFile())
43165
43198
  return void 0;
43166
- const manifest = JSON.parse(await fs151.readFile(path63.join(path63.dirname(real), "..", "package.json"), "utf8"));
43199
+ const manifest = JSON.parse(await fs152.readFile(path63.join(path63.dirname(real), "..", "package.json"), "utf8"));
43167
43200
  if (typeof manifest?.version !== "string" || !manifest.version)
43168
43201
  return void 0;
43169
43202
  return admitProjectSuppliedTsserver(real, options?.sessionRoot ?? process.cwd(), projectSupplied || projectRoots.some((dir) => isUnderDir(real, dir)), options?.projectCodeAllowed);
@@ -43179,7 +43212,7 @@ async function findTsserverPath(root, allowInstall, options) {
43179
43212
  }
43180
43213
  const cwdCandidate = path63.join(process.cwd(), "node_modules", "typescript", "lib", "tsserver.js");
43181
43214
  try {
43182
- await fs151.access(cwdCandidate);
43215
+ await fs152.access(cwdCandidate);
43183
43216
  const admittedCwd = await admitCandidate(cwdCandidate, false);
43184
43217
  if (admittedCwd)
43185
43218
  return admittedCwd;
@@ -43329,9 +43362,9 @@ async function tryGemInstall(gem) {
43329
43362
  const result = await safeSpawnAsync("gem", ["install", gem, "--bindir", binDir, "--no-document"], { timeout: 18e4, ignoreAmbientSignal: true });
43330
43363
  const ok = !result.error && result.status === 0;
43331
43364
  if (ok) {
43332
- const sep12 = process.platform === "win32" ? ";" : ":";
43365
+ const sep13 = process.platform === "win32" ? ";" : ":";
43333
43366
  if (!process.env.PATH?.includes(binDir)) {
43334
- process.env.PATH = `${binDir}${sep12}${process.env.PATH ?? ""}`;
43367
+ process.env.PATH = `${binDir}${sep13}${process.env.PATH ?? ""}`;
43335
43368
  }
43336
43369
  }
43337
43370
  return ok;
@@ -49706,7 +49739,7 @@ function saveProjectSnapshot(cwd, snapshot) {
49706
49739
  }
49707
49740
  async function waitForProjectSnapshotPersistsForTests() {
49708
49741
  for (let attempts2 = 0; attempts2 < 200 && (_snapshotWorkerRequests.size > 0 || _activeSnapshotPersists.size > 0 || _queuedSnapshotPersists.size > 0); attempts2++) {
49709
- await new Promise((resolve153) => setTimeout(resolve153, 10));
49742
+ await new Promise((resolve154) => setTimeout(resolve154, 10));
49710
49743
  }
49711
49744
  }
49712
49745
  async function settleProjectSnapshotPersistsForTests() {
@@ -59678,237 +59711,26 @@ ${stderr}`;
59678
59711
  }
59679
59712
  });
59680
59713
 
59681
- // dist/clients/metrics/function-metrics.js
59682
- function isLogicalOperator(type, children, table) {
59683
- if (type !== "binary_expression" && type !== "boolean_operator")
59684
- return false;
59685
- return children.some((c) => table.logical.has(c?.type));
59686
- }
59687
- function step(walk3, node, depth, cognitiveDepth, inFunction) {
59688
- const { table, tally: tally2 } = walk3;
59689
- const type = node.type;
59690
- const children = node.children ?? [];
59691
- walk3.visit?.(node, type, children);
59692
- tally2.nesting = Math.max(tally2.nesting, depth);
59693
- if (table.decisions.has(type))
59694
- tally2.cyclomatic++;
59695
- if (table.cognitive.has(type))
59696
- tally2.cognitive += 1 + cognitiveDepth;
59697
- if (isLogicalOperator(type, children, table)) {
59698
- tally2.cyclomatic++;
59699
- tally2.cognitive++;
59700
- }
59701
- if ((type === "break_statement" || type === "continue_statement") && children.some((c) => c?.type === "statement_identifier" || c?.type === "label_name")) {
59702
- tally2.cognitive++;
59703
- }
59704
- const nests = table.nesting.has(type);
59705
- const isFunction = table.functions.has(type);
59706
- const nextDepth = nests ? depth + 1 : depth;
59707
- const deepens = nests || isFunction && inFunction;
59708
- const nextCognitiveDepth = deepens ? cognitiveDepth + 1 : cognitiveDepth;
59709
- for (const child of children) {
59710
- if (child)
59711
- step(walk3, child, nextDepth, nextCognitiveDepth, inFunction || isFunction);
59712
- }
59713
- }
59714
- function tally(scope, table, insideFunction, visit2) {
59715
- const walk3 = {
59716
- table,
59717
- visit: visit2,
59718
- tally: { cyclomatic: 1, cognitive: 0, nesting: 0 }
59719
- };
59720
- if (scope)
59721
- step(walk3, scope, 0, 0, insideFunction);
59722
- return walk3.tally;
59723
- }
59724
- function bodyOf(fn) {
59725
- const id = fn.childForFieldName("body")?.id;
59726
- if (id === void 0)
59727
- return null;
59728
- return (fn.children ?? []).find((c) => c?.id === id) ?? null;
59729
- }
59730
- function countParameters(fn) {
59731
- const list = fn.childForFieldName("parameters");
59732
- if (!list)
59733
- return fn.childForFieldName("parameter") ? 1 : 0;
59734
- let count = 0;
59735
- for (const param of list.namedChildren ?? []) {
59736
- if (!param || NOT_PARAMETERS.has(param.type))
59714
+ // dist/clients/symbol-containment.js
59715
+ function findOwnerName(candidates, targetStart, targetEnd) {
59716
+ let best;
59717
+ for (const candidate of candidates) {
59718
+ const span = candidate.endLine - candidate.startLine;
59719
+ const targetSpan = targetEnd - targetStart;
59720
+ const contains = candidate.startLine <= targetStart && candidate.endLine >= targetEnd && span > targetSpan;
59721
+ if (!contains)
59737
59722
  continue;
59738
- count += Math.max(1, param.childrenForFieldName("name").length);
59723
+ if (!best || span < best.endLine - best.startLine)
59724
+ best = candidate;
59739
59725
  }
59740
- return count;
59741
- }
59742
- function measureFunction(fn, languageId, visit2) {
59743
- const { cyclomatic, cognitive, nesting } = tally(bodyOf(fn), TABLES[languageId], true, visit2);
59744
- return {
59745
- cyclomatic,
59746
- cognitive,
59747
- nesting,
59748
- length: fn.endPosition.row - fn.startPosition.row + 1,
59749
- parameters: countParameters(fn)
59750
- };
59726
+ return best?.name;
59751
59727
  }
59752
- function measureFile(root, languageId) {
59753
- const table = TABLES[languageId];
59754
- const functions = [];
59755
- const { cognitive, nesting } = tally(root, table, false, (node, type) => {
59756
- if (!table.functions.has(type) || !node.isNamed)
59757
- return;
59758
- const line = node.startPosition.row + 1;
59759
- functions.push({
59760
- name: node.childForFieldName("name")?.text ?? `<anonymous@L${line}>`,
59761
- line,
59762
- ...measureFunction(node, languageId)
59763
- });
59764
- });
59765
- return { cognitive, nesting, functions };
59728
+ function buildQualifiedName(ownerName, symbolName) {
59729
+ return ownerName ? `${ownerName}.${symbolName}` : void 0;
59766
59730
  }
59767
- var JSTS, PYTHON, GO, RUST, TABLES, NOT_PARAMETERS;
59768
- var init_function_metrics = __esm({
59769
- "dist/clients/metrics/function-metrics.js"() {
59731
+ var init_symbol_containment = __esm({
59732
+ "dist/clients/symbol-containment.js"() {
59770
59733
  "use strict";
59771
- JSTS = {
59772
- functions: /* @__PURE__ */ new Set([
59773
- "function_declaration",
59774
- "function_expression",
59775
- "arrow_function",
59776
- "method_definition",
59777
- "generator_function",
59778
- "generator_function_declaration"
59779
- ]),
59780
- // `switch_default` is not a decision.
59781
- decisions: /* @__PURE__ */ new Set([
59782
- "if_statement",
59783
- "for_statement",
59784
- "for_in_statement",
59785
- "while_statement",
59786
- "do_statement",
59787
- "switch_case",
59788
- "catch_clause",
59789
- "ternary_expression"
59790
- ]),
59791
- cognitive: /* @__PURE__ */ new Set([
59792
- "if_statement",
59793
- "for_statement",
59794
- "for_in_statement",
59795
- "while_statement",
59796
- "do_statement",
59797
- "switch_statement",
59798
- "catch_clause",
59799
- "ternary_expression"
59800
- ]),
59801
- nesting: /* @__PURE__ */ new Set([
59802
- "if_statement",
59803
- "for_statement",
59804
- "for_in_statement",
59805
- "while_statement",
59806
- "do_statement",
59807
- "switch_statement",
59808
- "try_statement"
59809
- ]),
59810
- logical: /* @__PURE__ */ new Set(["&&", "||", "??"])
59811
- };
59812
- PYTHON = {
59813
- functions: /* @__PURE__ */ new Set(["function_definition", "lambda"]),
59814
- decisions: /* @__PURE__ */ new Set([
59815
- "if_statement",
59816
- "elif_clause",
59817
- "for_statement",
59818
- "while_statement",
59819
- "case_clause",
59820
- "conditional_expression",
59821
- "except_clause"
59822
- ]),
59823
- cognitive: /* @__PURE__ */ new Set([
59824
- "if_statement",
59825
- "elif_clause",
59826
- "for_statement",
59827
- "while_statement",
59828
- "match_statement",
59829
- "conditional_expression",
59830
- "except_clause"
59831
- ]),
59832
- nesting: /* @__PURE__ */ new Set([
59833
- "if_statement",
59834
- "for_statement",
59835
- "while_statement",
59836
- "match_statement",
59837
- "try_statement"
59838
- ]),
59839
- logical: /* @__PURE__ */ new Set(["and", "or"])
59840
- };
59841
- GO = {
59842
- functions: /* @__PURE__ */ new Set([
59843
- "function_declaration",
59844
- "method_declaration",
59845
- "func_literal"
59846
- ]),
59847
- // `default_case` is not a decision.
59848
- decisions: /* @__PURE__ */ new Set([
59849
- "if_statement",
59850
- "for_statement",
59851
- "expression_case",
59852
- "type_case",
59853
- "communication_case"
59854
- ]),
59855
- cognitive: /* @__PURE__ */ new Set([
59856
- "if_statement",
59857
- "for_statement",
59858
- "expression_switch_statement",
59859
- "type_switch_statement",
59860
- "select_statement"
59861
- ]),
59862
- nesting: /* @__PURE__ */ new Set([
59863
- "if_statement",
59864
- "for_statement",
59865
- "expression_switch_statement",
59866
- "type_switch_statement",
59867
- "select_statement"
59868
- ]),
59869
- logical: /* @__PURE__ */ new Set(["&&", "||"])
59870
- };
59871
- RUST = {
59872
- functions: /* @__PURE__ */ new Set(["function_item", "closure_expression"]),
59873
- decisions: /* @__PURE__ */ new Set([
59874
- "if_expression",
59875
- "while_expression",
59876
- "for_expression",
59877
- "loop_expression",
59878
- "match_arm"
59879
- ]),
59880
- cognitive: /* @__PURE__ */ new Set([
59881
- "if_expression",
59882
- "while_expression",
59883
- "for_expression",
59884
- "loop_expression",
59885
- "match_expression"
59886
- ]),
59887
- nesting: /* @__PURE__ */ new Set([
59888
- "if_expression",
59889
- "while_expression",
59890
- "for_expression",
59891
- "loop_expression",
59892
- "match_expression"
59893
- ]),
59894
- logical: /* @__PURE__ */ new Set(["&&", "||"])
59895
- };
59896
- TABLES = {
59897
- typescript: JSTS,
59898
- tsx: JSTS,
59899
- javascript: JSTS,
59900
- python: PYTHON,
59901
- go: GO,
59902
- rust: RUST
59903
- };
59904
- NOT_PARAMETERS = /* @__PURE__ */ new Set([
59905
- "comment",
59906
- "line_comment",
59907
- "block_comment",
59908
- "attribute_item",
59909
- "keyword_separator",
59910
- "positional_separator"
59911
- ]);
59912
59734
  }
59913
59735
  });
59914
59736
 
@@ -65848,6 +65670,403 @@ var init_tree_sitter_shared = __esm({
65848
65670
  }
65849
65671
  });
65850
65672
 
65673
+ // dist/clients/metrics/function-metrics.js
65674
+ function isLogicalOperator(type, children, table) {
65675
+ if (type !== "binary_expression" && type !== "boolean_operator")
65676
+ return false;
65677
+ return children.some((c) => table.logical.has(c?.type));
65678
+ }
65679
+ function step(walk3, node, depth, cognitiveDepth, inFunction) {
65680
+ const { table, tally: tally2 } = walk3;
65681
+ const type = node.type;
65682
+ const children = node.children ?? [];
65683
+ walk3.visit?.(node, type, children);
65684
+ tally2.nesting = Math.max(tally2.nesting, depth);
65685
+ if (table.decisions.has(type))
65686
+ tally2.cyclomatic++;
65687
+ if (table.cognitive.has(type))
65688
+ tally2.cognitive += 1 + cognitiveDepth;
65689
+ if (isLogicalOperator(type, children, table)) {
65690
+ tally2.cyclomatic++;
65691
+ tally2.cognitive++;
65692
+ }
65693
+ if ((type === "break_statement" || type === "continue_statement") && children.some((c) => c?.type === "statement_identifier" || c?.type === "label_name")) {
65694
+ tally2.cognitive++;
65695
+ }
65696
+ const nests = table.nesting.has(type);
65697
+ const isFunction = table.functions.has(type);
65698
+ const nextDepth = nests ? depth + 1 : depth;
65699
+ const deepens = nests || isFunction && inFunction;
65700
+ const nextCognitiveDepth = deepens ? cognitiveDepth + 1 : cognitiveDepth;
65701
+ for (const child of children) {
65702
+ if (child)
65703
+ step(walk3, child, nextDepth, nextCognitiveDepth, inFunction || isFunction);
65704
+ }
65705
+ }
65706
+ function tally(scope, table, insideFunction, visit2) {
65707
+ const walk3 = {
65708
+ table,
65709
+ visit: visit2,
65710
+ tally: { cyclomatic: 1, cognitive: 0, nesting: 0 }
65711
+ };
65712
+ if (scope)
65713
+ step(walk3, scope, 0, 0, insideFunction);
65714
+ return walk3.tally;
65715
+ }
65716
+ function bodyOf(fn) {
65717
+ const id = fn.childForFieldName("body")?.id;
65718
+ if (id === void 0)
65719
+ return null;
65720
+ return (fn.children ?? []).find((c) => c?.id === id) ?? null;
65721
+ }
65722
+ function countParameters(fn) {
65723
+ const list = fn.childForFieldName("parameters");
65724
+ if (!list)
65725
+ return fn.childForFieldName("parameter") ? 1 : 0;
65726
+ let count = 0;
65727
+ for (const param of list.namedChildren ?? []) {
65728
+ if (!param || NOT_PARAMETERS.has(param.type))
65729
+ continue;
65730
+ count += Math.max(1, param.childrenForFieldName("name").length);
65731
+ }
65732
+ return count;
65733
+ }
65734
+ function measureFunction(fn, languageId, visit2) {
65735
+ const { cyclomatic, cognitive, nesting } = tally(bodyOf(fn), TABLES[languageId], true, visit2);
65736
+ return {
65737
+ cyclomatic,
65738
+ cognitive,
65739
+ nesting,
65740
+ length: fn.endPosition.row - fn.startPosition.row + 1,
65741
+ parameters: countParameters(fn)
65742
+ };
65743
+ }
65744
+ function functionName(node) {
65745
+ const type = node.type;
65746
+ if (type === "function_declaration") {
65747
+ return firstChildOfType(node, "identifier")?.text;
65748
+ }
65749
+ if (type === "method_definition") {
65750
+ const kids = node.children ?? [];
65751
+ const paramsIdx = kids.findIndex((c) => c?.type === "formal_parameters");
65752
+ for (let i = paramsIdx - 1; i >= 0; i -= 1) {
65753
+ const t2 = kids[i]?.type;
65754
+ if (t2 === "property_identifier" || t2 === "private_property_identifier" || t2 === "computed_property_name" || t2 === "string" || t2 === "number") {
65755
+ return kids[i].text;
65756
+ }
65757
+ }
65758
+ return void 0;
65759
+ }
65760
+ if (type === "arrow_function" || type === "function_expression") {
65761
+ const parent = node.parent;
65762
+ if (parent?.type === "variable_declarator") {
65763
+ return firstChildOfType(parent, "identifier")?.text;
65764
+ }
65765
+ if (parent?.type === "pair")
65766
+ return (parent.children ?? [])[0]?.text;
65767
+ return void 0;
65768
+ }
65769
+ if (type === "lambda") {
65770
+ const parent = node.parent;
65771
+ return parent?.type === "assignment" ? parent.childForFieldName("left")?.text : void 0;
65772
+ }
65773
+ return node.childForFieldName("name")?.text;
65774
+ }
65775
+ function receiverType(fn) {
65776
+ const receiver = fn.childForFieldName("receiver");
65777
+ if (!receiver)
65778
+ return void 0;
65779
+ let found;
65780
+ const visit2 = (node) => {
65781
+ if (found !== void 0)
65782
+ return;
65783
+ if (node.type === "type_identifier") {
65784
+ found = node.text;
65785
+ return;
65786
+ }
65787
+ for (const child of node.children ?? [])
65788
+ if (child)
65789
+ visit2(child);
65790
+ };
65791
+ visit2(receiver);
65792
+ return found;
65793
+ }
65794
+ function containerName(node) {
65795
+ return node.childForFieldName("name")?.text ?? node.childForFieldName("type")?.text;
65796
+ }
65797
+ function assignKeys(functions, declared, receivers, containers, languageId) {
65798
+ const owners = [...containers];
65799
+ functions.forEach((fn, i) => {
65800
+ const name2 = declared[i];
65801
+ if (name2 !== void 0)
65802
+ owners.push({ name: name2, startLine: fn.line, endLine: fn.endLine });
65803
+ });
65804
+ owners.forEach((owner, priority) => {
65805
+ owner.priority = priority;
65806
+ });
65807
+ const entries = [
65808
+ ...owners.map((owner) => ({ ...owner, index: -1 })),
65809
+ ...functions.map((fn, index) => ({
65810
+ name: void 0,
65811
+ startLine: fn.line,
65812
+ endLine: fn.endLine,
65813
+ index
65814
+ }))
65815
+ ];
65816
+ const byEnd = [];
65817
+ let lastLine = 0;
65818
+ for (const entry of entries) {
65819
+ (byEnd[entry.endLine] ??= []).push(entry);
65820
+ lastLine = Math.max(lastLine, entry.endLine);
65821
+ }
65822
+ const byStart = [];
65823
+ for (let line = lastLine; line >= 0; line--) {
65824
+ for (const entry of byEnd[line] ?? []) {
65825
+ (byStart[entry.startLine] ??= []).push(entry);
65826
+ }
65827
+ }
65828
+ const ending = [];
65829
+ for (const owner of owners) {
65830
+ const prior = ending[owner.endLine];
65831
+ const span = owner.endLine - owner.startLine;
65832
+ if (span > 0 && (!prior || span < prior.endLine - prior.startLine))
65833
+ ending[owner.endLine] = owner;
65834
+ }
65835
+ const open = [];
65836
+ const ownerNames = [];
65837
+ for (let line = 0; line <= lastLine; line++) {
65838
+ for (const entry of byStart[line] ?? []) {
65839
+ while (open.length && open[open.length - 1].endLine < entry.endLine)
65840
+ open.pop();
65841
+ const top = open[open.length - 1];
65842
+ const equal = top?.startLine === entry.startLine && top.endLine === entry.endLine;
65843
+ if (entry.index >= 0) {
65844
+ let owner = equal ? open[open.length - 2] : top;
65845
+ const boundary = ending[entry.endLine];
65846
+ if (entry.startLine === entry.endLine && boundary && (!owner || boundary.endLine - boundary.startLine < owner.endLine - owner.startLine || boundary.endLine - boundary.startLine === owner.endLine - owner.startLine && boundary.priority < owner.priority))
65847
+ owner = boundary;
65848
+ ownerNames[entry.index] = owner?.name;
65849
+ }
65850
+ if (entry.name !== void 0 && !equal)
65851
+ open.push({ ...entry, name: entry.name });
65852
+ }
65853
+ }
65854
+ const seen = /* @__PURE__ */ new Map();
65855
+ return functions.map((fn, i) => {
65856
+ const base = declared[i] ?? ANONYMOUS_KEY;
65857
+ const owner = languageId === "go" && receivers[i] !== null ? receivers[i] : ownerNames[i];
65858
+ const qualified = buildQualifiedName(owner, base) ?? base;
65859
+ const count = (seen.get(qualified) ?? 0) + 1;
65860
+ seen.set(qualified, count);
65861
+ return { ...fn, key: count === 1 ? qualified : `${qualified}#${count}` };
65862
+ });
65863
+ }
65864
+ function measureFile(root, languageId, keyFunctions = true) {
65865
+ const table = TABLES[languageId];
65866
+ const functions = [];
65867
+ const declared = [];
65868
+ const receivers = [];
65869
+ const containers = [];
65870
+ const { cognitive, nesting } = tally(root, table, false, (node, type) => {
65871
+ if (keyFunctions && table.containers.has(type)) {
65872
+ const name2 = containerName(node);
65873
+ if (name2 !== void 0)
65874
+ containers.push({
65875
+ name: name2,
65876
+ startLine: node.startPosition.row + 1,
65877
+ endLine: node.endPosition.row + 1
65878
+ });
65879
+ return;
65880
+ }
65881
+ if (!table.functions.has(type) || !node.isNamed)
65882
+ return;
65883
+ const line = node.startPosition.row + 1;
65884
+ if (keyFunctions) {
65885
+ declared.push(functionName(node));
65886
+ receivers.push(languageId === "go" && type === "method_declaration" ? receiverType(node) : null);
65887
+ }
65888
+ functions.push({
65889
+ name: functionName(node) ?? `<anonymous@L${line}>`,
65890
+ line,
65891
+ endLine: node.endPosition.row + 1,
65892
+ ...measureFunction(node, languageId)
65893
+ });
65894
+ });
65895
+ let keyed;
65896
+ return {
65897
+ cognitive,
65898
+ nesting,
65899
+ functions: !keyFunctions ? functions.map((fn) => ({ ...fn, key: ANONYMOUS_KEY })) : functions.map((fn, index) => ({
65900
+ ...fn,
65901
+ get key() {
65902
+ keyed ??= assignKeys(functions, declared, receivers, containers, languageId);
65903
+ return keyed[index].key;
65904
+ }
65905
+ }))
65906
+ };
65907
+ }
65908
+ var JSTS, PYTHON, GO, RUST, TABLES, NOT_PARAMETERS, ANONYMOUS_KEY, MAX_MEASURED_BYTES;
65909
+ var init_function_metrics = __esm({
65910
+ "dist/clients/metrics/function-metrics.js"() {
65911
+ "use strict";
65912
+ init_symbol_containment();
65913
+ init_tree_sitter_shared();
65914
+ JSTS = {
65915
+ functions: /* @__PURE__ */ new Set([
65916
+ "function_declaration",
65917
+ "function_expression",
65918
+ "arrow_function",
65919
+ "method_definition",
65920
+ "generator_function",
65921
+ "generator_function_declaration"
65922
+ ]),
65923
+ containers: /* @__PURE__ */ new Set([
65924
+ "class_declaration",
65925
+ "abstract_class_declaration",
65926
+ "class",
65927
+ "interface_declaration"
65928
+ ]),
65929
+ // `switch_default` is not a decision.
65930
+ decisions: /* @__PURE__ */ new Set([
65931
+ "if_statement",
65932
+ "for_statement",
65933
+ "for_in_statement",
65934
+ "while_statement",
65935
+ "do_statement",
65936
+ "switch_case",
65937
+ "catch_clause",
65938
+ "ternary_expression"
65939
+ ]),
65940
+ cognitive: /* @__PURE__ */ new Set([
65941
+ "if_statement",
65942
+ "for_statement",
65943
+ "for_in_statement",
65944
+ "while_statement",
65945
+ "do_statement",
65946
+ "switch_statement",
65947
+ "catch_clause",
65948
+ "ternary_expression"
65949
+ ]),
65950
+ nesting: /* @__PURE__ */ new Set([
65951
+ "if_statement",
65952
+ "for_statement",
65953
+ "for_in_statement",
65954
+ "while_statement",
65955
+ "do_statement",
65956
+ "switch_statement",
65957
+ "try_statement"
65958
+ ]),
65959
+ logical: /* @__PURE__ */ new Set(["&&", "||", "??"])
65960
+ };
65961
+ PYTHON = {
65962
+ functions: /* @__PURE__ */ new Set(["function_definition", "lambda"]),
65963
+ containers: /* @__PURE__ */ new Set(["class_definition"]),
65964
+ decisions: /* @__PURE__ */ new Set([
65965
+ "if_statement",
65966
+ "elif_clause",
65967
+ "for_statement",
65968
+ "while_statement",
65969
+ "case_clause",
65970
+ "conditional_expression",
65971
+ "except_clause"
65972
+ ]),
65973
+ cognitive: /* @__PURE__ */ new Set([
65974
+ "if_statement",
65975
+ "elif_clause",
65976
+ "for_statement",
65977
+ "while_statement",
65978
+ "match_statement",
65979
+ "conditional_expression",
65980
+ "except_clause"
65981
+ ]),
65982
+ nesting: /* @__PURE__ */ new Set([
65983
+ "if_statement",
65984
+ "for_statement",
65985
+ "while_statement",
65986
+ "match_statement",
65987
+ "try_statement"
65988
+ ]),
65989
+ logical: /* @__PURE__ */ new Set(["and", "or"])
65990
+ };
65991
+ GO = {
65992
+ functions: /* @__PURE__ */ new Set([
65993
+ "function_declaration",
65994
+ "method_declaration",
65995
+ "func_literal"
65996
+ ]),
65997
+ // A Go method's owner is its receiver type (`ownerOf`), not a container.
65998
+ containers: /* @__PURE__ */ new Set(),
65999
+ // `default_case` is not a decision.
66000
+ decisions: /* @__PURE__ */ new Set([
66001
+ "if_statement",
66002
+ "for_statement",
66003
+ "expression_case",
66004
+ "type_case",
66005
+ "communication_case"
66006
+ ]),
66007
+ cognitive: /* @__PURE__ */ new Set([
66008
+ "if_statement",
66009
+ "for_statement",
66010
+ "expression_switch_statement",
66011
+ "type_switch_statement",
66012
+ "select_statement"
66013
+ ]),
66014
+ nesting: /* @__PURE__ */ new Set([
66015
+ "if_statement",
66016
+ "for_statement",
66017
+ "expression_switch_statement",
66018
+ "type_switch_statement",
66019
+ "select_statement"
66020
+ ]),
66021
+ logical: /* @__PURE__ */ new Set(["&&", "||"])
66022
+ };
66023
+ RUST = {
66024
+ functions: /* @__PURE__ */ new Set(["function_item", "closure_expression"]),
66025
+ containers: /* @__PURE__ */ new Set(["impl_item", "trait_item", "mod_item"]),
66026
+ decisions: /* @__PURE__ */ new Set([
66027
+ "if_expression",
66028
+ "while_expression",
66029
+ "for_expression",
66030
+ "loop_expression",
66031
+ "match_arm"
66032
+ ]),
66033
+ cognitive: /* @__PURE__ */ new Set([
66034
+ "if_expression",
66035
+ "while_expression",
66036
+ "for_expression",
66037
+ "loop_expression",
66038
+ "match_expression"
66039
+ ]),
66040
+ nesting: /* @__PURE__ */ new Set([
66041
+ "if_expression",
66042
+ "while_expression",
66043
+ "for_expression",
66044
+ "loop_expression",
66045
+ "match_expression"
66046
+ ]),
66047
+ logical: /* @__PURE__ */ new Set(["&&", "||"])
66048
+ };
66049
+ TABLES = {
66050
+ typescript: JSTS,
66051
+ tsx: JSTS,
66052
+ javascript: JSTS,
66053
+ python: PYTHON,
66054
+ go: GO,
66055
+ rust: RUST
66056
+ };
66057
+ NOT_PARAMETERS = /* @__PURE__ */ new Set([
66058
+ "comment",
66059
+ "line_comment",
66060
+ "block_comment",
66061
+ "attribute_item",
66062
+ "keyword_separator",
66063
+ "positional_separator"
66064
+ ]);
66065
+ ANONYMOUS_KEY = "<anonymous>";
66066
+ MAX_MEASURED_BYTES = 256 * 1024;
66067
+ }
66068
+ });
66069
+
65851
66070
  // dist/clients/complexity-client.js
65852
66071
  var complexity_client_exports = {};
65853
66072
  __export(complexity_client_exports, {
@@ -65978,7 +66197,8 @@ var init_complexity_client = __esm({
65978
66197
  }
65979
66198
  computeMetrics(absolutePath, content, root, languageId) {
65980
66199
  const { codeLines, commentLines } = countLines(content, root);
65981
- const file = measureFile(root, languageId);
66200
+ const keyFunctions = Buffer.byteLength(content, "utf-8") <= MAX_MEASURED_BYTES;
66201
+ const file = measureFile(root, languageId, keyFunctions);
65982
66202
  const functions = file.functions.map((f) => ({
65983
66203
  name: f.name,
65984
66204
  line: f.line,
@@ -66005,7 +66225,8 @@ var init_complexity_client = __esm({
66005
66225
  aiCommentPatterns: countAICommentPatterns(content),
66006
66226
  singleUseFunctions: countSingleUseFunctions(functions),
66007
66227
  tryCatchCount: countTryCatch(root),
66008
- functions
66228
+ functions,
66229
+ measuredFunctions: keyFunctions ? file.functions : void 0
66009
66230
  };
66010
66231
  }
66011
66232
  aggregateFunctionStats(functions) {
@@ -74380,14 +74601,14 @@ function packHorizontalRow(recs, totalWidth, theme) {
74380
74601
  return "";
74381
74602
  const dim = (s) => theme.fg("dim", s);
74382
74603
  const indent = " ";
74383
- const sep12 = " ";
74604
+ const sep13 = " ";
74384
74605
  const overflowReserve = 4;
74385
74606
  let used = visibleWidth(indent);
74386
74607
  const parts = [indent];
74387
74608
  const addedTokenWidths = [];
74388
74609
  let droppedAt = -1;
74389
74610
  for (let i = 0; i < recs.length; i++) {
74390
- const sepWidth = parts.length > 1 ? visibleWidth(sep12) : 0;
74611
+ const sepWidth = parts.length > 1 ? visibleWidth(sep13) : 0;
74391
74612
  const willOverflow = i < recs.length - 1;
74392
74613
  const reserve = willOverflow ? overflowReserve : 0;
74393
74614
  const remaining = totalWidth - used - sepWidth - reserve;
@@ -74402,7 +74623,7 @@ function packHorizontalRow(recs, totalWidth, theme) {
74402
74623
  break;
74403
74624
  }
74404
74625
  if (sepWidth > 0) {
74405
- parts.push(sep12);
74626
+ parts.push(sep13);
74406
74627
  used += sepWidth;
74407
74628
  }
74408
74629
  parts.push(token);
@@ -75282,9 +75503,9 @@ function isRuleIgnoredForPath(filePath, root, patterns) {
75282
75503
  if (!patterns || patterns.length === 0)
75283
75504
  return false;
75284
75505
  const pathApi = isWindowsPath(root) || isWindowsPath(filePath) ? path112.win32 : path112.posix;
75285
- const relative27 = relativeInside(root, filePath, pathApi);
75286
- const outsideRoot = relative27 === void 0;
75287
- const displayPath = toPosix(outsideRoot ? filePath : relative27);
75506
+ const relative28 = relativeInside(root, filePath, pathApi);
75507
+ const outsideRoot = relative28 === void 0;
75508
+ const displayPath = toPosix(outsideRoot ? filePath : relative28);
75288
75509
  return patterns.some((pattern) => (!outsideRoot || !toPosix(pattern).endsWith("/**")) && minimatch(displayPath, pattern, { dot: true }));
75289
75510
  }
75290
75511
  function loadRuleIgnorePatterns(root) {
@@ -77984,8 +78205,8 @@ var require_semaphore = __commonJS({
77984
78205
  this._waiting = [];
77985
78206
  }
77986
78207
  lock(thunk) {
77987
- return new Promise((resolve153, reject) => {
77988
- this._waiting.push({ thunk, resolve: resolve153, reject });
78208
+ return new Promise((resolve154, reject) => {
78209
+ this._waiting.push({ thunk, resolve: resolve154, reject });
77989
78210
  this.runNext();
77990
78211
  });
77991
78212
  }
@@ -79612,9 +79833,9 @@ ${JSON.stringify(message, null, 4)}`);
79612
79833
  if (typeof cancellationStrategy.sender.enableCancellation === "function") {
79613
79834
  cancellationStrategy.sender.enableCancellation(requestMessage);
79614
79835
  }
79615
- return new Promise(async (resolve153, reject) => {
79836
+ return new Promise(async (resolve154, reject) => {
79616
79837
  const resolveWithCleanup = (r) => {
79617
- resolve153(r);
79838
+ resolve154(r);
79618
79839
  cancellationStrategy.sender.cleanup(id);
79619
79840
  disposable?.dispose();
79620
79841
  };
@@ -80044,10 +80265,10 @@ var require_ril = __commonJS({
80044
80265
  return api_1.Disposable.create(() => this.stream.off("end", listener));
80045
80266
  }
80046
80267
  write(data, encoding) {
80047
- return new Promise((resolve153, reject) => {
80268
+ return new Promise((resolve154, reject) => {
80048
80269
  const callback = (error) => {
80049
80270
  if (error === void 0 || error === null) {
80050
- resolve153();
80271
+ resolve154();
80051
80272
  } else {
80052
80273
  reject(error);
80053
80274
  }
@@ -80188,7 +80409,7 @@ var require_main = __commonJS({
80188
80409
  ril_1.default.install();
80189
80410
  var path239 = __importStar(__require("path"));
80190
80411
  var os42 = __importStar(__require("os"));
80191
- var fs151 = __importStar(__require("fs"));
80412
+ var fs152 = __importStar(__require("fs"));
80192
80413
  var crypto_1 = __require("crypto");
80193
80414
  var net_1 = __require("net");
80194
80415
  var api_1 = require_api();
@@ -80329,7 +80550,7 @@ var require_main = __commonJS({
80329
80550
  }
80330
80551
  let randomLength = 32;
80331
80552
  const fixedLength = "/lsp-.sock".length;
80332
- const tmpDir = fs151.realpathSync(XDG_RUNTIME_DIR ?? os42.tmpdir());
80553
+ const tmpDir = fs152.realpathSync(XDG_RUNTIME_DIR ?? os42.tmpdir());
80333
80554
  const limit = safeIpcPathLengths.get(process.platform);
80334
80555
  if (limit !== void 0) {
80335
80556
  randomLength = Math.min(limit - tmpDir.length - fixedLength, randomLength);
@@ -80342,10 +80563,10 @@ var require_main = __commonJS({
80342
80563
  }
80343
80564
  function createClientPipeTransport(pipeName, encoding = "utf-8") {
80344
80565
  let connectResolve;
80345
- const connected = new Promise((resolve153, _reject) => {
80346
- connectResolve = resolve153;
80566
+ const connected = new Promise((resolve154, _reject) => {
80567
+ connectResolve = resolve154;
80347
80568
  });
80348
- return new Promise((resolve153, reject) => {
80569
+ return new Promise((resolve154, reject) => {
80349
80570
  const server = (0, net_1.createServer)((socket) => {
80350
80571
  server.close();
80351
80572
  connectResolve([
@@ -80356,7 +80577,7 @@ var require_main = __commonJS({
80356
80577
  server.on("error", reject);
80357
80578
  server.listen(pipeName, () => {
80358
80579
  server.removeListener("error", reject);
80359
- resolve153({
80580
+ resolve154({
80360
80581
  onConnected: () => {
80361
80582
  return connected;
80362
80583
  },
@@ -80376,10 +80597,10 @@ var require_main = __commonJS({
80376
80597
  }
80377
80598
  function createClientSocketTransport(port, encoding = "utf-8") {
80378
80599
  let connectResolve;
80379
- const connected = new Promise((resolve153, _reject) => {
80380
- connectResolve = resolve153;
80600
+ const connected = new Promise((resolve154, _reject) => {
80601
+ connectResolve = resolve154;
80381
80602
  });
80382
- return new Promise((resolve153, reject) => {
80603
+ return new Promise((resolve154, reject) => {
80383
80604
  const server = (0, net_1.createServer)((socket) => {
80384
80605
  server.close();
80385
80606
  connectResolve([
@@ -80396,7 +80617,7 @@ var require_main = __commonJS({
80396
80617
  return;
80397
80618
  }
80398
80619
  const boundPort = address.port;
80399
- resolve153({
80620
+ resolve154({
80400
80621
  port: () => boundPort,
80401
80622
  onConnected: () => {
80402
80623
  return connected;
@@ -80461,14 +80682,14 @@ async function raceToCompletion(promises31, shouldComplete, options = { timeoutM
80461
80682
  const languageCount = promises31.length - auxIndices.size;
80462
80683
  let languageRemaining = languageCount;
80463
80684
  let auxGraceStarted = false;
80464
- return new Promise((resolve153) => {
80685
+ return new Promise((resolve154) => {
80465
80686
  const timeout = setTimeout(() => {
80466
80687
  completed = true;
80467
80688
  if (graceTimer)
80468
80689
  clearTimeout(graceTimer);
80469
80690
  if (auxGraceTimer)
80470
80691
  clearTimeout(auxGraceTimer);
80471
- resolve153(results.filter((r) => r !== void 0));
80692
+ resolve154(results.filter((r) => r !== void 0));
80472
80693
  }, options.timeoutMs);
80473
80694
  const finalize = () => {
80474
80695
  if (completed)
@@ -80479,7 +80700,7 @@ async function raceToCompletion(promises31, shouldComplete, options = { timeoutM
80479
80700
  clearTimeout(graceTimer);
80480
80701
  if (auxGraceTimer)
80481
80702
  clearTimeout(auxGraceTimer);
80482
- resolve153(results.filter((r) => r !== void 0));
80703
+ resolve154(results.filter((r) => r !== void 0));
80483
80704
  };
80484
80705
  const startAuxGrace = () => {
80485
80706
  if (auxGraceStarted || completed)
@@ -82580,8 +82801,8 @@ async function killProcessTree(proc, pid, options = {}) {
82580
82801
  proc.unref?.();
82581
82802
  return;
82582
82803
  }
82583
- await new Promise((resolve153) => {
82584
- killer.once("close", () => resolve153());
82804
+ await new Promise((resolve154) => {
82805
+ killer.once("close", () => resolve154());
82585
82806
  killer.once("error", (err) => {
82586
82807
  logLatency({
82587
82808
  type: "phase",
@@ -82590,7 +82811,7 @@ async function killProcessTree(proc, pid, options = {}) {
82590
82811
  durationMs: 0,
82591
82812
  metadata: { pid, platform: "win32", taskkillError: String(err) }
82592
82813
  });
82593
- resolve153();
82814
+ resolve154();
82594
82815
  });
82595
82816
  });
82596
82817
  } catch (err) {
@@ -82648,18 +82869,18 @@ async function killProcessTree(proc, pid, options = {}) {
82648
82869
  proc.unref?.();
82649
82870
  return;
82650
82871
  }
82651
- const exitedInTime = await new Promise((resolve153) => {
82872
+ const exitedInTime = await new Promise((resolve154) => {
82652
82873
  if (proc.exitCode != null || proc.signalCode != null) {
82653
- resolve153(true);
82874
+ resolve154(true);
82654
82875
  return;
82655
82876
  }
82656
82877
  const onExit = () => {
82657
82878
  clearTimeout(timer);
82658
- resolve153(true);
82879
+ resolve154(true);
82659
82880
  };
82660
82881
  const timer = setTimeout(() => {
82661
82882
  proc.off?.("exit", onExit);
82662
- resolve153(false);
82883
+ resolve154(false);
82663
82884
  }, 1500);
82664
82885
  proc.once?.("exit", onExit);
82665
82886
  });
@@ -83962,7 +84183,7 @@ async function clientWaitForDiagnostics(state9, filePath, timeoutMs, options = {
83962
84183
  const retryBudgetMs = strategy.pullRetryBudgetMs > 0 ? Math.min(timeoutMs, strategy.pullRetryBudgetMs) : 0;
83963
84184
  const startedAt = Date.now();
83964
84185
  while (outcome.status !== "found" && Date.now() - startedAt < retryBudgetMs) {
83965
- await new Promise((resolve153) => setTimeout(resolve153, PULL_DIAGNOSTICS_RETRY_INTERVAL_MS));
84186
+ await new Promise((resolve154) => setTimeout(resolve154, PULL_DIAGNOSTICS_RETRY_INTERVAL_MS));
83966
84187
  outcome = await clientRequestPullDiagnostics(state9, filePath, Math.max(0, retryBudgetMs - (Date.now() - startedAt)));
83967
84188
  if (outcome.status === "clean")
83968
84189
  sawClean = true;
@@ -83985,7 +84206,7 @@ async function clientWaitForDiagnostics(state9, filePath, timeoutMs, options = {
83985
84206
  return "answered";
83986
84207
  }
83987
84208
  const answerStored = () => hasFreshDiagnostics() && !isVersionStale() && (state9.pushDiagnostics.has(normalizedPath) || state9.documentPullDiagnostics.has(normalizedPath));
83988
- return new Promise((resolve153) => {
84209
+ return new Promise((resolve154) => {
83989
84210
  let debounceTimer;
83990
84211
  let settleDeferred = storedAnswerSettles();
83991
84212
  const finish = (outcome = "answered") => {
@@ -83994,7 +84215,7 @@ async function clientWaitForDiagnostics(state9, filePath, timeoutMs, options = {
83994
84215
  state9.diagnosticEmitter.off("diagnostics", onDiagnostics);
83995
84216
  state9.diagnosticEmitter.off(PENDING_RECEIPT_DROPPED, onReceiptDropped);
83996
84217
  clearTimeout(timeout);
83997
- resolve153(outcome);
84218
+ resolve154(outcome);
83998
84219
  };
83999
84220
  const onDiagnostics = (fp) => {
84000
84221
  if (normalizeMapKey(fp) !== normalizedPath)
@@ -84235,9 +84456,9 @@ function enqueueDocumentNotify(state9, normalizedPath, run, saved = false, readS
84235
84456
  queue = { running: false, active: void 0 };
84236
84457
  state9.notifyChangeQueues.set(normalizedPath, queue);
84237
84458
  }
84238
- return new Promise((resolve153, reject) => {
84459
+ return new Promise((resolve154, reject) => {
84239
84460
  if (queue.closing && !close) {
84240
- resolve153(false);
84461
+ resolve154(false);
84241
84462
  return;
84242
84463
  }
84243
84464
  const previous = queue?.pending;
@@ -84251,7 +84472,7 @@ function enqueueDocumentNotify(state9, normalizedPath, run, saved = false, readS
84251
84472
  const before = (a, b) => a !== void 0 && b !== void 0 && a < b;
84252
84473
  const stale = previous !== void 0 && (saveOnly || before(readStamp, previous.readStamp) || before(readStamp, lastSent));
84253
84474
  const heldStamp = before(previous?.readStamp, lastSent) ? void 0 : previous?.readStamp;
84254
- waiters.push({ resolve: resolve153, reject, stale });
84475
+ waiters.push({ resolve: resolve154, reject, stale });
84255
84476
  queue.pending = {
84256
84477
  run: stale ? previous.run : run,
84257
84478
  saveOnly: stale ? previous.saveOnly : saveOnly,
@@ -85500,8 +85721,8 @@ async function safeSendRequest(connection, method, params, signal, settlement, r
85500
85721
  if (signal) {
85501
85722
  tokenSource = new import_node.CancellationTokenSource();
85502
85723
  if (releaseOnAbort) {
85503
- released = new Promise((resolve153) => {
85504
- release2 = () => resolve153(RELEASED_ON_ABORT);
85724
+ released = new Promise((resolve154) => {
85725
+ release2 = () => resolve154(RELEASED_ON_ABORT);
85505
85726
  });
85506
85727
  }
85507
85728
  onAbort = () => {
@@ -85968,6 +86189,7 @@ var ADOPTED_ROOT_CAP, ADOPTED_ROOT_IDLE_EVICT_MS, BROKEN_BASE_COOLDOWN_MS, BROKE
85968
86189
  var init_client_registry = __esm({
85969
86190
  "dist/clients/lsp/client-registry.js"() {
85970
86191
  "use strict";
86192
+ init_turn_context();
85971
86193
  init_bounded_telemetry();
85972
86194
  init_degradation_ledger();
85973
86195
  init_ephemeral_root();
@@ -86104,6 +86326,7 @@ var init_client_registry = __esm({
86104
86326
  clientSpawnGate = Promise.resolve();
86105
86327
  /** True after shutdown() has been called; blocks new operations */
86106
86328
  isDestroyed = false;
86329
+ trustShutdown = new AbortController();
86107
86330
  /**
86108
86331
  * #850: teardown completion for every singleton generation retired before
86109
86332
  * this service was published. Only replacement services receive one; direct
@@ -86125,6 +86348,8 @@ var init_client_registry = __esm({
86125
86348
  /** The first step of `LSPService.shutdown`: block new operations. */
86126
86349
  markDestroyed() {
86127
86350
  this.isDestroyed = true;
86351
+ this.trustShutdown.abort();
86352
+ this.adoptedTrust.clear();
86128
86353
  }
86129
86354
  /** The notify-stall demotion's breaker cooldown (`LSPService.demoteForNotifyStall`). */
86130
86355
  coolDown(key4, cooldownMs) {
@@ -86236,8 +86461,8 @@ var init_client_registry = __esm({
86236
86461
  async withClientSpawnGate(operation) {
86237
86462
  const previous = this.clientSpawnGate;
86238
86463
  let release2;
86239
- this.clientSpawnGate = new Promise((resolve153) => {
86240
- release2 = resolve153;
86464
+ this.clientSpawnGate = new Promise((resolve154) => {
86465
+ release2 = resolve154;
86241
86466
  });
86242
86467
  await previous;
86243
86468
  try {
@@ -86701,17 +86926,34 @@ var init_client_registry = __esm({
86701
86926
  return false;
86702
86927
  return !isLspInstallDisabled();
86703
86928
  }
86704
- /**
86705
- * Internal: spawn a client for a server/root combination
86706
- */
86929
+ /** Per-turn reads belong to this registry, never to a workspace store. */
86930
+ adoptedTrustTurn;
86931
+ adoptedTrust = /* @__PURE__ */ new Map();
86932
+ trustForAdoptedRoot(root) {
86933
+ const turn = getTurnId();
86934
+ if (turn === "turn:0")
86935
+ return readAdoptedProjectTrust(root, this.trustShutdown.signal);
86936
+ if (this.adoptedTrustTurn !== turn) {
86937
+ this.adoptedTrust.clear();
86938
+ this.adoptedTrustTurn = turn;
86939
+ }
86940
+ const key4 = normalizeMapKey(root);
86941
+ const prior = this.adoptedTrust.get(key4);
86942
+ if (prior)
86943
+ return prior;
86944
+ const pending4 = readAdoptedProjectTrust(root, this.trustShutdown.signal);
86945
+ this.adoptedTrust.set(key4, pending4);
86946
+ return pending4;
86947
+ }
86707
86948
  async spawnClient(server, root, key4, filePath, allowInstall) {
86949
+ const adopted = this.analysisRootModeForFile(filePath) === "adopted";
86708
86950
  try {
86709
86951
  if (server.executesProjectCode === true) {
86710
86952
  refuseUntrustedLspExecution({
86711
86953
  kind: "project-code-server",
86712
86954
  serverId: server.id,
86713
86955
  root
86714
- });
86956
+ }, adopted ? await this.trustForAdoptedRoot(root) : void 0);
86715
86957
  }
86716
86958
  } catch (error) {
86717
86959
  logSessionStart(`lsp spawn ${server.id}: refused \u2014 ${error instanceof Error ? error.message : String(error)}`);
@@ -87313,13 +87555,13 @@ function isTsProjectFile(filePath) {
87313
87555
  return isJstsFactFile(filePath);
87314
87556
  }
87315
87557
  function suggestTsconfigInclude(filePath, cwd) {
87316
- const relative27 = toProjectRelativePath(filePath, cwd);
87317
- if (path120.posix.isAbsolute(relative27) || /^[A-Za-z]:/.test(relative27)) {
87318
- const dir = relative27.slice(0, relative27.lastIndexOf("/"));
87319
- return dir ? `${dir}/**` : relative27;
87558
+ const relative28 = toProjectRelativePath(filePath, cwd);
87559
+ if (path120.posix.isAbsolute(relative28) || /^[A-Za-z]:/.test(relative28)) {
87560
+ const dir = relative28.slice(0, relative28.lastIndexOf("/"));
87561
+ return dir ? `${dir}/**` : relative28;
87320
87562
  }
87321
- const segments = relative27.split("/").filter(Boolean);
87322
- return segments.length > 1 ? `${segments[0]}/**` : relative27;
87563
+ const segments = relative28.split("/").filter(Boolean);
87564
+ return segments.length > 1 ? `${segments[0]}/**` : relative28;
87323
87565
  }
87324
87566
  function inferredProjectNotice(filePath, cwd) {
87325
87567
  return `[${INFERRED_PROJECT_MARKER}; add ${suggestTsconfigInclude(filePath, cwd)} to a tsconfig for authoritative checking]`;
@@ -87538,7 +87780,7 @@ function contentHash(content) {
87538
87780
  return crypto5.createHash("sha256").update(content).digest("hex");
87539
87781
  }
87540
87782
  function requestOverWarmIpc(endpoint, timeoutMs, buildRequest, validate2) {
87541
- return new Promise((resolve153) => {
87783
+ return new Promise((resolve154) => {
87542
87784
  let settled = false;
87543
87785
  const finish = (value) => {
87544
87786
  if (settled)
@@ -87546,7 +87788,7 @@ function requestOverWarmIpc(endpoint, timeoutMs, buildRequest, validate2) {
87546
87788
  settled = true;
87547
87789
  clearTimeout(timer);
87548
87790
  socket.destroy();
87549
- resolve153(value);
87791
+ resolve154(value);
87550
87792
  };
87551
87793
  const deadlineAt = Date.now() + timeoutMs;
87552
87794
  const socket = net.createConnection(endpoint);
@@ -89357,8 +89599,8 @@ var init_lsp = __esm({
89357
89599
  return { outstandingMs: 0 };
89358
89600
  }
89359
89601
  let resolveSettled;
89360
- const settled = new Promise((resolve153) => {
89361
- resolveSettled = resolve153;
89602
+ const settled = new Promise((resolve154) => {
89603
+ resolveSettled = resolve154;
89362
89604
  });
89363
89605
  const token = {
89364
89606
  startedAt: Date.now(),
@@ -89572,8 +89814,8 @@ var init_lsp = __esm({
89572
89814
  const effectiveMaxWaitMs = hardCapMs !== void 0 ? serverBaseMs > 0 ? Math.min(serverBaseMs, hardCapMs) : hardCapMs : serverBaseMs;
89573
89815
  let knownSlowResolve;
89574
89816
  const knownSlowSentinel = /* @__PURE__ */ Symbol("lsp-client-wait-known-slow");
89575
- const knownSlow = new Promise((resolve153) => {
89576
- knownSlowResolve = () => resolve153(knownSlowSentinel);
89817
+ const knownSlow = new Promise((resolve154) => {
89818
+ knownSlowResolve = () => resolve154(knownSlowSentinel);
89577
89819
  });
89578
89820
  const noteSpawnInFlight = (serverId) => {
89579
89821
  const knownDurationMs = getSuccessfulLspSpawnDurationMs(serverId);
@@ -89664,8 +89906,8 @@ var init_lsp = __esm({
89664
89906
  waitResult = await Promise.race([
89665
89907
  withBudget2(),
89666
89908
  knownSlow,
89667
- new Promise((resolve153) => {
89668
- waitTimer = setTimeout(() => resolve153(timeoutSentinel), effectiveMaxWaitMs);
89909
+ new Promise((resolve154) => {
89910
+ waitTimer = setTimeout(() => resolve154(timeoutSentinel), effectiveMaxWaitMs);
89669
89911
  })
89670
89912
  ]);
89671
89913
  } finally {
@@ -91048,8 +91290,8 @@ var init_lsp = __esm({
91048
91290
  };
91049
91291
  }
91050
91292
  let timer;
91051
- const timeout = new Promise((resolve153) => {
91052
- timer = setTimeout(() => resolve153(false), budgetMs);
91293
+ const timeout = new Promise((resolve154) => {
91294
+ timer = setTimeout(() => resolve154(false), budgetMs);
91053
91295
  if (typeof timer === "object" && "unref" in timer) {
91054
91296
  timer.unref?.();
91055
91297
  }
@@ -91147,8 +91389,8 @@ var init_lsp = __esm({
91147
91389
  const graceMs = readTsserverSyncGraceMs();
91148
91390
  const primaryClient = spawned[0].client;
91149
91391
  const syncRacer = (async () => {
91150
- await new Promise((resolve153) => {
91151
- const timer = setTimeout(resolve153, graceMs);
91392
+ await new Promise((resolve154) => {
91393
+ const timer = setTimeout(resolve154, graceMs);
91152
91394
  timer.unref?.();
91153
91395
  });
91154
91396
  const publishedAt = primaryClient.getAllDiagnostics?.().get(normalizedPath)?.ts;
@@ -92932,8 +93174,8 @@ var init_lsp = __esm({
92932
93174
  if (failedServerIds.length > 0 && !options.signal?.aborted) {
92933
93175
  const backoffMs2 = warmupRetryBackoffMs();
92934
93176
  if (backoffMs2 > 0) {
92935
- await untilAborted(new Promise((resolve153) => {
92936
- const timer = setTimeout(resolve153, backoffMs2);
93177
+ await untilAborted(new Promise((resolve154) => {
93178
+ const timer = setTimeout(resolve154, backoffMs2);
92937
93179
  timer.unref?.();
92938
93180
  }), options.signal);
92939
93181
  }
@@ -95336,8 +95578,8 @@ async function drainPendingRunnerFindings(maxWaitMs = 2e3, currentSession, curre
95336
95578
  if (maxWaitMs === 0)
95337
95579
  await Promise.resolve();
95338
95580
  if (maxWaitMs > 0 && current.some((entry) => !entry.settled)) {
95339
- await new Promise((resolve153) => {
95340
- const timer = setTimeout(resolve153, maxWaitMs);
95581
+ await new Promise((resolve154) => {
95582
+ const timer = setTimeout(resolve154, maxWaitMs);
95341
95583
  timer.unref?.();
95342
95584
  });
95343
95585
  }
@@ -95419,6 +95661,7 @@ var init_adopted_root_runners = __esm({
95419
95661
  "dist/clients/dispatch/adopted-root-runners.js"() {
95420
95662
  "use strict";
95421
95663
  ADOPTED_ROOT_RUNNER_ALLOWLIST = [
95664
+ "lsp",
95422
95665
  "fish-indent",
95423
95666
  "php-lint"
95424
95667
  ];
@@ -96105,7 +96348,11 @@ function buildCoverageNotice(ctx, runnerLatencies, dedupe2) {
96105
96348
  const deniedRunnerIds = relevant.filter((r) => r.skipReason === DISABLED_BY_CONFIG_SKIP_REASON).map((r) => r.runnerId);
96106
96349
  const deniedNote = `${deniedRunnerIds.join(", ")} disabled in config by dispatch.disabledRunners`;
96107
96350
  const onlySwitchedOff = relevant.every((r) => r.skipReason === DISABLED_BY_CONFIG_SKIP_REASON || isNotApplicableSkipReason(r.skipReason) || r.primaryUnavailableCause === "disabled" || r.primaryUnavailableCause === "disabledFallback");
96108
- const verdict = unchecked(cause ? `no primary language server answered (${PRIMARY_UNAVAILABLE_CAUSE[cause]})${deniedRunnerIds.length > 0 ? `; ${deniedNote}` : ""}` : deniedRunnerIds.length > 0 ? onlySwitchedOff ? `not checked (${deniedNote})` : `not fully checked (a language tool is missing, timed out, or failed to run; ${deniedNote})` : "not fully checked (a language tool is missing, timed out, or failed to run)");
96351
+ const unavailableReason = cause ? `no primary language server answered (${PRIMARY_UNAVAILABLE_CAUSE[cause]})${deniedRunnerIds.length > 0 ? `; ${deniedNote}` : ""}` : deniedRunnerIds.length > 0 ? onlySwitchedOff ? `not checked (${deniedNote})` : `not fully checked (a language tool is missing, timed out, or failed to run; ${deniedNote})` : "not fully checked (a language tool is missing, timed out, or failed to run)";
96352
+ const verdict = unchecked(unavailableReason);
96353
+ if (ctx.analysisRootMode === "adopted") {
96354
+ return { verdict: unchecked(`not analyzed (${unavailableReason})`) };
96355
+ }
96109
96356
  if (onlySwitchedOff && (cause === "disabled" || cause === "disabledFallback" || cause === void 0 && deniedRunnerIds.length > 0)) {
96110
96357
  const disabledIds = [
96111
96358
  ...new Set(relevant.flatMap((r) => r.disabledPrimaryServerIds ?? []))
@@ -98669,8 +98916,8 @@ function explicitRuleFixSuggestion(rule) {
98669
98916
  const raw = (rule.fix ?? rule.note ?? "").trim();
98670
98917
  if (!raw)
98671
98918
  return void 0;
98672
- const oneLine = raw.replace(/\s+/g, " ").trim();
98673
- return oneLine.length > 240 ? `${oneLine.slice(0, 237)}...` : oneLine;
98919
+ const oneLine2 = raw.replace(/\s+/g, " ").trim();
98920
+ return oneLine2.length > 240 ? `${oneLine2.slice(0, 237)}...` : oneLine2;
98674
98921
  }
98675
98922
  function normalizeRuleId2(ruleId) {
98676
98923
  return ruleId.replace(/-js$/, "");
@@ -99587,29 +99834,6 @@ var init_project_scan_policy = __esm({
99587
99834
  }
99588
99835
  });
99589
99836
 
99590
- // dist/clients/symbol-containment.js
99591
- function findOwnerName(candidates, targetStart, targetEnd) {
99592
- let best;
99593
- for (const candidate of candidates) {
99594
- const span = candidate.endLine - candidate.startLine;
99595
- const targetSpan = targetEnd - targetStart;
99596
- const contains = candidate.startLine <= targetStart && candidate.endLine >= targetEnd && span > targetSpan;
99597
- if (!contains)
99598
- continue;
99599
- if (!best || span < best.endLine - best.startLine)
99600
- best = candidate;
99601
- }
99602
- return best?.name;
99603
- }
99604
- function buildQualifiedName(ownerName, symbolName) {
99605
- return ownerName ? `${ownerName}.${symbolName}` : void 0;
99606
- }
99607
- var init_symbol_containment = __esm({
99608
- "dist/clients/symbol-containment.js"() {
99609
- "use strict";
99610
- }
99611
- });
99612
-
99613
99837
  // dist/clients/review-graph-logger.js
99614
99838
  import * as path130 from "node:path";
99615
99839
  function makeReviewGraphBuildMetadata(graph, options = {}) {
@@ -100011,36 +100235,6 @@ function getParameters(node) {
100011
100235
  function parameterName2(param) {
100012
100236
  return param.type === "identifier" ? param.text : firstNamedChild(param)?.text ?? "";
100013
100237
  }
100014
- function getFunctionName(node) {
100015
- if (node.type === "function_declaration") {
100016
- return firstChildOfType(node, "identifier")?.text ?? "<anonymous>";
100017
- }
100018
- if (node.type === "method_definition") {
100019
- const kids = node.children ?? [];
100020
- const paramsIdx = kids.findIndex((c) => c?.type === "formal_parameters");
100021
- for (let i = paramsIdx - 1; i >= 0; i -= 1) {
100022
- const t2 = kids[i]?.type;
100023
- if (t2 === "property_identifier" || t2 === "private_property_identifier" || t2 === "computed_property_name" || t2 === "string" || t2 === "number") {
100024
- return kids[i].text;
100025
- }
100026
- }
100027
- return "<anonymous>";
100028
- }
100029
- if (node.type === "arrow_function" || node.type === "function_expression") {
100030
- const parent = node.parent;
100031
- if (parent?.type === "variable_declarator") {
100032
- const id = firstChildOfType(parent, "identifier");
100033
- if (id)
100034
- return id.text;
100035
- } else if (parent?.type === "pair") {
100036
- const key4 = (parent.children ?? [])[0];
100037
- if (key4)
100038
- return key4.text;
100039
- }
100040
- return "<anonymous>";
100041
- }
100042
- return "<unknown>";
100043
- }
100044
100238
  function isCallPassThrough(stmt, paramNames) {
100045
100239
  if (stmt.type !== "return_statement")
100046
100240
  return { pass: false };
@@ -100182,7 +100376,7 @@ var init_function_facts = __esm({
100182
100376
  const isBoundaryWrapper = BOUNDARY_PREFIXES.some((prefix2) => lowerTarget.startsWith(prefix2));
100183
100377
  const bodySummary = summarizeBody(node, params);
100184
100378
  summaries.push({
100185
- name: getFunctionName(node),
100379
+ name: functionName(node) ?? "<anonymous>",
100186
100380
  line: node.startPosition.row + 1,
100187
100381
  column: node.startPosition.column + 1,
100188
100382
  endLine: body.endPosition.row + 1,
@@ -102121,7 +102315,7 @@ function flushReviewGraphPersistsForTests() {
102121
102315
  }
102122
102316
  async function waitForReviewGraphPersistsForTests() {
102123
102317
  for (let attempts2 = 0; attempts2 < 200 && (_workerRequests.size > 0 || _checkpointWorkerRequests.size > 0); attempts2++) {
102124
- await new Promise((resolve153) => setTimeout(resolve153, 10));
102318
+ await new Promise((resolve154) => setTimeout(resolve154, 10));
102125
102319
  }
102126
102320
  }
102127
102321
  async function terminateReviewGraphPersistWorkerForTests() {
@@ -104085,7 +104279,7 @@ var init_builder = __esm({
104085
104279
  _retainedGraphSites = /* @__PURE__ */ new Map();
104086
104280
  _cwdWorktreeCheckedCwds = /* @__PURE__ */ new Set();
104087
104281
  STAT_YIELD_EVERY = 100;
104088
- yieldToLoop = () => new Promise((resolve153) => setImmediate(resolve153));
104282
+ yieldToLoop = () => new Promise((resolve154) => setImmediate(resolve154));
104089
104283
  DEFAULT_REVIEW_GRAPH_SIZE_SKIP_TTL_MS = 15 * 6e4;
104090
104284
  _sizeSkipTtl = lazyEnvNumber("PI_LENS_REVIEW_GRAPH_SIZE_SKIP_TTL_MS", DEFAULT_REVIEW_GRAPH_SIZE_SKIP_TTL_MS);
104091
104285
  _resetReviewGraphSizeSkipTtlForTests = _sizeSkipTtl._resetForTests;
@@ -106722,8 +106916,8 @@ function diagnosticLocation(message, chartRoot) {
106722
106916
  return { filePath: path147.join(chartRoot, "Chart.yaml"), message };
106723
106917
  }
106724
106918
  const embedded = !message.startsWith(found);
106725
- const relative27 = embedded ? found.slice(found.indexOf("/") + 1) : found;
106726
- const candidate = path147.resolve(chartRoot, relative27);
106919
+ const relative28 = embedded ? found.slice(found.indexOf("/") + 1) : found;
106920
+ const candidate = path147.resolve(chartRoot, relative28);
106727
106921
  return {
106728
106922
  filePath: isWithinIdentity(candidate, chartRoot) ? candidate : path147.join(chartRoot, "Chart.yaml"),
106729
106923
  line: rawLine ? Number(rawLine) : void 0,
@@ -106930,9 +107124,9 @@ function mapRenderedToSource(options) {
106930
107124
  if (resolved2)
106931
107125
  return { filePath: resolved2, mapped: true };
106932
107126
  }
106933
- const relative27 = toProjectRelativePath(options.renderedPath, options.outputDir);
106934
- if (!isAbsoluteFilePath(relative27)) {
106935
- const resolved2 = resolveTemplateSource(relative27, chartRoot, realChartRoot);
107127
+ const relative28 = toProjectRelativePath(options.renderedPath, options.outputDir);
107128
+ if (!isAbsoluteFilePath(relative28)) {
107129
+ const resolved2 = resolveTemplateSource(relative28, chartRoot, realChartRoot);
106936
107130
  if (resolved2)
106937
107131
  return { filePath: resolved2, mapped: true };
106938
107132
  }
@@ -118521,7 +118715,7 @@ async function buildActionableWarningsReport(args) {
118521
118715
  }
118522
118716
  };
118523
118717
  const deferredWork2 = (async () => {
118524
- await new Promise((resolve153) => setTimeout(resolve153, 0));
118718
+ await new Promise((resolve154) => setTimeout(resolve154, 0));
118525
118719
  const deferredRecords = [...carried];
118526
118720
  const deferredDeadline = Date.now() + ACTIONABLE_WARNINGS_DEFERRED_BUDGET_MS;
118527
118721
  deferredDeps.deadlineAt = deferredDeadline;
@@ -120717,6 +120911,280 @@ var init_project_changes = __esm({
120717
120911
  }
120718
120912
  });
120719
120913
 
120914
+ // dist/clients/metrics/complexity-baseline.js
120915
+ import * as fs127 from "node:fs";
120916
+ import * as nodePath5 from "node:path";
120917
+ function complexityBaselineKey(filePath) {
120918
+ return normalizeMapKey(nodePath5.resolve(filePath));
120919
+ }
120920
+ function overMeasureCap(content) {
120921
+ return Buffer.byteLength(content, "utf-8") > MAX_MEASURED_BYTES;
120922
+ }
120923
+ function functionTableOf(functions) {
120924
+ const table = /* @__PURE__ */ new Map();
120925
+ for (const fn of functions) {
120926
+ if (fn.key.includes(ANONYMOUS_KEY))
120927
+ continue;
120928
+ if (table.size >= MAX_TABLE_FUNCTIONS)
120929
+ break;
120930
+ table.set(fn.key, {
120931
+ name: fn.name,
120932
+ cyclomatic: fn.cyclomatic,
120933
+ nesting: fn.nesting
120934
+ });
120935
+ }
120936
+ return table;
120937
+ }
120938
+ async function measureFunctionTable(filePath, content, treeKey = filePath) {
120939
+ const languageId = resolveTreeSitterLanguage(filePath);
120940
+ if (!languageId || !isComplexityLanguageId(languageId))
120941
+ return void 0;
120942
+ if (overMeasureCap(content))
120943
+ return void 0;
120944
+ const client = getSharedTreeSitterClient();
120945
+ if (!client || !await client.init())
120946
+ return void 0;
120947
+ const parsed = await client.withParsedTree(treeKey, languageId, content, (tree) => measureFile(tree.rootNode, languageId).functions, "complexity-baseline");
120948
+ return parsed.parsed ? functionTableOf(parsed.value) : void 0;
120949
+ }
120950
+ function gitFailureReason(result, fallback) {
120951
+ return result.failure ? `git-${result.failure}` : fallback;
120952
+ }
120953
+ function existingDir(start) {
120954
+ for (const dir of walkUpDirs(start)) {
120955
+ if (fs127.existsSync(dir))
120956
+ return dir;
120957
+ }
120958
+ return void 0;
120959
+ }
120960
+ function shortRef(ref) {
120961
+ return ref.replace(/^refs\/heads\//, "").replace(/^refs\/remotes\//, "");
120962
+ }
120963
+ async function resolveDefaultBranch(cwd, signal) {
120964
+ const result = await safeSpawnAsync("git", [
120965
+ "for-each-ref",
120966
+ "--format=%(refname)%09%(symref)",
120967
+ "refs/remotes/origin/HEAD",
120968
+ ...DEFAULT_BRANCH_REFS
120969
+ ], {
120970
+ cwd,
120971
+ timeout: GIT_TIMEOUT_MS,
120972
+ ...signal && { signal },
120973
+ resourceLabel: "complexity-main"
120974
+ });
120975
+ if (result.status !== 0)
120976
+ return { unavailable: gitFailureReason(result, "not-a-git-repository") };
120977
+ const rows = /* @__PURE__ */ new Map();
120978
+ for (const line of result.stdout.split("\n")) {
120979
+ const [ref, symref] = line.split(" ");
120980
+ if (ref)
120981
+ rows.set(ref, symref ?? "");
120982
+ }
120983
+ const originHead = rows.get("refs/remotes/origin/HEAD");
120984
+ if (originHead)
120985
+ return { ref: originHead };
120986
+ const found = DEFAULT_BRANCH_REFS.find((ref) => rows.has(ref));
120987
+ return found ? { ref: found } : { unavailable: "no-default-branch" };
120988
+ }
120989
+ async function readAtDefaultBranch(filePath, signal) {
120990
+ const target = realpathOrResolve(filePath);
120991
+ const cwd = existingDir(nodePath5.dirname(target));
120992
+ if (!cwd)
120993
+ return { kind: "unavailable", reason: "no-directory" };
120994
+ const branch = await resolveDefaultBranch(cwd, signal);
120995
+ if ("unavailable" in branch)
120996
+ return { kind: "unavailable", reason: branch.unavailable };
120997
+ const relative28 = nodePath5.relative(cwd, target).split(nodePath5.sep).join("/");
120998
+ const shown = await safeSpawnAsync("git", ["show", `${branch.ref}:./${relative28}`], {
120999
+ cwd,
121000
+ timeout: GIT_TIMEOUT_MS,
121001
+ ...signal && { signal },
121002
+ maxOutputBytes: MAX_BLOB_BYTES,
121003
+ env: { LC_ALL: "C" },
121004
+ resourceLabel: "complexity-main"
121005
+ });
121006
+ const ref = shortRef(branch.ref);
121007
+ if (shown.status === 0) {
121008
+ if (shown.outputTruncated)
121009
+ return { kind: "unavailable", reason: "blob-too-large" };
121010
+ return { kind: "file", ref, content: shown.stdout };
121011
+ }
121012
+ if (shown.failure)
121013
+ return { kind: "unavailable", reason: `git-${shown.failure}` };
121014
+ if (/does not exist|exists on disk, but not in/.test(shown.stderr))
121015
+ return { kind: "absent", ref };
121016
+ return { kind: "unavailable", reason: "git-show-failed" };
121017
+ }
121018
+ function captureComplexityBaseline(measured) {
121019
+ let last;
121020
+ return {
121021
+ main: void 0,
121022
+ get last() {
121023
+ return last ??= measured ? functionTableOf(measured) : void 0;
121024
+ }
121025
+ };
121026
+ }
121027
+ async function mainBaselineOf(filePath, signal) {
121028
+ const blob = await readAtDefaultBranch(filePath, signal);
121029
+ if (blob.kind !== "file")
121030
+ return blob;
121031
+ const functions = await measureFunctionTable(filePath, blob.content, `${filePath}\0${blob.ref}`);
121032
+ return functions ? { kind: "file", ref: blob.ref, functions } : { kind: "unavailable", reason: "default-branch-unparsable" };
121033
+ }
121034
+ function worsenedFunctions(entry, after, thresholds) {
121035
+ const last = entry?.last;
121036
+ const main = entry?.main;
121037
+ const out = [];
121038
+ for (const [key4, now] of after) {
121039
+ const prior = last?.get(key4);
121040
+ const reference = main?.kind === "file" ? main.functions.get(key4) : main?.kind === "absent" ? void 0 : prior;
121041
+ const changes = [];
121042
+ for (const metric of METRICS) {
121043
+ const threshold = thresholds[metric];
121044
+ const value = now[metric];
121045
+ if (value < threshold)
121046
+ continue;
121047
+ if (prior !== void 0 && value <= prior[metric])
121048
+ continue;
121049
+ if (reference !== void 0 && value <= reference[metric])
121050
+ continue;
121051
+ changes.push({
121052
+ metric,
121053
+ before: reference?.[metric],
121054
+ after: value,
121055
+ threshold
121056
+ });
121057
+ }
121058
+ if (changes.length > 0)
121059
+ out.push({ key: key4, name: now.name, changes });
121060
+ }
121061
+ const excess = (fn) => Math.max(...fn.changes.map((c) => c.after - c.threshold));
121062
+ return out.sort((a, b) => excess(b) - excess(a));
121063
+ }
121064
+ function baselineLabel(entry) {
121065
+ const main = entry?.main;
121066
+ if (main?.kind === "file" || main?.kind === "absent")
121067
+ return main.ref;
121068
+ return "session start";
121069
+ }
121070
+ function oneLine(text, maxBytes) {
121071
+ const flat = text.replace(/\s+/g, " ");
121072
+ if (Buffer.byteLength(flat, "utf-8") <= maxBytes)
121073
+ return flat;
121074
+ let out = "";
121075
+ let bytes = Buffer.byteLength("\u2026", "utf-8");
121076
+ for (const char of flat) {
121077
+ bytes += Buffer.byteLength(char, "utf-8");
121078
+ if (bytes > maxBytes)
121079
+ break;
121080
+ out += char;
121081
+ }
121082
+ return `${out}\u2026`;
121083
+ }
121084
+ function renderFunction(fn) {
121085
+ const parts = fn.changes.map((c) => `${METRIC_LABEL[c.metric]} ${c.before === void 0 ? "new" : c.before}\u2192${c.after} (\u2265${c.threshold})`);
121086
+ return `${oneLine(fn.key, MAX_NAME_BYTES)} ${parts.join(", ")}`;
121087
+ }
121088
+ function formatComplexityAdvisory(worsened, label, maxBytes = MAX_ADVISORY_BYTES) {
121089
+ if (worsened.length === 0)
121090
+ return void 0;
121091
+ const head = `\u26A0 complexity vs ${oneLine(label, MAX_LABEL_BYTES)}: `;
121092
+ const bytes = (s) => Buffer.byteLength(s, "utf-8");
121093
+ const shown = [];
121094
+ for (let i = 0; i < worsened.length; i++) {
121095
+ const next = [...shown, renderFunction(worsened[i])];
121096
+ const rest2 = worsened.length - next.length;
121097
+ const line = `${head}${next.join("; ")}${rest2 > 0 ? `; +${rest2} more` : ""}`;
121098
+ if (bytes(line) > maxBytes)
121099
+ break;
121100
+ shown.push(next[next.length - 1]);
121101
+ }
121102
+ const rest = worsened.length - shown.length;
121103
+ if (shown.length === 0) {
121104
+ const only = `${head}${worsened.length} function${worsened.length === 1 ? "" : "s"} worse`;
121105
+ return bytes(only) <= maxBytes ? only : void 0;
121106
+ }
121107
+ return `${head}${shown.join("; ")}${rest > 0 ? `; +${rest} more` : ""}`;
121108
+ }
121109
+ async function adviseOnEdit(args) {
121110
+ const { filePath, store, session, thresholds, signal } = args;
121111
+ if (!thresholds)
121112
+ return void 0;
121113
+ const startedAt = Date.now();
121114
+ let content;
121115
+ try {
121116
+ content = fs127.readFileSync(filePath, "utf-8");
121117
+ } catch {
121118
+ return void 0;
121119
+ }
121120
+ if (overMeasureCap(content)) {
121121
+ recordDegradationOnce({
121122
+ kind: "complexity-delta-failed",
121123
+ subject: filePath,
121124
+ reason: `the file is over ${MAX_MEASURED_BYTES} bytes; its functions are not judged`
121125
+ });
121126
+ return void 0;
121127
+ }
121128
+ const after = await measureFunctionTable(filePath, content);
121129
+ if (!after || signal?.aborted)
121130
+ return void 0;
121131
+ const key4 = complexityBaselineKey(filePath);
121132
+ const held = store.get(key4);
121133
+ const main = held ? held.main ?? await mainBaselineOf(filePath, signal) : void 0;
121134
+ if (signal?.aborted)
121135
+ return void 0;
121136
+ const entry = { main, last: held?.last };
121137
+ const worsened = held ? worsenedFunctions(entry, after, thresholds) : [];
121138
+ const label = baselineLabel(entry);
121139
+ const advisory = formatComplexityAdvisory(worsened, label);
121140
+ session.guardedWrite(filePath, () => store.set(key4, { main: entry.main, last: after }));
121141
+ logLatency({
121142
+ type: "phase",
121143
+ phase: "complexity_delta",
121144
+ filePath,
121145
+ durationMs: Date.now() - startedAt,
121146
+ metadata: {
121147
+ against: label,
121148
+ main: entry.main?.kind === "unavailable" ? `unavailable:${entry.main.reason}` : entry.main?.kind,
121149
+ functions: after.size,
121150
+ worsened: worsened.length,
121151
+ advised: advisory !== void 0
121152
+ }
121153
+ });
121154
+ return { advisory, worsened: worsened.length, against: label };
121155
+ }
121156
+ var MAX_BASELINE_FILES, MAX_TABLE_FUNCTIONS, MAX_ADVISORY_BYTES, MAX_BLOB_BYTES, MAX_LABEL_BYTES, MAX_NAME_BYTES, GIT_TIMEOUT_MS, DEFAULT_BRANCH_REFS, METRICS, METRIC_LABEL;
121157
+ var init_complexity_baseline = __esm({
121158
+ "dist/clients/metrics/complexity-baseline.js"() {
121159
+ "use strict";
121160
+ init_latency_logger();
121161
+ init_degradation_ledger();
121162
+ init_function_metrics();
121163
+ init_path_utils();
121164
+ init_safe_spawn();
121165
+ init_tree_sitter_shared();
121166
+ init_function_metrics();
121167
+ MAX_BASELINE_FILES = 256;
121168
+ MAX_TABLE_FUNCTIONS = 512;
121169
+ MAX_ADVISORY_BYTES = 240;
121170
+ MAX_BLOB_BYTES = 2 * 1024 * 1024;
121171
+ MAX_LABEL_BYTES = 40;
121172
+ MAX_NAME_BYTES = 80;
121173
+ GIT_TIMEOUT_MS = 2e3;
121174
+ DEFAULT_BRANCH_REFS = [
121175
+ "refs/heads/main",
121176
+ "refs/heads/master",
121177
+ "refs/remotes/origin/main",
121178
+ "refs/remotes/origin/master"
121179
+ ];
121180
+ METRICS = ["cyclomatic", "nesting"];
121181
+ METRIC_LABEL = {
121182
+ cyclomatic: "cc",
121183
+ nesting: "nest"
121184
+ };
121185
+ }
121186
+ });
121187
+
120720
121188
  // dist/clients/turn-summary.js
120721
121189
  function formatToolCounts(byTool) {
120722
121190
  return Object.entries(byTool).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([tool, count]) => `${tool} ${count}`).join(", ");
@@ -120817,9 +121285,9 @@ function deriveProviderFromModelId(modelId) {
120817
121285
  return "";
120818
121286
  const separators = [...id].filter((c) => c === "/" || c === ":").length;
120819
121287
  if (separators === 1) {
120820
- const sep12 = id.includes("/") ? "/" : ":";
120821
- const [providerPart, ...rest] = id.split(sep12);
120822
- if (providerPart && rest.join(sep12).length > 0)
121288
+ const sep13 = id.includes("/") ? "/" : ":";
121289
+ const [providerPart, ...rest] = id.split(sep13);
121290
+ if (providerPart && rest.join(sep13).length > 0)
120823
121291
  return providerPart;
120824
121292
  return "";
120825
121293
  }
@@ -120851,7 +121319,7 @@ var init_model_provider = __esm({
120851
121319
 
120852
121320
  // dist/clients/runtime-coordinator.js
120853
121321
  import { randomBytes as randomBytes3 } from "node:crypto";
120854
- import * as fs127 from "node:fs";
121322
+ import * as fs128 from "node:fs";
120855
121323
  import * as path193 from "node:path";
120856
121324
  function nextTelemetrySessionId() {
120857
121325
  const state9 = getProcessSingleton("runtime-coordinator-telemetry", 1, () => ({
@@ -120904,6 +121372,7 @@ var init_runtime_coordinator = __esm({
120904
121372
  init_path_utils();
120905
121373
  init_path_keyed_map();
120906
121374
  init_bounded_cache();
121375
+ init_complexity_baseline();
120907
121376
  init_line_alignment();
120908
121377
  init_partial_edit_apply();
120909
121378
  init_read_guard();
@@ -120959,7 +121428,12 @@ var init_runtime_coordinator = __esm({
120959
121428
  diagnosticsSurfaced: 0,
120960
121429
  coldSnapshotTouches: 0
120961
121430
  };
120962
- _complexityBaselines = /* @__PURE__ */ new Set();
121431
+ /**
121432
+ * #5087: per-file complexity baselines, keyed by
121433
+ * `complexityBaselineKey`. Bounded (LRU), and every write goes through a
121434
+ * session handle captured before the write's first await (#4220).
121435
+ */
121436
+ _complexityBaselines = new BoundedLruCache(MAX_BASELINE_FILES);
120963
121437
  _fixedThisTurn = new PathKeyedMap(normalizeMapKey);
120964
121438
  _writtenThisTurn = new PathKeyedMap(normalizeMapKey);
120965
121439
  _autofixDemotedThisTurn = new PathKeyedMap(normalizeMapKey);
@@ -121835,8 +122309,8 @@ var init_runtime_coordinator = __esm({
121835
122309
  });
121836
122310
  return entry;
121837
122311
  });
121838
- const timeout = new Promise((resolve153) => {
121839
- setTimeout(resolve153, maxWaitMs).unref?.();
122312
+ const timeout = new Promise((resolve154) => {
122313
+ setTimeout(resolve154, maxWaitMs).unref?.();
121840
122314
  });
121841
122315
  await Promise.race([
121842
122316
  Promise.allSettled(tracked.map((t2) => t2.promise)),
@@ -122524,7 +122998,7 @@ var init_runtime_coordinator = __esm({
122524
122998
  * to retire.
122525
122999
  */
122526
123000
  retireForeignRowsOfMissingFiles(of) {
122527
- return this.retireForeignRows("cited-file-missing", (row) => path193.isAbsolute(row.filePath) && !fs127.existsSync(row.filePath), void 0, of);
123001
+ return this.retireForeignRows("cited-file-missing", (row) => path193.isAbsolute(row.filePath) && !fs128.existsSync(row.filePath), void 0, of);
122528
123002
  }
122529
123003
  /**
122530
123004
  * #3218 criterion 2: a retirement no turn_end has delivered yet. The
@@ -122569,7 +123043,7 @@ var init_runtime_coordinator = __esm({
122569
123043
  reconcileInlineBlockers() {
122570
123044
  const survivors = [];
122571
123045
  for (const [displayPath, value] of this._pendingInlineBlockers.entries()) {
122572
- if (fs127.existsSync(displayPath))
123046
+ if (fs128.existsSync(displayPath))
122573
123047
  survivors.push([displayPath, value]);
122574
123048
  }
122575
123049
  if (survivors.length !== this._pendingInlineBlockers.size) {
@@ -123060,15 +123534,15 @@ var init_print_mode = __esm({
123060
123534
  });
123061
123535
 
123062
123536
  // dist/clients/rules-scanner.js
123063
- import * as fs128 from "node:fs";
123537
+ import * as fs129 from "node:fs";
123064
123538
  import * as path195 from "node:path";
123065
123539
  function findMarkdownFiles(dir, baseDir, depth = 0, collected = { count: 0 }) {
123066
123540
  const results = [];
123067
123541
  if (depth > RULES_SCAN_MAX_DEPTH)
123068
123542
  return results;
123069
- if (!fs128.existsSync(dir))
123543
+ if (!fs129.existsSync(dir))
123070
123544
  return results;
123071
- const entries = fs128.readdirSync(dir, { withFileTypes: true });
123545
+ const entries = fs129.readdirSync(dir, { withFileTypes: true });
123072
123546
  for (const entry of entries) {
123073
123547
  if (collected.count >= RULES_SCAN_MAX_FILES)
123074
123548
  break;
@@ -123091,7 +123565,7 @@ function scanProjectRules(cwd) {
123091
123565
  const rules2 = [];
123092
123566
  for (const { dir, source } of RULE_DIRS) {
123093
123567
  const dirPath = path195.join(cwd, dir);
123094
- if (fs128.existsSync(dirPath)) {
123568
+ if (fs129.existsSync(dirPath)) {
123095
123569
  const found = findMarkdownFiles(dirPath, path195.join(cwd, dir));
123096
123570
  for (const rule of found) {
123097
123571
  rules2.push({
@@ -123105,7 +123579,7 @@ function scanProjectRules(cwd) {
123105
123579
  }
123106
123580
  for (const { file, source } of RULE_FILES) {
123107
123581
  const filePath = path195.join(cwd, file);
123108
- if (fs128.existsSync(filePath)) {
123582
+ if (fs129.existsSync(filePath)) {
123109
123583
  rules2.push({
123110
123584
  source,
123111
123585
  name: file,
@@ -123504,7 +123978,7 @@ __export(call_graph_exports, {
123504
123978
  parseSymbolKey: () => parseSymbolKey2,
123505
123979
  saveCallGraph: () => saveCallGraph
123506
123980
  });
123507
- import * as fs129 from "node:fs";
123981
+ import * as fs130 from "node:fs";
123508
123982
  import * as path197 from "node:path";
123509
123983
  function severityForDepth(depth) {
123510
123984
  if (depth === 1)
@@ -123790,7 +124264,7 @@ function saveCallGraph(cwd, graph, identity) {
123790
124264
  const cacheFile = cacheFilePath(cwd);
123791
124265
  const metaFile = metaFilePath(cwd);
123792
124266
  try {
123793
- fs129.mkdirSync(path197.dirname(cacheFile), { recursive: true });
124267
+ fs130.mkdirSync(path197.dirname(cacheFile), { recursive: true });
123794
124268
  const persisted = {
123795
124269
  version: CALL_GRAPH_CACHE_VERSION,
123796
124270
  builtAt: graph.builtAt,
@@ -124002,7 +124476,7 @@ function validatePersistedCallGraph(raw, coverage) {
124002
124476
  function loadCallGraph(cwd, expectedIdentity) {
124003
124477
  const cacheFile = cacheFilePath(cwd);
124004
124478
  try {
124005
- const raw = JSON.parse(fs129.readFileSync(cacheFile, "utf-8"));
124479
+ const raw = JSON.parse(fs130.readFileSync(cacheFile, "utf-8"));
124006
124480
  if (raw.version !== CALL_GRAPH_CACHE_VERSION)
124007
124481
  return void 0;
124008
124482
  if (typeof raw.reviewGraphVersion !== "string" || typeof raw.reviewGraphSignature !== "string")
@@ -124157,7 +124631,7 @@ __export(codebase_model_exports, {
124157
124631
  loadCodebaseModel: () => loadCodebaseModel,
124158
124632
  saveCodebaseModel: () => saveCodebaseModel
124159
124633
  });
124160
- import * as fs130 from "node:fs";
124634
+ import * as fs131 from "node:fs";
124161
124635
  import * as path198 from "node:path";
124162
124636
  function inferKind(symbolKey) {
124163
124637
  const parsed = parseSymbolKey2(symbolKey);
@@ -124236,7 +124710,7 @@ function metaFilePath2(cwd) {
124236
124710
  function saveCodebaseModel(cwd, model) {
124237
124711
  const cacheFile = cacheFilePath2(cwd);
124238
124712
  try {
124239
- fs130.mkdirSync(path198.dirname(cacheFile), { recursive: true });
124713
+ fs131.mkdirSync(path198.dirname(cacheFile), { recursive: true });
124240
124714
  writeFileAtomic(cacheFile, JSON.stringify(model));
124241
124715
  writeFileAtomic(metaFilePath2(cwd), JSON.stringify({
124242
124716
  savedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -124248,7 +124722,7 @@ function saveCodebaseModel(cwd, model) {
124248
124722
  }
124249
124723
  function loadCodebaseModel(cwd, expectedIdentity) {
124250
124724
  try {
124251
- const raw = JSON.parse(fs130.readFileSync(cacheFilePath2(cwd), "utf-8"));
124725
+ const raw = JSON.parse(fs131.readFileSync(cacheFilePath2(cwd), "utf-8"));
124252
124726
  if (raw.version !== CODEBASE_MODEL_VERSION || typeof raw.reviewGraphVersion !== "string" || raw.reviewGraphVersion.length === 0 || typeof raw.reviewGraphSignature !== "string" || raw.reviewGraphSignature.length === 0 || typeof raw.generatedAt !== "string" || !Array.isArray(raw.entries))
124253
124727
  return void 0;
124254
124728
  if (raw.reviewGraphVersion !== expectedIdentity.reviewGraphVersion || raw.reviewGraphSignature !== expectedIdentity.reviewGraphSignature)
@@ -124914,7 +125388,7 @@ function scheduleStartupScansWithClients(deps, runtime2, sessionGeneration, anal
124914
125388
  const delay = STARTUP_TASK_DEFER_MS[name2] ?? 0;
124915
125389
  dbg2(`session_start task ${name2}: scheduled deferMs=${delay}`);
124916
125390
  runtime2.markStartupScanInFlight(name2, sessionGeneration);
124917
- const completion = new Promise((resolve153) => {
125391
+ const completion = new Promise((resolve154) => {
124918
125392
  const fire = () => {
124919
125393
  const startedAt = Date.now();
124920
125394
  dbg2(`session_start task ${name2}: start queuedMs=${startedAt - queuedAt}`);
@@ -124926,7 +125400,7 @@ function scheduleStartupScansWithClients(deps, runtime2, sessionGeneration, anal
124926
125400
  }).finally(() => {
124927
125401
  runtime2.clearStartupScanInFlight(name2, sessionGeneration);
124928
125402
  dbg2(`session_start task ${name2}: end`);
124929
- resolve153();
125403
+ resolve154();
124930
125404
  });
124931
125405
  };
124932
125406
  if (delay > 0) {
@@ -126057,8 +126531,8 @@ var init_runtime_session = __esm({
126057
126531
  });
126058
126532
 
126059
126533
  // dist/clients/deferred-runner-blockers.js
126060
- import * as fs131 from "node:fs";
126061
- import { resolve as resolve120 } from "node:path";
126534
+ import * as fs132 from "node:fs";
126535
+ import { resolve as resolve121 } from "node:path";
126062
126536
  function judgeDeferredRunnerFindings(pending4, cwd, options = {}) {
126063
126537
  const findings = (pending4.result?.diagnostics ?? []).flatMap((d) => d.runnerFault === true ? [] : [d]);
126064
126538
  if (findings.length === 0) {
@@ -126099,7 +126573,7 @@ function judgeDeferredRunnerFindings(pending4, cwd, options = {}) {
126099
126573
  };
126100
126574
  }
126101
126575
  function recordDeferredRunnerBlockers(runtime2, pending4, survivors, bytes) {
126102
- const blocking = stampLineHashes(withoutLaneCopies(runtime2, pending4, survivors).flatMap((d) => d.semantic === "blocking" ? [{ ...d, runnerId: d.runnerId ?? pending4.runnerId }] : []), bytes?.toString("utf-8"), (d) => !d.filePath || resolve120(d.filePath) === resolve120(pending4.filePath));
126576
+ const blocking = stampLineHashes(withoutLaneCopies(runtime2, pending4, survivors).flatMap((d) => d.semantic === "blocking" ? [{ ...d, runnerId: d.runnerId ?? pending4.runnerId }] : []), bytes?.toString("utf-8"), (d) => !d.filePath || resolve121(d.filePath) === resolve121(pending4.filePath));
126103
126577
  if (blocking.length === 0)
126104
126578
  return 0;
126105
126579
  const recorded = runtime2.recordDeferredInlineBlockers(
@@ -126153,7 +126627,7 @@ function withoutLaneCopies(runtime2, pending4, findings) {
126153
126627
  }
126154
126628
  function readBytes(filePath) {
126155
126629
  try {
126156
- return fs131.readFileSync(filePath);
126630
+ return fs132.readFileSync(filePath);
126157
126631
  } catch {
126158
126632
  return void 0;
126159
126633
  }
@@ -127559,7 +128033,7 @@ __export(metrics_history_exports, {
127559
128033
  computeTDI: () => computeTDI,
127560
128034
  loadHistory: () => loadHistory
127561
128035
  });
127562
- import * as fs133 from "node:fs";
128036
+ import * as fs134 from "node:fs";
127563
128037
  import * as path203 from "node:path";
127564
128038
  function isInsideGitRepo(startDir) {
127565
128039
  return findNearestContaining(startDir, [".git"]) !== void 0;
@@ -127571,7 +128045,7 @@ function getCurrentCommit(filePath) {
127571
128045
  }
127572
128046
  let spawnDir;
127573
128047
  for (const dir of walkUpDirs(startDir)) {
127574
- if (fs133.existsSync(dir)) {
128048
+ if (fs134.existsSync(dir)) {
127575
128049
  spawnDir = dir;
127576
128050
  break;
127577
128051
  }
@@ -127586,7 +128060,7 @@ function getCurrentCommit(filePath) {
127586
128060
  }
127587
128061
  function loadHistory() {
127588
128062
  const historyPath = path203.join(getProjectDataDir(process.cwd()), HISTORY_FILE);
127589
- if (!fs133.existsSync(historyPath)) {
128063
+ if (!fs134.existsSync(historyPath)) {
127590
128064
  return {
127591
128065
  version: 1,
127592
128066
  files: {},
@@ -127594,7 +128068,7 @@ function loadHistory() {
127594
128068
  };
127595
128069
  }
127596
128070
  try {
127597
- const content = fs133.readFileSync(historyPath, "utf-8");
128071
+ const content = fs134.readFileSync(historyPath, "utf-8");
127598
128072
  return JSON.parse(content);
127599
128073
  } catch {
127600
128074
  return {
@@ -127606,8 +128080,8 @@ function loadHistory() {
127606
128080
  }
127607
128081
  function saveHistory(history) {
127608
128082
  const historyDir = getProjectDataDir(process.cwd());
127609
- if (!fs133.existsSync(historyDir)) {
127610
- fs133.mkdirSync(historyDir, { recursive: true });
128083
+ if (!fs134.existsSync(historyDir)) {
128084
+ fs134.mkdirSync(historyDir, { recursive: true });
127611
128085
  }
127612
128086
  history.capturedAt = (/* @__PURE__ */ new Date()).toISOString();
127613
128087
  const historyPath = path203.join(historyDir, "metrics-history.json");
@@ -128282,7 +128756,7 @@ var init_delivery_holds = __esm({
128282
128756
  });
128283
128757
 
128284
128758
  // dist/clients/knip-scan-roots.js
128285
- import { resolve as resolve128 } from "node:path";
128759
+ import { resolve as resolve129 } from "node:path";
128286
128760
  function resolveKnipScanRoots(sessionCwd, modifiedFiles) {
128287
128761
  const session = resolveGitCheckout(sessionCwd);
128288
128762
  if (!session || modifiedFiles.length === 0) {
@@ -128291,7 +128765,7 @@ function resolveKnipScanRoots(sessionCwd, modifiedFiles) {
128291
128765
  let sessionOwnsEdit = false;
128292
128766
  const linked = [];
128293
128767
  for (const file of modifiedFiles) {
128294
- const owner = resolveLinkedWorktreeOwner(session, resolve128(sessionCwd, file));
128768
+ const owner = resolveLinkedWorktreeOwner(session, resolve129(sessionCwd, file));
128295
128769
  if (owner === null) {
128296
128770
  sessionOwnsEdit = true;
128297
128771
  } else if (!linked.some((known) => pathsEqual(known.root, owner.root))) {
@@ -128316,7 +128790,7 @@ var init_knip_scan_roots = __esm({
128316
128790
  });
128317
128791
 
128318
128792
  // dist/clients/project-diagnostics/cache.js
128319
- import * as fs134 from "node:fs";
128793
+ import * as fs135 from "node:fs";
128320
128794
  import * as path208 from "node:path";
128321
128795
  function cachePath2(cwd, fileName) {
128322
128796
  return path208.join(getProjectDataDir(cwd), "cache", fileName);
@@ -128335,7 +128809,7 @@ function loadProjectDiagnosticsSnapshot(cwd) {
128335
128809
  }
128336
128810
  function saveProjectDiagnosticsSnapshot(cwd, snapshot) {
128337
128811
  const filePath = cachePath2(cwd, SNAPSHOT_CACHE_FILE);
128338
- fs134.mkdirSync(path208.dirname(filePath), { recursive: true });
128812
+ fs135.mkdirSync(path208.dirname(filePath), { recursive: true });
128339
128813
  writeFileAtomic(filePath, JSON.stringify(snapshot, null, 2));
128340
128814
  }
128341
128815
  function loadProjectDiagnosticsDeltaReport(cwd) {
@@ -128352,7 +128826,7 @@ function loadProjectDiagnosticsDeltaReport(cwd) {
128352
128826
  }
128353
128827
  function writeProjectDiagnosticsDeltaReport(cwd, report) {
128354
128828
  const filePath = cachePath2(cwd, DELTA_CACHE_FILE);
128355
- fs134.mkdirSync(path208.dirname(filePath), { recursive: true });
128829
+ fs135.mkdirSync(path208.dirname(filePath), { recursive: true });
128356
128830
  writeFileAtomic(filePath, JSON.stringify(report, null, 2));
128357
128831
  }
128358
128832
  function reconcileProjectDiagnosticsSnapshot(snapshot) {
@@ -128367,7 +128841,7 @@ function reconcileProjectDiagnosticsSnapshot(snapshot) {
128367
128841
  let stale;
128368
128842
  let stat6;
128369
128843
  try {
128370
- stat6 = fs134.statSync(filePath);
128844
+ stat6 = fs135.statSync(filePath);
128371
128845
  } catch {
128372
128846
  stat6 = void 0;
128373
128847
  }
@@ -128376,7 +128850,7 @@ function reconcileProjectDiagnosticsSnapshot(snapshot) {
128376
128850
  stale = true;
128377
128851
  if (stat6.size === fingerprint2.sizeBytes) {
128378
128852
  try {
128379
- stale = hashDiagnosticContent(fs134.readFileSync(filePath, "utf-8")) !== fingerprint2.contentHash;
128853
+ stale = hashDiagnosticContent(fs135.readFileSync(filePath, "utf-8")) !== fingerprint2.contentHash;
128380
128854
  } catch {
128381
128855
  stale = true;
128382
128856
  }
@@ -128512,14 +128986,14 @@ var init_knip = __esm({
128512
128986
  });
128513
128987
 
128514
128988
  // dist/clients/test-target-roots.js
128515
- import { dirname as dirname63 } from "node:path";
128989
+ import { dirname as dirname64 } from "node:path";
128516
128990
  function createTurnEndTestRoots(sessionCwd) {
128517
128991
  const session = resolveGitCheckout(sessionCwd);
128518
128992
  const ownerByDir = /* @__PURE__ */ new Map();
128519
128993
  return (absoluteFile) => {
128520
128994
  if (session === null)
128521
128995
  return sessionCwd;
128522
- const dir = dirname63(absoluteFile);
128996
+ const dir = dirname64(absoluteFile);
128523
128997
  let owner = ownerByDir.get(dir);
128524
128998
  if (owner === void 0) {
128525
128999
  owner = resolveLinkedWorktreeOwner(session, absoluteFile);
@@ -128595,7 +129069,7 @@ var init_blocker_past_eof = __esm({
128595
129069
  });
128596
129070
 
128597
129071
  // dist/clients/persistent-reverify.js
128598
- import * as fs135 from "node:fs";
129072
+ import * as fs136 from "node:fs";
128599
129073
  function selectPersistentReverifyFiles(report, nowMs = Date.now()) {
128600
129074
  const candidates = [];
128601
129075
  let skippedChanged = 0;
@@ -128610,7 +129084,7 @@ function selectPersistentReverifyFiles(report, nowMs = Date.now()) {
128610
129084
  continue;
128611
129085
  let mtimeMs;
128612
129086
  try {
128613
- mtimeMs = fs135.statSync(entry.filePath).mtimeMs;
129087
+ mtimeMs = fs136.statSync(entry.filePath).mtimeMs;
128614
129088
  } catch {
128615
129089
  continue;
128616
129090
  }
@@ -128652,7 +129126,7 @@ async function runPersistentReverify(args) {
128652
129126
  processed += 1;
128653
129127
  let content;
128654
129128
  try {
128655
- content = fs135.readFileSync(entry.filePath, "utf-8");
129129
+ content = fs136.readFileSync(entry.filePath, "utf-8");
128656
129130
  } catch {
128657
129131
  outcomes.push({
128658
129132
  filePath: entry.filePath,
@@ -128771,11 +129245,11 @@ var init_persistent_reverify = __esm({
128771
129245
  });
128772
129246
 
128773
129247
  // dist/clients/inline-blocker-dispositions.js
128774
- import * as fs136 from "node:fs";
129248
+ import * as fs137 from "node:fs";
128775
129249
  import * as path211 from "node:path";
128776
129250
  function readCurrentContent(filePath) {
128777
129251
  try {
128778
- return fs136.readFileSync(filePath, "utf-8");
129252
+ return fs137.readFileSync(filePath, "utf-8");
128779
129253
  } catch {
128780
129254
  return "";
128781
129255
  }
@@ -129020,7 +129494,7 @@ var init_call_graph_impact = __esm({
129020
129494
  });
129021
129495
 
129022
129496
  // dist/clients/runtime-turn.js
129023
- import * as fs137 from "node:fs";
129497
+ import * as fs138 from "node:fs";
129024
129498
  import * as path213 from "node:path";
129025
129499
  async function runTestTargetsBounded(args) {
129026
129500
  const results = [];
@@ -129064,7 +129538,7 @@ async function runTestTargetsBounded(args) {
129064
129538
  });
129065
129539
  void pool.catch(() => {
129066
129540
  });
129067
- await new Promise((resolve153) => {
129541
+ await new Promise((resolve154) => {
129068
129542
  let settled = false;
129069
129543
  const finish = (reason) => {
129070
129544
  if (settled)
@@ -129076,7 +129550,7 @@ async function runTestTargetsBounded(args) {
129076
129550
  batchAbort.abort();
129077
129551
  clearTimeout(timer);
129078
129552
  args.signal?.removeEventListener("abort", onAbort);
129079
- resolve153();
129553
+ resolve154();
129080
129554
  };
129081
129555
  const onAbort = () => finish("abort");
129082
129556
  const timer = setTimeout(() => finish("budget"), budgetMs);
@@ -131053,7 +131527,7 @@ ${lines.join("\n")}`;
131053
131527
  }
131054
131528
  const config = RUNNERS[carried.runner];
131055
131529
  const carriedRoot = testRootFor(testFile);
131056
- if (!config || isExcludedTestTarget(testFile, carriedRoot) || !fs137.existsSync(testFile)) {
131530
+ if (!config || isExcludedTestTarget(testFile, carriedRoot) || !fs138.existsSync(testFile)) {
131057
131531
  resolvedDeferralKeys.add(carriedKey);
131058
131532
  deadDeferred++;
131059
131533
  continue;
@@ -131133,7 +131607,7 @@ ${lines.join("\n")}`;
131133
131607
  dbg2(`turn_end: ${display} \u2192 test target excluded by the built-in turn-end policy, skipping spawn (${toRunnerDisplayPath(cwd, target.testFile)})`);
131134
131608
  continue;
131135
131609
  }
131136
- if (!fs137.existsSync(target.testFile)) {
131610
+ if (!fs138.existsSync(target.testFile)) {
131137
131611
  missingTargetFiles++;
131138
131612
  dbg2(`turn_end: ${display} \u2192 test file missing, skipping spawn (${toRunnerDisplayPath(cwd, target.testFile)})`);
131139
131613
  continue;
@@ -131902,7 +132376,7 @@ ${impactLines.join("\n")}`;
131902
132376
  if (!lateAuxContentRead) {
131903
132377
  lateAuxContentRead = true;
131904
132378
  try {
131905
- lateAuxContentValue = fs137.readFileSync(lateAuxPath, "utf-8");
132379
+ lateAuxContentValue = fs138.readFileSync(lateAuxPath, "utf-8");
131906
132380
  } catch {
131907
132381
  lateAuxContentValue = void 0;
131908
132382
  }
@@ -132562,7 +133036,7 @@ var init_host_shim = __esm({
132562
133036
  });
132563
133037
 
132564
133038
  // dist/clients/mcp/analyze.js
132565
- import * as fs141 from "node:fs";
133039
+ import * as fs142 from "node:fs";
132566
133040
  import * as path221 from "node:path";
132567
133041
  function positiveEnv(name2, fallback) {
132568
133042
  const parsed = Number.parseInt(process.env[name2] ?? "", 10);
@@ -132706,7 +133180,7 @@ async function warmLspForFile(absPath, host2) {
132706
133180
  return;
132707
133181
  let content;
132708
133182
  try {
132709
- content = fs141.readFileSync(absPath, "utf8");
133183
+ content = fs142.readFileSync(absPath, "utf8");
132710
133184
  } catch {
132711
133185
  return;
132712
133186
  }
@@ -132763,7 +133237,7 @@ async function analyzeFile(filePath, cwd, options = {}) {
132763
133237
  }
132764
133238
  if (options.registerTurnState) {
132765
133239
  try {
132766
- const lineCount3 = fs141.readFileSync(absPath, "utf8").split("\n").length;
133240
+ const lineCount3 = fs142.readFileSync(absPath, "utf8").split("\n").length;
132767
133241
  new CacheManager().addModifiedRange(absPath, { start: 1, end: lineCount3 }, true, cwd, options.ownerId ?? MCP_TURN_STATE_OWNER_ID, "mcp");
132768
133242
  } catch {
132769
133243
  }
@@ -132781,7 +133255,7 @@ async function analyzeFile(filePath, cwd, options = {}) {
132781
133255
  try {
132782
133256
  if (warmIndex) {
132783
133257
  try {
132784
- const content = fs141.readFileSync(absPath, "utf8");
133258
+ const content = fs142.readFileSync(absPath, "utf8");
132785
133259
  if (!canWriteAnalysisRoot(analysisRootMode)) {
132786
133260
  emitBounded("adopted_root_writer_skipped", `${absPath}:word-index`, {
132787
133261
  filePath: absPath,
@@ -132890,7 +133364,7 @@ var init_analyze = __esm({
132890
133364
  });
132891
133365
 
132892
133366
  // dist/clients/project-diagnostics/scanner.js
132893
- import * as fs142 from "node:fs";
133367
+ import * as fs143 from "node:fs";
132894
133368
  import * as os39 from "node:os";
132895
133369
  import * as path222 from "node:path";
132896
133370
  function normalizeSeverity4(severity) {
@@ -133018,7 +133492,7 @@ async function scanFileMajorRules(cwd, files2, signal) {
133018
133492
  let astGrepLang;
133019
133493
  if (sgModule && canHandle(filePath)) {
133020
133494
  try {
133021
- if (fs142.statSync(filePath).size <= AST_GREP_MAX_FILE_BYTES) {
133495
+ if (fs143.statSync(filePath).size <= AST_GREP_MAX_FILE_BYTES) {
133022
133496
  astGrepLang = getLang(filePath, sgModule);
133023
133497
  }
133024
133498
  } catch {
@@ -133031,7 +133505,7 @@ async function scanFileMajorRules(cwd, files2, signal) {
133031
133505
  let content;
133032
133506
  let contentBytes;
133033
133507
  try {
133034
- const buf = fs142.readFileSync(filePath);
133508
+ const buf = fs143.readFileSync(filePath);
133035
133509
  contentBytes = buf.length;
133036
133510
  content = buf.toString("utf-8");
133037
133511
  } catch {
@@ -133090,7 +133564,7 @@ async function scanFileMajorRules(cwd, files2, signal) {
133090
133564
  } finally {
133091
133565
  facts.dropFileFacts(filePath);
133092
133566
  }
133093
- await new Promise((resolve153) => setImmediate(resolve153));
133567
+ await new Promise((resolve154) => setImmediate(resolve154));
133094
133568
  }
133095
133569
  if (wasmAborted) {
133096
133570
  astGrep.length = 0;
@@ -133256,13 +133730,13 @@ var init_scanner = __esm({
133256
133730
 
133257
133731
  // dist/clients/mcp/review.js
133258
133732
  import { spawn as spawn2 } from "node:child_process";
133259
- import { existsSync as existsSync66 } from "node:fs";
133733
+ import { existsSync as existsSync67 } from "node:fs";
133260
133734
  import { join as join121 } from "node:path";
133261
133735
  function resolveRebuildScript(serverFilePath) {
133262
133736
  return toPosix(serverFilePath).includes("/dist/") ? "build:dist" : "build";
133263
133737
  }
133264
133738
  function analyzeFileFresh(workerPath, file, cwd, options = {}, timeoutMs = 12e4) {
133265
- return new Promise((resolve153) => {
133739
+ return new Promise((resolve154) => {
133266
133740
  const args = [workerPath, `--file=${file}`, `--cwd=${cwd}`];
133267
133741
  if (options.flags)
133268
133742
  args.push(`--flags=${JSON.stringify(options.flags)}`);
@@ -133272,7 +133746,7 @@ function analyzeFileFresh(workerPath, file, cwd, options = {}, timeoutMs = 12e4)
133272
133746
  stdio: ["ignore", "pipe", "pipe"]
133273
133747
  });
133274
133748
  } catch (err) {
133275
- resolve153({
133749
+ resolve154({
133276
133750
  error: `failed to fork worker: ${err instanceof Error ? err.message : String(err)}`
133277
133751
  });
133278
133752
  return;
@@ -133285,7 +133759,7 @@ function analyzeFileFresh(workerPath, file, cwd, options = {}, timeoutMs = 12e4)
133285
133759
  return;
133286
133760
  settled = true;
133287
133761
  clearTimeout(timer);
133288
- resolve153(outcome);
133762
+ resolve154(outcome);
133289
133763
  };
133290
133764
  const timer = setTimeout(() => {
133291
133765
  child.kill();
@@ -133343,7 +133817,7 @@ function analyzeFileFresh(workerPath, file, cwd, options = {}, timeoutMs = 12e4)
133343
133817
  }
133344
133818
  function canRebuildPiLens(repoRoot) {
133345
133819
  const inNodeModules = /(^|[\\/])node_modules([\\/]|$)/i.test(repoRoot);
133346
- return !inNodeModules && existsSync66(join121(repoRoot, "tsconfig.dist.json"));
133820
+ return !inNodeModules && existsSync67(join121(repoRoot, "tsconfig.dist.json"));
133347
133821
  }
133348
133822
  async function runRebuild(repoRoot, script, timeoutMs = 3e5) {
133349
133823
  const start = Date.now();
@@ -133403,7 +133877,7 @@ var init_review = __esm({
133403
133877
 
133404
133878
  // dist/clients/mcp/session.js
133405
133879
  import * as crypto6 from "node:crypto";
133406
- import * as fs143 from "node:fs";
133880
+ import * as fs144 from "node:fs";
133407
133881
  import * as path223 from "node:path";
133408
133882
  function getMcpSessionContext() {
133409
133883
  contextPromise ??= (async () => {
@@ -133484,7 +133958,7 @@ async function runTurnEndNowImpl(cwd, files2 = [], deferredDelivery = false) {
133484
133958
  const abs = path223.isAbsolute(file) ? file : path223.resolve(cwd, file);
133485
133959
  let lineCount3 = 1;
133486
133960
  try {
133487
- lineCount3 = fs143.readFileSync(abs, "utf8").split("\n").length;
133961
+ lineCount3 = fs144.readFileSync(abs, "utf8").split("\n").length;
133488
133962
  } catch {
133489
133963
  continue;
133490
133964
  }
@@ -133659,10 +134133,10 @@ var init_session = __esm({
133659
134133
  if (this.pending.length >= 1) {
133660
134134
  return Promise.reject(new Error("turn_end queue is busy"));
133661
134135
  }
133662
- return new Promise((resolve153, reject) => {
134136
+ return new Promise((resolve154, reject) => {
133663
134137
  const item = {
133664
134138
  work,
133665
- resolve: resolve153,
134139
+ resolve: resolve154,
133666
134140
  reject,
133667
134141
  timer: setTimeout(() => {
133668
134142
  const index = this.pending.indexOf(item);
@@ -133705,9 +134179,9 @@ var init_session = __esm({
133705
134179
  });
133706
134180
 
133707
134181
  // dist/clients/middle-man-analysis.js
133708
- function buildForwardRegex(token, sep12) {
134182
+ function buildForwardRegex(token, sep13) {
133709
134183
  const t2 = escapeRegExp(token);
133710
- const s = escapeRegExp(sep12);
134184
+ const s = escapeRegExp(sep13);
133711
134185
  return new RegExp(`^(?:return\\s+)?(?:await\\s+)?${t2}${s}(\\w+)${s}(\\w+)\\(([^()]*)\\)\\s*;?$`);
133712
134186
  }
133713
134187
  function splitArgs(s) {
@@ -133872,7 +134346,7 @@ var init_middle_man_analysis = __esm({
133872
134346
  });
133873
134347
 
133874
134348
  // dist/clients/module-report.js
133875
- import * as fs144 from "node:fs";
134349
+ import * as fs145 from "node:fs";
133876
134350
  import * as path224 from "node:path";
133877
134351
  function normalizeMaxRefsPerSymbol(value) {
133878
134352
  if (value === void 0 || !Number.isFinite(value))
@@ -134606,7 +135080,7 @@ async function moduleReport(file, cwd, options) {
134606
135080
  const normalizedPath = normalizeMapKey(absPath);
134607
135081
  let content;
134608
135082
  try {
134609
- content = fs144.readFileSync(absPath, "utf-8");
135083
+ content = fs145.readFileSync(absPath, "utf-8");
134610
135084
  } catch {
134611
135085
  return unavailableReport(toDisplayPath(absPath, cwd));
134612
135086
  }
@@ -135022,7 +135496,7 @@ async function readSymbol(file, symbolName, cwd, options = {}) {
135022
135496
  };
135023
135497
  let content;
135024
135498
  try {
135025
- content = fs144.readFileSync(absPath, "utf-8");
135499
+ content = fs145.readFileSync(absPath, "utf-8");
135026
135500
  } catch (err) {
135027
135501
  log2(false);
135028
135502
  return {
@@ -135229,7 +135703,7 @@ async function readEnclosing(file, line, cwd, options) {
135229
135703
  };
135230
135704
  let content;
135231
135705
  try {
135232
- content = fs144.readFileSync(absPath, "utf-8");
135706
+ content = fs145.readFileSync(absPath, "utf-8");
135233
135707
  } catch {
135234
135708
  log2(false);
135235
135709
  return { found: false, path: absPath, line: targetLine };
@@ -135741,7 +136215,7 @@ function computeTrust(graph, cwd, drift) {
135741
136215
  const coverage = filesTotal > 0 ? filesCovered / filesTotal : 1;
135742
136216
  let exact = 0;
135743
136217
  let imp = 0;
135744
- let receiverType = 0;
136218
+ let receiverType2 = 0;
135745
136219
  let nameOnly = 0;
135746
136220
  for (const edge of graph.edges) {
135747
136221
  if (edge.kind !== "calls" && edge.kind !== "references")
@@ -135754,7 +136228,7 @@ function computeTrust(graph, cwd, drift) {
135754
136228
  imp += 1;
135755
136229
  break;
135756
136230
  case "receiver-type":
135757
- receiverType += 1;
136231
+ receiverType2 += 1;
135758
136232
  break;
135759
136233
  case "name-only":
135760
136234
  nameOnly += 1;
@@ -135766,7 +136240,7 @@ function computeTrust(graph, cwd, drift) {
135766
136240
  break;
135767
136241
  }
135768
136242
  }
135769
- const sampleSize = exact + imp + receiverType + nameOnly;
136243
+ const sampleSize = exact + imp + receiverType2 + nameOnly;
135770
136244
  const frac = (n) => sampleSize > 0 ? n / sampleSize : 0;
135771
136245
  const ageMs = Date.now() - Date.parse(graph.builtAt);
135772
136246
  const stale = Number.isFinite(ageMs) && ageMs > STALE_THRESHOLD_MS;
@@ -135800,7 +136274,7 @@ function computeTrust(graph, cwd, drift) {
135800
136274
  resolution: {
135801
136275
  exact: frac(exact),
135802
136276
  import: frac(imp),
135803
- receiverType: frac(receiverType),
136277
+ receiverType: frac(receiverType2),
135804
136278
  nameOnly: frac(nameOnly),
135805
136279
  sampleSize
135806
136280
  },
@@ -136856,7 +137330,7 @@ __export(lens_map_exports, {
136856
137330
  parseUntrackedIgnoredOutput: () => parseUntrackedIgnoredOutput,
136857
137331
  renderMapHtml: () => renderMapHtml
136858
137332
  });
136859
- import * as fs149 from "node:fs";
137333
+ import * as fs150 from "node:fs";
136860
137334
  import * as path237 from "node:path";
136861
137335
  function aggregateGraphToFiles(graph, options) {
136862
137336
  const maxNodes = Math.max(1, options?.maxNodes ?? DEFAULT_MAX_MAP_NODES);
@@ -137031,9 +137505,9 @@ function aggregateGraphToFiles(graph, options) {
137031
137505
  function buildEdgeList(keepIds2) {
137032
137506
  const out = [];
137033
137507
  for (const [key4, weight] of edgeWeights) {
137034
- const sep12 = key4.indexOf("\0");
137035
- const from = key4.slice(0, sep12);
137036
- const to = key4.slice(sep12 + 1);
137508
+ const sep13 = key4.indexOf("\0");
137509
+ const from = key4.slice(0, sep13);
137510
+ const to = key4.slice(sep13 + 1);
137037
137511
  if (keepIds2 && (!keepIds2.has(from) || !keepIds2.has(to)))
137038
137512
  continue;
137039
137513
  out.push({ from, to, weight });
@@ -137807,9 +138281,9 @@ async function generateLensMap(cwd) {
137807
138281
  };
137808
138282
  const html = renderMapHtml(payload);
137809
138283
  const outDir = path237.join(getProjectDataDir(cwd), "reports");
137810
- fs149.mkdirSync(outDir, { recursive: true });
138284
+ fs150.mkdirSync(outDir, { recursive: true });
137811
138285
  const filePath = path237.join(outDir, "lens-map.html");
137812
- fs149.writeFileSync(filePath, html, "utf-8");
138286
+ fs150.writeFileSync(filePath, html, "utf-8");
137813
138287
  return {
137814
138288
  filePath,
137815
138289
  fileCount: aggregated.nodes.length,
@@ -137900,7 +138374,7 @@ __export(performance_report_exports, {
137900
138374
  resolveLogByteBudget: () => resolveLogByteBudget,
137901
138375
  summarizePhaseLatency: () => summarizePhaseLatency
137902
138376
  });
137903
- import * as fs150 from "node:fs";
138377
+ import * as fs151 from "node:fs";
137904
138378
  import * as readline from "node:readline";
137905
138379
  function resolveLogByteBudget() {
137906
138380
  return getMaxLogSizeMB() * 1024 * 1024;
@@ -138033,7 +138507,7 @@ async function readPhaseLogTail(filePath, windowBytes, maxSamples, processId, se
138033
138507
  });
138034
138508
  let handle;
138035
138509
  try {
138036
- handle = await fs150.promises.open(filePath, "r");
138510
+ handle = await fs151.promises.open(filePath, "r");
138037
138511
  const stat6 = await handle.stat();
138038
138512
  if (!stat6.isFile()) {
138039
138513
  const notAFile = new Error(`EISDIR: illegal operation on a directory, read '${filePath}'`);
@@ -138068,7 +138542,7 @@ async function readPhaseLogTail(filePath, windowBytes, maxSamples, processId, se
138068
138542
  for await (const line of lines) {
138069
138543
  lineCount3 += 1;
138070
138544
  if (lineCount3 % PARSE_YIELD_EVERY === 0) {
138071
- await new Promise((resolve153) => setImmediate(resolve153));
138545
+ await new Promise((resolve154) => setImmediate(resolve154));
138072
138546
  }
138073
138547
  if (discardPartialFirstLine) {
138074
138548
  discardPartialFirstLine = false;
@@ -140232,7 +140706,7 @@ async function snapshotDirInto(dir, ignoreMatcher, stack, snapshot, counter) {
140232
140706
  } catch {
140233
140707
  }
140234
140708
  if (++counter.n % SNAPSHOT_YIELD_EVERY === 0) {
140235
- await new Promise((resolve153) => setImmediate(resolve153));
140709
+ await new Promise((resolve154) => setImmediate(resolve154));
140236
140710
  }
140237
140711
  }
140238
140712
  }
@@ -142186,7 +142660,7 @@ async function handleAgentEnd({ signal, ctxCwd, getFlag, getFlagSource, notify,
142186
142660
  for (const entry of work) {
142187
142661
  if (!entry)
142188
142662
  continue;
142189
- await new Promise((resolve153) => setImmediate(resolve153));
142663
+ await new Promise((resolve154) => setImmediate(resolve154));
142190
142664
  const { record: record6, filePath, fileStart } = entry;
142191
142665
  if (entry.missing) {
142192
142666
  dbg2(`agent_end deferred_format skipped missing file: ${filePath}`);
@@ -142844,6 +143318,7 @@ function retargetReplacementIndentation(newText, oldText, correctedOldText, file
142844
143318
  init_fix_run_restore();
142845
143319
  init_language_policy();
142846
143320
  init_tree_sitter_shared();
143321
+ init_complexity_baseline();
142847
143322
  init_mutating_tool();
142848
143323
  init_mutation_attribution();
142849
143324
  init_observed_mutation();
@@ -142955,7 +143430,7 @@ init_path_utils();
142955
143430
  // dist/clients/read-expansion.js
142956
143431
  init_deadline_utils();
142957
143432
  init_language_registry();
142958
- import * as fs132 from "node:fs";
143433
+ import * as fs133 from "node:fs";
142959
143434
  import { extname as extname24 } from "node:path";
142960
143435
  var EXPANSION_LIMIT_LINES = 100;
142961
143436
  var EXPANDED_SIZE_CAP_LINES = 300;
@@ -143130,7 +143605,7 @@ async function tryExpandRead(filePath, requestedOffset, requestedLimit, totalLin
143130
143605
  const ext2 = filePath.slice(filePath.lastIndexOf(".")).toLowerCase();
143131
143606
  const startedAt = Date.now();
143132
143607
  try {
143133
- const content = fs132.readFileSync(filePath, "utf8");
143608
+ const content = fs133.readFileSync(filePath, "utf8");
143134
143609
  if (ext2 === ".md" || ext2 === ".mdx") {
143135
143610
  const requestedStartRow2 = requestedOffset - 1;
143136
143611
  const result = tryExpandMarkdownSection(content, requestedStartRow2, requestedLimit, totalLines);
@@ -144121,6 +144596,10 @@ async function lookOnce(root, key4, trigger, runtime2, options, skipWalk) {
144121
144596
 
144122
144597
  // dist/clients/runtime-tool-result.js
144123
144598
  init_hook_budgets();
144599
+ init_high_complexity();
144600
+ init_rule_policy();
144601
+ init_complexity_baseline();
144602
+ init_tree_sitter_shared();
144124
144603
  init_degradation_ledger();
144125
144604
  init_analysis_root();
144126
144605
  var AUTHORITATIVE_CONTENT_MAX_BYTES = RUNTIME_CONFIG.pipeline.lspMaxFileBytes;
@@ -144999,6 +145478,16 @@ function handleToolExecutionEnd(event, readGuard) {
144999
145478
  const toolCallId = resolveToolCallCorrelationId(event);
145000
145479
  return toolCallId !== void 0 ? readGuard.dropProvisionalReadByCall(toolCallId) : false;
145001
145480
  }
145481
+ function complexityThresholdsFor(filePath, root) {
145482
+ const resolution = resolveDispatchPolicyConfigForFile(filePath, root);
145483
+ const kept = applyRulePolicy([{ rule: "high-complexity" }], rulePolicyMapFromResolution(resolution, root), { root, filePath });
145484
+ if (kept.length === 0)
145485
+ return void 0;
145486
+ return {
145487
+ cyclomatic: ruleThresholdFromResolution(resolution, "high-complexity") ?? DEFAULT_HIGH_COMPLEXITY_THRESHOLD,
145488
+ nesting: DEFAULT_HIGH_COMPLEXITY_DEPTH_THRESHOLD
145489
+ };
145490
+ }
145002
145491
  function composePartialApplyResult(pending4, event, result) {
145003
145492
  const hostRefused = event.isError === true;
145004
145493
  const content = result ? result.content : event.content;
@@ -146357,6 +146846,33 @@ async function handleToolResult(deps) {
146357
146846
 
146358
146847
  ${formatBehaviorWarnings(behaviorWarnings)}`;
146359
146848
  }
146849
+ if (!result.hasBlockers && resultLive && !getFlag("no-complexity") && isComplexitySupportedFile(filePath)) {
146850
+ const verdict = await bounded(adviseOnEdit({
146851
+ filePath,
146852
+ store: runtime2.complexityBaselines,
146853
+ session: writeSession,
146854
+ thresholds: complexityThresholdsFor(filePath, turnStateCwd),
146855
+ signal: deps.signal
146856
+ }).catch((err) => {
146857
+ recordDegradationOnce({
146858
+ kind: "complexity-delta-failed",
146859
+ subject: filePath,
146860
+ // The error name only: a parser message can quote file text (shape 27).
146861
+ reason: `the complexity delta threw ${err instanceof Error ? err.name : typeof err}`
146862
+ });
146863
+ return void 0;
146864
+ }), {
146865
+ ms: HOOK_WALL_BUDGET_MS.tool_result_edit,
146866
+ signal: deps.signal,
146867
+ hook: "tool_result_edit",
146868
+ label: "complexity-delta"
146869
+ });
146870
+ if (verdict?.advisory) {
146871
+ output = output ? `${output}
146872
+
146873
+ ${verdict.advisory}` : verdict.advisory;
146874
+ }
146875
+ }
146360
146876
  const totalMs = Date.now() - toolResultStart;
146361
146877
  logLatency({
146362
146878
  type: "tool_result",
@@ -146611,6 +147127,7 @@ async function handleToolCall(deps) {
146611
147127
  async function handleToolCallImpl(deps) {
146612
147128
  const { event, ctx, lensEnabled, getFlag, dbg: dbg2, runtime: runtime2, cacheManager: cacheManager2, ensureLSPConfigInitialized: ensureLSPConfigInitialized2, updateLspStatus, getTreeSitterClient = getSharedTreeSitterClient } = deps;
146613
147129
  const callSessionId = deps.sessionId ?? runtime2.telemetrySessionId;
147130
+ const callSession = runtime2.captureSessionGeneration();
146614
147131
  dropHashlineAnchorMemo();
146615
147132
  const readGuardCorrelationId = getReadGuardCorrelationId(event);
146616
147133
  let filePath;
@@ -147004,7 +147521,7 @@ async function handleToolCallImpl(deps) {
147004
147521
  { captureLineHashes: false }
147005
147522
  );
147006
147523
  }
147007
- if (!getFlag("no-complexity") && !isExternalOrVendor && filePath && !runtime2.complexityBaselines.has(filePath) && isComplexitySupportedFile(filePath)) {
147524
+ if (!getFlag("no-complexity") && !isExternalOrVendor && filePath && !runtime2.complexityBaselines.has(complexityBaselineKey(filePath)) && isComplexitySupportedFile(filePath)) {
147008
147525
  const complexityClient = (await requestBootstrapClients({
147009
147526
  reason: "tool-call-complexity-baseline",
147010
147527
  // The pre-dispatch hook. It carries no wall budget in #2523's
@@ -147023,18 +147540,20 @@ async function handleToolCallImpl(deps) {
147023
147540
  // exists to prevent.
147024
147541
  signal: deps.ctx.signal
147025
147542
  }))?.complexityClient;
147026
- const baseline = await complexityClient?.analyzeFile(filePath);
147027
- if (baseline) {
147028
- runtime2.complexityBaselines.add(filePath);
147543
+ const analysis = complexityClient ? await complexityClient.analyzeFile(filePath) : void 0;
147544
+ if (complexityClient) {
147545
+ callSession.guardedWrite(filePath, () => runtime2.complexityBaselines.set(complexityBaselineKey(filePath), captureComplexityBaseline(analysis?.measuredFunctions)));
147546
+ }
147547
+ if (analysis && callSession.isCurrent()) {
147029
147548
  const { captureSnapshot: captureSnapshot2 } = await Promise.resolve().then(() => (init_metrics_history(), metrics_history_exports));
147030
- captureSnapshot2(filePath, {
147031
- maintainabilityIndex: baseline.maintainabilityIndex,
147032
- cognitiveComplexity: baseline.cognitiveComplexity,
147033
- maxNestingDepth: baseline.maxNestingDepth,
147034
- linesOfCode: baseline.linesOfCode,
147035
- maxCyclomatic: baseline.maxCyclomaticComplexity,
147036
- entropy: baseline.codeEntropy
147037
- });
147549
+ callSession.guardedWrite(filePath, () => captureSnapshot2(filePath, {
147550
+ maintainabilityIndex: analysis.maintainabilityIndex,
147551
+ cognitiveComplexity: analysis.cognitiveComplexity,
147552
+ maxNestingDepth: analysis.maxNestingDepth,
147553
+ linesOfCode: analysis.linesOfCode,
147554
+ maxCyclomatic: analysis.maxCyclomaticComplexity,
147555
+ entropy: analysis.codeEntropy
147556
+ }));
147038
147557
  }
147039
147558
  } else if (getFlag("no-complexity") && filePath && isComplexitySupportedFile(filePath)) {
147040
147559
  recordDegradationOnce({
@@ -147492,7 +148011,7 @@ init_file_utils();
147492
148011
  init_path_utils();
147493
148012
  init_source_filter();
147494
148013
  init_source_walker();
147495
- import * as fs138 from "node:fs";
148014
+ import * as fs139 from "node:fs";
147496
148015
  import * as path214 from "node:path";
147497
148016
  function fileMatchesPathGlobs(file, cwd, globs) {
147498
148017
  const rel = path214.relative(cwd, file).split(path214.sep).join("/");
@@ -147514,13 +148033,13 @@ async function isGlobEntry(resolved2, cwd) {
147514
148033
  const spelled = relativeInside(path214.resolve(cwd), resolved2) ?? resolved2;
147515
148034
  if (!hasGlobMagic(spelled))
147516
148035
  return false;
147517
- return fs138.promises.lstat(resolved2).then(() => false, (refusal) => {
148036
+ return fs139.promises.lstat(resolved2).then(() => false, (refusal) => {
147518
148037
  return refusal.code === "ENOENT" || refusal.code === "ENOTDIR";
147519
148038
  });
147520
148039
  }
147521
- function literalRoot(cwd, relative27) {
148040
+ function literalRoot(cwd, relative28) {
147522
148041
  let root = cwd;
147523
- for (const segment of relative27.split("/")) {
148042
+ for (const segment of relative28.split("/")) {
147524
148043
  if (hasGlobMagic(segment))
147525
148044
  break;
147526
148045
  root = path214.join(root, segment);
@@ -147532,11 +148051,11 @@ async function expandPathsEntry(entry, cwd, budget, options = {}) {
147532
148051
  const absolute = path214.resolve(cwdAbsolute, entry);
147533
148052
  if (!await isGlobEntry(absolute, cwdAbsolute))
147534
148053
  return { entries: [absolute], root: cwdAbsolute };
147535
- const relative27 = relativeInside(cwdAbsolute, absolute);
147536
- if (relative27 === void 0) {
148054
+ const relative28 = relativeInside(cwdAbsolute, absolute);
148055
+ if (relative28 === void 0) {
147537
148056
  return { entries: [], refusal: "outside", root: cwdAbsolute };
147538
148057
  }
147539
- const root = literalRoot(cwdAbsolute, relative27);
148058
+ const root = literalRoot(cwdAbsolute, relative28);
147540
148059
  const { signal } = options;
147541
148060
  const matcher = getProjectIgnoreMatcher(cwdAbsolute);
147542
148061
  const policy = { ignoreMatcher: matcher };
@@ -147810,7 +148329,7 @@ function createActivateToolsTool(pi, lazyTools, options = {}) {
147810
148329
 
147811
148330
  // dist/tools/lens-diagnostics.js
147812
148331
  init_bounded_cache();
147813
- import { promises as fs146 } from "node:fs";
148332
+ import { promises as fs147 } from "node:fs";
147814
148333
  import * as fsSync from "node:fs";
147815
148334
  import * as os41 from "node:os";
147816
148335
  import * as path229 from "node:path";
@@ -147902,7 +148421,7 @@ init_gitleaks_client();
147902
148421
  init_govulncheck_client();
147903
148422
  init_project_trust();
147904
148423
  init_trivy_client();
147905
- import * as fs140 from "node:fs";
148424
+ import * as fs141 from "node:fs";
147906
148425
  import * as os38 from "node:os";
147907
148426
  import * as path220 from "node:path";
147908
148427
  init_dead_code();
@@ -148015,7 +148534,7 @@ function opengrepResultToProjectDiagnostics(cwd, result) {
148015
148534
  // dist/clients/project-diagnostics/runner-adapters/runner-findings.js
148016
148535
  init_test_runner_client();
148017
148536
  init_advisory_provenance();
148018
- import * as fs139 from "node:fs";
148537
+ import * as fs140 from "node:fs";
148019
148538
  import * as path219 from "node:path";
148020
148539
  function failureMessage(failure) {
148021
148540
  const firstLine2 = failure.message.split("\n")[0]?.slice(0, 300) ?? "";
@@ -148082,7 +148601,7 @@ function testRunnerFindingsToProjectDiagnostics(cache3, cwd, runtime2) {
148082
148601
  return [];
148083
148602
  const validation = cwd ? validateAdvisoryProvenance(cache3, cwd, runtime2) : { status: "unknown", reasons: ["validation-context-missing"] };
148084
148603
  const root = cwd ?? process.cwd();
148085
- const missingKeys = new Set((cache3.provenance?.files ?? []).filter((file) => !fs139.existsSync(path219.resolve(root, file.path))).map((file) => advisoryPathKey(file.path, root)));
148604
+ const missingKeys = new Set((cache3.provenance?.files ?? []).filter((file) => !fs140.existsSync(path219.resolve(root, file.path))).map((file) => advisoryPathKey(file.path, root)));
148086
148605
  const historical = cache3.superseded === true || cache3.stale === true || validation.status !== "current";
148087
148606
  return cache3.results.filter((result) => !missingKeys.has(advisoryPathKey(result.file, root))).flatMap((result) => testResultToProjectDiagnostics(result, historical)).map((diagnostic) => historical ? {
148088
148607
  ...diagnostic,
@@ -148118,10 +148637,10 @@ async function fetchFreshProjectDiagnostics(cacheManager2, cwd, clients, signal,
148118
148637
  let analysisRootValidation;
148119
148638
  if (options.analysisRoot !== void 0) {
148120
148639
  try {
148121
- if (!fs140.statSync(requestedRoot).isDirectory()) {
148640
+ if (!fs141.statSync(requestedRoot).isDirectory()) {
148122
148641
  throw new Error("is not a directory");
148123
148642
  }
148124
- analysisRoot = fs140.realpathSync(requestedRoot);
148643
+ analysisRoot = fs141.realpathSync(requestedRoot);
148125
148644
  } catch (error) {
148126
148645
  const detail = error instanceof Error ? error.message : String(error);
148127
148646
  const reason = `the explicit analysis root ${requestedRoot} is unavailable or ${detail}`;
@@ -148280,7 +148799,7 @@ async function fetchFreshProjectDiagnostics(cacheManager2, cwd, clients, signal,
148280
148799
  markCold("jscpd", reasonFromAvailabilityVerdict("jscpd", clients.jscpdClient.getAvailabilityVerdict?.()));
148281
148800
  return;
148282
148801
  }
148283
- const isTsProject = fs140.existsSync(path220.join(analysisRoot, "tsconfig.json"));
148802
+ const isTsProject = fs141.existsSync(path220.join(analysisRoot, "tsconfig.json"));
148284
148803
  const scannerKey = isTsProject ? "jscpd-ts" : "jscpd";
148285
148804
  const startMs = Date.now();
148286
148805
  const result = await clients.jscpdClient.scan(analysisRoot, void 0, void 0, isTsProject);
@@ -148614,7 +149133,7 @@ init_auxiliary_lsp();
148614
149133
  init_finding_policy();
148615
149134
  init_utils();
148616
149135
  init_types();
148617
- import * as fs145 from "node:fs";
149136
+ import * as fs146 from "node:fs";
148618
149137
  import * as path228 from "node:path";
148619
149138
  init_diagnostic_dispositions();
148620
149139
  init_finding_delivery_gate();
@@ -148737,7 +149256,7 @@ async function collectFiles(dir, extensions, maxFiles, isIgnored = () => false)
148737
149256
  return;
148738
149257
  let entries;
148739
149258
  try {
148740
- entries = await fs145.promises.readdir(current, { withFileTypes: true });
149259
+ entries = await fs146.promises.readdir(current, { withFileTypes: true });
148741
149260
  } catch {
148742
149261
  return;
148743
149262
  }
@@ -148866,7 +149385,7 @@ function createLspDiagnosticsTool(nextWriteIndex, onConfirmedNoBlockers, getServ
148866
149385
  const absPath = normalizeMapKey(typedParams.pathAlreadyResolved === true ? rawPath : resolveHostToolPath(rawPath, cwd));
148867
149386
  let stat6;
148868
149387
  try {
148869
- stat6 = fs145.statSync(absPath);
149388
+ stat6 = fs146.statSync(absPath);
148870
149389
  } catch {
148871
149390
  return {
148872
149391
  content: [
@@ -148898,7 +149417,7 @@ async function collectDiagnosticsForFile(absPath, lspService, scanRoot, waitMs,
148898
149417
  let content;
148899
149418
  let touched;
148900
149419
  try {
148901
- content = fs145.readFileSync(absPath, "utf-8");
149420
+ content = fs146.readFileSync(absPath, "utf-8");
148902
149421
  const contentLimit = explicitQuery ? exceedsExplicitQueryLimits(content) : exceedsLspSyncLimits(content);
148903
149422
  if (contentLimit.tooLarge) {
148904
149423
  const reason = `file too large for LSP diagnostics (${contentLimit.reason})`;
@@ -149174,7 +149693,7 @@ async function collectFileDiagnosticResult(file, severity, lspService, waitMs, n
149174
149693
  const scannedAt = Date.now();
149175
149694
  let stat6;
149176
149695
  try {
149177
- stat6 = fs145.statSync(file);
149696
+ stat6 = fs146.statSync(file);
149178
149697
  if (!stat6.isFile()) {
149179
149698
  return { file, diagnostics: [], error: `${file}: not a file` };
149180
149699
  }
@@ -149723,7 +150242,7 @@ async function expandPathsToFiles(cwd, rawPaths, pathsAlreadyResolved = false) {
149723
150242
  const abs = normalizeMapKey(pathsAlreadyResolved ? entry : resolveHostToolPath(entry, cwd));
149724
150243
  let stat6;
149725
150244
  try {
149726
- stat6 = fs145.statSync(abs);
150245
+ stat6 = fs146.statSync(abs);
149727
150246
  } catch {
149728
150247
  }
149729
150248
  if (stat6?.isDirectory()) {
@@ -150082,7 +150601,7 @@ async function findFullScanBindingMismatches(results) {
150082
150601
  result.boundToCurrentDisk !== true && result.contentHash !== void 0
150083
150602
  ) {
150084
150603
  try {
150085
- const content = await fs146.readFile(result.filePath, "utf-8");
150604
+ const content = await fs147.readFile(result.filePath, "utf-8");
150086
150605
  if (hashDiagnosticContent(content) !== result.contentHash) {
150087
150606
  mismatched.add(result);
150088
150607
  }
@@ -150092,7 +150611,7 @@ async function findFullScanBindingMismatches(results) {
150092
150611
  sinceYield += 1;
150093
150612
  if (sinceYield >= FULL_SCAN_BINDING_YIELD_EVERY) {
150094
150613
  sinceYield = 0;
150095
- await new Promise((resolve153) => setImmediate(resolve153));
150614
+ await new Promise((resolve154) => setImmediate(resolve154));
150096
150615
  }
150097
150616
  }
150098
150617
  return mismatched;
@@ -150203,7 +150722,6 @@ function createLensDiagnosticsTool(cacheManager2, getCwd, getLspService = getLSP
150203
150722
  parts.push(`${w} warnings`);
150204
150723
  return `lens_diagnostics ${mode} \u2014 ${parts.join(" \xB7 ")}${cacheVerdict === "inconclusive" || cacheVerdict === "unverified" ? ` \xB7 ${cacheVerdict}` : ""}${uncheckedSuffix} (${files2} files)${coldSuffix}${failedSuffix}`;
150205
150724
  }),
150206
- constrainedSampling: CONSTRAINED_JSON_SCHEMA_SAMPLING,
150207
150725
  parameters: Type.Object({
150208
150726
  source: Type.Optional(Type.String({
150209
150727
  enum: ["session", "lsp"],
@@ -151146,7 +151664,7 @@ async function applyInlineSuppressionsToSummaries(summaries, cwd, policyMap, dis
151146
151664
  return summary;
151147
151665
  let content;
151148
151666
  try {
151149
- content = await fs146.readFile(summary.filePath, "utf8");
151667
+ content = await fs147.readFile(summary.filePath, "utf8");
151150
151668
  } catch {
151151
151669
  const policyKept2 = applyRulePolicy(summary.diagnostics, policyMap, {
151152
151670
  root: cwd,
@@ -151926,7 +152444,7 @@ Summary (${visibleSummaries.length} files diagnosed this session):`,
151926
152444
  }
151927
152445
 
151928
152446
  // dist/tools/lens-diagnostic-mark.js
151929
- import { promises as fs147 } from "node:fs";
152447
+ import { promises as fs148 } from "node:fs";
151930
152448
  import * as path231 from "node:path";
151931
152449
  init_diagnostic_dispositions();
151932
152450
 
@@ -152159,7 +152677,7 @@ function createLensDiagnosticMarkTool(getCwd, getIdentity, captureLineage) {
152159
152677
  const readVerifyWrite = async () => {
152160
152678
  let content2;
152161
152679
  try {
152162
- content2 = await fs147.readFile(absPath, "utf-8");
152680
+ content2 = await fs148.readFile(absPath, "utf-8");
152163
152681
  } catch (err) {
152164
152682
  return {
152165
152683
  refusal: refuse(`Could not read ${absPath}: ${err instanceof Error ? err.message : String(err)}`)
@@ -152203,7 +152721,7 @@ function createLensDiagnosticMarkTool(getCwd, getIdentity, captureLineage) {
152203
152721
  refusal: refuse(err instanceof Error ? err.message : String(err))
152204
152722
  };
152205
152723
  }
152206
- await fs147.writeFile(absPath, updated, "utf-8");
152724
+ await fs148.writeFile(absPath, updated, "utf-8");
152207
152725
  return { content: content2, verifiedLine: verifiedLine2, reanchorNote: reanchorNote2, wrote: true };
152208
152726
  };
152209
152727
  let step2;
@@ -152490,7 +153008,6 @@ function createAstGrepReplaceTool(astGrepClient, captureLineage, getFlag) {
152490
153008
  const state9 = details?.applied ? "applied" : "preview";
152491
153009
  return `ast_grep_replace \u2014 ${n} match${n === 1 ? "" : "es"}, ${state9}`;
152492
153010
  }),
152493
- constrainedSampling: CONSTRAINED_JSON_SCHEMA_SAMPLING,
152494
153011
  parameters: Type.Object({
152495
153012
  pattern: Type.String({
152496
153013
  description: "AST pattern to match (be specific with context)"
@@ -152971,7 +153488,6 @@ function createAstGrepSearchTool(astGrepClient) {
152971
153488
  const applied = details?.applied ? " (applied)" : "";
152972
153489
  return `ast_grep_search \u2014 ${count}${ofTotal} match${count === 1 && !ofTotal ? "" : "es"}${applied}`;
152973
153490
  }),
152974
- constrainedSampling: CONSTRAINED_JSON_SCHEMA_SAMPLING,
152975
153491
  parameters: Type.Object({
152976
153492
  dump: Type.Optional(Type.Boolean()),
152977
153493
  pattern: Type.Optional(Type.String({ description: "AST pattern." })),
@@ -153467,7 +153983,6 @@ function createAstGrepOutlineTool(astGrepClient) {
153467
153983
  const trunc = details?.truncatedFiles ? " (truncated)" : "";
153468
153984
  return `ast_grep_outline \u2014 ${items} symbols across ${files2} file${files2 === 1 ? "" : "s"}${trunc}`;
153469
153985
  }),
153470
- constrainedSampling: CONSTRAINED_JSON_SCHEMA_SAMPLING,
153471
153986
  parameters: Type.Object({
153472
153987
  paths: Type.Array(Type.String(), {
153473
153988
  minItems: 1,
@@ -155402,7 +155917,7 @@ Note: ${snapshotWithheldLine}` : ""}`
155402
155917
  const msg = err instanceof Error ? err.message : String(err);
155403
155918
  if (rawPath && /No Project/i.test(msg)) {
155404
155919
  await openFileBestEffort(lspService, filePath);
155405
- await new Promise((resolve153) => setTimeout(resolve153, 120));
155920
+ await new Promise((resolve154) => setTimeout(resolve154, 120));
155406
155921
  const retryRaw = await lspService.workspaceSymbol(query ?? "", filePath);
155407
155922
  const retrySymbols = (Array.isArray(retryRaw) ? retryRaw : [retryRaw]).filter((s) => typeof s === "object" && s !== null);
155408
155923
  return dedupeWorkspaceSymbols(retrySymbols);
@@ -155929,7 +156444,6 @@ function createReadEnclosingTool(getProjectRoot, recordSymbolRead) {
155929
156444
  const range2 = details?.startLine && details?.endLine ? `:${details.startLine}-${details.endLine}` : "";
155930
156445
  return `read_enclosing ${details?.kind ?? ""} ${details?.name ?? ""} ${base}${range2}`.replace(/\s+/g, " ");
155931
156446
  }),
155932
- constrainedSampling: CONSTRAINED_JSON_SCHEMA_SAMPLING,
155933
156447
  parameters: Type.Object({
155934
156448
  path: Type.String({
155935
156449
  description: "Absolute or workspace-relative path to the source file."
@@ -157829,7 +158343,7 @@ init_env_utils();
157829
158343
  init_package_root();
157830
158344
  init_path_utils();
157831
158345
  init_git_identity();
157832
- import * as fs148 from "node:fs";
158346
+ import * as fs149 from "node:fs";
157833
158347
  import * as path236 from "node:path";
157834
158348
  import { fileURLToPath as fileURLToPath10 } from "node:url";
157835
158349
  function resolveOwnedCommit(root) {
@@ -157843,7 +158357,7 @@ function resolveOwnedCommit(root) {
157843
158357
  }
157844
158358
  function readPackageVersion(root) {
157845
158359
  try {
157846
- const raw = fs148.readFileSync(path236.join(root, "package.json"), "utf-8");
158360
+ const raw = fs149.readFileSync(path236.join(root, "package.json"), "utf-8");
157847
158361
  const pkg = JSON.parse(raw);
157848
158362
  return pkg.version ?? "unknown";
157849
158363
  } catch {
@@ -157852,7 +158366,7 @@ function readPackageVersion(root) {
157852
158366
  }
157853
158367
  function statEntryMtime(entryImportMetaUrl) {
157854
158368
  try {
157855
- return fs148.statSync(fileURLToPath10(entryImportMetaUrl)).mtime.toISOString();
158369
+ return fs149.statSync(fileURLToPath10(entryImportMetaUrl)).mtime.toISOString();
157856
158370
  } catch {
157857
158371
  return "unknown";
157858
158372
  }
@@ -158266,7 +158780,9 @@ function cleanStaleTsBuildInfo(cwd) {
158266
158780
  }
158267
158781
  function activateExtension(hostPi) {
158268
158782
  const pi = withConsoleCaptureWindows(hostPi);
158269
- setHostFileMutationQueueLoader(() => import("@earendil-works/pi-coding-agent"));
158783
+ const loadHostSdk2 = () => import("@earendil-works/pi-coding-agent");
158784
+ setHostProjectTrustLoader(loadHostSdk2);
158785
+ setHostFileMutationQueueLoader(loadHostSdk2);
158270
158786
  const testRunnerDeliveryOwnerId = `activation-${++_nextTestRunnerDeliveryOwnerId}`;
158271
158787
  let ownEventCtx;
158272
158788
  let ownedSessionRole;