pi-lens 4.4.3 → 4.4.5

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 (185) hide show
  1. package/CHANGELOG.md +721 -0
  2. package/README.md +25 -3
  3. package/config/dependency-cruiser-eager-allowlist.json +1 -0
  4. package/dist/chunk-22Y2BM7H.js +23 -0
  5. package/dist/{chunk-WU567RSC.js → chunk-27VWVB23.js} +16 -14
  6. package/dist/{chunk-FLKWCIZH.js → chunk-2FYKETQJ.js} +10 -6
  7. package/dist/{chunk-MQLUAEOC.js → chunk-2LDMXL2M.js} +2 -2
  8. package/dist/{chunk-YSZNHOBY.js → chunk-2SDHYHHO.js} +17 -17
  9. package/dist/chunk-2Y6OJRSI.js +38 -0
  10. package/dist/chunk-3SNDVPOR.js +507 -0
  11. package/dist/{chunk-EJIUXPBX.js → chunk-3WCEHYOI.js} +1 -1
  12. package/dist/chunk-44X7VIKR.js +73 -0
  13. package/dist/{chunk-Q7DUK4LX.js → chunk-4FHUGDKU.js} +16 -14
  14. package/dist/{chunk-H6MF6EVN.js → chunk-4ODSZ35Z.js} +1498 -534
  15. package/dist/{chunk-ZGDGW2V3.js → chunk-4U7GDSZQ.js} +2 -2
  16. package/dist/chunk-54NIOJJZ.js +25 -0
  17. package/dist/{chunk-ZWFS3OEF.js → chunk-5DKE4HGX.js} +38 -37
  18. package/dist/{chunk-VRZP76YM.js → chunk-5LRUKYFA.js} +34 -4
  19. package/dist/{chunk-QOBUHWHX.js → chunk-63NMUNYP.js} +12 -16
  20. package/dist/{chunk-VWCXW2E7.js → chunk-6XSESGWD.js} +13 -6
  21. package/dist/{chunk-QGQ5CCCG.js → chunk-72J27ICO.js} +2 -3
  22. package/dist/{chunk-CSHFH5IN.js → chunk-7FLRUH6B.js} +1 -1
  23. package/dist/chunk-7IYC4ENJ.js +297 -0
  24. package/dist/chunk-7WWQAW5P.js +30 -0
  25. package/dist/{chunk-EU63SDCG.js → chunk-7ZS7MC24.js} +885 -451
  26. package/dist/{chunk-KBG47GHP.js → chunk-AHWA4AKM.js} +18 -12
  27. package/dist/{chunk-FMSO6RDZ.js → chunk-AI3GP74G.js} +17 -19
  28. package/dist/chunk-APFJKOP6.js +67 -0
  29. package/dist/{chunk-RXCOMYPY.js → chunk-ASRAO7KG.js} +31 -33
  30. package/dist/{chunk-BW5KFIQC.js → chunk-AWQWXSW4.js} +1 -0
  31. package/dist/{chunk-QILIYSJF.js → chunk-CG5V25HX.js} +1 -1
  32. package/dist/chunk-CKEQFGLT.js +32 -0
  33. package/dist/{chunk-RPLINGVB.js → chunk-COOUUC5W.js} +6 -6
  34. package/dist/{chunk-GBPP5P7X.js → chunk-CPZ5JJW6.js} +4 -4
  35. package/dist/{chunk-OCAGUNBC.js → chunk-DS2USX5G.js} +13 -15
  36. package/dist/chunk-EA2ZRG44.js +27 -0
  37. package/dist/{chunk-ZHFZWTZV.js → chunk-EDMLIW6W.js} +13 -14
  38. package/dist/{chunk-2EECBNC5.js → chunk-EIKRZ32J.js} +75 -0
  39. package/dist/chunk-EKNWOL2I.js +27 -0
  40. package/dist/{chunk-CMMHNUZ2.js → chunk-ELZRSR5N.js} +65 -43
  41. package/dist/{chunk-BKE7E7TC.js → chunk-EN5AM7PX.js} +11 -12
  42. package/dist/{chunk-N2H3ZPZY.js → chunk-EWXXLS26.js} +227 -24
  43. package/dist/chunk-EX4EXBW7.js +37 -0
  44. package/dist/{chunk-YYOIQFRS.js → chunk-EXVXBSGN.js} +130 -52
  45. package/dist/{chunk-6GFRNVYR.js → chunk-F7BO6FWH.js} +12 -13
  46. package/dist/chunk-FEDWAYDS.js +2485 -0
  47. package/dist/{chunk-JAU72XNY.js → chunk-FWZRGGGY.js} +73 -9
  48. package/dist/{chunk-GXW6K4YJ.js → chunk-G224FADB.js} +1 -1
  49. package/dist/chunk-G5UCJFT7.js +26 -0
  50. package/dist/{chunk-67WMNWEE.js → chunk-GLW3YDZZ.js} +22 -13
  51. package/dist/{chunk-724UL2TJ.js → chunk-GTDSYEA2.js} +72 -39
  52. package/dist/{chunk-PHDMFAKM.js → chunk-GYRZ72R4.js} +10 -4
  53. package/dist/chunk-HYVXA3BB.js +49 -0
  54. package/dist/{chunk-SAEFPSB6.js → chunk-IEBJF3PN.js} +23 -15
  55. package/dist/chunk-IJYGIDF4.js +186 -0
  56. package/dist/{chunk-ACXEQZOU.js → chunk-IL7K66ZQ.js} +101 -109
  57. package/dist/{chunk-ZXYDQ3TZ.js → chunk-JWOVP5BL.js} +50 -19
  58. package/dist/{chunk-OXXKQCSV.js → chunk-K2GUZ4DN.js} +4 -4
  59. package/dist/{chunk-AW7R2GWG.js → chunk-K4SZB56V.js} +39 -39
  60. package/dist/{chunk-WOA4LN2R.js → chunk-KCBRHV5E.js} +3 -3
  61. package/dist/{chunk-3W7IEVVL.js → chunk-KFXCL4OV.js} +47 -45
  62. package/dist/{chunk-2BBLFX75.js → chunk-KJJAVH3X.js} +81 -15
  63. package/dist/{chunk-VCHXCQFG.js → chunk-KPVLQHCZ.js} +4 -6
  64. package/dist/{chunk-P7266HLM.js → chunk-KX56K73G.js} +10 -13
  65. package/dist/{chunk-VSSBEUFT.js → chunk-LMCTHJ2H.js} +19 -19
  66. package/dist/{chunk-IBGIOBEE.js → chunk-MEFLGBCS.js} +69 -8
  67. package/dist/{chunk-TYM6OUIT.js → chunk-MKPCELNI.js} +17 -17
  68. package/dist/{chunk-XTMJ7XDT.js → chunk-N3PLNNCW.js} +1 -1
  69. package/dist/chunk-N5FBM25N.js +22 -0
  70. package/dist/{chunk-CHOW74WE.js → chunk-NFNVDDGB.js} +7 -12
  71. package/dist/{chunk-52FUZI6K.js → chunk-NLIVE7L6.js} +2 -30
  72. package/dist/{chunk-SS36ZX4J.js → chunk-OMJ3OFBJ.js} +6 -6
  73. package/dist/{chunk-4W4VLAPJ.js → chunk-OZNCKLOX.js} +13 -14
  74. package/dist/chunk-P5XUGPIX.js +31 -0
  75. package/dist/{chunk-5UCAH366.js → chunk-PJXNTPB2.js} +253 -33
  76. package/dist/chunk-PKOXJIVT.js +88 -0
  77. package/dist/{chunk-6C7JWPCP.js → chunk-PP2A5V2T.js} +27 -26
  78. package/dist/{chunk-L3BLXZG7.js → chunk-Q42LJANT.js} +31 -70
  79. package/dist/{chunk-AB3YYG6N.js → chunk-Q4BKKOVC.js} +8 -8
  80. package/dist/{chunk-3EFKIGZN.js → chunk-QT66NEYN.js} +4 -4
  81. package/dist/{chunk-3VPVG5SU.js → chunk-RCHO5W7M.js} +19 -18
  82. package/dist/{chunk-77M37OKR.js → chunk-RG3MXTRI.js} +7 -7
  83. package/dist/chunk-RG7OODGM.js +57 -0
  84. package/dist/{chunk-T6CPIZNT.js → chunk-RU34BA4D.js} +44 -39
  85. package/dist/{chunk-JMYYOTQG.js → chunk-S26LC76R.js} +13 -1
  86. package/dist/{chunk-5NGR67U5.js → chunk-S55TEC7I.js} +33 -5
  87. package/dist/{chunk-M6HSLBWY.js → chunk-SJHC3BCZ.js} +7956 -8047
  88. package/dist/{chunk-XCJN5IJU.js → chunk-SNEUMLM7.js} +4 -4
  89. package/dist/{chunk-UZ3TUTRV.js → chunk-T4NGVFYI.js} +2 -2
  90. package/dist/{chunk-2VUQMUMT.js → chunk-THEXI2QO.js} +49 -43
  91. package/dist/{chunk-R3PCY3YS.js → chunk-TL2TCJYL.js} +15 -16
  92. package/dist/{chunk-C34ZXZ7O.js → chunk-TPYYEDP5.js} +838 -352
  93. package/dist/{chunk-AOHZU2BM.js → chunk-TVZRLTG6.js} +8 -1
  94. package/dist/{chunk-XMSXXAHW.js → chunk-UCVMSOXF.js} +2 -2
  95. package/dist/chunk-UL5SXQVX.js +32 -0
  96. package/dist/{chunk-GAEGEPOC.js → chunk-UO66IMVP.js} +2 -2
  97. package/dist/{chunk-N3X6Q4YT.js → chunk-UVY4TOJH.js} +3 -3
  98. package/dist/{chunk-2CD5RS6M.js → chunk-VIDEKABZ.js} +23 -2
  99. package/dist/{chunk-JSQFTSC6.js → chunk-VITFDI3O.js} +13 -14
  100. package/dist/{chunk-YIUAVF7E.js → chunk-VUAVE3QC.js} +42 -42
  101. package/dist/{chunk-QOZXJ4NA.js → chunk-WUY4BZEP.js} +21 -20
  102. package/dist/{chunk-VCO24T4L.js → chunk-X3UTCXAA.js} +43 -53
  103. package/dist/chunk-XHDBJODR.js +45 -0
  104. package/dist/{chunk-MXGY6KPT.js → chunk-XHLK33VM.js} +28 -21
  105. package/dist/{chunk-RWWYJ623.js → chunk-XI34NWDI.js} +2 -2
  106. package/dist/{chunk-QQNQ7SJW.js → chunk-XWFIHYCH.js} +12 -4
  107. package/dist/{chunk-6SDEP3AJ.js → chunk-Y2TPADJR.js} +10 -11
  108. package/dist/{chunk-MRXKYPCS.js → chunk-Y5KTA2OB.js} +17 -17
  109. package/dist/{chunk-7DYBLXYA.js → chunk-YKVDBNPO.js} +11 -5
  110. package/dist/{chunk-2B73ZPOK.js → chunk-YSDPVDFC.js} +3 -3
  111. package/dist/chunk-YWNO5Q4R.js +44 -0
  112. package/dist/{chunk-QHJ6DQ2R.js → chunk-YWWG4AQA.js} +165 -32
  113. package/dist/{chunk-3JNKMP3B.js → chunk-YXDCRUKQ.js} +4 -4
  114. package/dist/{chunk-UXGETRP4.js → chunk-YXGRRORB.js} +16 -17
  115. package/dist/{chunk-SQ4TVJBR.js → chunk-ZAPSUBLU.js} +13 -7
  116. package/dist/{chunk-76MWC2K6.js → chunk-ZPJM7DID.js} +90 -97
  117. package/dist/{chunk-XVF2VVXP.js → chunk-ZSUX7KEM.js} +16 -15
  118. package/dist/index.js +31038 -20893
  119. package/dist/mcp/analyze-cli.js +11 -11
  120. package/dist/mcp/cli.js +47 -43
  121. package/dist/mcp/server.js +2188 -906
  122. package/dist/mcp/worker.js +66 -63
  123. package/dist/probes/installer.js +21 -23
  124. package/dist/workers/project-snapshot-persist-worker.js +28 -9
  125. package/dist/workers/review-graph-persist-worker.js +1 -1
  126. package/docs/adr/0010-trace-validation-session-lifecycle.md +390 -0
  127. package/docs/adr/README.md +1 -0
  128. package/docs/ast-grep_rules_catalog.md +5 -3
  129. package/docs/configuration.md +20 -0
  130. package/docs/engineering-principles.md +44 -0
  131. package/docs/environment-variables.md +20 -0
  132. package/docs/features.md +16 -1
  133. package/docs/globalconfig.md +37 -8
  134. package/docs/lsp-capability-matrix.md +105 -12
  135. package/docs/lsp-idle-eviction.md +44 -36
  136. package/docs/pi-lens-fixer.md +139 -14
  137. package/docs/pi-lens-investigator.md +14 -0
  138. package/docs/pi-lens-merge-policy.md +120 -17
  139. package/docs/pi-lens-monitor.md +71 -9
  140. package/docs/pi-lens-retro.md +6 -3
  141. package/docs/pi-lens-reviewer.md +160 -5
  142. package/docs/pi-lens-subagent.md +29 -14
  143. package/docs/release-qa-baseline.md +21 -7
  144. package/docs/servercapabilities.md +53 -63
  145. package/docs/settings.md +9 -5
  146. package/docs/subagent-compat.md +1 -1
  147. package/docs/usage.md +1 -0
  148. package/package.json +9 -5
  149. package/rules/ast-grep-rules/rule-tests/no-return-value-in-generator-test.yml +17 -0
  150. package/rules/ast-grep-rules/rule-tests/no-sql-in-code-execute-js-test.yml +86 -0
  151. package/rules/ast-grep-rules/rule-tests/no-sql-in-code-execute-test.yml +86 -0
  152. package/rules/ast-grep-rules/rule-tests/unchecked-numeric-parse-python-test.yml +15 -0
  153. package/rules/ast-grep-rules/rules/no-return-value-in-generator.yml +9 -4
  154. package/rules/ast-grep-rules/rules/no-sql-in-code-execute-js.yml +119 -0
  155. package/rules/ast-grep-rules/rules/no-sql-in-code-execute.yml +119 -0
  156. package/rules/ast-grep-rules/rules/unchecked-numeric-parse-python.yml +13 -2
  157. package/rules/rule-catalog.json +25 -1
  158. package/scripts/analyze-pi-lens-logs.mjs +15 -5
  159. package/scripts/download-grammars.js +40 -7
  160. package/scripts/lib/is-main-module.mjs +27 -0
  161. package/scripts/lib/latency-log-phases.mjs +95 -0
  162. package/scripts/lib/scratch-home-env.mjs +21 -0
  163. package/scripts/rpc-load-check.mjs +568 -81
  164. package/scripts/warm-loader-cache.mjs +2 -5
  165. package/dist/chunk-23WOO7TX.js +0 -23
  166. package/dist/chunk-3YN6V5TV.js +0 -85
  167. package/dist/chunk-466Z26MG.js +0 -30
  168. package/dist/chunk-4UNXBNE2.js +0 -24
  169. package/dist/chunk-6STA6Z7I.js +0 -47
  170. package/dist/chunk-ABBOA7UD.js +0 -157
  171. package/dist/chunk-BRGDSBJE.js +0 -28
  172. package/dist/chunk-EC47DWFA.js +0 -56
  173. package/dist/chunk-FCSOVF55.js +0 -273
  174. package/dist/chunk-IZSHAIJ7.js +0 -26
  175. package/dist/chunk-KDERNTCQ.js +0 -28
  176. package/dist/chunk-KSX3TXSZ.js +0 -69
  177. package/dist/chunk-LOP6GRPH.js +0 -31
  178. package/dist/chunk-PNQDPDRC.js +0 -184
  179. package/dist/chunk-UOPVJQ4N.js +0 -103
  180. package/dist/chunk-XAGLWMJ4.js +0 -51
  181. package/dist/chunk-XIJZVPD5.js +0 -39
  182. package/dist/chunk-Z3CCVDUB.js +0 -76
  183. package/dist/chunk-Z527N6YQ.js +0 -28
  184. package/dist/chunk-ZANLILYD.js +0 -79
  185. /package/dist/{chunk-FC4RP4I2.js → chunk-6HWVI6MI.js} +0 -0
@@ -1,5 +1,6 @@
1
1
  import { createRequire as __pilensCreateRequire } from "node:module"; const require = __pilensCreateRequire(import.meta.url);
2
2
  import {
3
+ PathKeyedMap,
3
4
  detectFileRole,
4
5
  findNestedProjectMutationValue,
5
6
  findPiLensConfigInDir,
@@ -12,7 +13,7 @@ import {
12
13
  reportPiLensConfigRecords,
13
14
  resolveOnePiLensConfigDocument,
14
15
  warnIgnoredConfigOnce
15
- } from "./chunk-2BBLFX75.js";
16
+ } from "./chunk-KJJAVH3X.js";
16
17
  import {
17
18
  CANONICAL_GLOBAL_CONFIG_FILE,
18
19
  FRESHNESS_CADENCE_MS,
@@ -22,16 +23,19 @@ import {
22
23
  errorClassName,
23
24
  getPiLensGlobalConfigPath,
24
25
  getProductionGlobalConfigResolution
25
- } from "./chunk-XVF2VVXP.js";
26
+ } from "./chunk-ZSUX7KEM.js";
26
27
  import {
27
28
  DEFAULT_MAX_OUTPUT_BYTES,
28
29
  createBoundedOutputSink,
30
+ getProjectTrustState,
29
31
  truncatedByOutputCap,
32
+ writeFileAtomic,
30
33
  writeFileAtomicAsync
31
- } from "./chunk-2EECBNC5.js";
34
+ } from "./chunk-EIKRZ32J.js";
32
35
  import {
33
36
  GLOBAL_NON_FLAG_CONFIG_SECTIONS,
34
37
  LENS_FLAGS,
38
+ PROJECT_NON_FLAG_CONFIG_SECTIONS,
35
39
  assignFlagConfigSection,
36
40
  compareOrdinal,
37
41
  flagConfigSectionKeys,
@@ -39,39 +43,47 @@ import {
39
43
  getLensFlagSpec,
40
44
  incrementDegradationCount,
41
45
  readFlagConfigValue,
46
+ readLazyToolsSetting,
42
47
  readToolConfig,
43
48
  recordDegradation,
44
49
  recordDegradationOnce
45
- } from "./chunk-JAU72XNY.js";
50
+ } from "./chunk-FWZRGGGY.js";
46
51
  import {
47
52
  logExtension
48
- } from "./chunk-XTMJ7XDT.js";
53
+ } from "./chunk-N3PLNNCW.js";
49
54
  import {
50
55
  logLatency
51
- } from "./chunk-QQNQ7SJW.js";
56
+ } from "./chunk-XWFIHYCH.js";
52
57
  import {
53
- getProcessSingleton
54
- } from "./chunk-AOHZU2BM.js";
58
+ getProcessSingleton,
59
+ machineStateDir
60
+ } from "./chunk-TVZRLTG6.js";
55
61
  import {
62
+ STAGE_TMP_PATTERN,
63
+ stagePathFor,
56
64
  sweepOwnStagingFiles
57
65
  } from "./chunk-LJDODBBZ.js";
58
66
  import {
59
67
  BoundedFifoMap,
60
- BoundedSet
61
- } from "./chunk-ABBOA7UD.js";
62
- import {
68
+ BoundedSet,
63
69
  Minimatch,
64
70
  homeRelativePath,
71
+ isAtOrAboveHomeDir,
65
72
  isExternalOrVendorFile,
66
73
  isFullyQualifiedWin32,
67
74
  isRealGitMarker,
68
75
  isUnderDir,
76
+ isWithinForm,
69
77
  normalizeEphemeralMapKey,
70
78
  normalizeFilePath,
71
79
  normalizeLoggedPath,
72
80
  normalizeMapKey,
73
- toProjectRelativePath
74
- } from "./chunk-N2H3ZPZY.js";
81
+ normalizePathSpelling,
82
+ pathsEqual,
83
+ realpathOrResolve,
84
+ toProjectRelativePath,
85
+ walkUpDirs
86
+ } from "./chunk-EWXXLS26.js";
75
87
  import {
76
88
  __commonJS,
77
89
  __require,
@@ -205,10 +217,10 @@ var require_history = __commonJS({
205
217
  var require_ps = __commonJS({
206
218
  "node_modules/pidusage/lib/ps.js"(exports, module) {
207
219
  "use strict";
208
- var os3 = __require("os");
220
+ var os4 = __require("os");
209
221
  var bin = require_bin();
210
222
  var history = require_history();
211
- var PLATFORM = os3.platform();
223
+ var PLATFORM = os4.platform();
212
224
  function parseTime(timestr, centisec) {
213
225
  let time = 0;
214
226
  const tpart = timestr.split(/-|:|\./);
@@ -253,7 +265,7 @@ var require_ps = __commonJS({
253
265
  return done(new Error("pidusage ps command exited with code " + code));
254
266
  }
255
267
  const date = Date.now();
256
- stdout = stdout.split(os3.EOL);
268
+ stdout = stdout.split(os4.EOL);
257
269
  const statistics = {};
258
270
  for (let i = 1; i < stdout.length; i++) {
259
271
  const line = stdout[i].trim().split(/\s+/);
@@ -334,8 +346,8 @@ var require_parallel = __commonJS({
334
346
  // node_modules/pidusage/lib/helpers/cpu.js
335
347
  var require_cpu = __commonJS({
336
348
  "node_modules/pidusage/lib/helpers/cpu.js"(exports, module) {
337
- var os3 = __require("os");
338
- var fs9 = __require("fs");
349
+ var os4 = __require("os");
350
+ var fs10 = __require("fs");
339
351
  var exec = __require("child_process").exec;
340
352
  var parallel = require_parallel();
341
353
  function updateCpu(cpu, next) {
@@ -362,12 +374,12 @@ var require_cpu = __commonJS({
362
374
  }
363
375
  module.exports = updateCpu;
364
376
  function getRealUptime(next) {
365
- fs9.readFile("/proc/uptime", "utf8", function(err, uptime) {
377
+ fs10.readFile("/proc/uptime", "utf8", function(err, uptime) {
366
378
  if (err || uptime === void 0) {
367
379
  if (!process.env.PIDUSAGE_SILENT) {
368
380
  console.warn("[pidusage] We couldn't find uptime from /proc/uptime, using os.uptime() value");
369
381
  }
370
- return next(null, os3.uptime() || /* @__PURE__ */ new Date() / 1e3);
382
+ return next(null, os4.uptime() || /* @__PURE__ */ new Date() / 1e3);
371
383
  }
372
384
  return next(null, parseFloat(uptime.split(" ")[0]));
373
385
  });
@@ -407,101 +419,42 @@ var require_cpu = __commonJS({
407
419
  }
408
420
  });
409
421
 
410
- // node_modules/safe-buffer/index.js
411
- var require_safe_buffer = __commonJS({
412
- "node_modules/safe-buffer/index.js"(exports, module) {
413
- var buffer = __require("buffer");
414
- var Buffer2 = buffer.Buffer;
415
- function copyProps(src, dst) {
416
- for (var key in src) {
417
- dst[key] = src[key];
418
- }
419
- }
420
- if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) {
421
- module.exports = buffer;
422
- } else {
423
- copyProps(buffer, exports);
424
- exports.Buffer = SafeBuffer;
425
- }
426
- function SafeBuffer(arg, encodingOrOffset, length) {
427
- return Buffer2(arg, encodingOrOffset, length);
428
- }
429
- SafeBuffer.prototype = Object.create(Buffer2.prototype);
430
- copyProps(Buffer2, SafeBuffer);
431
- SafeBuffer.from = function(arg, encodingOrOffset, length) {
432
- if (typeof arg === "number") {
433
- throw new TypeError("Argument must not be a number");
434
- }
435
- return Buffer2(arg, encodingOrOffset, length);
436
- };
437
- SafeBuffer.alloc = function(size, fill, encoding) {
438
- if (typeof size !== "number") {
439
- throw new TypeError("Argument must be a number");
440
- }
441
- var buf = Buffer2(size);
442
- if (fill !== void 0) {
443
- if (typeof encoding === "string") {
444
- buf.fill(fill, encoding);
445
- } else {
446
- buf.fill(fill);
447
- }
448
- } else {
449
- buf.fill(0);
450
- }
451
- return buf;
452
- };
453
- SafeBuffer.allocUnsafe = function(size) {
454
- if (typeof size !== "number") {
455
- throw new TypeError("Argument must be a number");
456
- }
457
- return Buffer2(size);
458
- };
459
- SafeBuffer.allocUnsafeSlow = function(size) {
460
- if (typeof size !== "number") {
461
- throw new TypeError("Argument must be a number");
462
- }
463
- return buffer.SlowBuffer(size);
464
- };
465
- }
466
- });
467
-
468
422
  // node_modules/pidusage/lib/procfile.js
469
423
  var require_procfile = __commonJS({
470
424
  "node_modules/pidusage/lib/procfile.js"(exports, module) {
471
- var fs9 = __require("fs");
472
- var path12 = __require("path");
425
+ var fs10 = __require("fs");
426
+ var path13 = __require("path");
473
427
  var updateCpu = require_cpu();
474
428
  var parallel = require_parallel();
475
429
  var history = require_history();
476
430
  var cpuInfo = null;
477
- var Buffer2 = require_safe_buffer().Buffer;
478
431
  var SIZE = 1024;
479
432
  function noop() {
480
433
  }
481
- function open(path13, history2, cb) {
434
+ function open(path14, history2, cb) {
482
435
  if (history2.fd) {
483
436
  return cb(null, history2.fd);
484
437
  }
485
- fs9.open(path13, "r", cb);
438
+ fs10.open(path14, "r", cb);
486
439
  }
487
440
  function close(history2) {
488
441
  if (history2.fd) {
489
- fs9.close(history2.fd, noop);
442
+ fs10.close(history2.fd, noop);
490
443
  }
491
444
  }
492
445
  function readUntilEnd(fd, buf, cb) {
493
446
  let firstRead = false;
494
447
  if (typeof buf === "function") {
495
448
  cb = buf;
496
- buf = Buffer2.alloc(SIZE);
449
+ buf = Buffer.alloc(SIZE);
497
450
  firstRead = true;
498
451
  }
499
- fs9.read(fd, buf, 0, SIZE, 0, function(err, bytesRead, buffer) {
452
+ fs10.read(fd, buf, 0, SIZE, 0, function(err, bytesRead, buffer) {
500
453
  if (err) {
501
454
  cb(err);
502
455
  return;
503
456
  }
504
- const data = Buffer2.concat([buf, buffer], firstRead ? bytesRead : buf.length + bytesRead);
457
+ const data = Buffer.concat([buf, buffer], firstRead ? bytesRead : buf.length + bytesRead);
505
458
  if (bytesRead === SIZE) {
506
459
  readUntilEnd(fd, data, cb);
507
460
  return;
@@ -516,7 +469,7 @@ var require_procfile = __commonJS({
516
469
  again = true;
517
470
  hst = {};
518
471
  }
519
- open(path12.join("/proc", "" + pid, "stat"), hst, function(err, fd) {
472
+ open(path13.join("/proc", "" + pid, "stat"), hst, function(err, fd) {
520
473
  if (err) {
521
474
  if (err.code === "ENOENT") {
522
475
  err.message = "No matching pid found";
@@ -587,7 +540,7 @@ var require_procfile = __commonJS({
587
540
  var require_wmic = __commonJS({
588
541
  "node_modules/pidusage/lib/wmic.js"(exports, module) {
589
542
  "use strict";
590
- var os3 = __require("os");
543
+ var os4 = __require("os");
591
544
  var bin = require_bin();
592
545
  var history = require_history();
593
546
  function parseDate(datestr) {
@@ -631,8 +584,8 @@ var require_wmic = __commonJS({
631
584
  return done(new Error("pidusage wmic command exited with code " + code));
632
585
  }
633
586
  const date = Date.now();
634
- const uptime = Math.floor(os3.uptime() || date / 1e3);
635
- stdout = stdout.split(os3.EOL);
587
+ const uptime = Math.floor(os4.uptime() || date / 1e3);
588
+ stdout = stdout.split(os4.EOL);
636
589
  let again = false;
637
590
  const statistics = {};
638
591
  for (let i = 1; i < stdout.length; i++) {
@@ -682,7 +635,7 @@ var require_wmic = __commonJS({
682
635
  var require_gwmi = __commonJS({
683
636
  "node_modules/pidusage/lib/gwmi.js"(exports, module) {
684
637
  "use strict";
685
- var os3 = __require("os");
638
+ var os4 = __require("os");
686
639
  var bin = require_bin();
687
640
  var history = require_history();
688
641
  function parseDate(datestr) {
@@ -707,8 +660,8 @@ var require_gwmi = __commonJS({
707
660
  whereClause += " or ProcessId=" + pids[i];
708
661
  }
709
662
  const property = "CreationDate,KernelModeTime,ParentProcessId,ProcessId,UserModeTime,WorkingSetSize";
710
- const args = ["win32_process", "-Filter", "'" + whereClause + "'", "| select " + property, "| format-table"];
711
- bin("gwmi", args, { windowsHide: true, windowsVerbatimArguments: true, shell: "powershell.exe" }, function(err, stdout, code) {
663
+ const command = "gwmi win32_process -Filter '" + whereClause + "' | select " + property + " | format-table";
664
+ bin("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], { windowsHide: true }, function(err, stdout, code) {
712
665
  if (err) {
713
666
  if (err.message.indexOf("No Instance(s) Available.") !== -1) {
714
667
  const error = new Error("No matching pid found");
@@ -721,8 +674,8 @@ var require_gwmi = __commonJS({
721
674
  return done(new Error("pidusage gwmi command exited with code " + code));
722
675
  }
723
676
  const date = Date.now();
724
- const uptime = Math.floor(os3.uptime() || date / 1e3);
725
- stdout = stdout.split(os3.EOL).slice(1);
677
+ const uptime = Math.floor(os4.uptime() || date / 1e3);
678
+ stdout = stdout.split(os4.EOL).slice(1);
726
679
  const index = stdout.findIndex((v) => !!v);
727
680
  stdout = stdout.slice(index + 2);
728
681
  if (!stdout.length) {
@@ -779,9 +732,9 @@ var require_gwmi = __commonJS({
779
732
  var require_stats = __commonJS({
780
733
  "node_modules/pidusage/lib/stats.js"(exports, module) {
781
734
  "use strict";
782
- var fs9 = __require("fs");
783
- var os3 = __require("os");
784
- var spawn2 = __require("child_process").spawn;
735
+ var fs10 = __require("fs");
736
+ var os4 = __require("os");
737
+ var path13 = __require("path");
785
738
  var requireMap = {
786
739
  ps: () => require_ps(),
787
740
  procfile: () => require_procfile(),
@@ -802,8 +755,8 @@ var require_stats = __commonJS({
802
755
  sunos: "ps",
803
756
  win: "wmic"
804
757
  };
805
- var platform = os3.platform();
806
- if (fs9.existsSync("/etc/alpine-release")) {
758
+ var platform = os4.platform();
759
+ if (fs10.existsSync("/etc/alpine-release")) {
807
760
  platform = "alpine";
808
761
  }
809
762
  if (platform.match(/^win/)) {
@@ -814,27 +767,23 @@ var require_stats = __commonJS({
814
767
  stat = requireMap[platformToMethod[platform]]();
815
768
  } catch (err) {
816
769
  }
770
+ var wmicAvailable;
771
+ function hasWmic() {
772
+ if (wmicAvailable === void 0) {
773
+ wmicAvailable = fs10.existsSync(path13.join(process.env.SystemRoot || "C:\\Windows", "System32", "wbem", "WMIC.exe"));
774
+ }
775
+ return wmicAvailable;
776
+ }
817
777
  function get(pids, options, callback) {
818
778
  let fn = stat;
819
779
  if (platform !== "win" && options.usePs === true) {
820
780
  fn = requireMap.ps();
821
781
  }
822
782
  if (platform === "win") {
823
- let child;
824
- try {
825
- child = spawn2("wmic", function(err) {
826
- if (err) throw new Error(err);
827
- });
828
- } catch (err) {
829
- fn = requireMap.gwmi();
830
- } finally {
831
- if (child) {
832
- child.kill();
833
- }
834
- }
783
+ fn = options.useGwmi === true || !hasWmic() ? requireMap.gwmi() : requireMap.wmic();
835
784
  }
836
785
  if (fn === void 0) {
837
- return callback(new Error(os3.platform() + " is not supported yet, please open an issue (https://github.com/soyuka/pidusage)"));
786
+ return callback(new Error(os4.platform() + " is not supported yet, please open an issue (https://github.com/soyuka/pidusage)"));
838
787
  }
839
788
  let single = false;
840
789
  if (!Array.isArray(pids)) {
@@ -886,10 +835,10 @@ var require_pidusage = __commonJS({
886
835
  stats(pids, options, callback);
887
836
  return;
888
837
  }
889
- return new Promise(function(resolve6, reject) {
838
+ return new Promise(function(resolve7, reject) {
890
839
  stats(pids, options, function(err, data) {
891
840
  if (err) return reject(err);
892
- resolve6(data);
841
+ resolve7(data);
893
842
  });
894
843
  });
895
844
  }
@@ -899,9 +848,293 @@ var require_pidusage = __commonJS({
899
848
  });
900
849
 
901
850
  // dist/clients/safe-spawn.js
851
+ import { AsyncLocalStorage } from "node:async_hooks";
902
852
  import { spawn, spawnSync } from "node:child_process";
903
- import * as fs8 from "node:fs";
904
- import * as path11 from "node:path";
853
+ import * as fs9 from "node:fs";
854
+ import * as path12 from "node:path";
855
+
856
+ // dist/clients/session-repository.js
857
+ import * as fs2 from "node:fs";
858
+ import * as os from "node:os";
859
+ import * as path2 from "node:path";
860
+
861
+ // dist/clients/review-graph/git-identity.js
862
+ import * as fs from "node:fs";
863
+ import * as path from "node:path";
864
+ import { dirname, join as join2, resolve as resolve2 } from "node:path";
865
+ function createGitIdentityResolver() {
866
+ const memo = /* @__PURE__ */ new Map();
867
+ return (cwd) => {
868
+ if (memo.has(cwd))
869
+ return memo.get(cwd);
870
+ const identity = resolveGitIdentity(cwd);
871
+ memo.set(cwd, identity);
872
+ return identity;
873
+ };
874
+ }
875
+ function readCommonDir(gitDir) {
876
+ try {
877
+ const raw = fs.readFileSync(path.join(gitDir, "commondir"), "utf-8").trim();
878
+ if (!raw)
879
+ return gitDir;
880
+ return path.isAbsolute(raw) ? raw : path.resolve(gitDir, raw);
881
+ } catch {
882
+ return gitDir;
883
+ }
884
+ }
885
+ function resolveGitDir(cwd) {
886
+ for (const dir of walkUpDirs(cwd, { spelling: true })) {
887
+ const gitPath = path.join(dir, ".git");
888
+ let stat;
889
+ try {
890
+ stat = fs.statSync(gitPath);
891
+ } catch {
892
+ continue;
893
+ }
894
+ if (stat.isDirectory()) {
895
+ if (!fs.statSync(path.join(gitPath, "HEAD"), { throwIfNoEntry: false }))
896
+ continue;
897
+ return {
898
+ gitDir: gitPath,
899
+ commonDir: readCommonDir(gitPath),
900
+ worktreeRoot: dir
901
+ };
902
+ }
903
+ if (stat.isFile()) {
904
+ try {
905
+ const contents = fs.readFileSync(gitPath, "utf-8").trim();
906
+ const match = contents.match(/^gitdir:\s*(.+)$/);
907
+ if (!match)
908
+ return null;
909
+ const linkedGitDir = path.isAbsolute(match[1]) ? match[1] : path.resolve(dir, match[1]);
910
+ if (!fs.statSync(linkedGitDir).isDirectory())
911
+ return null;
912
+ return {
913
+ gitDir: linkedGitDir,
914
+ commonDir: readCommonDir(linkedGitDir),
915
+ worktreeRoot: dir
916
+ };
917
+ } catch {
918
+ return null;
919
+ }
920
+ }
921
+ return null;
922
+ }
923
+ return null;
924
+ }
925
+ function getResolvedGitDir(cwd) {
926
+ let resolved;
927
+ try {
928
+ resolved = resolveGitDir(cwd);
929
+ } catch {
930
+ resolved = null;
931
+ }
932
+ return resolved;
933
+ }
934
+ function canonicalDirectory(dir) {
935
+ try {
936
+ return fs.realpathSync.native(dir);
937
+ } catch {
938
+ return dir;
939
+ }
940
+ }
941
+ function resolveGitCheckout(startPath) {
942
+ const resolved = getResolvedGitDir(startPath);
943
+ return resolved ? {
944
+ root: canonicalDirectory(resolved.worktreeRoot),
945
+ spelledRoot: resolved.worktreeRoot,
946
+ commonDir: canonicalDirectory(resolved.commonDir)
947
+ } : null;
948
+ }
949
+ function sameCheckoutOtherRoot(session, other) {
950
+ return other !== null && !pathsEqual(other.root, session.root) && pathsEqual(other.commonDir, session.commonDir);
951
+ }
952
+ function resolveLinkedWorktreeOwner(session, absoluteFile) {
953
+ const owner = resolveGitCheckout(dirname(absoluteFile));
954
+ return sameCheckoutOtherRoot(session, owner) ? owner : null;
955
+ }
956
+ function listLinkedWorktreeRoots(commonDir) {
957
+ const roots = [];
958
+ let names;
959
+ try {
960
+ names = fs.readdirSync(join2(commonDir, "worktrees"));
961
+ } catch {
962
+ return roots;
963
+ }
964
+ for (const name of names) {
965
+ try {
966
+ const entryDir = join2(commonDir, "worktrees", name);
967
+ const gitFile = fs.readFileSync(join2(entryDir, "gitdir"), "utf-8").trim();
968
+ if (gitFile) {
969
+ const root = canonicalDirectory(dirname(resolve2(entryDir, gitFile)));
970
+ if (fs.existsSync(join2(root, ".git")))
971
+ roots.push(root);
972
+ }
973
+ } catch {
974
+ }
975
+ }
976
+ return roots;
977
+ }
978
+ function listNestedLinkedWorktreeRoots(scanRoot) {
979
+ const checkout = resolveGitCheckout(scanRoot);
980
+ if (!checkout)
981
+ return [];
982
+ const base = canonicalDirectory(scanRoot);
983
+ const nested = [];
984
+ for (const root of listLinkedWorktreeRoots(checkout.commonDir)) {
985
+ if (!pathsEqual(root, base) && isUnderDir(root, base))
986
+ nested.push(root);
987
+ }
988
+ return nested;
989
+ }
990
+ function resolveRefToSha(commonDir, ref) {
991
+ try {
992
+ const loose = fs.readFileSync(path.join(commonDir, ref), "utf-8").trim();
993
+ if (loose)
994
+ return loose;
995
+ } catch {
996
+ }
997
+ try {
998
+ const packed = fs.readFileSync(path.join(commonDir, "packed-refs"), "utf-8");
999
+ for (const line of packed.split("\n")) {
1000
+ if (line.startsWith("#") || line.startsWith("^") || !line.trim())
1001
+ continue;
1002
+ const [sha, packedRef] = line.trim().split(/\s+/, 2);
1003
+ if (packedRef === ref)
1004
+ return sha;
1005
+ }
1006
+ } catch {
1007
+ }
1008
+ return null;
1009
+ }
1010
+ function resolveGitIdentity(cwd) {
1011
+ try {
1012
+ const resolved = getResolvedGitDir(cwd);
1013
+ if (!resolved)
1014
+ return void 0;
1015
+ const headRaw = fs.readFileSync(path.join(resolved.gitDir, "HEAD"), "utf-8").trim();
1016
+ const refMatch = headRaw.match(/^ref:\s*(.+)$/);
1017
+ let headCommit;
1018
+ if (refMatch) {
1019
+ headCommit = resolveRefToSha(resolved.commonDir, refMatch[1].trim());
1020
+ } else {
1021
+ headCommit = /^[0-9a-f]{7,40}$/i.test(headRaw) ? headRaw : null;
1022
+ }
1023
+ if (!headCommit)
1024
+ return void 0;
1025
+ return {
1026
+ headCommit,
1027
+ worktreeRoot: normalizeFilePath(resolved.worktreeRoot)
1028
+ };
1029
+ } catch {
1030
+ return void 0;
1031
+ }
1032
+ }
1033
+
1034
+ // dist/clients/session-repository.js
1035
+ var NODE_MODULES_BIN_DIRS = [
1036
+ path2.join("node_modules", ".bin")
1037
+ ];
1038
+ var VENDOR_BIN_DIRS = [path2.join("vendor", "bin")];
1039
+ var VENV_BIN_DIRS = [
1040
+ path2.join(".venv", "bin"),
1041
+ path2.join("venv", "bin"),
1042
+ path2.join(".venv", "Scripts"),
1043
+ path2.join("venv", "Scripts")
1044
+ ];
1045
+ var PROJECT_LOCAL_BIN_DIRS = [
1046
+ ...NODE_MODULES_BIN_DIRS,
1047
+ ...VENDOR_BIN_DIRS,
1048
+ ...VENV_BIN_DIRS
1049
+ ];
1050
+ function* projectLocalBinDirs(dir, home = os.homedir()) {
1051
+ for (const ancestor of walkUpDirs(dir, { spelling: true, homeDir: home })) {
1052
+ for (const binDir of PROJECT_LOCAL_BIN_DIRS)
1053
+ yield path2.join(ancestor, binDir);
1054
+ }
1055
+ }
1056
+ function sessionRepositoryJudge() {
1057
+ const home = realpathOrResolve(os.homedir());
1058
+ const session = realpathOrResolve(process.cwd());
1059
+ if (isAtOrAboveHomeDir(session, home))
1060
+ return () => false;
1061
+ const sessionForm = pathForm(session);
1062
+ const dataDirForm = pathForm(realpathOrResolve(machineStateDir()));
1063
+ const binDirForms = [...projectLocalBinDirs(session, home)].filter((dir) => fs2.existsSync(dir)).map((dir) => pathForm(realpathOrResolve(dir)));
1064
+ let sessionCheckout;
1065
+ const ownerByDir = new PathKeyedMap(pathForm);
1066
+ return (target) => {
1067
+ const real = realpathOrResolve(target);
1068
+ const form = pathForm(real);
1069
+ if (isWithinForm(form, dataDirForm))
1070
+ return false;
1071
+ if (isWithinForm(form, sessionForm))
1072
+ return true;
1073
+ if (binDirForms.some((binDir) => isWithinForm(form, binDir)))
1074
+ return true;
1075
+ sessionCheckout ??= resolveGitCheckout(session);
1076
+ if (!sessionCheckout || isAtOrAboveHomeDir(sessionCheckout.root, home))
1077
+ return false;
1078
+ return ownerCommonDirForm(real) === pathForm(sessionCheckout.commonDir);
1079
+ };
1080
+ function ownerCommonDirForm(real) {
1081
+ const walked = [];
1082
+ let answer = null;
1083
+ for (const dir of walkUpDirs(real)) {
1084
+ const known = ownerByDir.get(dir);
1085
+ if (known !== void 0) {
1086
+ answer = known;
1087
+ break;
1088
+ }
1089
+ walked.push(dir);
1090
+ if (!hasGitEntry(dir))
1091
+ continue;
1092
+ const owner = resolveGitCheckout(dir);
1093
+ answer = owner && !isAtOrAboveHomeDir(owner.root, home) ? pathForm(owner.commonDir) : null;
1094
+ break;
1095
+ }
1096
+ for (const dir of walked)
1097
+ ownerByDir.set(dir, answer);
1098
+ return answer;
1099
+ }
1100
+ }
1101
+ function hasGitEntry(dir) {
1102
+ return fs2.existsSync(path2.join(dir, ".git"));
1103
+ }
1104
+ function pathForm(real) {
1105
+ return process.platform === "win32" ? normalizeEphemeralMapKey(real) : real;
1106
+ }
1107
+ function isSessionRepositoryPath(target) {
1108
+ return sessionRepositoryJudge()(target);
1109
+ }
1110
+ function isUntrustedProjectPath(target) {
1111
+ if (getProjectTrustState() === "trusted")
1112
+ return false;
1113
+ return isSessionRepositoryPath(target);
1114
+ }
1115
+ function recordProjectCommandRefusal(resolvedCommand) {
1116
+ const trust = getProjectTrustState();
1117
+ const target = realpathOrResolve(resolvedCommand);
1118
+ if (recordDegradationOnce({
1119
+ kind: "trust-refusal",
1120
+ subject: `project-command:${target}`,
1121
+ reason: `lookup resolved inside the project and was refused: pi project trust is ${trust}`
1122
+ })) {
1123
+ logExtension({
1124
+ subsystem: "project-trust",
1125
+ level: "warn",
1126
+ message: "lookup resolved inside the project and was refused: mark the project trusted in pi or upgrade pi",
1127
+ metadata: { command: resolvedCommand, target, trust }
1128
+ });
1129
+ }
1130
+ }
1131
+ function admittedLookupAnswer(stdout) {
1132
+ const answer = stdout.trim().split(/\r?\n/)[0] || null;
1133
+ if (answer === null || !isUntrustedProjectPath(answer))
1134
+ return answer;
1135
+ recordProjectCommandRefusal(answer);
1136
+ return null;
1137
+ }
905
1138
 
906
1139
  // dist/clients/resource-sampler.js
907
1140
  var import_pidusage = __toESM(require_pidusage(), 1);
@@ -911,18 +1144,18 @@ import { spawn as nodeSpawn2 } from "node:child_process";
911
1144
 
912
1145
  // dist/clients/bounded-pid-file-lock.js
913
1146
  import { randomUUID } from "node:crypto";
914
- import * as fs2 from "node:fs";
1147
+ import * as fs4 from "node:fs";
915
1148
  import fsp from "node:fs/promises";
916
- import path2 from "node:path";
1149
+ import path4 from "node:path";
917
1150
 
918
1151
  // dist/clients/generation-lock.js
919
1152
  import { randomInt } from "node:crypto";
920
- import * as fs from "node:fs";
921
- import * as path from "node:path";
1153
+ import * as fs3 from "node:fs";
1154
+ import * as path3 from "node:path";
922
1155
  var GENERATION = /^lock\.(\d+)(\.released)?$/;
923
1156
  function pidFileOwner(file) {
924
1157
  try {
925
- const pid = Number(fs.readFileSync(file, "utf8").trim().split(/\s+/)[0]);
1158
+ const pid = Number(fs3.readFileSync(file, "utf8").trim().split(/\s+/)[0]);
926
1159
  return Number.isInteger(pid) && pid > 0 ? pid : void 0;
927
1160
  } catch {
928
1161
  return void 0;
@@ -940,7 +1173,7 @@ function isPidAlive(pid) {
940
1173
  }
941
1174
  function pidFileIsStale(file, staleMs) {
942
1175
  try {
943
- const stat = fs.statSync(file);
1176
+ const stat = fs3.statSync(file);
944
1177
  if (Date.now() - stat.mtimeMs > staleMs)
945
1178
  return true;
946
1179
  const pid = pidFileOwner(file);
@@ -954,7 +1187,7 @@ function isLockContention(error) {
954
1187
  return code === "EEXIST" || code === "EPERM" || code === "EBUSY";
955
1188
  }
956
1189
  function generationPath(dir, generation) {
957
- return path.join(dir, `lock.${generation}`);
1190
+ return path3.join(dir, `lock.${generation}`);
958
1191
  }
959
1192
  function releasedName(generation) {
960
1193
  return `lock.${generation}.released`;
@@ -974,7 +1207,7 @@ function removeBelowPredecessor(dir, entries, generation) {
974
1207
  if (!match || Number(match[1]) + 1 >= generation)
975
1208
  continue;
976
1209
  try {
977
- fs.unlinkSync(path.join(dir, name));
1210
+ fs3.unlinkSync(path3.join(dir, name));
978
1211
  } catch {
979
1212
  }
980
1213
  }
@@ -982,20 +1215,20 @@ function removeBelowPredecessor(dir, entries, generation) {
982
1215
  function recordGenerationTakeover(hold) {
983
1216
  incrementDegradationCount({
984
1217
  kind: "generation-lock-stale-takeover",
985
- subject: path.resolve(hold.dir),
1218
+ subject: path3.resolve(hold.dir),
986
1219
  reason: `took over lock generation ${hold.generation - 1} from a dead or aged-out holder`
987
1220
  });
988
1221
  }
989
1222
  function recordLegacyLockHeld(legacyPath) {
990
1223
  incrementDegradationCount({
991
1224
  kind: "generation-lock-legacy-held",
992
- subject: path.resolve(legacyPath),
993
- reason: `backed off: ${path.basename(legacyPath)} is held by another writer (one from before #3476, or a holder past the generation lease)`
1225
+ subject: path3.resolve(legacyPath),
1226
+ reason: `backed off: ${path3.basename(legacyPath)} is held by another writer (one from before #3476, or a holder past the generation lease)`
994
1227
  });
995
1228
  }
996
1229
  function releaseGeneration(hold) {
997
1230
  try {
998
- fs.writeFileSync(path.join(hold.dir, releasedName(hold.generation)), "");
1231
+ fs3.writeFileSync(path3.join(hold.dir, releasedName(hold.generation)), "");
999
1232
  } catch {
1000
1233
  }
1001
1234
  }
@@ -1007,7 +1240,7 @@ function startGenerationHeartbeat(hold, intervalMs) {
1007
1240
  const timer = setInterval(() => {
1008
1241
  try {
1009
1242
  const now = /* @__PURE__ */ new Date();
1010
- fs.utimesSync(file, now, now);
1243
+ fs3.utimesSync(file, now, now);
1011
1244
  } catch {
1012
1245
  }
1013
1246
  }, intervalMs);
@@ -1016,7 +1249,7 @@ function startGenerationHeartbeat(hold, intervalMs) {
1016
1249
  }
1017
1250
  function ownsTopGeneration(hold) {
1018
1251
  try {
1019
- const entries = fs.readdirSync(hold.dir);
1252
+ const entries = fs3.readdirSync(hold.dir);
1020
1253
  if (entries.includes(releasedName(hold.generation)))
1021
1254
  return false;
1022
1255
  return topGeneration(entries) === hold.generation;
@@ -1025,8 +1258,8 @@ function ownsTopGeneration(hold) {
1025
1258
  }
1026
1259
  }
1027
1260
  function tryAcquireGeneration(dir, staleMs) {
1028
- fs.mkdirSync(dir, { recursive: true });
1029
- const listed = fs.readdirSync(dir);
1261
+ fs3.mkdirSync(dir, { recursive: true });
1262
+ const listed = fs3.readdirSync(dir);
1030
1263
  const top = topGeneration(listed);
1031
1264
  const free = top === 0 || listed.includes(releasedName(top));
1032
1265
  if (!free && !pidFileIsStale(generationPath(dir, top), staleMs)) {
@@ -1034,7 +1267,7 @@ function tryAcquireGeneration(dir, staleMs) {
1034
1267
  }
1035
1268
  const hold = { dir, generation: top + 1, tookOverStale: !free };
1036
1269
  try {
1037
- fs.writeFileSync(generationPath(dir, hold.generation), `${process.pid} ${Date.now()}
1270
+ fs3.writeFileSync(generationPath(dir, hold.generation), `${process.pid} ${Date.now()}
1038
1271
  `, { flag: "wx" });
1039
1272
  } catch (error) {
1040
1273
  if (isLockContention(error))
@@ -1043,7 +1276,7 @@ function tryAcquireGeneration(dir, staleMs) {
1043
1276
  }
1044
1277
  let entries;
1045
1278
  try {
1046
- entries = fs.readdirSync(dir);
1279
+ entries = fs3.readdirSync(dir);
1047
1280
  } catch (cause) {
1048
1281
  releaseGeneration(hold);
1049
1282
  throw cause;
@@ -1058,8 +1291,8 @@ function tryAcquireGeneration(dir, staleMs) {
1058
1291
  var timedOutHolders = new BoundedFifoMap(16);
1059
1292
  function topGenerationHolder(dir) {
1060
1293
  try {
1061
- const top = topGeneration(fs.readdirSync(dir));
1062
- return `lock.${top} ${fs.readFileSync(generationPath(dir, top), "utf8").trim()}`;
1294
+ const top = topGeneration(fs3.readdirSync(dir));
1295
+ return `lock.${top} ${fs3.readFileSync(generationPath(dir, top), "utf8").trim()}`;
1063
1296
  } catch {
1064
1297
  return void 0;
1065
1298
  }
@@ -1106,11 +1339,11 @@ function generationDir(lockPath) {
1106
1339
  return `${lockPath}s`;
1107
1340
  }
1108
1341
  function boundedLockIsStale(lockPath) {
1109
- const [pidText] = fs2.readFileSync(lockPath, "utf8").split(":", 1);
1342
+ const [pidText] = fs4.readFileSync(lockPath, "utf8").split(":", 1);
1110
1343
  const pid = Number.parseInt(pidText ?? "", 10);
1111
1344
  if (Number.isSafeInteger(pid) && pid > 0)
1112
1345
  return !ownerPidIsLive(pid);
1113
- return Date.now() - fs2.statSync(lockPath).mtimeMs > UNREADABLE_LOCK_STALE_MS;
1346
+ return Date.now() - fs4.statSync(lockPath).mtimeMs > UNREADABLE_LOCK_STALE_MS;
1114
1347
  }
1115
1348
  function ownerPidIsLive(pid) {
1116
1349
  if (!Number.isSafeInteger(pid) || pid <= 0)
@@ -1142,13 +1375,13 @@ async function releaseQuarantineLock(lockPath, token) {
1142
1375
  } catch (error) {
1143
1376
  if (error.code !== "ENOENT" || attempt === 2)
1144
1377
  return;
1145
- await new Promise((resolve6) => setImmediate(resolve6));
1378
+ await new Promise((resolve7) => setImmediate(resolve7));
1146
1379
  }
1147
1380
  }
1148
1381
  if (!renamed)
1149
1382
  return;
1150
1383
  try {
1151
- const owner = JSON.parse(await fsp.readFile(path2.join(quarantined, "owner.json"), "utf8"));
1384
+ const owner = JSON.parse(await fsp.readFile(path4.join(quarantined, "owner.json"), "utf8"));
1152
1385
  if (owner.token === token) {
1153
1386
  await fsp.rm(quarantined, { recursive: true, force: true });
1154
1387
  } else {
@@ -1173,7 +1406,7 @@ async function reclaimQuarantineLock(lockPath, staleMs) {
1173
1406
  }
1174
1407
  let stale = false;
1175
1408
  try {
1176
- const owner = JSON.parse(await fsp.readFile(path2.join(quarantined, "owner.json"), "utf8"));
1409
+ const owner = JSON.parse(await fsp.readFile(path4.join(quarantined, "owner.json"), "utf8"));
1177
1410
  stale = quarantineOwnerIsStale(owner, staleMs);
1178
1411
  } catch {
1179
1412
  try {
@@ -1199,7 +1432,7 @@ async function tryAcquireQuarantineLock(lockPath, staleMs) {
1199
1432
  try {
1200
1433
  await fsp.mkdir(lockPath);
1201
1434
  try {
1202
- await fsp.writeFile(path2.join(lockPath, "owner.json"), JSON.stringify(owner), "utf8");
1435
+ await fsp.writeFile(path4.join(lockPath, "owner.json"), JSON.stringify(owner), "utf8");
1203
1436
  } catch (error) {
1204
1437
  await fsp.rm(lockPath, { recursive: true, force: true }).catch(() => {
1205
1438
  });
@@ -1212,7 +1445,7 @@ async function tryAcquireQuarantineLock(lockPath, staleMs) {
1212
1445
  }
1213
1446
  let stale;
1214
1447
  try {
1215
- const existing = JSON.parse(await fsp.readFile(path2.join(lockPath, "owner.json"), "utf8"));
1448
+ const existing = JSON.parse(await fsp.readFile(path4.join(lockPath, "owner.json"), "utf8"));
1216
1449
  stale = quarantineOwnerIsStale(existing, staleMs);
1217
1450
  } catch {
1218
1451
  try {
@@ -1269,12 +1502,12 @@ async function acquireQuarantinePidFileLock(lockPath, options) {
1269
1502
  }
1270
1503
  throw new Error(options.timeoutMessage);
1271
1504
  }
1272
- await new Promise((resolve6) => setTimeout(resolve6, Math.min(options.retryMs, remaining)));
1505
+ await new Promise((resolve7) => setTimeout(resolve7, Math.min(options.retryMs, remaining)));
1273
1506
  }
1274
1507
  }
1275
1508
  function createLegacyBoundedLock(lockPath, token) {
1276
1509
  try {
1277
- fs2.writeFileSync(lockPath, token, { encoding: "utf8", flag: "wx" });
1510
+ fs4.writeFileSync(lockPath, token, { encoding: "utf8", flag: "wx" });
1278
1511
  return true;
1279
1512
  } catch (cause) {
1280
1513
  if (isLockContention(cause))
@@ -1288,7 +1521,7 @@ function takeLegacyBoundedLock(lockPath, token) {
1288
1521
  try {
1289
1522
  if (!boundedLockIsStale(lockPath))
1290
1523
  return false;
1291
- fs2.unlinkSync(lockPath);
1524
+ fs4.unlinkSync(lockPath);
1292
1525
  } catch {
1293
1526
  return false;
1294
1527
  }
@@ -1296,8 +1529,8 @@ function takeLegacyBoundedLock(lockPath, token) {
1296
1529
  }
1297
1530
  function releaseLegacyBoundedLock(lockPath, token) {
1298
1531
  try {
1299
- if (fs2.readFileSync(lockPath, "utf8") === token)
1300
- fs2.unlinkSync(lockPath);
1532
+ if (fs4.readFileSync(lockPath, "utf8") === token)
1533
+ fs4.unlinkSync(lockPath);
1301
1534
  } catch {
1302
1535
  }
1303
1536
  }
@@ -1324,7 +1557,7 @@ function currentHolderIdentity(dir, lockPath, hold) {
1324
1557
  if (hold === "busy")
1325
1558
  return topGenerationHolder(dir);
1326
1559
  try {
1327
- const content = fs2.readFileSync(lockPath, "utf8");
1560
+ const content = fs4.readFileSync(lockPath, "utf8");
1328
1561
  return content ? `legacy ${content}` : void 0;
1329
1562
  } catch {
1330
1563
  return void 0;
@@ -1351,7 +1584,7 @@ function acquireBoundedPidFileLock(lockPath, options) {
1351
1584
  if (timedOutHolder !== void 0 && currentHolderIdentity(dir, lockPath, hold) === timedOutHolder) {
1352
1585
  recordDegradationOnce({
1353
1586
  kind: "bounded-pid-lock-wait-skipped",
1354
- subject: path2.resolve(dir),
1587
+ subject: path4.resolve(dir),
1355
1588
  reason: `did not wait: ${timedOutHolder} still holds the lock after an earlier wait ran out`
1356
1589
  });
1357
1590
  if (options.onContention === "skip-log") {
@@ -1384,7 +1617,7 @@ function unrefChildAndPipes(child) {
1384
1617
  }
1385
1618
  }
1386
1619
  function spawnCollectStdoutResult(command, args, options, collectOptions = {}) {
1387
- return new Promise((resolve6) => {
1620
+ return new Promise((resolve7) => {
1388
1621
  let settled = false;
1389
1622
  let timer;
1390
1623
  const settle = (result) => {
@@ -1393,7 +1626,7 @@ function spawnCollectStdoutResult(command, args, options, collectOptions = {}) {
1393
1626
  settled = true;
1394
1627
  if (timer)
1395
1628
  clearTimeout(timer);
1396
- resolve6(result);
1629
+ resolve7(result);
1397
1630
  };
1398
1631
  try {
1399
1632
  const child = nodeSpawn(command, args, options);
@@ -1435,13 +1668,13 @@ async function terminateTimedOutChild(child, onTimeout) {
1435
1668
  }
1436
1669
 
1437
1670
  // dist/clients/file-utils.js
1438
- import * as fs4 from "node:fs";
1671
+ import * as fs5 from "node:fs";
1439
1672
  import { createHash, randomBytes } from "node:crypto";
1440
- import * as os2 from "node:os";
1441
- import * as path7 from "node:path";
1673
+ import * as os3 from "node:os";
1674
+ import * as path8 from "node:path";
1442
1675
 
1443
1676
  // dist/clients/spawn-timeout-cooldown.js
1444
- import path3 from "node:path";
1677
+ import path5 from "node:path";
1445
1678
  var COOLDOWN_STATE_KEY = /* @__PURE__ */ Symbol.for("pi-lens:spawn-timeout-cooldown");
1446
1679
  var _global = globalThis;
1447
1680
  if (!_global[COOLDOWN_STATE_KEY]) {
@@ -1449,11 +1682,11 @@ if (!_global[COOLDOWN_STATE_KEY]) {
1449
1682
  }
1450
1683
  var timedOutByCommand = _global[COOLDOWN_STATE_KEY].timedOutByCommand;
1451
1684
  function wrapperKindOf(command) {
1452
- const ext = path3.extname(command);
1685
+ const ext = path5.extname(command);
1453
1686
  return ext ? ext.slice(1) : "bare";
1454
1687
  }
1455
1688
  function cooldownKey(command) {
1456
- return path3.basename(command).replace(/\.[^.]+$/, "").toLowerCase();
1689
+ return path5.basename(command).replace(/\.[^.]+$/, "").toLowerCase();
1457
1690
  }
1458
1691
  function noteSpawnTimeout(input) {
1459
1692
  const key = cooldownKey(input.command);
@@ -1492,7 +1725,7 @@ function resetSpawnTimeoutCooldowns() {
1492
1725
  }
1493
1726
 
1494
1727
  // dist/clients/git-tracked-ignore.js
1495
- import * as path4 from "node:path";
1728
+ import * as path6 from "node:path";
1496
1729
  function recordTruncatedLsFiles(parseSite) {
1497
1730
  recordDegradationOnce({
1498
1731
  kind: "git-tracked-ignore-truncated",
@@ -1510,7 +1743,7 @@ function parseUntrackedIgnoredOutput(stdout, cwd) {
1510
1743
  const dirSegments = rel.split("/").slice(0, -1);
1511
1744
  if (dirSegments.some((segment) => isExcludedDirName(segment)))
1512
1745
  continue;
1513
- ids.add(normalizeMapKey(path4.join(cwd, rel)));
1746
+ ids.add(normalizeMapKey(path6.join(cwd, rel)));
1514
1747
  }
1515
1748
  return ids;
1516
1749
  }
@@ -1555,7 +1788,7 @@ function parseTrackedFilesOutput(stdout, cwd) {
1555
1788
  const dirSegments = rel.split("/").slice(0, -1);
1556
1789
  if (dirSegments.some((segment) => isExcludedDirName(segment)))
1557
1790
  continue;
1558
- ids.add(normalizeEphemeralMapKey(path4.join(base, rel)));
1791
+ ids.add(normalizeEphemeralMapKey(path6.join(base, rel)));
1559
1792
  }
1560
1793
  return ids;
1561
1794
  }
@@ -1602,7 +1835,6 @@ function getTrackedFilesSnapshot(cwd) {
1602
1835
  }
1603
1836
 
1604
1837
  // dist/clients/lens-config.js
1605
- import * as path5 from "node:path";
1606
1838
  function globalCanonicalLocation() {
1607
1839
  const location = GLOBAL_CONFIG_LOCATIONS.find((candidate) => candidate.relativePath === CANONICAL_GLOBAL_CONFIG_FILE);
1608
1840
  if (!location) {
@@ -1695,6 +1927,14 @@ function loadPiLensGlobalConfig(configPath) {
1695
1927
  const toolConfig = readToolConfig(raw, warnInvalid);
1696
1928
  if (toolConfig)
1697
1929
  config.tools = toolConfig;
1930
+ const toolsSection = asConfigObject(raw.tools);
1931
+ if (toolsSection && "lazy" in toolsSection) {
1932
+ const lazy = readLazyToolsSetting(raw);
1933
+ if (lazy === void 0)
1934
+ warnInvalid('tools.lazy must be "auto", true, or false');
1935
+ else
1936
+ config.tools = { ...config.tools, lazy };
1937
+ }
1698
1938
  for (const spec of LENS_FLAGS) {
1699
1939
  if (spec.readGlobal)
1700
1940
  continue;
@@ -1784,7 +2024,7 @@ function loadPiLensGlobalConfig(configPath) {
1784
2024
  ]);
1785
2025
  for (const key of Object.keys(raw)) {
1786
2026
  if (!knownGlobalConfigKeys.has(key)) {
1787
- warnInvalid(`unknown key "${key}" is not a recognized pi-lens setting (check for a typo); ignored`);
2027
+ warnInvalid(PROJECT_NON_FLAG_CONFIG_SECTIONS.includes(key) ? `"${key}" is a project-scoped pi-lens setting; set it in <project>/.pi-lens.json, not in the global config; ignored` : `unknown key "${key}" is not a recognized pi-lens setting (check for a typo); ignored`);
1788
2028
  }
1789
2029
  }
1790
2030
  return config;
@@ -1812,7 +2052,7 @@ function resolvePiLensFlagWithSource(name, value, config, projectConfig, editedF
1812
2052
  if (nested) {
1813
2053
  return {
1814
2054
  value: flagValueFromConfig(spec, nested.value),
1815
- source: path5.resolve(nested.dir) === path5.resolve(projectRoot) ? "project" : `nested-project:${nested.dir}`
2055
+ source: pathsEqual(nested.dir, projectRoot) ? "project" : `nested-project:${nested.dir}`
1816
2056
  };
1817
2057
  }
1818
2058
  const projectValue = readFlagConfigValue(projectConfig, spec.configKey);
@@ -1834,47 +2074,33 @@ function resolvePiLensFlag(name, value, config, projectConfig, editedFilePath, p
1834
2074
  }
1835
2075
 
1836
2076
  // dist/clients/ephemeral-root.js
1837
- import * as fs3 from "node:fs";
1838
- import * as os from "node:os";
1839
- import * as path6 from "node:path";
2077
+ import * as os2 from "node:os";
2078
+ import * as path7 from "node:path";
1840
2079
  var NOT_EPHEMERAL = { checkout: false };
1841
2080
  var classified = new BoundedFifoMap(1024);
1842
- function realPathOfNearestExisting(target) {
1843
- const resolved = path6.resolve(target);
1844
- const tail = [];
1845
- for (let current = resolved; ; current = path6.dirname(current)) {
1846
- try {
1847
- return path6.join(fs3.realpathSync.native(current), ...tail.reverse());
1848
- } catch {
1849
- if (path6.dirname(current) === current)
1850
- return resolved;
1851
- tail.push(path6.basename(current));
1852
- }
1853
- }
1854
- }
1855
2081
  function classifyTmpDir(dir) {
1856
- const tmpSpelling = os.tmpdir();
1857
- const key = `${normalizeEphemeralMapKey(tmpSpelling)}\0${normalizeEphemeralMapKey(path6.resolve(dir))}`;
2082
+ const tmpSpelling = os2.tmpdir();
2083
+ const key = `${normalizeEphemeralMapKey(tmpSpelling)}\0${normalizeEphemeralMapKey(path7.resolve(dir))}`;
1858
2084
  const memo = classified.get(key);
1859
2085
  if (memo)
1860
2086
  return memo;
1861
- const tmpRoot = realPathOfNearestExisting(tmpSpelling);
1862
- const real = realPathOfNearestExisting(dir);
2087
+ const tmpRoot = realpathOrResolve(tmpSpelling);
2088
+ const real = realpathOrResolve(dir);
1863
2089
  let result = NOT_EPHEMERAL;
1864
2090
  if (isUnderDir(real, tmpRoot)) {
1865
- for (let current = real; current !== tmpRoot && path6.dirname(current) !== current; current = path6.dirname(current)) {
1866
- if (isRealGitMarker(path6.join(current, ".git"))) {
2091
+ for (let current = real; current !== tmpRoot && path7.dirname(current) !== current; current = path7.dirname(current)) {
2092
+ if (isRealGitMarker(path7.join(current, ".git"))) {
1867
2093
  result = { checkout: true };
1868
2094
  break;
1869
2095
  }
1870
2096
  }
1871
2097
  if (!result.checkout) {
1872
- const segments = path6.relative(tmpRoot, real).split(path6.sep);
2098
+ const segments = path7.relative(tmpRoot, real).split(path7.sep);
1873
2099
  const index = segments.findIndex((segment) => /^pi-agent(?:-|$)/i.test(segment));
1874
2100
  if (index >= 0) {
1875
2101
  result = {
1876
2102
  checkout: false,
1877
- stagingRoot: path6.join(tmpRoot, ...segments.slice(0, index + 1))
2103
+ stagingRoot: path7.join(tmpRoot, ...segments.slice(0, index + 1))
1878
2104
  };
1879
2105
  }
1880
2106
  }
@@ -1883,17 +2109,17 @@ function classifyTmpDir(dir) {
1883
2109
  return result;
1884
2110
  }
1885
2111
  function ephemeralStagingRoot(filePath) {
1886
- return classifyTmpDir(path6.dirname(path6.resolve(filePath))).stagingRoot;
2112
+ return classifyTmpDir(path7.dirname(path7.resolve(filePath))).stagingRoot;
1887
2113
  }
1888
2114
  function isPiOwnedTempPath(filePath) {
1889
- const tmpRoot = realPathOfNearestExisting(os.tmpdir());
1890
- const real = realPathOfNearestExisting(filePath);
2115
+ const tmpRoot = realpathOrResolve(os2.tmpdir());
2116
+ const real = realpathOrResolve(filePath);
1891
2117
  if (!isUnderDir(real, tmpRoot))
1892
2118
  return false;
1893
- const relative3 = path6.relative(tmpRoot, real);
1894
- if (relative3.length === 0 || path6.isAbsolute(relative3))
2119
+ const relative3 = path7.relative(tmpRoot, real);
2120
+ if (relative3.length === 0 || path7.isAbsolute(relative3))
1895
2121
  return false;
1896
- const segments = relative3.split(path6.sep);
2122
+ const segments = relative3.split(path7.sep);
1897
2123
  return segments.length === 1 || /^pi-/i.test(segments[0] ?? "");
1898
2124
  }
1899
2125
  function isEphemeralCheckoutRoot(dir) {
@@ -1902,31 +2128,139 @@ function isEphemeralCheckoutRoot(dir) {
1902
2128
 
1903
2129
  // dist/clients/file-utils.js
1904
2130
  function getProjectDataDir(cwd) {
1905
- const legacyProjectDir = path7.join(cwd, ".pi-lens");
2131
+ const legacyProjectDir = path8.join(cwd, ".pi-lens");
1906
2132
  const configuredBase = process.env.PILENS_DATA_DIR?.trim();
1907
2133
  const resolvedBase = projectDataBase();
1908
- const memoKey = `${resolvedBase}\0${path7.resolve(cwd)}`;
2134
+ const memoKey = `${resolvedBase}\0${path8.resolve(cwd)}`;
1909
2135
  const cached = settledDataDirs.get(memoKey);
1910
2136
  if (cached !== void 0)
1911
2137
  return cached;
1912
- if (!configuredBase && fs4.existsSync(legacyProjectDir)) {
2138
+ if (!configuredBase && fs5.existsSync(legacyProjectDir)) {
1913
2139
  return legacyProjectDir;
1914
2140
  }
1915
- const canonical = canonicalProjectRoot(cwd);
2141
+ const canonical = dataDirCanonicalRoot(cwd);
1916
2142
  const readable = projectDataDirReadableSlug(canonical.root);
1917
2143
  const hash = projectDataDirRootHash(canonical.root);
1918
2144
  const slug = `${readable || "default"}-${hash}`;
1919
2145
  const base = isEphemeralCheckoutRoot(cwd) ? ephemeralDataBase(resolvedBase) : resolvedBase;
1920
- const dir = path7.join(base, slug);
2146
+ const dir = path8.join(base, slug);
1921
2147
  if (base !== resolvedBase && pendingDataDirMigrations.length < 32) {
1922
2148
  pendingDataDirMigrations.push({ to: dir, outcome: "ephemeral" });
1923
2149
  }
1924
2150
  const settled = settleProjectDataDir(base, readable || "default", dir, memoKey, canonical.fallback);
2151
+ if (settled === dir) {
2152
+ adoptSpelledDataDirs(path8.resolve(cwd), base, dir, readable || "default");
2153
+ }
1925
2154
  return settled;
1926
2155
  }
2156
+ var ADOPT_MAX_ENTRIES = 4096;
2157
+ var ADOPTED_MARKER_PREFIX = ".adopted-";
2158
+ function adoptSpelledDataDirs(spelledRoot, base, dir, settledOldSlug) {
2159
+ const readable = projectDataDirReadableSlug(spelledRoot) || "default";
2160
+ const sources = [`${readable}-${projectDataDirRootHash(spelledRoot)}`];
2161
+ if (readable !== settledOldSlug)
2162
+ sources.push(readable);
2163
+ let copied = 0;
2164
+ let failed = 0;
2165
+ for (const source of sources) {
2166
+ const outcome = adoptSource(base, source, dir);
2167
+ copied += outcome.copied;
2168
+ failed += outcome.failed;
2169
+ }
2170
+ if ((copied > 0 || failed > 0) && pendingDataDirMigrations.length < 32) {
2171
+ pendingDataDirMigrations.push({
2172
+ to: dir,
2173
+ outcome: failed > 0 ? "adopt-failed" : "adopted"
2174
+ });
2175
+ }
2176
+ }
2177
+ function adoptSource(base, source, dir) {
2178
+ const from = path8.join(base, source);
2179
+ if (from === dir || !isDirectory(from))
2180
+ return { copied: 0, failed: 0 };
2181
+ const marker = path8.join(dir, `${ADOPTED_MARKER_PREFIX}${source}`);
2182
+ if (fs5.existsSync(marker))
2183
+ return { copied: 0, failed: 0 };
2184
+ const { copied, failed } = copyMissingFiles(from, dir);
2185
+ return { copied, failed: failed + (markAdopted(marker) ? 0 : 1) };
2186
+ }
2187
+ function markAdopted(marker) {
2188
+ try {
2189
+ fs5.mkdirSync(path8.dirname(marker), { recursive: true });
2190
+ writeFileAtomic(marker, "", { bestEffort: false });
2191
+ return true;
2192
+ } catch {
2193
+ return false;
2194
+ }
2195
+ }
2196
+ function isDirectory(dir) {
2197
+ try {
2198
+ return fs5.statSync(dir).isDirectory();
2199
+ } catch {
2200
+ return false;
2201
+ }
2202
+ }
2203
+ function copyMissingFiles(from, to) {
2204
+ let copied = 0;
2205
+ let failed = 0;
2206
+ let seen = 0;
2207
+ const pending = [""];
2208
+ while (pending.length > 0) {
2209
+ const rel = pending.pop() ?? "";
2210
+ let entries;
2211
+ try {
2212
+ entries = fs5.readdirSync(path8.join(from, rel), { withFileTypes: true });
2213
+ } catch {
2214
+ failed++;
2215
+ continue;
2216
+ }
2217
+ for (const entry of entries) {
2218
+ const name = entry.name;
2219
+ if (name.endsWith(".lock") || name.endsWith(".locks"))
2220
+ continue;
2221
+ if (STAGE_TMP_PATTERN.test(name))
2222
+ continue;
2223
+ if (name.startsWith(ADOPTED_MARKER_PREFIX))
2224
+ continue;
2225
+ const child = path8.join(rel, name);
2226
+ if (entry.isDirectory()) {
2227
+ if (++seen > ADOPT_MAX_ENTRIES)
2228
+ return { copied, failed: failed + 1 };
2229
+ pending.push(child);
2230
+ continue;
2231
+ }
2232
+ if (!entry.isFile())
2233
+ continue;
2234
+ if (++seen > ADOPT_MAX_ENTRIES)
2235
+ return { copied, failed: failed + 1 };
2236
+ const outcome = copyIfMissing(path8.join(from, child), path8.join(to, child));
2237
+ if (outcome === "copied")
2238
+ copied++;
2239
+ else if (outcome === "failed")
2240
+ failed++;
2241
+ }
2242
+ }
2243
+ return { copied, failed };
2244
+ }
2245
+ function copyIfMissing(source, target) {
2246
+ const stage = stagePathFor(target);
2247
+ let staged = false;
2248
+ try {
2249
+ fs5.mkdirSync(path8.dirname(target), { recursive: true });
2250
+ staged = true;
2251
+ fs5.copyFileSync(source, stage);
2252
+ fs5.linkSync(stage, target);
2253
+ return "copied";
2254
+ } catch (cause) {
2255
+ return staged && cause.code === "EEXIST" ? "present" : "failed";
2256
+ } finally {
2257
+ if (staged)
2258
+ fs5.rmSync(stage, { force: true });
2259
+ }
2260
+ }
1927
2261
  function projectDataBase() {
1928
2262
  const configuredBase = process.env.PILENS_DATA_DIR?.trim();
1929
- return configuredBase || path7.join(getGlobalPiLensDir(), "projects");
2263
+ return configuredBase || path8.join(getGlobalPiLensDir(), "projects");
1930
2264
  }
1931
2265
  var EPHEMERAL_DATA_DIR_NAME = ".ephemeral";
1932
2266
  var EPHEMERAL_TOKEN_PATTERN = /^(\d+)-[0-9a-f]{8}$/;
@@ -1942,20 +2276,20 @@ function ephemeralDataBase(resolvedBase) {
1942
2276
  state.exitHook = true;
1943
2277
  process.once("exit", removeEphemeralDataDirs);
1944
2278
  }
1945
- return path7.join(resolvedBase, EPHEMERAL_DATA_DIR_NAME, state.token);
2279
+ return path8.join(resolvedBase, EPHEMERAL_DATA_DIR_NAME, state.token);
1946
2280
  }
1947
2281
  function removeEphemeralDataDirs() {
1948
- const dir = path7.join(projectDataBase(), EPHEMERAL_DATA_DIR_NAME, ephemeralDataToken().token);
2282
+ const dir = path8.join(projectDataBase(), EPHEMERAL_DATA_DIR_NAME, ephemeralDataToken().token);
1949
2283
  try {
1950
- fs4.rmSync(dir, { recursive: true, force: true });
2284
+ fs5.rmSync(dir, { recursive: true, force: true });
1951
2285
  } catch {
1952
2286
  }
1953
2287
  }
1954
2288
  async function sweepDeadEphemeralDataDirs(options) {
1955
- const parent = path7.join(projectDataBase(), EPHEMERAL_DATA_DIR_NAME);
2289
+ const parent = path8.join(projectDataBase(), EPHEMERAL_DATA_DIR_NAME);
1956
2290
  let handle;
1957
2291
  try {
1958
- handle = await fs4.promises.opendir(parent);
2292
+ handle = await fs5.promises.opendir(parent);
1959
2293
  } catch {
1960
2294
  return 0;
1961
2295
  }
@@ -1969,7 +2303,7 @@ async function sweepDeadEphemeralDataDirs(options) {
1969
2303
  if (pid === void 0 || options.isPidAlive(Number(pid)))
1970
2304
  continue;
1971
2305
  try {
1972
- await fs4.promises.rm(path7.join(parent, entry.name), {
2306
+ await fs5.promises.rm(path8.join(parent, entry.name), {
1973
2307
  recursive: true,
1974
2308
  force: true
1975
2309
  });
@@ -1985,17 +2319,18 @@ async function sweepDeadEphemeralDataDirs(options) {
1985
2319
  return removed;
1986
2320
  }
1987
2321
  function projectDataDirReadableSlug(canonicalRoot) {
1988
- const normalized = normalizeFilePath(canonicalRoot);
2322
+ const normalized = normalizePathSpelling(canonicalRoot);
1989
2323
  return normalized.replace(/^[a-z]:/i, "").replace(/\/+/g, "-").replace(/[^A-Za-z0-9-]/g, "").replace(/^-+/, "").replace(/-+$/, "");
1990
2324
  }
1991
- function canonicalProjectRoot(cwd) {
1992
- const resolved = path7.resolve(cwd);
2325
+ function dataDirCanonicalRoot(cwd, platform = process.platform) {
2326
+ const resolved = path8.resolve(cwd);
2327
+ const root = platform === "win32" ? resolved : realpathOrResolve(resolved);
1993
2328
  try {
1994
- fs4.realpathSync(resolved);
2329
+ fs5.realpathSync(resolved);
1995
2330
  } catch {
1996
- return { root: resolved, fallback: true };
2331
+ return { root, fallback: true };
1997
2332
  }
1998
- return { root: resolved, fallback: false };
2333
+ return { root, fallback: false };
1999
2334
  }
2000
2335
  function projectDataDirRootHash(canonicalRoot) {
2001
2336
  return createHash("sha256").update(canonicalRoot).digest("hex").slice(0, 8);
@@ -2006,9 +2341,9 @@ function resetProjectDataDirSessionState() {
2006
2341
  pendingDataDirMigrations.splice(0);
2007
2342
  }
2008
2343
  function settleProjectDataDir(base, oldSlug, dir, memoKey, identityFallback) {
2009
- const oldDir = path7.join(base, oldSlug);
2010
- const newExists = fs4.existsSync(dir);
2011
- const oldExists = fs4.existsSync(oldDir);
2344
+ const oldDir = path8.join(base, oldSlug);
2345
+ const newExists = fs5.existsSync(dir);
2346
+ const oldExists = fs5.existsSync(oldDir);
2012
2347
  if (!oldExists) {
2013
2348
  if (identityFallback && pendingDataDirMigrations.length < 32) {
2014
2349
  pendingDataDirMigrations.push({
@@ -2021,14 +2356,14 @@ function settleProjectDataDir(base, oldSlug, dir, memoKey, identityFallback) {
2021
2356
  }
2022
2357
  if (!newExists) {
2023
2358
  try {
2024
- fs4.renameSync(oldDir, dir);
2359
+ fs5.renameSync(oldDir, dir);
2025
2360
  } catch (error) {
2026
2361
  if (error.code === "ENOENT") {
2027
- if (fs4.existsSync(dir)) {
2362
+ if (fs5.existsSync(dir)) {
2028
2363
  settledDataDirs.set(memoKey, dir);
2029
2364
  return dir;
2030
2365
  }
2031
- if (fs4.existsSync(oldDir))
2366
+ if (fs5.existsSync(oldDir))
2032
2367
  return oldDir;
2033
2368
  return dir;
2034
2369
  }
@@ -2055,7 +2390,7 @@ function drainProjectDataDirMigrations() {
2055
2390
  return pendingDataDirMigrations.splice(0);
2056
2391
  }
2057
2392
  function displayProjectDataPath(cwd, ...segments) {
2058
- const absolute = path7.resolve(getProjectDataDir(cwd), ...segments);
2393
+ const absolute = path8.resolve(getProjectDataDir(cwd), ...segments);
2059
2394
  const absolutePosix = absolute.replace(/\\/g, "/");
2060
2395
  const relative3 = toProjectRelativePath(absolute, cwd);
2061
2396
  if (relative3 !== absolutePosix) {
@@ -2064,19 +2399,16 @@ function displayProjectDataPath(cwd, ...segments) {
2064
2399
  return homeRelativePath(absolutePosix);
2065
2400
  }
2066
2401
  function getGlobalPiLensDir() {
2067
- const override = process.env.PI_LENS_HOME?.trim();
2068
- if (override)
2069
- return path7.resolve(override);
2070
- return path7.join(os2.homedir(), ".pi-lens");
2402
+ return machineStateDir();
2071
2403
  }
2072
2404
  function isPiLensInternalPath(filePath, projectRoot) {
2073
- const absolute = path7.resolve(filePath);
2074
- const home = path7.resolve(os2.homedir());
2405
+ const absolute = path8.resolve(filePath);
2406
+ const home = path8.resolve(os3.homedir());
2075
2407
  const candidates = [
2076
2408
  getGlobalPiLensDir(),
2077
2409
  getProjectDataDir(projectRoot),
2078
- path7.join(home, ".pi"),
2079
- path7.join(home, ".pi-lens")
2410
+ path8.join(home, ".pi"),
2411
+ path8.join(home, ".pi-lens")
2080
2412
  ];
2081
2413
  if (candidates.some((dir) => isUnderDir(absolute, dir)))
2082
2414
  return true;
@@ -2140,12 +2472,12 @@ var EXCLUDED_DIRS = [
2140
2472
  "vendors"
2141
2473
  ];
2142
2474
  function resolveGitIgnoreRoot(startDir) {
2143
- const fallback = path7.resolve(startDir);
2475
+ const fallback = realpathOrResolve(startDir);
2144
2476
  let current = fallback;
2145
2477
  while (true) {
2146
- if (fs4.existsSync(path7.join(current, ".git")))
2478
+ if (fs5.existsSync(path8.join(current, ".git")))
2147
2479
  return current;
2148
- const parent = path7.dirname(current);
2480
+ const parent = path8.dirname(current);
2149
2481
  if (parent === current)
2150
2482
  return fallback;
2151
2483
  current = parent;
@@ -2234,13 +2566,13 @@ function expandGitignorePattern(pattern) {
2234
2566
  return [body];
2235
2567
  return [body, `**/${body}`];
2236
2568
  }
2237
- function matchesGitignorePattern(pattern, relativePath, isDirectory, matchExpanded) {
2569
+ function matchesGitignorePattern(pattern, relativePath, isDirectory2, matchExpanded) {
2238
2570
  const candidate = stripLeadingSlashes(normalizeIgnorePath(relativePath));
2239
2571
  if (!candidate)
2240
2572
  return false;
2241
- const candidates = isDirectory ? [candidate, `${candidate}/`] : [candidate];
2573
+ const candidates = isDirectory2 ? [candidate, `${candidate}/`] : [candidate];
2242
2574
  return expandGitignorePattern(pattern).some((expanded) => {
2243
- if (isDirectory && expanded.endsWith("/**")) {
2575
+ if (isDirectory2 && expanded.endsWith("/**")) {
2244
2576
  const prefix = expanded.slice(0, -3);
2245
2577
  if (candidate === prefix || candidate.startsWith(`${prefix}/`))
2246
2578
  return true;
@@ -2249,23 +2581,23 @@ function matchesGitignorePattern(pattern, relativePath, isDirectory, matchExpand
2249
2581
  });
2250
2582
  }
2251
2583
  function readGitignorePatterns(rootDir, layer = "gitignore") {
2252
- const gitignorePath = path7.join(rootDir, ".gitignore");
2584
+ const gitignorePath = path8.join(rootDir, ".gitignore");
2253
2585
  try {
2254
- return parseGitignoreContent(fs4.readFileSync(gitignorePath, "utf-8"), layer);
2586
+ return parseGitignoreContent(fs5.readFileSync(gitignorePath, "utf-8"), layer);
2255
2587
  } catch {
2256
2588
  return [];
2257
2589
  }
2258
2590
  }
2259
2591
  function ancestorDirsBetween(rootDir, targetDir) {
2260
- const relative3 = path7.relative(rootDir, targetDir);
2261
- if (relative3.startsWith("..") || path7.isAbsolute(relative3))
2592
+ const relative3 = path8.relative(rootDir, targetDir);
2593
+ if (relative3.startsWith("..") || path8.isAbsolute(relative3))
2262
2594
  return [];
2263
2595
  const dirs = [rootDir];
2264
2596
  if (!relative3)
2265
2597
  return dirs;
2266
2598
  let current = rootDir;
2267
- for (const segment of relative3.split(path7.sep).filter(Boolean)) {
2268
- current = path7.join(current, segment);
2599
+ for (const segment of relative3.split(path8.sep).filter(Boolean)) {
2600
+ current = path8.join(current, segment);
2269
2601
  dirs.push(current);
2270
2602
  }
2271
2603
  return dirs;
@@ -2275,7 +2607,7 @@ function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
2275
2607
  const rememberIgnoreSource = (filePath, signature = fileFreshnessSignature(filePath)) => {
2276
2608
  consumedIgnoreSources.set(filePath, { path: filePath, ...signature });
2277
2609
  };
2278
- rememberIgnoreSource(path7.join(resolvedRoot, ".gitignore"));
2610
+ rememberIgnoreSource(path8.join(resolvedRoot, ".gitignore"));
2279
2611
  const nestedCache = /* @__PURE__ */ new Map();
2280
2612
  const patternsForDir = (dir) => {
2281
2613
  if (dir === resolvedRoot)
@@ -2286,7 +2618,7 @@ function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
2286
2618
  return cached.patterns;
2287
2619
  }
2288
2620
  const gitignoreSig = gitignoreSignature(dir);
2289
- rememberIgnoreSource(path7.join(dir, ".gitignore"), gitignoreSig);
2621
+ rememberIgnoreSource(path8.join(dir, ".gitignore"), gitignoreSig);
2290
2622
  const pilensInfo = findPiLensConfigInDir(dir);
2291
2623
  const pilensMtime = pilensInfo?.mtimeMs ?? -1;
2292
2624
  const pilensSize = pilensInfo?.size ?? -1;
@@ -2313,18 +2645,31 @@ function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
2313
2645
  };
2314
2646
  const patternMemo = /* @__PURE__ */ new Map();
2315
2647
  function dropVerdictsUnder(subtree) {
2316
- const resolvedSubtree = path7.resolve(subtree);
2648
+ const resolvedSubtree = path8.resolve(subtree);
2317
2649
  for (const key of patternMemo.keys()) {
2318
2650
  const memoPath = key.slice(2);
2319
- const relative3 = path7.relative(resolvedSubtree, memoPath);
2320
- if (!relative3 || !relative3.startsWith("..") && !path7.isAbsolute(relative3)) {
2651
+ const relative3 = path8.relative(resolvedSubtree, memoPath);
2652
+ if (!relative3 || !relative3.startsWith("..") && !path8.isAbsolute(relative3)) {
2321
2653
  patternMemo.delete(key);
2322
2654
  }
2323
2655
  }
2324
2656
  }
2657
+ const dirIdentities = /* @__PURE__ */ new Map();
2658
+ const identityOfDir = (dir) => {
2659
+ let identity = dirIdentities.get(dir);
2660
+ if (identity === void 0) {
2661
+ identity = realpathOrResolve(dir);
2662
+ dirIdentities.set(dir, identity);
2663
+ }
2664
+ return identity;
2665
+ };
2666
+ const rootPrefix = resolvedRoot.endsWith(path8.sep) ? resolvedRoot : resolvedRoot + path8.sep;
2667
+ const isUnderRootText = (absolute) => absolute === resolvedRoot || absolute.startsWith(rootPrefix);
2325
2668
  const invalidateSubtree = (subtree) => {
2326
- dropVerdictsUnder(subtree);
2327
- nestedCache.delete(path7.resolve(subtree));
2669
+ const absolute = path8.resolve(subtree);
2670
+ const local = isUnderRootText(absolute) ? absolute : identityOfDir(absolute);
2671
+ dropVerdictsUnder(local);
2672
+ nestedCache.delete(local);
2328
2673
  };
2329
2674
  const gitignoreGlobOptions = {
2330
2675
  dot: true,
@@ -2357,26 +2702,27 @@ function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
2357
2702
  ensureTrackedIndex() {
2358
2703
  return collectTrackedFiles(resolvedRoot).then(() => void 0);
2359
2704
  },
2360
- isIgnored(filePath, isDirectory = false) {
2361
- const resolved = path7.resolve(filePath);
2362
- const memoKey = (isDirectory ? "D:" : "F:") + resolved;
2705
+ isIgnored(filePath, isDirectory2 = false) {
2706
+ const spelled = path8.resolve(filePath);
2707
+ const resolved = isUnderRootText(spelled) ? spelled : path8.join(identityOfDir(path8.dirname(spelled)), path8.basename(spelled));
2708
+ const memoKey = (isDirectory2 ? "D:" : "F:") + resolved;
2363
2709
  let verdict = patternMemo.get(memoKey);
2364
2710
  if (verdict === void 0) {
2365
- const rootRelative = path7.relative(resolvedRoot, resolved);
2366
- if (!rootRelative || rootRelative.startsWith("..") || path7.isAbsolute(rootRelative)) {
2711
+ const rootRelative = path8.relative(resolvedRoot, resolved);
2712
+ if (!rootRelative || rootRelative.startsWith("..") || path8.isAbsolute(rootRelative)) {
2367
2713
  verdict = { ignored: false, layer: void 0 };
2368
2714
  } else {
2369
2715
  let ignored = false;
2370
2716
  let layer;
2371
- const patternDirs = ancestorDirsBetween(resolvedRoot, path7.dirname(resolved));
2717
+ const patternDirs = ancestorDirsBetween(resolvedRoot, path8.dirname(resolved));
2372
2718
  for (const dir of patternDirs) {
2373
2719
  const dirPatterns = patternsForDir(dir);
2374
2720
  if (dirPatterns.length === 0)
2375
2721
  continue;
2376
- const relative3 = path7.relative(dir, resolved);
2722
+ const relative3 = path8.relative(dir, resolved);
2377
2723
  const normalized = normalizeIgnorePath(relative3);
2378
2724
  for (const pattern of dirPatterns) {
2379
- if (!matchesGitignorePattern(pattern, normalized, isDirectory, matchExpanded))
2725
+ if (!matchesGitignorePattern(pattern, normalized, isDirectory2, matchExpanded))
2380
2726
  continue;
2381
2727
  ignored = !pattern.negated;
2382
2728
  layer = pattern.layer;
@@ -2388,7 +2734,7 @@ function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
2388
2734
  }
2389
2735
  if (!verdict.ignored)
2390
2736
  return false;
2391
- if (!isDirectory && verdict.layer !== "pilens" && isTrackedAndRescued(resolved)) {
2737
+ if (!isDirectory2 && verdict.layer !== "pilens" && isTrackedAndRescued(resolved)) {
2392
2738
  return false;
2393
2739
  }
2394
2740
  return true;
@@ -2408,7 +2754,7 @@ var projectIgnoreMatcherCache = /* @__PURE__ */ new Map();
2408
2754
  var PROJECT_IGNORE_FRESHNESS_CADENCE_MS = FRESHNESS_CADENCE_MS;
2409
2755
  function fileFreshnessSignature(filePath) {
2410
2756
  try {
2411
- const stat = fs4.statSync(filePath);
2757
+ const stat = fs5.statSync(filePath);
2412
2758
  return { mtimeMs: stat.mtimeMs, size: stat.size };
2413
2759
  } catch {
2414
2760
  return { mtimeMs: -1, size: -1 };
@@ -2418,7 +2764,7 @@ function globalConfigSignature() {
2418
2764
  return fileFreshnessSignature(getPiLensGlobalConfigPath());
2419
2765
  }
2420
2766
  function gitignoreSignature(rootDir) {
2421
- return fileFreshnessSignature(path7.join(rootDir, ".gitignore"));
2767
+ return fileFreshnessSignature(path8.join(rootDir, ".gitignore"));
2422
2768
  }
2423
2769
  function hasIgnoreSourceDrift(sources) {
2424
2770
  return sources.some((source) => {
@@ -2479,21 +2825,21 @@ function getProjectIgnoreMatcher(rootDir) {
2479
2825
  return matcher;
2480
2826
  }
2481
2827
  function invalidateProjectIgnoreMatcherForPath(filePath) {
2482
- const resolvedPath = path7.resolve(filePath);
2483
- if (path7.basename(resolvedPath).toLowerCase() !== ".gitignore")
2828
+ const resolvedPath = path8.resolve(filePath);
2829
+ if (path8.basename(resolvedPath).toLowerCase() !== ".gitignore")
2484
2830
  return;
2485
2831
  for (const [cachedRoot, cached] of projectIgnoreMatcherCache) {
2486
2832
  if (!isUnderDir(resolvedPath, cachedRoot))
2487
2833
  continue;
2488
- if (normalizeFilePath(resolvedPath) === normalizeFilePath(path7.join(cachedRoot, ".gitignore"))) {
2834
+ if (normalizeFilePath(resolvedPath) === normalizeFilePath(path8.join(cachedRoot, ".gitignore"))) {
2489
2835
  projectIgnoreMatcherCache.delete(cachedRoot);
2490
2836
  continue;
2491
2837
  }
2492
- cached.matcher.invalidateSubtree(path7.dirname(resolvedPath));
2838
+ cached.matcher.invalidateSubtree(path8.dirname(resolvedPath));
2493
2839
  }
2494
2840
  }
2495
- function isPathIgnoredByProject(filePath, rootDir, isDirectory = false) {
2496
- return getProjectIgnoreMatcher(rootDir).isIgnored(filePath, isDirectory);
2841
+ function isPathIgnoredByProject(filePath, rootDir, isDirectory2 = false) {
2842
+ return getProjectIgnoreMatcher(rootDir).isIgnored(filePath, isDirectory2);
2497
2843
  }
2498
2844
  function isRecordableProjectPath(filePath, projectRoot) {
2499
2845
  if (isPathIgnoredByProject(filePath, projectRoot, false))
@@ -2504,7 +2850,7 @@ function isRecordableProjectPath(filePath, projectRoot) {
2504
2850
  }
2505
2851
  var projectIgnoreGlobsCache = /* @__PURE__ */ new Map();
2506
2852
  function getProjectIgnoreGlobs(rootDir) {
2507
- const resolvedRoot = path7.resolve(rootDir);
2853
+ const resolvedRoot = path8.resolve(rootDir);
2508
2854
  const signature = gitignoreSignature(resolvedRoot);
2509
2855
  const cached = projectIgnoreGlobsCache.get(resolvedRoot);
2510
2856
  if (cached && cached.mtimeMs === signature.mtimeMs && cached.size === signature.size) {
@@ -2564,8 +2910,8 @@ function isTestFile(filePath) {
2564
2910
  }
2565
2911
 
2566
2912
  // dist/clients/instance-registry.js
2567
- import * as fs7 from "node:fs";
2568
- import * as path10 from "node:path";
2913
+ import * as fs8 from "node:fs";
2914
+ import * as path11 from "node:path";
2569
2915
 
2570
2916
  // dist/clients/generation-guard.js
2571
2917
  var declaredSources = /* @__PURE__ */ new Set();
@@ -2689,9 +3035,9 @@ function createGenerationMap(name, options = {}) {
2689
3035
  }
2690
3036
 
2691
3037
  // dist/clients/instance-registry-lock.js
2692
- import * as fs5 from "node:fs";
3038
+ import * as fs6 from "node:fs";
2693
3039
  import { randomInt as randomInt2 } from "node:crypto";
2694
- import * as path8 from "node:path";
3040
+ import * as path9 from "node:path";
2695
3041
  var OWN_HOLDS_FAMILY = "instance-registry.lock-own-holds";
2696
3042
  var OWN_HOLDS_VERSION = 1;
2697
3043
  function ownAsyncHolds() {
@@ -2711,7 +3057,7 @@ function legacyLockPath(target) {
2711
3057
  }
2712
3058
  function createLegacyLock(lock) {
2713
3059
  try {
2714
- fs5.writeFileSync(lock, `${process.pid} ${Date.now()}
3060
+ fs6.writeFileSync(lock, `${process.pid} ${Date.now()}
2715
3061
  `, { flag: "wx" });
2716
3062
  return true;
2717
3063
  } catch (error) {
@@ -2726,7 +3072,7 @@ function takeLegacyLock(lock) {
2726
3072
  if (!pidFileIsStale(lock, LOCK_STALE_MS))
2727
3073
  return false;
2728
3074
  try {
2729
- fs5.unlinkSync(lock);
3075
+ fs6.unlinkSync(lock);
2730
3076
  } catch {
2731
3077
  }
2732
3078
  return createLegacyLock(lock);
@@ -2735,7 +3081,7 @@ function releaseLegacyLock(lock) {
2735
3081
  if (pidFileOwner(lock) !== process.pid)
2736
3082
  return;
2737
3083
  try {
2738
- fs5.unlinkSync(lock);
3084
+ fs6.unlinkSync(lock);
2739
3085
  } catch {
2740
3086
  }
2741
3087
  }
@@ -2767,14 +3113,14 @@ function recordLockFailure(target, cause) {
2767
3113
  const code = cause?.code ?? "unknown";
2768
3114
  incrementDegradationCount({
2769
3115
  kind: "instance-registry-lock-failed",
2770
- subject: path8.resolve(target),
2771
- reason: `lock acquisition failed for ${path8.basename(target)} (${code}); the registry write was skipped`
3116
+ subject: path9.resolve(target),
3117
+ reason: `lock acquisition failed for ${path9.basename(target)} (${code}); the registry write was skipped`
2772
3118
  });
2773
3119
  }
2774
3120
  function recordStaleTakeover(target, hold) {
2775
3121
  incrementDegradationCount({
2776
3122
  kind: "instance-registry-lock-stale-takeover",
2777
- subject: path8.resolve(target),
3123
+ subject: path9.resolve(target),
2778
3124
  reason: `took over lock generation ${hold.generation - 1} from a dead or aged-out holder`
2779
3125
  });
2780
3126
  }
@@ -2782,15 +3128,15 @@ function recordLegacyHeld(target) {
2782
3128
  const lock = legacyLockPath(target);
2783
3129
  incrementDegradationCount({
2784
3130
  kind: "instance-registry-lock-legacy-held",
2785
- subject: path8.resolve(lock),
2786
- reason: `backed off: ${path8.basename(lock)} is held by pid ${pidFileOwner(lock) ?? "unknown"}, a writer from before #3476`
3131
+ subject: path9.resolve(lock),
3132
+ reason: `backed off: ${path9.basename(lock)} is held by pid ${pidFileOwner(lock) ?? "unknown"}, a writer from before #3476`
2787
3133
  });
2788
3134
  }
2789
3135
  function recordLockTimeout(target) {
2790
3136
  incrementDegradationCount({
2791
3137
  kind: "instance-registry-lock-timeout",
2792
- subject: path8.resolve(target),
2793
- reason: `lock acquisition exhausted for ${path8.basename(target)}`
3138
+ subject: path9.resolve(target),
3139
+ reason: `lock acquisition exhausted for ${path9.basename(target)}`
2794
3140
  });
2795
3141
  }
2796
3142
  function backoffMs() {
@@ -2805,7 +3151,7 @@ async function withInstanceRegistryLock(target, op, waitMs = LOCK_WAIT_MS) {
2805
3151
  return void 0;
2806
3152
  if (hold === "busy") {
2807
3153
  if (Date.now() <= deadline)
2808
- await new Promise((resolve6) => setTimeout(resolve6, backoffMs()));
3154
+ await new Promise((resolve7) => setTimeout(resolve7, backoffMs()));
2809
3155
  continue;
2810
3156
  }
2811
3157
  const holds = ownAsyncHolds();
@@ -2822,8 +3168,8 @@ async function withInstanceRegistryLock(target, op, waitMs = LOCK_WAIT_MS) {
2822
3168
  }
2823
3169
 
2824
3170
  // dist/scripts/lib/process-scan.mjs
2825
- import fs6 from "node:fs";
2826
- import path9 from "node:path";
3171
+ import fs7 from "node:fs";
3172
+ import path10 from "node:path";
2827
3173
  function runningOnWindows() {
2828
3174
  return process.platform === "win32";
2829
3175
  }
@@ -2841,13 +3187,13 @@ var FIELD_ORDER = Object.freeze(Object.keys(FIELD_COLUMNS));
2841
3187
  var ALL_PROCESS_FIELDS = Object.freeze(["pid", "ppid", "command"]);
2842
3188
  var FILTERABLE_COLUMNS = /* @__PURE__ */ new Set(["ProcessId", "Name", "CommandLine"]);
2843
3189
  function windowsExe(name) {
2844
- return path9.join(process.env.SystemRoot ?? path9.join("C:", "Windows"), "System32", name);
3190
+ return path10.join(process.env.SystemRoot ?? path10.join("C:", "Windows"), "System32", name);
2845
3191
  }
2846
3192
  function posixPsPath() {
2847
3193
  try {
2848
- if (fs6.existsSync("/bin/ps"))
3194
+ if (fs7.existsSync("/bin/ps"))
2849
3195
  return "/bin/ps";
2850
- if (fs6.existsSync("/usr/bin/ps"))
3196
+ if (fs7.existsSync("/usr/bin/ps"))
2851
3197
  return "/usr/bin/ps";
2852
3198
  } catch {
2853
3199
  }
@@ -2944,8 +3290,8 @@ function posixStartEnv() {
2944
3290
  }
2945
3291
  function readLinuxProcessStart(pid) {
2946
3292
  try {
2947
- const ticks = parseLinuxStatStart(fs6.readFileSync(`/proc/${assertPid(pid)}/stat`, "utf8"));
2948
- const boot = fs6.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
3293
+ const ticks = parseLinuxStatStart(fs7.readFileSync(`/proc/${assertPid(pid)}/stat`, "utf8"));
3294
+ const boot = fs7.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
2949
3295
  const offset = readBoottimeOffsetTicks();
2950
3296
  return ticks === void 0 || offset === void 0 || !/^[0-9a-f-]{36}$/.test(boot) ? void 0 : `${Number(ticks) - offset}@${boot}`;
2951
3297
  } catch {
@@ -2957,7 +3303,7 @@ var NSEC_PER_TICK = 1e9 / USER_HZ;
2957
3303
  function readBoottimeOffsetTicks() {
2958
3304
  let text;
2959
3305
  try {
2960
- text = fs6.readFileSync("/proc/self/timens_offsets", "utf8");
3306
+ text = fs7.readFileSync("/proc/self/timens_offsets", "utf8");
2961
3307
  } catch (error) {
2962
3308
  return (
2963
3309
  /** @type {NodeJS.ErrnoException} */
@@ -2979,7 +3325,7 @@ function parseLinuxStatStart(stat) {
2979
3325
  }
2980
3326
  function readLinuxPidNamespace(pid) {
2981
3327
  try {
2982
- return fs6.readlinkSync(`/proc/${assertPid(pid)}/ns/pid`);
3328
+ return fs7.readlinkSync(`/proc/${assertPid(pid)}/ns/pid`);
2983
3329
  } catch {
2984
3330
  return void 0;
2985
3331
  }
@@ -3242,7 +3588,7 @@ function subagentLightModeNotice() {
3242
3588
 
3243
3589
  // dist/clients/instance-registry.js
3244
3590
  function registryPath() {
3245
- return path10.join(getGlobalPiLensDir(), "instances.json");
3591
+ return path11.join(getGlobalPiLensDir(), "instances.json");
3246
3592
  }
3247
3593
  function startReadOptions() {
3248
3594
  return {
@@ -3272,7 +3618,7 @@ function recordCorruptRegistryRead(reasonCode) {
3272
3618
  }
3273
3619
  async function readRegistryAsync() {
3274
3620
  try {
3275
- const raw = await fs7.promises.readFile(registryPath(), "utf-8");
3621
+ const raw = await fs8.promises.readFile(registryPath(), "utf-8");
3276
3622
  const parsed = JSON.parse(raw);
3277
3623
  if (parsed && Array.isArray(parsed.instances)) {
3278
3624
  return parsed;
@@ -3294,7 +3640,7 @@ async function writeRegistryAsync(file) {
3294
3640
  const dir = getGlobalPiLensDir();
3295
3641
  const target = registryPath();
3296
3642
  try {
3297
- await fs7.promises.mkdir(dir, { recursive: true });
3643
+ await fs8.promises.mkdir(dir, { recursive: true });
3298
3644
  } catch {
3299
3645
  return;
3300
3646
  }
@@ -3708,8 +4054,8 @@ async function sweepAtomicWriteStages(directories, options = {}) {
3708
4054
  var KILL_VERIFY_ATTEMPTS = 5;
3709
4055
  var KILL_VERIFY_INTERVAL_MS = 100;
3710
4056
  function sleepUnref(ms) {
3711
- return new Promise((resolve6) => {
3712
- const timer = setTimeout(resolve6, ms);
4057
+ return new Promise((resolve7) => {
4058
+ const timer = setTimeout(resolve7, ms);
3713
4059
  timer.unref();
3714
4060
  });
3715
4061
  }
@@ -3727,9 +4073,9 @@ async function killPidTree(pid, options = {}) {
3727
4073
  stdio: "ignore"
3728
4074
  });
3729
4075
  unrefChildAndPipes(killer);
3730
- await new Promise((resolve6) => {
3731
- killer.once("close", () => resolve6());
3732
- killer.once("error", () => resolve6());
4076
+ await new Promise((resolve7) => {
4077
+ killer.once("close", () => resolve7());
4078
+ killer.once("error", () => resolve7());
3733
4079
  });
3734
4080
  } catch {
3735
4081
  }
@@ -4016,9 +4362,9 @@ async function sampleProcessTreeCpuPercent(pid, windowMs = 1200, floorPercent =
4016
4362
  }
4017
4363
  };
4018
4364
  const first = await readOnce();
4019
- const second = await new Promise((resolve6) => {
4365
+ const second = await new Promise((resolve7) => {
4020
4366
  const timer = setTimeout(() => {
4021
- void readOnce().then(resolve6);
4367
+ void readOnce().then(resolve7);
4022
4368
  }, windowMs);
4023
4369
  timer.unref?.();
4024
4370
  });
@@ -4163,7 +4509,7 @@ async function cwdIsUnresolvable(cwd) {
4163
4509
  if (cwd === void 0)
4164
4510
  return false;
4165
4511
  try {
4166
- return !(await fs8.promises.stat(cwd)).isDirectory();
4512
+ return !(await fs9.promises.stat(cwd)).isDirectory();
4167
4513
  } catch {
4168
4514
  return true;
4169
4515
  }
@@ -4172,7 +4518,7 @@ function cwdIsUnresolvableSync(cwd) {
4172
4518
  if (cwd === void 0)
4173
4519
  return false;
4174
4520
  try {
4175
- return !fs8.statSync(cwd).isDirectory();
4521
+ return !fs9.statSync(cwd).isDirectory();
4176
4522
  } catch {
4177
4523
  return true;
4178
4524
  }
@@ -4185,19 +4531,19 @@ function commandProbablyPresent(command) {
4185
4531
  const existsWithExt = (base) => {
4186
4532
  for (const ext of exts) {
4187
4533
  try {
4188
- if (fs8.existsSync(base + ext))
4534
+ if (fs9.existsSync(base + ext))
4189
4535
  return true;
4190
4536
  } catch {
4191
4537
  }
4192
4538
  }
4193
4539
  return false;
4194
4540
  };
4195
- if (path11.isAbsolute(command))
4541
+ if (path12.isAbsolute(command))
4196
4542
  return existsWithExt(command);
4197
4543
  if (command.includes("/") || command.includes("\\"))
4198
4544
  return "ambiguous";
4199
- for (const dir of (process.env.PATH ?? "").split(path11.delimiter)) {
4200
- if (dir && existsWithExt(path11.join(dir, command)))
4545
+ for (const dir of (process.env.PATH ?? "").split(path12.delimiter)) {
4546
+ if (dir && existsWithExt(path12.join(dir, command)))
4201
4547
  return true;
4202
4548
  }
4203
4549
  return false;
@@ -4267,7 +4613,7 @@ var PROC_PPID_READABLE = (() => {
4267
4613
  if (process.platform !== "linux")
4268
4614
  return false;
4269
4615
  try {
4270
- return /^PPid:\s*\d+$/m.test(fs8.readFileSync("/proc/self/status", "utf8"));
4616
+ return /^PPid:\s*\d+$/m.test(fs9.readFileSync("/proc/self/status", "utf8"));
4271
4617
  } catch {
4272
4618
  return false;
4273
4619
  }
@@ -4298,7 +4644,15 @@ function holdOwnChildPid(pid, site) {
4298
4644
  return owned;
4299
4645
  verifiedOwnPids.delete(pid);
4300
4646
  sweepHeldOwnPids();
4301
- heldOwnPids.add(pid);
4647
+ const evicted = heldOwnPids.add(pid);
4648
+ if (evicted.length > 0) {
4649
+ incrementDegradationCount({
4650
+ kind: "held-own-pid-evicted",
4651
+ subject: site,
4652
+ reason: `held-pid set full of live groups at ${HELD_OWN_PID_SWEEP_AT}; dropped oldest pid ${evicted.join(",")}, a group kill after its leader dies is refused`,
4653
+ metadata: { evicted: evicted.length }
4654
+ });
4655
+ }
4302
4656
  return true;
4303
4657
  }
4304
4658
  function releaseOwnChildPid(pid) {
@@ -4325,7 +4679,7 @@ function isOwnLiveChild(pid, site, handle) {
4325
4679
  }
4326
4680
  let status;
4327
4681
  try {
4328
- status = fs8.readFileSync(`/proc/${pid}/status`, "utf8");
4682
+ status = fs9.readFileSync(`/proc/${pid}/status`, "utf8");
4329
4683
  } catch {
4330
4684
  return heldOwnPids.has(pid) || verifiedOwnPids.has(pid);
4331
4685
  }
@@ -4450,13 +4804,13 @@ function mergeWindowsEnvironment(base, overrides) {
4450
4804
  merged[key] = value;
4451
4805
  return merged;
4452
4806
  }
4807
+ function windowsEnvironmentKeys(env, name) {
4808
+ const folded = name.toLowerCase();
4809
+ return Object.keys(env).filter((key) => key.toLowerCase() === folded);
4810
+ }
4453
4811
  function getWindowsEnvironmentValue(env, name) {
4454
- let value;
4455
- for (const [key, entry] of Object.entries(env)) {
4456
- if (key.toLowerCase() === name.toLowerCase())
4457
- value = entry;
4458
- }
4459
- return value;
4812
+ const key = windowsEnvironmentKeys(env, name).at(-1);
4813
+ return key === void 0 ? void 0 : env[key];
4460
4814
  }
4461
4815
  function driveLetter(value) {
4462
4816
  const match = /^([A-Za-z]):/.exec(value);
@@ -4481,30 +4835,30 @@ function isRootedWindowsPath(value) {
4481
4835
  function resolveRootedWindowsPath(value, driveSource) {
4482
4836
  const drive = driveLetter(driveSource);
4483
4837
  if (drive === void 0)
4484
- return path11.win32.normalize(value);
4485
- return path11.win32.normalize(path11.win32.resolve(`${drive}:\\`, value));
4838
+ return path12.win32.normalize(value);
4839
+ return path12.win32.normalize(path12.win32.resolve(`${drive}:\\`, value));
4486
4840
  }
4487
4841
  function getValidatedPerDriveCwd(env, drive) {
4488
4842
  const value = getWindowsEnvironmentValue(env, `=${drive}:`);
4489
4843
  if (value === void 0 || !isDriveAbsolute(value, drive))
4490
4844
  return void 0;
4491
- return path11.win32.normalize(value);
4845
+ return path12.win32.normalize(value);
4492
4846
  }
4493
4847
  function resolveEffectiveWindowsCwd(cwd, env) {
4494
4848
  if (cwd === void 0) {
4495
- return path11.win32.normalize(process.cwd());
4849
+ return path12.win32.normalize(process.cwd());
4496
4850
  }
4497
4851
  const requestedDrive = driveLetter(cwd);
4498
4852
  if (requestedDrive !== void 0 && !isDriveAbsoluteAnyDrive(cwd)) {
4499
4853
  const base = getValidatedPerDriveCwd(env, requestedDrive);
4500
- return base === void 0 ? void 0 : path11.win32.normalize(path11.win32.resolve(base, cwd));
4854
+ return base === void 0 ? void 0 : path12.win32.normalize(path12.win32.resolve(base, cwd));
4501
4855
  }
4502
4856
  if (isFullyQualifiedWindowsPath(cwd))
4503
- return path11.win32.normalize(cwd);
4857
+ return path12.win32.normalize(cwd);
4504
4858
  if (isRootedWindowsPath(cwd)) {
4505
4859
  return resolveRootedWindowsPath(cwd, process.cwd());
4506
4860
  }
4507
- return path11.win32.normalize(path11.win32.resolve(process.cwd(), cwd));
4861
+ return path12.win32.normalize(path12.win32.resolve(process.cwd(), cwd));
4508
4862
  }
4509
4863
  function resolveDriveRelativeWindowsPath(value, effectiveCwd, env) {
4510
4864
  const drive = driveLetter(value);
@@ -4514,20 +4868,20 @@ function resolveDriveRelativeWindowsPath(value, effectiveCwd, env) {
4514
4868
  const base = cwdDrive?.toUpperCase() === drive ? effectiveCwd : getValidatedPerDriveCwd(env, drive);
4515
4869
  if (base === void 0)
4516
4870
  return void 0;
4517
- return path11.win32.normalize(path11.win32.resolve(base, value));
4871
+ return path12.win32.normalize(path12.win32.resolve(base, value));
4518
4872
  }
4519
4873
  function resolveWindowsPathEntry(entry, effectiveCwd, env) {
4520
4874
  if (driveLetter(entry) !== void 0 && !isDriveAbsoluteAnyDrive(entry)) {
4521
4875
  return resolveDriveRelativeWindowsPath(entry, effectiveCwd, env);
4522
4876
  }
4523
4877
  if (isFullyQualifiedWindowsPath(entry))
4524
- return path11.win32.normalize(entry);
4878
+ return path12.win32.normalize(entry);
4525
4879
  if (isRootedWindowsPath(entry)) {
4526
4880
  return effectiveCwd === void 0 ? void 0 : resolveRootedWindowsPath(entry, effectiveCwd);
4527
4881
  }
4528
4882
  if (effectiveCwd === void 0)
4529
4883
  return void 0;
4530
- return path11.win32.normalize(path11.win32.resolve(effectiveCwd, entry));
4884
+ return path12.win32.normalize(path12.win32.resolve(effectiveCwd, entry));
4531
4885
  }
4532
4886
  var WINDOWS_COMMAND_CACHE_MAX_ENTRIES = 256;
4533
4887
  var WINDOWS_COMMAND_NEGATIVE_CACHE_TTL_MS = 1e3;
@@ -4545,14 +4899,14 @@ function getPathExts(env) {
4545
4899
  }
4546
4900
  function statIsFile(candidate) {
4547
4901
  try {
4548
- return fs8.statSync(candidate).isFile();
4902
+ return fs9.statSync(candidate).isFile();
4549
4903
  } catch {
4550
4904
  return false;
4551
4905
  }
4552
4906
  }
4553
4907
  function resolveWindowsCommandUncached(command, effectiveCwd, env) {
4554
4908
  const pathExts = getPathExts(env);
4555
- const existingExt = path11.win32.extname(command).toLowerCase();
4909
+ const existingExt = path12.win32.extname(command).toLowerCase();
4556
4910
  const hasExplicitExt = existingExt.length > 0;
4557
4911
  const isKnownExecutableExt = (ext) => WINDOWS_DIRECT_RESOLVABLE_EXTS.has(ext) || pathExts.includes(ext);
4558
4912
  const tryBase = (base) => {
@@ -4573,25 +4927,25 @@ function resolveWindowsCommandUncached(command, effectiveCwd, env) {
4573
4927
  if (hasPathSep || hasDrivePrefix || isFullyQualifiedWindowsPath(command)) {
4574
4928
  let base;
4575
4929
  if (isFullyQualifiedWindowsPath(command)) {
4576
- base = path11.win32.normalize(command);
4930
+ base = path12.win32.normalize(command);
4577
4931
  } else if (hasDrivePrefix) {
4578
4932
  base = resolveDriveRelativeWindowsPath(command, effectiveCwd, env);
4579
4933
  } else if (isRootedWindowsPath(command)) {
4580
4934
  base = effectiveCwd === void 0 ? void 0 : resolveRootedWindowsPath(command, effectiveCwd);
4581
4935
  } else if (effectiveCwd !== void 0) {
4582
- base = path11.win32.normalize(path11.win32.resolve(effectiveCwd, command));
4936
+ base = path12.win32.normalize(path12.win32.resolve(effectiveCwd, command));
4583
4937
  }
4584
4938
  return base === void 0 ? null : tryBase(base);
4585
4939
  }
4586
4940
  const pathValue = getWindowsEnvironmentValue(env, "PATH") ?? "";
4587
- const pathDirs = pathValue.split(path11.win32.delimiter);
4941
+ const pathDirs = pathValue.split(path12.win32.delimiter);
4588
4942
  for (const dir of pathDirs) {
4589
4943
  if (!dir)
4590
4944
  continue;
4591
4945
  const resolvedDir = resolveWindowsPathEntry(dir, effectiveCwd, env);
4592
4946
  if (resolvedDir === void 0)
4593
4947
  continue;
4594
- const found = tryBase(path11.win32.join(resolvedDir, command));
4948
+ const found = tryBase(path12.win32.join(resolvedDir, command));
4595
4949
  if (found)
4596
4950
  return found;
4597
4951
  }
@@ -4638,6 +4992,113 @@ function getSpawnEnvironment(overrides, stripNpmConfig) {
4638
4992
  }
4639
4993
  return stripped;
4640
4994
  }
4995
+ function isSpawnLookup(command) {
4996
+ if (process.platform !== "win32")
4997
+ return !command.includes("/");
4998
+ return !/[\\/]/.test(command) && driveLetter(command) === void 0;
4999
+ }
5000
+ function searchPathEntryDir(entry, cwd, env) {
5001
+ if (process.platform === "win32") {
5002
+ if (entry === "")
5003
+ return void 0;
5004
+ return resolveWindowsPathEntry(entry, resolveEffectiveWindowsCwd(cwd, env), env);
5005
+ }
5006
+ return posixSearchPathEntryDir(entry, cwd);
5007
+ }
5008
+ function posixSearchPathEntryDir(entry, cwd) {
5009
+ if (entry === "")
5010
+ return cwd;
5011
+ return path12.isAbsolute(entry) ? entry : `${cwd}${path12.sep}${entry}`;
5012
+ }
5013
+ function trustScopedSearchPath(pathValue, cwd = process.cwd(), env = process.env) {
5014
+ if (pathValue === void 0)
5015
+ return void 0;
5016
+ const trust = getProjectTrustState();
5017
+ if (trust === "trusted")
5018
+ return pathValue;
5019
+ const owned = sessionRepositoryJudge();
5020
+ const kept = [];
5021
+ for (const entry of pathValue.split(path12.delimiter)) {
5022
+ const dir = searchPathEntryDir(entry, cwd, env);
5023
+ if (dir === void 0 || !owned(dir)) {
5024
+ kept.push(entry);
5025
+ continue;
5026
+ }
5027
+ const real = realpathOrResolve(dir);
5028
+ if (recordDegradationOnce({
5029
+ kind: "trust-refusal",
5030
+ subject: `project-path-entry:${real}`,
5031
+ reason: `search-path entry inside the project ignored: pi project trust is ${trust}`
5032
+ })) {
5033
+ logExtension({
5034
+ subsystem: "project-trust",
5035
+ level: "warn",
5036
+ message: "search-path entry inside the project ignored: mark the project trusted in pi or upgrade pi",
5037
+ metadata: { entry, dir: real, trust }
5038
+ });
5039
+ }
5040
+ }
5041
+ return kept.length > 0 ? kept.join(path12.delimiter) : void 0;
5042
+ }
5043
+ function trustScopedEnvironment(env, cwd = process.cwd()) {
5044
+ const keys = process.platform === "win32" ? windowsEnvironmentKeys(env, "PATH") : ["PATH"];
5045
+ const lastKey = keys.at(-1);
5046
+ if (lastKey === void 0)
5047
+ return env;
5048
+ const value = env[lastKey];
5049
+ const scoped = trustScopedSearchPath(value, cwd, env);
5050
+ if (scoped === value)
5051
+ return env;
5052
+ const next = { ...env };
5053
+ for (const key of keys) {
5054
+ if (scoped === void 0)
5055
+ delete next[key];
5056
+ else
5057
+ next[key] = scoped;
5058
+ }
5059
+ return next;
5060
+ }
5061
+ function resolveSearchPathCommand(command, pathValue, cwd) {
5062
+ if (pathValue === void 0)
5063
+ return void 0;
5064
+ for (const entry of pathValue.split(path12.delimiter)) {
5065
+ const dir = posixSearchPathEntryDir(entry, cwd);
5066
+ const candidate = `${dir}${path12.sep}${command}`;
5067
+ try {
5068
+ if (!fs9.statSync(candidate).isFile())
5069
+ continue;
5070
+ fs9.accessSync(candidate, fs9.constants.X_OK);
5071
+ return candidate;
5072
+ } catch {
5073
+ }
5074
+ }
5075
+ return void 0;
5076
+ }
5077
+ function admitSpawn(command, cwd, env) {
5078
+ if (getProjectTrustState() === "trusted")
5079
+ return { admitted: true, env };
5080
+ const childCwd = cwd ?? process.cwd();
5081
+ const scoped = trustScopedEnvironment(env, childCwd);
5082
+ if (!isSpawnLookup(command))
5083
+ return { admitted: true, env: scoped };
5084
+ const executable = process.platform === "win32" ? resolveWindowsCommandForEnvironment(command, cwd, scoped)?.resolvedPath : resolveSearchPathCommand(command, scoped.PATH, childCwd);
5085
+ if (executable === void 0 || !isSessionRepositoryPath(executable))
5086
+ return { admitted: true, env: scoped };
5087
+ recordProjectCommandRefusal(executable);
5088
+ return { admitted: false, executable };
5089
+ }
5090
+ function trustRefusalResult(command, executable) {
5091
+ const message = `Refusing to run "${command}": ${executable} is inside the project, which pi has not trusted (${getProjectTrustState()})`;
5092
+ const cause = Object.assign(new Error(message), { code: "EACCES" });
5093
+ return {
5094
+ stdout: "",
5095
+ stderr: message,
5096
+ status: null,
5097
+ error: cause,
5098
+ failure: "spawn",
5099
+ spawnFailure: new SpawnFailureError("trust-refused", message, cause)
5100
+ };
5101
+ }
4641
5102
  var CMD_UNSAFE_CHARS = /["%!\r\n]/;
4642
5103
  function findCmdUnsafeValue(command, args) {
4643
5104
  if (CMD_UNSAFE_CHARS.test(command))
@@ -4678,15 +5139,18 @@ function resetUtf8ConsoleCodePageStateForTests() {
4678
5139
  var EXIT_PIPE_IDLE_GRACE_MS = 100;
4679
5140
  var EXIT_PIPE_IDLE_MAX_WAIT_MS = 2e3;
4680
5141
  var SPAWN_SAMPLER_TEARDOWN_GRACE_MS = 5e3;
5142
+ var spawnAbortScope = new AsyncLocalStorage();
4681
5143
  async function safeSpawnAsync(command, args, options) {
4682
5144
  const configuredTimeout = options?.timeout !== void 0 && Number.isFinite(options.timeout) && options.timeout >= 0 ? options.timeout : 3e4;
4683
5145
  const deadlineRemaining = options?.deadlineAt !== void 0 && Number.isFinite(options.deadlineAt) ? options.deadlineAt - Date.now() : Number.POSITIVE_INFINITY;
4684
5146
  const timeout = Math.max(0, Math.min(configuredTimeout, deadlineRemaining));
4685
- const abortSignal = options?.signal ?? (options?.ignoreAmbientSignal ? void 0 : ambientAbortSignal);
4686
- return new Promise((resolve6) => {
5147
+ const callerSignal = options?.signal ?? (options?.ignoreAmbientSignal ? void 0 : ambientAbortSignal);
5148
+ const scopedSignal = spawnAbortScope.getStore();
5149
+ const abortSignal = scopedSignal && callerSignal ? AbortSignal.any([scopedSignal, callerSignal]) : scopedSignal ?? callerSignal;
5150
+ return new Promise((resolve7) => {
4687
5151
  if (abortSignal?.aborted) {
4688
5152
  const cause = new Error("Spawn aborted before start");
4689
- resolve6({
5153
+ resolve7({
4690
5154
  stdout: "",
4691
5155
  stderr: "",
4692
5156
  status: null,
@@ -4698,7 +5162,7 @@ async function safeSpawnAsync(command, args, options) {
4698
5162
  }
4699
5163
  if (timeout <= 0) {
4700
5164
  const cause = new Error(`Process timed out after ${timeout}ms`);
4701
- resolve6({
5165
+ resolve7({
4702
5166
  stdout: "",
4703
5167
  stderr: "",
4704
5168
  status: null,
@@ -4829,7 +5293,12 @@ async function safeSpawnAsync(command, args, options) {
4829
5293
  }
4830
5294
  };
4831
5295
  const isWindows2 = process.platform === "win32";
4832
- const spawnEnv = getSpawnEnvironment(options?.env, options?.stripNpmConfig);
5296
+ const admission = admitSpawn(command, options?.cwd, getSpawnEnvironment(options?.env, options?.stripNpmConfig));
5297
+ if (!admission.admitted) {
5298
+ resolve7(trustRefusalResult(command, admission.executable));
5299
+ return;
5300
+ }
5301
+ const spawnEnv = admission.env;
4833
5302
  const spawnCwd = isWindows2 ? resolveEffectiveWindowsCwd(options?.cwd, spawnEnv) ?? options?.cwd : options?.cwd;
4834
5303
  let spawnCmd = command;
4835
5304
  let spawnArgs = args;
@@ -4863,7 +5332,7 @@ async function safeSpawnAsync(command, args, options) {
4863
5332
  void classifySpawnFailure(resolutionError, {
4864
5333
  command,
4865
5334
  cwd: options?.cwd
4866
- }).then((spawnFailure) => resolve6({
5335
+ }).then((spawnFailure) => resolve7({
4867
5336
  stdout: "",
4868
5337
  stderr: "",
4869
5338
  status: null,
@@ -4886,7 +5355,7 @@ async function safeSpawnAsync(command, args, options) {
4886
5355
  });
4887
5356
  } catch (err) {
4888
5357
  const cause = toError(err);
4889
- void classifySpawnFailure(cause, { command, cwd: options?.cwd }).then((spawnFailure) => resolve6({
5358
+ void classifySpawnFailure(cause, { command, cwd: options?.cwd }).then((spawnFailure) => resolve7({
4890
5359
  stdout: "",
4891
5360
  stderr: "",
4892
5361
  status: null,
@@ -5179,7 +5648,7 @@ async function safeSpawnAsync(command, args, options) {
5179
5648
  deathObservedAtMs: closedAtMs,
5180
5649
  escalated: teardownEscalated
5181
5650
  });
5182
- resolve6({
5651
+ resolve7({
5183
5652
  stdout,
5184
5653
  stderr,
5185
5654
  status: null,
@@ -5194,7 +5663,7 @@ async function safeSpawnAsync(command, args, options) {
5194
5663
  });
5195
5664
  } else if (aborted) {
5196
5665
  const cause = new Error("Spawn aborted");
5197
- resolve6({
5666
+ resolve7({
5198
5667
  stdout,
5199
5668
  stderr,
5200
5669
  status: null,
@@ -5208,7 +5677,7 @@ async function safeSpawnAsync(command, args, options) {
5208
5677
  });
5209
5678
  } else if (signal) {
5210
5679
  const cause = new Error(`Process killed by signal: ${signal}`);
5211
- resolve6({
5680
+ resolve7({
5212
5681
  stdout,
5213
5682
  stderr,
5214
5683
  status: null,
@@ -5226,7 +5695,7 @@ async function safeSpawnAsync(command, args, options) {
5226
5695
  command,
5227
5696
  cwd: options?.cwd
5228
5697
  });
5229
- resolve6({
5698
+ resolve7({
5230
5699
  stdout,
5231
5700
  stderr,
5232
5701
  status: code,
@@ -5238,7 +5707,7 @@ async function safeSpawnAsync(command, args, options) {
5238
5707
  resourceUsage
5239
5708
  });
5240
5709
  } else {
5241
- resolve6({
5710
+ resolve7({
5242
5711
  stdout,
5243
5712
  stderr,
5244
5713
  status: code,
@@ -5270,7 +5739,7 @@ async function safeSpawnAsync(command, args, options) {
5270
5739
  else if (timedOut)
5271
5740
  failure = "timeout";
5272
5741
  const controlFailure = aborted ? new SpawnFailureError("killed", err.message, err) : timedOut ? new SpawnFailureError("timeout", err.message, err) : void 0;
5273
- const finish = (spawnFailure) => resolve6({
5742
+ const finish = (spawnFailure) => resolve7({
5274
5743
  stdout,
5275
5744
  stderr,
5276
5745
  status: null,
@@ -5310,10 +5779,13 @@ async function findCommandAsync(command) {
5310
5779
  const result = await safeSpawnAsync(finder, [command], { timeout: 5e3 });
5311
5780
  if (result.status !== 0 || result.error)
5312
5781
  return null;
5313
- return result.stdout.trim().split("\n")[0] || null;
5782
+ return admittedLookupAnswer(result.stdout);
5314
5783
  }
5315
5784
  function safeSpawn(command, args, options) {
5316
- const spawnEnv = getSpawnEnvironment(options?.env, options?.stripNpmConfig);
5785
+ const admission = admitSpawn(command, options?.cwd, getSpawnEnvironment(options?.env, options?.stripNpmConfig));
5786
+ if (!admission.admitted)
5787
+ return trustRefusalResult(command, admission.executable);
5788
+ const spawnEnv = admission.env;
5317
5789
  if (process.platform === "win32") {
5318
5790
  const spawnCwd = resolveEffectiveWindowsCwd(options?.cwd, spawnEnv) ?? options?.cwd;
5319
5791
  const resolved = resolveWindowsCommand(command, options?.cwd, spawnEnv);
@@ -5412,13 +5884,27 @@ function findCommand(command) {
5412
5884
  const result = safeSpawn(finder, [command], { timeout: 5e3 });
5413
5885
  if (result.status !== 0)
5414
5886
  return null;
5415
- return result.stdout.trim().split("\n")[0] || null;
5887
+ return admittedLookupAnswer(result.stdout);
5416
5888
  }
5417
5889
 
5418
5890
  export {
5419
5891
  noteSpawnTimeout,
5420
5892
  isInSpawnTimeoutCooldown,
5421
5893
  resetSpawnTimeoutCooldowns,
5894
+ createGitIdentityResolver,
5895
+ canonicalDirectory,
5896
+ resolveGitCheckout,
5897
+ resolveLinkedWorktreeOwner,
5898
+ listNestedLinkedWorktreeRoots,
5899
+ resolveGitIdentity,
5900
+ NODE_MODULES_BIN_DIRS,
5901
+ VENDOR_BIN_DIRS,
5902
+ VENV_BIN_DIRS,
5903
+ projectLocalBinDirs,
5904
+ isSessionRepositoryPath,
5905
+ isUntrustedProjectPath,
5906
+ recordProjectCommandRefusal,
5907
+ admittedLookupAnswer,
5422
5908
  isLockContention,
5423
5909
  recordGenerationTakeover,
5424
5910
  recordLegacyLockHeld,
@@ -5461,8 +5947,13 @@ export {
5461
5947
  mergeWindowsEnvironment,
5462
5948
  WINDOWS_COMMAND_CACHE_MAX_ENTRIES,
5463
5949
  resetSafeSpawnWindowsCommandCache,
5950
+ statIsFile,
5464
5951
  resolveWindowsCommandForEnvironment,
5952
+ trustScopedSearchPath,
5953
+ trustScopedEnvironment,
5954
+ resolveSearchPathCommand,
5465
5955
  resetUtf8ConsoleCodePageStateForTests,
5956
+ spawnAbortScope,
5466
5957
  safeSpawnAsync,
5467
5958
  safeSpawnBatch,
5468
5959
  isCommandAvailableAsync,
@@ -5493,8 +5984,3 @@ export {
5493
5984
  getKnipIgnorePatterns,
5494
5985
  isTestFile
5495
5986
  };
5496
- /*! Bundled license information:
5497
-
5498
- safe-buffer/index.js:
5499
- (*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
5500
- */