pi-lens 4.4.6 → 4.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/CHANGELOG.md +232 -0
  2. package/README.md +17 -3
  3. package/config/markdownlint/run-no-fix.mjs +36 -0
  4. package/dist/{chunk-ZQ6NZZTB.js → chunk-2453RRJ2.js} +44 -6
  5. package/dist/{chunk-GZE7WOI4.js → chunk-2BKUFQKR.js} +696 -330
  6. package/dist/chunk-2TS4GLOJ.js +31 -0
  7. package/dist/{chunk-2DMLM3ZO.js → chunk-2ZE3AUJQ.js} +12 -14
  8. package/dist/{chunk-OJLTLYHB.js → chunk-35WKJWO5.js} +51 -33
  9. package/dist/chunk-3JAHQBSY.js +27 -0
  10. package/dist/{chunk-PO45POGF.js → chunk-3O5EII3W.js} +2 -2
  11. package/dist/chunk-447YZL4S.js +25 -0
  12. package/dist/{chunk-TIYGSODX.js → chunk-4B2YFN4U.js} +28 -22
  13. package/dist/{chunk-OSTKYB55.js → chunk-4BKU7PV3.js} +1 -1
  14. package/dist/{chunk-XQCSWV2G.js → chunk-4LL2VRNY.js} +27 -28
  15. package/dist/{chunk-MA77RSFN.js → chunk-4NBWFYWW.js} +9 -9
  16. package/dist/{chunk-75SY4F24.js → chunk-4QG55RRC.js} +12 -12
  17. package/dist/{chunk-K2YGBXOA.js → chunk-4W52ZKZX.js} +2 -2
  18. package/dist/{chunk-Z2XAOKHK.js → chunk-565VRUP4.js} +2 -2
  19. package/dist/{chunk-CFRQMBGP.js → chunk-57X2CDRX.js} +23 -23
  20. package/dist/{chunk-XAIT2YGS.js → chunk-5F3XF3SX.js} +7 -15
  21. package/dist/{chunk-UHGF5UT5.js → chunk-5RNB4HVK.js} +1 -1
  22. package/dist/{chunk-Q4EMRFNA.js → chunk-5T5A6YAJ.js} +35 -34
  23. package/dist/{chunk-W5LGKNET.js → chunk-6FIRFP6A.js} +12 -12
  24. package/dist/{chunk-KLQVC3XC.js → chunk-6GMGEKQN.js} +36 -9
  25. package/dist/{chunk-UN4TEBWN.js → chunk-6LJOJ6EO.js} +20 -15
  26. package/dist/{chunk-HK6JVFZC.js → chunk-6YUNI7B5.js} +3 -3
  27. package/dist/{chunk-PKES3ISE.js → chunk-7ANZ7XDD.js} +2 -2
  28. package/dist/{chunk-VQH24FIP.js → chunk-7CGIDRIK.js} +16 -15
  29. package/dist/{chunk-SCIUNBPF.js → chunk-7MAD5ZAY.js} +16 -17
  30. package/dist/{chunk-OOU2WZZE.js → chunk-7TNILKGY.js} +1 -1
  31. package/dist/{chunk-LEJOJDXL.js → chunk-A5GRLYPZ.js} +9 -9
  32. package/dist/{chunk-AE37FEGH.js → chunk-AGGUWKRK.js} +1 -1
  33. package/dist/{chunk-BWYQUPOS.js → chunk-BBET6HD6.js} +1 -1
  34. package/dist/{chunk-GAACZY6R.js → chunk-BHWW6FAX.js} +14 -13
  35. package/dist/{chunk-A3YNG5KP.js → chunk-BOPDQ7AZ.js} +23 -21
  36. package/dist/{chunk-MKVZQUEG.js → chunk-BQG2QFVO.js} +215 -134
  37. package/dist/{chunk-EVDGNG4F.js → chunk-BUZIQDFS.js} +3 -3
  38. package/dist/{chunk-2PHMIAKO.js → chunk-CM73PPGD.js} +4 -4
  39. package/dist/{chunk-63RIVFQI.js → chunk-CUDD35TW.js} +10 -9
  40. package/dist/{chunk-BM5GS6ZH.js → chunk-CZL44WFN.js} +2 -2
  41. package/dist/{chunk-QGSTQH4D.js → chunk-DIWK3LBC.js} +12 -15
  42. package/dist/{chunk-JL6CXUMW.js → chunk-DYRZGUMA.js} +2 -2
  43. package/dist/{chunk-NDMCVUYK.js → chunk-FHEV6T4L.js} +22 -18
  44. package/dist/{chunk-4PCQCU47.js → chunk-FRLAUP2B.js} +4 -4
  45. package/dist/{chunk-RZOXUSPC.js → chunk-G5GV2Q7K.js} +2 -2
  46. package/dist/{chunk-2RLWJO5K.js → chunk-G6JKM4O7.js} +7 -7
  47. package/dist/chunk-GGYOZWHW.js +27 -0
  48. package/dist/{chunk-DC4CFXM5.js → chunk-GIRBSBGL.js} +6 -5
  49. package/dist/{chunk-PQJFG24Z.js → chunk-GMROJJRN.js} +1292 -946
  50. package/dist/{chunk-ZUUI3ZSA.js → chunk-HHR7WGCI.js} +3 -3
  51. package/dist/{chunk-TIQJPRDD.js → chunk-HKIL6DCL.js} +3 -2
  52. package/dist/{chunk-VPBIMOAQ.js → chunk-HUAM7QG3.js} +15 -13
  53. package/dist/{chunk-ZYNI26MI.js → chunk-HXFUTMX2.js} +2 -2
  54. package/dist/{chunk-W5R5SABV.js → chunk-I22THIHI.js} +12 -12
  55. package/dist/chunk-IE5D3RA5.js +58 -0
  56. package/dist/{chunk-MT6BVNFW.js → chunk-IYVYZQRL.js} +10 -16
  57. package/dist/{chunk-ARD426WI.js → chunk-JBP7KESM.js} +1 -1
  58. package/dist/{chunk-MN7MHUXQ.js → chunk-JE6HKLC7.js} +2 -2
  59. package/dist/{chunk-3MYEA7QD.js → chunk-JPRDTY5S.js} +85 -3
  60. package/dist/{chunk-CJYKEW2L.js → chunk-JYLOYTZD.js} +17 -1
  61. package/dist/{chunk-5APMQ2IJ.js → chunk-JZRP4DGP.js} +2 -2
  62. package/dist/{chunk-AMXIUN2R.js → chunk-KZ4ALBCH.js} +2 -2
  63. package/dist/{chunk-W2V54OCL.js → chunk-L3CLUGDY.js} +3 -3
  64. package/dist/{chunk-DMSLNKF7.js → chunk-L4NEVZ4T.js} +28 -27
  65. package/dist/chunk-LPYTPNOJ.js +22 -0
  66. package/dist/{chunk-BI5LAQ3Y.js → chunk-LSFXZLPW.js} +2071 -1725
  67. package/dist/{chunk-2DDDCJDL.js → chunk-MC6VB2E5.js} +4 -4
  68. package/dist/{chunk-U2SDMG7C.js → chunk-NM2NWH55.js} +5 -5
  69. package/dist/{chunk-Q4FCYCRE.js → chunk-NSPVR3FN.js} +19 -18
  70. package/dist/{chunk-VG5JS5SW.js → chunk-O2ARHQKF.js} +2 -2
  71. package/dist/{chunk-KSR7RGQY.js → chunk-O4N5BQ3T.js} +10 -10
  72. package/dist/{chunk-5ZR3APIM.js → chunk-OC7VWJBZ.js} +39 -40
  73. package/dist/chunk-OFNMHPBT.js +89 -0
  74. package/dist/{chunk-YSBHPOY6.js → chunk-OWTG6UMO.js} +21 -21
  75. package/dist/{chunk-7RQXA5GG.js → chunk-OY7WZI7Q.js} +13 -12
  76. package/dist/{chunk-5CV5ITZF.js → chunk-OZWXLJMX.js} +2 -2
  77. package/dist/{chunk-F6X3YJWD.js → chunk-PIQQM32Y.js} +2 -2
  78. package/dist/chunk-PKLB2XJL.js +8 -0
  79. package/dist/{chunk-DQXSPYRI.js → chunk-PKSUMEPT.js} +17 -4
  80. package/dist/{chunk-YISME6ON.js → chunk-PPKECBPP.js} +1 -1
  81. package/dist/{chunk-4AVZ3TG7.js → chunk-R2QQC33W.js} +14 -14
  82. package/dist/{chunk-GMTFDAOK.js → chunk-R4QWJQ2H.js} +11 -11
  83. package/dist/{chunk-V63BC55Q.js → chunk-RGGH6M34.js} +1 -1
  84. package/dist/{chunk-SJJYRZB4.js → chunk-RZG472YW.js} +116 -26
  85. package/dist/{chunk-NIU2IPC5.js → chunk-SDFKOLSF.js} +6 -6
  86. package/dist/{chunk-H7HTEQUZ.js → chunk-SFLHSL5R.js} +9 -9
  87. package/dist/{chunk-FA5LDARD.js → chunk-SP4TFY5F.js} +14 -13
  88. package/dist/{chunk-J6JP25XU.js → chunk-SQC7K3SP.js} +4 -3
  89. package/dist/{chunk-T7FTXGS3.js → chunk-T2S3FNNJ.js} +44 -42
  90. package/dist/{chunk-S67UJDGQ.js → chunk-TV6RXRYH.js} +10 -10
  91. package/dist/{chunk-GNSIWBAT.js → chunk-U3AS2FR6.js} +3 -3
  92. package/dist/{chunk-WIZWZR4C.js → chunk-UHHLR2VY.js} +43 -41
  93. package/dist/chunk-UYXV5NIS.js +20 -0
  94. package/dist/{chunk-VSFLRN5Y.js → chunk-VLQ7UKZH.js} +1 -1
  95. package/dist/{chunk-FFL3A2VP.js → chunk-VN3L2JWZ.js} +46 -72
  96. package/dist/{chunk-Z7IGUAXL.js → chunk-VOP4PJKA.js} +12 -8
  97. package/dist/{chunk-F5Z6URKM.js → chunk-VOXTCULR.js} +2 -2
  98. package/dist/{chunk-NNKXDXXS.js → chunk-VPLBLWFO.js} +14 -8
  99. package/dist/chunk-W3BGKBBK.js +27 -0
  100. package/dist/{chunk-ZKXQKGWZ.js → chunk-WC6WRNQT.js} +4 -3
  101. package/dist/{chunk-Q3UZHW6N.js → chunk-WMDUT4KH.js} +1150 -1138
  102. package/dist/{chunk-KXF5R4UN.js → chunk-WQV6BI4Q.js} +1 -1
  103. package/dist/chunk-WXUDRAG6.js +24 -0
  104. package/dist/{chunk-OLAWH5UQ.js → chunk-X35S7HSB.js} +29 -10
  105. package/dist/{chunk-YBSONGSZ.js → chunk-X66YJ2SS.js} +40 -34
  106. package/dist/{chunk-U6OC3QEM.js → chunk-XOMGO63G.js} +22 -21
  107. package/dist/{chunk-WQOIR3QY.js → chunk-XWIME22V.js} +13 -13
  108. package/dist/{chunk-3WEPUD2V.js → chunk-XYLC35E4.js} +202 -103
  109. package/dist/{chunk-UCGQT677.js → chunk-YHGYAEFH.js} +18 -18
  110. package/dist/{chunk-V3APN3DY.js → chunk-ZFORSIED.js} +13 -13
  111. package/dist/{chunk-BHUWL2Y3.js → chunk-ZKLTNLAW.js} +64 -73
  112. package/dist/chunk-ZONZ6YY3.js +74 -0
  113. package/dist/chunk-ZSM35JF4.js +30 -0
  114. package/dist/{chunk-PPIBVH4R.js → chunk-ZZDIOAAJ.js} +15 -6
  115. package/dist/index.js +8817 -6239
  116. package/dist/mcp/analyze-cli.js +10 -10
  117. package/dist/mcp/cli.js +44 -42
  118. package/dist/mcp/server.js +2236 -861
  119. package/dist/mcp/worker.js +62 -61
  120. package/dist/probes/installer.js +20 -19
  121. package/docs/adr/0003-git-guard-latch-writer.md +11 -6
  122. package/docs/agent-tools.md +29 -11
  123. package/docs/alignment-families.md +29 -0
  124. package/docs/ast-grep_rules_catalog.md +6 -4
  125. package/docs/ci-bot-pr-checks.md +126 -0
  126. package/docs/configuration.md +99 -3
  127. package/docs/defect-shapes.md +68 -11
  128. package/docs/dependencies.md +1 -0
  129. package/docs/engineering-principles.md +27 -2
  130. package/docs/environment-variables.md +14 -0
  131. package/docs/features.md +13 -3
  132. package/docs/globalconfig.md +12 -1
  133. package/docs/invariants/git-guard-host.md +38 -0
  134. package/docs/invariants/language-config.md +15 -4
  135. package/docs/invariants/lsp-trust-exec.md +22 -2
  136. package/docs/invariants/paths-os.md +4 -2
  137. package/docs/invariants/session-telemetry.md +42 -2
  138. package/docs/lsp-capability-matrix.md +208 -84
  139. package/docs/lsp-idle-eviction.md +3 -5
  140. package/docs/merge-queue-rollout.md +1 -1
  141. package/docs/pi-lens-fixer.md +31 -17
  142. package/docs/pi-lens-merge-policy.md +27 -15
  143. package/docs/pi-lens-monitor.md +9 -0
  144. package/docs/pi-lens-orchestration.md +4 -1
  145. package/docs/pi-lens-reviewer.md +5 -5
  146. package/docs/pi-lens-subagent.md +13 -7
  147. package/docs/public-api-stability.md +18 -2
  148. package/docs/schema/pi-lens-config-v1.json +33 -0
  149. package/docs/servercapabilities.md +1 -1
  150. package/docs/settings.md +15 -6
  151. package/docs/usage.md +5 -0
  152. package/docs/word-index.md +17 -5
  153. package/package.json +5 -3
  154. package/rules/ast-grep-rules/rule-tests/no-accumulating-spread-js-test.yml +37 -0
  155. package/rules/ast-grep-rules/rule-tests/ts-redundant-filter-map-test.yml +12 -1
  156. package/rules/ast-grep-rules/rule-tests-disabled/filter-then-map-js-test.yml +12 -0
  157. package/rules/ast-grep-rules/rule-tests-disabled/filter-then-map-test.yml +25 -0
  158. package/rules/ast-grep-rules/rules/no-accumulating-spread-js.yml +49 -1
  159. package/rules/ast-grep-rules/rules/ts-redundant-filter-map.yml +9 -1
  160. package/rules/ast-grep-rules/rules-disabled/filter-then-map-js.yml +17 -0
  161. package/rules/ast-grep-rules/rules-disabled/filter-then-map.yml +36 -0
  162. package/rules/ast-grep-rules/self-scan-baseline.json +1 -1
  163. package/dist/chunk-2F47TQOA.js +0 -73
  164. package/dist/chunk-2X4VLOCC.js +0 -55
  165. package/dist/chunk-4WX4CTUE.js +0 -57
  166. package/dist/chunk-FJIVKLPH.js +0 -31
  167. package/dist/chunk-G2B7F6ZU.js +0 -88
  168. package/dist/chunk-GTAI2J6U.js +0 -27
  169. package/dist/chunk-IPDG45G5.js +0 -26
  170. package/dist/chunk-P4QNXS6I.js +0 -27
  171. package/dist/chunk-Q6D6VMI4.js +0 -22
  172. package/dist/chunk-SXGD4ANG.js +0 -25
  173. package/dist/chunk-XCUHKYCQ.js +0 -23
  174. package/dist/chunk-YRD4ISED.js +0 -30
@@ -13,7 +13,7 @@ import {
13
13
  reportPiLensConfigRecords,
14
14
  resolveOnePiLensConfigDocument,
15
15
  warnIgnoredConfigOnce
16
- } from "./chunk-OLAWH5UQ.js";
16
+ } from "./chunk-X35S7HSB.js";
17
17
  import {
18
18
  CANONICAL_GLOBAL_CONFIG_FILE,
19
19
  FRESHNESS_CADENCE_MS,
@@ -23,7 +23,7 @@ import {
23
23
  errorClassName,
24
24
  getPiLensGlobalConfigPath,
25
25
  getProductionGlobalConfigResolution
26
- } from "./chunk-J6JP25XU.js";
26
+ } from "./chunk-SQC7K3SP.js";
27
27
  import {
28
28
  DEFAULT_MAX_OUTPUT_BYTES,
29
29
  createBoundedOutputSink,
@@ -31,7 +31,7 @@ import {
31
31
  truncatedByOutputCap,
32
32
  writeFileAtomic,
33
33
  writeFileAtomicAsync
34
- } from "./chunk-MN7MHUXQ.js";
34
+ } from "./chunk-JE6HKLC7.js";
35
35
  import {
36
36
  GLOBAL_NON_FLAG_CONFIG_SECTIONS,
37
37
  LENS_FLAGS,
@@ -47,17 +47,17 @@ import {
47
47
  readToolConfig,
48
48
  recordDegradation,
49
49
  recordDegradationOnce
50
- } from "./chunk-ZQ6NZZTB.js";
50
+ } from "./chunk-2453RRJ2.js";
51
51
  import {
52
52
  logExtension
53
- } from "./chunk-KXF5R4UN.js";
53
+ } from "./chunk-WQV6BI4Q.js";
54
54
  import {
55
55
  logLatency
56
- } from "./chunk-Z2XAOKHK.js";
56
+ } from "./chunk-565VRUP4.js";
57
57
  import {
58
58
  getProcessSingleton,
59
59
  machineStateDir
60
- } from "./chunk-VSFLRN5Y.js";
60
+ } from "./chunk-VLQ7UKZH.js";
61
61
  import {
62
62
  STAGE_TMP_PATTERN,
63
63
  stagePathFor,
@@ -82,10 +82,11 @@ import {
82
82
  normalizePathSpelling,
83
83
  pathsEqual,
84
84
  realpathOrResolve,
85
+ relativeInside,
85
86
  toPosix,
86
87
  toProjectRelativePath,
87
88
  walkUpDirs
88
- } from "./chunk-PQJFG24Z.js";
89
+ } from "./chunk-GMROJJRN.js";
89
90
  import {
90
91
  __commonJS,
91
92
  __require,
@@ -1138,571 +1139,935 @@ function admittedLookupAnswer(stdout) {
1138
1139
  return null;
1139
1140
  }
1140
1141
 
1141
- // dist/clients/resource-sampler.js
1142
- var import_pidusage = __toESM(require_pidusage(), 1);
1143
-
1144
- // dist/clients/instance-reaper.js
1145
- import { spawn as nodeSpawn2 } from "node:child_process";
1146
-
1147
- // dist/clients/bounded-pid-file-lock.js
1148
- import { randomUUID } from "node:crypto";
1149
- import * as fs4 from "node:fs";
1150
- import fsp from "node:fs/promises";
1151
- import path4 from "node:path";
1152
-
1153
- // dist/clients/generation-lock.js
1154
- import { randomInt } from "node:crypto";
1155
- import * as fs3 from "node:fs";
1156
- import * as path3 from "node:path";
1157
- var GENERATION = /^lock\.(\d+)(\.released)?$/;
1158
- function pidFileOwner(file) {
1142
+ // dist/clients/child-unref.js
1143
+ import { spawn as nodeSpawn } from "node:child_process";
1144
+ function unrefChildAndPipes(child) {
1159
1145
  try {
1160
- const pid = Number(fs3.readFileSync(file, "utf8").trim().split(/\s+/)[0]);
1161
- return Number.isInteger(pid) && pid > 0 ? pid : void 0;
1146
+ child.unref();
1147
+ for (const stream of [child.stdout, child.stderr, child.stdin]) {
1148
+ stream?.unref?.();
1149
+ }
1162
1150
  } catch {
1163
- return void 0;
1164
1151
  }
1165
1152
  }
1166
- function isPidAlive(pid) {
1167
- if (pid === void 0)
1168
- return false;
1153
+ function spawnCollectStdoutResult(command, args, options, collectOptions = {}) {
1154
+ return new Promise((resolve7) => {
1155
+ let settled = false;
1156
+ let timer;
1157
+ const settle = (result) => {
1158
+ if (settled)
1159
+ return;
1160
+ settled = true;
1161
+ if (timer)
1162
+ clearTimeout(timer);
1163
+ resolve7(result);
1164
+ };
1165
+ try {
1166
+ const child = nodeSpawn(command, args, options);
1167
+ unrefChildAndPipes(child);
1168
+ const out = createBoundedOutputSink();
1169
+ child.stdout?.on("data", (chunk) => out.append(chunk));
1170
+ child.once("error", (error) => settle({ stdout: "", status: "spawn-error", error }));
1171
+ child.once("close", (code, signal) => settle(code === 0 && signal === null ? { stdout: out.text, status: "ok" } : {
1172
+ stdout: "",
1173
+ status: "exit-error",
1174
+ exitCode: code,
1175
+ exitSignal: signal
1176
+ }));
1177
+ const timeoutMs = collectOptions.timeoutMs;
1178
+ if (typeof timeoutMs === "number" && timeoutMs > 0) {
1179
+ timer = setTimeout(() => {
1180
+ void terminateTimedOutChild(child, collectOptions.onTimeout).then((timeoutKill) => settle({ stdout: out.text, status: "timeout", timeoutKill }));
1181
+ }, timeoutMs);
1182
+ timer.unref();
1183
+ }
1184
+ } catch (error) {
1185
+ settle({ stdout: "", status: "spawn-error", error });
1186
+ }
1187
+ });
1188
+ }
1189
+ async function terminateTimedOutChild(child, onTimeout) {
1190
+ if (onTimeout) {
1191
+ try {
1192
+ return await onTimeout(child);
1193
+ } catch {
1194
+ return "unverified";
1195
+ }
1196
+ }
1169
1197
  try {
1170
- process.kill(pid, 0);
1171
- return true;
1172
- } catch (error) {
1173
- return error?.code !== "ESRCH";
1198
+ child.kill();
1199
+ } catch {
1174
1200
  }
1201
+ return "unverified";
1175
1202
  }
1176
- function pidFileIsStale(file, staleMs) {
1203
+
1204
+ // dist/scripts/lib/process-scan.mjs
1205
+ import fs3 from "node:fs";
1206
+ import path3 from "node:path";
1207
+ function runningOnWindows() {
1208
+ return process.platform === "win32";
1209
+ }
1210
+ var FIELD_COLUMNS = Object.freeze({
1211
+ pid: { wmi: "ProcessId", ps: "pid", token: "int" },
1212
+ ppid: { wmi: "ParentProcessId", ps: "ppid", token: "int" },
1213
+ ageMs: { wmi: "CreationDate", ps: "etime", token: "age" },
1214
+ rssBytes: { wmi: "WorkingSetSize", ps: null, token: "int" },
1215
+ cpuKernel100ns: { wmi: "KernelModeTime", ps: null, token: "int" },
1216
+ cpuUser100ns: { wmi: "UserModeTime", ps: null, token: "int" },
1217
+ startedAt: { wmi: "CreationDate", ps: "lstart", token: "lstart" },
1218
+ command: { wmi: "CommandLine", ps: "args", token: "tail" }
1219
+ });
1220
+ var FIELD_ORDER = Object.freeze(Object.keys(FIELD_COLUMNS));
1221
+ var ALL_PROCESS_FIELDS = Object.freeze(["pid", "ppid", "command"]);
1222
+ var FILTERABLE_COLUMNS = /* @__PURE__ */ new Set(["ProcessId", "Name", "CommandLine"]);
1223
+ function windowsExe(name) {
1224
+ return path3.win32.join(process.env.SystemRoot ?? path3.win32.join("C:", "Windows"), "System32", name);
1225
+ }
1226
+ function posixPsPath() {
1177
1227
  try {
1178
- const stat = fs3.statSync(file);
1179
- if (Date.now() - stat.mtimeMs > staleMs)
1180
- return true;
1181
- const pid = pidFileOwner(file);
1182
- return pid !== void 0 && !isPidAlive(pid);
1228
+ if (fs3.existsSync("/bin/ps"))
1229
+ return "/bin/ps";
1230
+ if (fs3.existsSync("/usr/bin/ps"))
1231
+ return "/usr/bin/ps";
1183
1232
  } catch {
1184
- return false;
1185
1233
  }
1234
+ return "/bin/ps";
1186
1235
  }
1187
- function isLockContention(error) {
1188
- const code = error?.code;
1189
- return code === "EEXIST" || code === "EPERM" || code === "EBUSY";
1236
+ function normalizeProcessFields(fields) {
1237
+ const requested = new Set((fields ?? ALL_PROCESS_FIELDS).filter((field) => field in FIELD_COLUMNS));
1238
+ requested.add("pid");
1239
+ return FIELD_ORDER.filter((field) => requested.has(field));
1190
1240
  }
1191
- function generationPath(dir, generation) {
1192
- return path3.join(dir, `lock.${generation}`);
1241
+ function escapeWqlLikeValue(value) {
1242
+ return String(value).replaceAll("'", "''").replaceAll(/[%_]/g, (ch) => `[${ch}]`);
1193
1243
  }
1194
- function releasedName(generation) {
1195
- return `lock.${generation}.released`;
1244
+ function escapeWqlStringValue(value) {
1245
+ return String(value).replaceAll("'", "''");
1196
1246
  }
1197
- function topGeneration(entries) {
1198
- let top = 0;
1199
- for (const name of entries) {
1200
- const match = GENERATION.exec(name);
1201
- if (match && !match[2])
1202
- top = Math.max(top, Number(match[1]));
1247
+ function assertPid(value) {
1248
+ const pid = Number(value);
1249
+ if (!Number.isInteger(pid) || pid <= 0) {
1250
+ throw new Error(`process filter: invalid pid ${String(value)}`);
1203
1251
  }
1204
- return top;
1252
+ return pid;
1205
1253
  }
1206
- function removeBelowPredecessor(dir, entries, generation) {
1207
- for (const name of entries) {
1208
- const match = GENERATION.exec(name);
1209
- if (!match || Number(match[1]) + 1 >= generation)
1210
- continue;
1211
- try {
1212
- fs3.unlinkSync(path3.join(dir, name));
1213
- } catch {
1214
- }
1254
+ function wqlFilterExpression(filter) {
1255
+ const { column, op, values } = filter;
1256
+ if (!FILTERABLE_COLUMNS.has(column)) {
1257
+ throw new Error(`process filter: unsupported column ${String(column)}`);
1215
1258
  }
1216
- }
1217
- function recordGenerationTakeover(hold) {
1218
- incrementDegradationCount({
1219
- kind: "generation-lock-stale-takeover",
1220
- subject: path3.resolve(hold.dir),
1221
- reason: `took over lock generation ${hold.generation - 1} from a dead or aged-out holder`
1222
- });
1223
- }
1224
- function recordLegacyLockHeld(legacyPath) {
1225
- incrementDegradationCount({
1226
- kind: "generation-lock-legacy-held",
1227
- subject: path3.resolve(legacyPath),
1228
- reason: `backed off: ${path3.basename(legacyPath)} is held by another writer (one from before #3476, or a holder past the generation lease)`
1229
- });
1230
- }
1231
- function releaseGeneration(hold) {
1232
- try {
1233
- fs3.writeFileSync(path3.join(hold.dir, releasedName(hold.generation)), "");
1234
- } catch {
1259
+ const list = [...values];
1260
+ if (list.length === 0) {
1261
+ throw new Error(`process filter: ${column} filter has no values`);
1262
+ }
1263
+ if (column === "ProcessId") {
1264
+ return list.map((value) => `ProcessId=${assertPid(value)}`).join(" OR ");
1265
+ }
1266
+ if (op === "like") {
1267
+ return list.map((value) => `${column} LIKE '%${escapeWqlLikeValue(value)}%'`).join(" OR ");
1235
1268
  }
1269
+ return list.map((value) => `${column} = '${escapeWqlStringValue(value)}'`).join(" OR ");
1236
1270
  }
1237
- function heartbeatIntervalMs(leaseMs) {
1238
- return Math.max(1e3, Math.floor(leaseMs / 4));
1271
+ function buildProcessQuery(fields = ALL_PROCESS_FIELDS, options = {}) {
1272
+ const layout = normalizeProcessFields(fields);
1273
+ const filter = options.filter;
1274
+ if (runningOnWindows()) {
1275
+ const columns2 = [
1276
+ ...new Set(layout.map((field) => FIELD_COLUMNS[field].wmi))
1277
+ ];
1278
+ const where = filter ? ` WHERE ${wqlFilterExpression(filter)}` : "";
1279
+ const excludeSelf = options.excludeSelfPid ? " | Where-Object { $_.ProcessId -ne $PID }" : "";
1280
+ const prelude = (layout.includes("ageMs") ? "$age = if ($_.CreationDate -is [datetime]) { [int64]((Get-Date) - $_.CreationDate).TotalMilliseconds } else { '' }; " : "") + (layout.includes("startedAt") ? "$st = if ($_.CreationDate -is [datetime]) { $_.CreationDate.ToUniversalTime().ToString('o') } else { '' }; " : "");
1281
+ const row = layout.map((field) => {
1282
+ if (field === "ageMs")
1283
+ return "$age";
1284
+ if (field === "startedAt")
1285
+ return "$st";
1286
+ return `$($_.${FIELD_COLUMNS[field].wmi})`;
1287
+ }).join("`t");
1288
+ return {
1289
+ command: windowsExe("WindowsPowerShell\\v1.0\\powershell.exe"),
1290
+ args: [
1291
+ "-NoProfile",
1292
+ "-NonInteractive",
1293
+ "-Command",
1294
+ `Get-CimInstance -Query "SELECT ${columns2.join(",")} FROM Win32_Process${where}"${excludeSelf} | ForEach-Object { ${prelude}"${row}" }`
1295
+ ],
1296
+ tabSeparated: true,
1297
+ fields: layout,
1298
+ serverSideFiltered: Boolean(filter)
1299
+ };
1300
+ }
1301
+ const unsupported = layout.filter((field) => !FIELD_COLUMNS[field].ps);
1302
+ if (unsupported.length > 0) {
1303
+ throw new Error(`process query: ${unsupported.join(", ")} has no POSIX ps column`);
1304
+ }
1305
+ if (layout.includes("startedAt") && process.platform === "linux") {
1306
+ throw new Error("process query: startedAt on Linux is read from /proc, not ps");
1307
+ }
1308
+ const columns = layout.map((field) => `${FIELD_COLUMNS[field].ps}=`).join(",");
1309
+ const pidFilter = filter && filter.column === "ProcessId" && filter.op === "eq" ? [...filter.values].map((value) => assertPid(value)) : null;
1310
+ return {
1311
+ command: posixPsPath(),
1312
+ args: pidFilter ? ["-p", pidFilter.join(","), "-o", columns] : ["-eo", columns],
1313
+ tabSeparated: false,
1314
+ fields: layout,
1315
+ serverSideFiltered: Boolean(pidFilter),
1316
+ // BSD `ps` formats `lstart` with strftime("%c") in the local zone, so
1317
+ // two readers with different locales or zones would print one process
1318
+ // two ways. Pinned, every reader prints the same text.
1319
+ ...layout.includes("startedAt") ? { env: posixStartEnv() } : {}
1320
+ };
1239
1321
  }
1240
- function startGenerationHeartbeat(hold, intervalMs) {
1241
- const file = generationPath(hold.dir, hold.generation);
1242
- const timer = setInterval(() => {
1243
- try {
1244
- const now = /* @__PURE__ */ new Date();
1245
- fs3.utimesSync(file, now, now);
1246
- } catch {
1247
- }
1248
- }, intervalMs);
1249
- timer.unref();
1250
- return { stop: () => clearInterval(timer) };
1322
+ function posixStartEnv() {
1323
+ return { ...process.env, LC_ALL: "C", TZ: "UTC0" };
1251
1324
  }
1252
- function ownsTopGeneration(hold) {
1325
+ function readLinuxProcessStart(pid) {
1253
1326
  try {
1254
- const entries = fs3.readdirSync(hold.dir);
1255
- if (entries.includes(releasedName(hold.generation)))
1256
- return false;
1257
- return topGeneration(entries) === hold.generation;
1327
+ const ticks = parseLinuxStatStart(fs3.readFileSync(`/proc/${assertPid(pid)}/stat`, "utf8"));
1328
+ const boot = fs3.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
1329
+ const offset = readBoottimeOffsetTicks();
1330
+ return ticks === void 0 || offset === void 0 || !/^[0-9a-f-]{36}$/.test(boot) ? void 0 : `${Number(ticks) - offset}@${boot}`;
1258
1331
  } catch {
1259
- return false;
1260
- }
1261
- }
1262
- function tryAcquireGeneration(dir, staleMs) {
1263
- fs3.mkdirSync(dir, { recursive: true });
1264
- const listed = fs3.readdirSync(dir);
1265
- const top = topGeneration(listed);
1266
- const free = top === 0 || listed.includes(releasedName(top));
1267
- if (!free && !pidFileIsStale(generationPath(dir, top), staleMs)) {
1268
1332
  return void 0;
1269
1333
  }
1270
- const hold = { dir, generation: top + 1, tookOverStale: !free };
1334
+ }
1335
+ var USER_HZ = 100;
1336
+ var NSEC_PER_TICK = 1e9 / USER_HZ;
1337
+ function readBoottimeOffsetTicks() {
1338
+ let text;
1271
1339
  try {
1272
- fs3.writeFileSync(generationPath(dir, hold.generation), `${process.pid} ${Date.now()}
1273
- `, { flag: "wx" });
1340
+ text = fs3.readFileSync("/proc/self/timens_offsets", "utf8");
1274
1341
  } catch (error) {
1275
- if (isLockContention(error))
1276
- return void 0;
1277
- throw error;
1278
- }
1279
- let entries;
1280
- try {
1281
- entries = fs3.readdirSync(dir);
1282
- } catch (cause) {
1283
- releaseGeneration(hold);
1284
- throw cause;
1342
+ return (
1343
+ /** @type {NodeJS.ErrnoException} */
1344
+ error.code === "ENOENT" ? 0 : void 0
1345
+ );
1285
1346
  }
1286
- if (topGeneration(entries) > hold.generation) {
1287
- releaseGeneration(hold);
1347
+ const match = /^boottime\s+(-?\d+)\s+(\d+)\s*$/m.exec(String(text));
1348
+ if (!match)
1288
1349
  return void 0;
1289
- }
1290
- removeBelowPredecessor(dir, entries, hold.generation);
1291
- return hold;
1350
+ const nsec = Number(match[2]);
1351
+ if (nsec % NSEC_PER_TICK !== 0)
1352
+ return void 0;
1353
+ return Number(match[1]) * USER_HZ + nsec / NSEC_PER_TICK;
1292
1354
  }
1293
- var timedOutHolders = new BoundedFifoMap(16);
1294
- function topGenerationHolder(dir) {
1355
+ function parseLinuxStatStart(stat) {
1356
+ const fields = String(stat).slice(stat.lastIndexOf(")") + 2).split(" ");
1357
+ const start = fields[19];
1358
+ return /^\d+$/.test(start ?? "") ? start : void 0;
1359
+ }
1360
+ function readLinuxPidNamespace(pid) {
1295
1361
  try {
1296
- const top = topGeneration(fs3.readdirSync(dir));
1297
- return `lock.${top} ${fs3.readFileSync(generationPath(dir, top), "utf8").trim()}`;
1362
+ return fs3.readlinkSync(`/proc/${assertPid(pid)}/ns/pid`);
1298
1363
  } catch {
1299
1364
  return void 0;
1300
1365
  }
1301
1366
  }
1302
- function withGenerationLockSync(dir, timing, op) {
1303
- const deadline = Date.now() + timing.waitMs;
1304
- const timedOutHolder = timedOutHolders.get(dir);
1305
- for (; ; ) {
1306
- let hold;
1307
- try {
1308
- hold = tryAcquireGeneration(dir, timing.staleMs);
1309
- } catch (cause) {
1310
- return { held: false, cause };
1311
- }
1312
- if (hold) {
1313
- if (hold.tookOverStale)
1314
- recordGenerationTakeover(hold);
1315
- try {
1316
- return { held: true, value: op() };
1317
- } finally {
1318
- releaseGeneration(hold);
1319
- }
1320
- }
1321
- if (timedOutHolder !== void 0 && topGenerationHolder(dir) === timedOutHolder) {
1322
- recordDegradationOnce({
1323
- kind: "generation-lock-wait-skipped",
1324
- subject: dir,
1325
- reason: `did not wait: ${timedOutHolder} still holds the lock after an earlier wait ran out`
1326
- });
1327
- return { held: false };
1328
- }
1329
- if (Date.now() >= deadline) {
1330
- timedOutHolders.set(dir, topGenerationHolder(dir));
1331
- return { held: false };
1332
- }
1333
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, randomInt(5, 26));
1334
- }
1335
- }
1336
-
1337
- // dist/clients/bounded-pid-file-lock.js
1338
- var waitArray = new Int32Array(new SharedArrayBuffer(4));
1339
- var UNREADABLE_LOCK_STALE_MS = 5e3;
1340
- function generationDir(lockPath) {
1341
- return `${lockPath}s`;
1342
- }
1343
- function boundedLockIsStale(lockPath) {
1344
- const [pidText] = fs4.readFileSync(lockPath, "utf8").split(":", 1);
1345
- const pid = Number.parseInt(pidText ?? "", 10);
1346
- if (Number.isSafeInteger(pid) && pid > 0)
1347
- return !ownerPidIsLive(pid);
1348
- return Date.now() - fs4.statSync(lockPath).mtimeMs > UNREADABLE_LOCK_STALE_MS;
1367
+ function parseNonNegativeInt(raw) {
1368
+ const token = String(raw ?? "").trim();
1369
+ if (!/^\d+$/.test(token))
1370
+ return void 0;
1371
+ const value = Number(token);
1372
+ return Number.isFinite(value) ? value : void 0;
1349
1373
  }
1350
- function ownerPidIsLive(pid) {
1351
- if (!Number.isSafeInteger(pid) || pid <= 0)
1352
- return false;
1353
- try {
1354
- process.kill(pid, 0);
1355
- return true;
1356
- } catch (error) {
1357
- return error.code === "EPERM";
1374
+ function ageMsFromPosixEtime(raw) {
1375
+ const token = String(raw ?? "").trim();
1376
+ if (!/^(?:\d+-)?(?:\d+:)?\d+:\d+$/.test(token))
1377
+ return void 0;
1378
+ let days = 0;
1379
+ let rest = token;
1380
+ const dash = rest.indexOf("-");
1381
+ if (dash >= 0) {
1382
+ days = Number(rest.slice(0, dash));
1383
+ rest = rest.slice(dash + 1);
1358
1384
  }
1385
+ const parts = rest.split(":").map(Number);
1386
+ if (parts.some((part) => !Number.isFinite(part)))
1387
+ return void 0;
1388
+ const [hours, minutes, seconds] = parts.length === 3 ? parts : [0, parts[0], parts[1]];
1389
+ return ((days * 24 + hours) * 60 * 60 + minutes * 60 + seconds) * 1e3;
1359
1390
  }
1360
- function quarantinePath(lockPath, token) {
1361
- return `${lockPath}.quarantine-${process.pid}-${token}`;
1391
+ function posixTokenPattern(field) {
1392
+ const token = FIELD_COLUMNS[field].token;
1393
+ if (token === "age")
1394
+ return "(\\S+)";
1395
+ if (token === "lstart")
1396
+ return "(\\S+\\s+\\S+\\s+\\d+\\s+\\d+:\\d+:\\d+\\s+\\d+)";
1397
+ return "(\\d+)";
1362
1398
  }
1363
- async function restoreQuarantinedLock(lockPath, quarantined) {
1364
- try {
1365
- await fsp.rename(quarantined, lockPath);
1366
- } catch {
1367
- }
1399
+ var LSTART_MONTHS = [
1400
+ "Jan",
1401
+ "Feb",
1402
+ "Mar",
1403
+ "Apr",
1404
+ "May",
1405
+ "Jun",
1406
+ "Jul",
1407
+ "Aug",
1408
+ "Sep",
1409
+ "Oct",
1410
+ "Nov",
1411
+ "Dec"
1412
+ ];
1413
+ function isoFromLstart(raw) {
1414
+ const match = /^\w{3}\s+(\w{3})\s+(\d{1,2})\s+(\d{1,2}):(\d{2}):(\d{2})\s+(\d{4})$/.exec(String(raw ?? "").trim());
1415
+ if (!match)
1416
+ return void 0;
1417
+ const month = LSTART_MONTHS.indexOf(match[1]);
1418
+ if (month === -1)
1419
+ return void 0;
1420
+ const [day, hours, minutes, seconds, year] = [2, 3, 4, 5, 6].map((i) => Number(match[i]));
1421
+ return new Date(Date.UTC(year, month, day, hours, minutes, seconds)).toISOString();
1368
1422
  }
1369
- async function releaseQuarantineLock(lockPath, token) {
1370
- const quarantined = quarantinePath(lockPath, `release-${token}`);
1371
- let renamed = false;
1372
- for (let attempt = 0; attempt < 3; attempt += 1) {
1373
- try {
1374
- await fsp.rename(lockPath, quarantined);
1375
- renamed = true;
1376
- break;
1377
- } catch (error) {
1378
- if (error.code !== "ENOENT" || attempt === 2)
1379
- return;
1380
- await new Promise((resolve7) => setImmediate(resolve7));
1381
- }
1382
- }
1383
- if (!renamed)
1384
- return;
1385
- try {
1386
- const owner = JSON.parse(await fsp.readFile(path4.join(quarantined, "owner.json"), "utf8"));
1387
- if (owner.token === token) {
1388
- await fsp.rm(quarantined, { recursive: true, force: true });
1423
+ function parseProcessTable(out, tabSeparated, fields = ALL_PROCESS_FIELDS) {
1424
+ const layout = normalizeProcessFields(fields);
1425
+ const commandIndex = layout.indexOf("command");
1426
+ const positional = tabSeparated ? null : new RegExp(`^\\s*${layout.filter((field) => field !== "command").map((field) => posixTokenPattern(field)).join("\\s+")}${commandIndex === -1 ? "\\s*$" : "\\s+(.*)$"}`);
1427
+ const rows = [];
1428
+ for (const line of String(out ?? "").split(/\r?\n/)) {
1429
+ if (!line.trim())
1430
+ continue;
1431
+ let parts;
1432
+ if (tabSeparated) {
1433
+ const split = line.split(" ");
1434
+ if (split.length < layout.length - (commandIndex === -1 ? 0 : 1))
1435
+ continue;
1436
+ parts = commandIndex === -1 ? split : [
1437
+ ...split.slice(0, commandIndex),
1438
+ split.slice(commandIndex).join(" ")
1439
+ ];
1389
1440
  } else {
1390
- await restoreQuarantinedLock(lockPath, quarantined);
1441
+ const match = positional?.exec(line);
1442
+ if (!match)
1443
+ continue;
1444
+ parts = match.slice(1);
1391
1445
  }
1392
- } catch {
1393
- await restoreQuarantinedLock(lockPath, quarantined);
1446
+ const value = (field) => {
1447
+ const at = layout.indexOf(field);
1448
+ return at === -1 ? void 0 : parts[at];
1449
+ };
1450
+ const pid = Number(value("pid"));
1451
+ if (!Number.isInteger(pid) || pid <= 0)
1452
+ continue;
1453
+ const ppid = Number(value("ppid"));
1454
+ const row = {
1455
+ pid,
1456
+ ppid: Number.isInteger(ppid) && ppid > 0 ? ppid : 0,
1457
+ command: value("command") ?? ""
1458
+ };
1459
+ for (const field of layout) {
1460
+ if (field === "pid" || field === "ppid" || field === "command")
1461
+ continue;
1462
+ const raw = value(field);
1463
+ if (field === "ageMs") {
1464
+ row.ageMs = tabSeparated ? parseNonNegativeInt(raw) : ageMsFromPosixEtime(raw ?? "");
1465
+ } else if (field === "startedAt") {
1466
+ row.startedAt = tabSeparated ? String(raw ?? "").trim() : isoFromLstart(raw ?? "");
1467
+ } else {
1468
+ row[field] = parseNonNegativeInt(raw);
1469
+ }
1470
+ }
1471
+ rows.push(row);
1394
1472
  }
1473
+ return rows;
1395
1474
  }
1396
- function quarantineOwnerIsStale(owner, staleMs) {
1397
- const pidUsable = Number.isInteger(owner.pid) && owner.pid > 0;
1398
- if (pidUsable && !ownerPidIsLive(owner.pid))
1399
- return true;
1400
- return Number.isFinite(owner.createdAt) && Date.now() - owner.createdAt > staleMs;
1401
- }
1402
- async function reclaimQuarantineLock(lockPath, staleMs) {
1403
- const quarantined = quarantinePath(lockPath, `reclaim-${Date.now()}-${randomUUID()}`);
1404
- try {
1405
- await fsp.rename(lockPath, quarantined);
1406
- } catch {
1407
- return false;
1408
- }
1409
- let stale = false;
1475
+
1476
+ // dist/clients/process-snapshot.js
1477
+ async function queryProcessTable(request, options) {
1478
+ let query;
1410
1479
  try {
1411
- const owner = JSON.parse(await fsp.readFile(path4.join(quarantined, "owner.json"), "utf8"));
1412
- stale = quarantineOwnerIsStale(owner, staleMs);
1480
+ query = buildProcessQuery(request.fields, {
1481
+ filter: request.filter,
1482
+ excludeSelfPid: request.excludeSelfPid
1483
+ });
1413
1484
  } catch {
1414
- try {
1415
- stale = Date.now() - (await fsp.stat(quarantined)).mtimeMs > staleMs;
1416
- } catch {
1417
- stale = false;
1418
- }
1419
- }
1420
- if (stale) {
1421
- await fsp.rm(quarantined, { recursive: true, force: true });
1422
- return true;
1485
+ return { rows: [], status: "spawn-error", serverSideFiltered: false };
1423
1486
  }
1424
- await restoreQuarantinedLock(lockPath, quarantined);
1425
- return false;
1426
- }
1427
- async function tryAcquireQuarantineLock(lockPath, staleMs) {
1428
- const owner = {
1429
- pid: process.pid,
1430
- createdAt: Date.now(),
1431
- token: `${process.pid}-${Date.now()}-${randomUUID()}`
1432
- };
1433
- for (let attempt = 0; attempt < 2; attempt += 1) {
1434
- try {
1435
- await fsp.mkdir(lockPath);
1436
- try {
1437
- await fsp.writeFile(path4.join(lockPath, "owner.json"), JSON.stringify(owner), "utf8");
1438
- } catch (error) {
1439
- await fsp.rm(lockPath, { recursive: true, force: true }).catch(() => {
1440
- });
1441
- throw error;
1442
- }
1443
- return () => releaseQuarantineLock(lockPath, owner.token);
1444
- } catch (error) {
1445
- if (error.code !== "EEXIST")
1446
- throw error;
1447
- }
1448
- let stale;
1449
- try {
1450
- const existing = JSON.parse(await fsp.readFile(path4.join(lockPath, "owner.json"), "utf8"));
1451
- stale = quarantineOwnerIsStale(existing, staleMs);
1452
- } catch {
1453
- try {
1454
- stale = Date.now() - (await fsp.stat(lockPath)).mtimeMs > staleMs;
1455
- } catch {
1456
- stale = true;
1457
- }
1458
- }
1459
- if (!stale || !await reclaimQuarantineLock(lockPath, staleMs))
1460
- return null;
1461
- }
1462
- return null;
1487
+ const result = await spawnCollectStdoutResult(query.command, query.args, {
1488
+ shell: false,
1489
+ windowsHide: true,
1490
+ stdio: ["ignore", "pipe", "ignore"],
1491
+ env: query.env
1492
+ }, { timeoutMs: options.timeoutMs, onTimeout: options.onTimeout });
1493
+ return {
1494
+ // Whatever the collector kept is parsed rather than discarded here: it
1495
+ // drops stdout on a non-zero exit (that output is not evidence of what
1496
+ // is NOT running) but KEEPS the partial table from a timed-out child,
1497
+ // and the caller decides what a partial table is worth by reading
1498
+ // `status`. Re-deciding that here would be a second policy.
1499
+ rows: parseProcessTable(result.stdout, query.tabSeparated, query.fields),
1500
+ status: result.status,
1501
+ exitCode: result.exitCode,
1502
+ timeoutKill: result.timeoutKill,
1503
+ serverSideFiltered: query.serverSideFiltered
1504
+ };
1463
1505
  }
1464
- async function tryAcquireQuarantineGeneration(lockPath, staleMs) {
1465
- const hold = tryAcquireGeneration(generationDir(lockPath), staleMs);
1466
- if (!hold)
1467
- return "busy";
1468
- if (hold.tookOverStale)
1469
- recordGenerationTakeover(hold);
1470
- let releaseLegacy;
1471
- try {
1472
- releaseLegacy = await tryAcquireQuarantineLock(lockPath, staleMs);
1473
- } catch (cause) {
1474
- releaseGeneration(hold);
1475
- throw cause;
1476
- }
1477
- if (releaseLegacy) {
1478
- const heartbeat = startGenerationHeartbeat(hold, heartbeatIntervalMs(staleMs));
1479
- return async () => {
1480
- heartbeat.stop();
1481
- await releaseLegacy();
1482
- releaseGeneration(hold);
1483
- };
1506
+ function validPids(pids) {
1507
+ return [...new Set(pids.filter((p) => Number.isInteger(p) && p > 0))];
1508
+ }
1509
+ async function queryProcessIdentities(pids, options) {
1510
+ const valid = validPids(pids);
1511
+ const identities = /* @__PURE__ */ new Map();
1512
+ if (valid.length === 0)
1513
+ return { identities, status: "ok" };
1514
+ const linux = process.platform === "linux";
1515
+ const result = await queryProcessTable({
1516
+ fields: linux ? ["pid", "command"] : ["pid", "startedAt", "command"],
1517
+ filter: { column: "ProcessId", op: "eq", values: valid }
1518
+ }, options);
1519
+ for (const row of result.rows) {
1520
+ const start = linux ? readLinuxProcessStart(row.pid) : row.startedAt;
1521
+ identities.set(row.pid, {
1522
+ command: row.command,
1523
+ start: start ? start : void 0
1524
+ });
1484
1525
  }
1485
- releaseGeneration(hold);
1486
- return "legacy-held";
1526
+ return { identities, status: result.status };
1487
1527
  }
1488
- async function acquireQuarantinePidFileLock(lockPath, options) {
1489
- const deadline = Date.now() + options.waitMs;
1490
- let legacyHeldRecorded = false;
1491
- for (; ; ) {
1492
- const release2 = await tryAcquireQuarantineGeneration(lockPath, options.staleMs);
1493
- if (typeof release2 === "function")
1494
- return release2;
1495
- if (release2 === "legacy-held" && !legacyHeldRecorded) {
1496
- legacyHeldRecorded = true;
1497
- recordLegacyLockHeld(lockPath);
1498
- }
1499
- const remaining = deadline - Date.now();
1500
- if (remaining <= 0) {
1501
- if (options.onContention === "skip-log") {
1502
- options.logContention();
1503
- return null;
1504
- }
1505
- throw new Error(options.timeoutMessage);
1506
- }
1507
- await new Promise((resolve7) => setTimeout(resolve7, Math.min(options.retryMs, remaining)));
1528
+ var OWNER_TAG_ENV = "PI_LENS_OWNER";
1529
+ function formatOwnerTag(tag) {
1530
+ return `${tag.pid}:${tag.start}`;
1531
+ }
1532
+ async function ownerTagForChildren(options) {
1533
+ if (process.platform === "win32")
1534
+ return void 0;
1535
+ const start = await ownProcessStart(options);
1536
+ return start === void 0 ? void 0 : formatOwnerTag({ pid: process.pid, start });
1537
+ }
1538
+ function isInPidNamespace(entry, namespace) {
1539
+ return entry.pidNamespace === void 0 || entry.pidNamespace === namespace;
1540
+ }
1541
+ function ownPidNamespace() {
1542
+ return process.platform === "linux" ? readLinuxPidNamespace(process.pid) : void 0;
1543
+ }
1544
+ var ownStart = null;
1545
+ function ownProcessStart(options) {
1546
+ if (process.platform === "linux")
1547
+ return Promise.resolve(readLinuxProcessStart(process.pid));
1548
+ if (ownStart)
1549
+ return ownStart.promise;
1550
+ const cell = {
1551
+ promise: readProcessStart(process.pid, options).then((start) => {
1552
+ if (start === void 0)
1553
+ ownStart = null;
1554
+ else
1555
+ cell.value = start;
1556
+ return start;
1557
+ })
1558
+ };
1559
+ ownStart = cell;
1560
+ return cell.promise;
1561
+ }
1562
+ async function readProcessStart(pid, options) {
1563
+ if (process.platform === "linux")
1564
+ return readLinuxProcessStart(pid);
1565
+ return (await queryProcessIdentities([pid], options)).identities.get(pid)?.start;
1566
+ }
1567
+
1568
+ // dist/clients/resource-sampler.js
1569
+ var import_pidusage = __toESM(require_pidusage(), 1);
1570
+
1571
+ // dist/clients/instance-reaper.js
1572
+ import { spawn as nodeSpawn2 } from "node:child_process";
1573
+
1574
+ // dist/clients/bounded-pid-file-lock.js
1575
+ import { randomUUID } from "node:crypto";
1576
+ import * as fs5 from "node:fs";
1577
+ import fsp from "node:fs/promises";
1578
+ import path5 from "node:path";
1579
+
1580
+ // dist/clients/generation-lock.js
1581
+ import { randomInt } from "node:crypto";
1582
+ import * as fs4 from "node:fs";
1583
+ import * as path4 from "node:path";
1584
+ var GENERATION = /^lock\.(\d+)(\.released)?$/;
1585
+ function pidFileOwner(file) {
1586
+ try {
1587
+ const pid = Number(fs4.readFileSync(file, "utf8").trim().split(/\s+/)[0]);
1588
+ return Number.isInteger(pid) && pid > 0 ? pid : void 0;
1589
+ } catch {
1590
+ return void 0;
1508
1591
  }
1509
1592
  }
1510
- function createLegacyBoundedLock(lockPath, token) {
1593
+ function isPidAlive(pid) {
1594
+ if (pid === void 0)
1595
+ return false;
1511
1596
  try {
1512
- fs4.writeFileSync(lockPath, token, { encoding: "utf8", flag: "wx" });
1597
+ process.kill(pid, 0);
1513
1598
  return true;
1514
- } catch (cause) {
1515
- if (isLockContention(cause))
1516
- return false;
1517
- throw cause;
1599
+ } catch (error) {
1600
+ return error?.code !== "ESRCH";
1518
1601
  }
1519
1602
  }
1520
- function takeLegacyBoundedLock(lockPath, token) {
1521
- if (createLegacyBoundedLock(lockPath, token))
1522
- return true;
1603
+ function pidFileIsStale(file, staleMs) {
1523
1604
  try {
1524
- if (!boundedLockIsStale(lockPath))
1525
- return false;
1526
- fs4.unlinkSync(lockPath);
1605
+ const stat = fs4.statSync(file);
1606
+ if (Date.now() - stat.mtimeMs > staleMs)
1607
+ return true;
1608
+ const pid = pidFileOwner(file);
1609
+ return pid !== void 0 && !isPidAlive(pid);
1527
1610
  } catch {
1528
1611
  return false;
1529
1612
  }
1530
- return createLegacyBoundedLock(lockPath, token);
1531
1613
  }
1532
- function releaseLegacyBoundedLock(lockPath, token) {
1533
- try {
1534
- if (fs4.readFileSync(lockPath, "utf8") === token)
1535
- fs4.unlinkSync(lockPath);
1536
- } catch {
1614
+ function isLockContention(error) {
1615
+ const code = error?.code;
1616
+ return code === "EEXIST" || code === "EPERM" || code === "EBUSY";
1617
+ }
1618
+ function generationPath(dir, generation) {
1619
+ return path4.join(dir, `lock.${generation}`);
1620
+ }
1621
+ function releasedName(generation) {
1622
+ return `lock.${generation}.released`;
1623
+ }
1624
+ function topGeneration(entries) {
1625
+ let top = 0;
1626
+ for (const name of entries) {
1627
+ const match = GENERATION.exec(name);
1628
+ if (match && !match[2])
1629
+ top = Math.max(top, Number(match[1]));
1537
1630
  }
1631
+ return top;
1538
1632
  }
1539
- function tryAcquireBoundedLock(lockPath, token) {
1540
- const hold = tryAcquireGeneration(generationDir(lockPath), UNREADABLE_LOCK_STALE_MS);
1541
- if (!hold)
1542
- return "busy";
1543
- if (hold.tookOverStale)
1544
- recordGenerationTakeover(hold);
1545
- let took;
1546
- try {
1547
- took = takeLegacyBoundedLock(lockPath, token);
1548
- } catch (cause) {
1549
- releaseGeneration(hold);
1550
- throw cause;
1633
+ function removeBelowPredecessor(dir, entries, generation) {
1634
+ for (const name of entries) {
1635
+ const match = GENERATION.exec(name);
1636
+ if (!match || Number(match[1]) + 1 >= generation)
1637
+ continue;
1638
+ try {
1639
+ fs4.unlinkSync(path4.join(dir, name));
1640
+ } catch {
1641
+ }
1551
1642
  }
1552
- if (took)
1553
- return hold;
1554
- releaseGeneration(hold);
1555
- return "legacy-held";
1556
1643
  }
1557
- var timedOutHolders2 = new BoundedFifoMap(16);
1558
- function currentHolderIdentity(dir, lockPath, hold) {
1559
- if (hold === "busy")
1560
- return topGenerationHolder(dir);
1644
+ function recordGenerationTakeover(hold) {
1645
+ incrementDegradationCount({
1646
+ kind: "generation-lock-stale-takeover",
1647
+ subject: path4.resolve(hold.dir),
1648
+ reason: `took over lock generation ${hold.generation - 1} from a dead or aged-out holder`
1649
+ });
1650
+ }
1651
+ function recordLegacyLockHeld(legacyPath) {
1652
+ incrementDegradationCount({
1653
+ kind: "generation-lock-legacy-held",
1654
+ subject: path4.resolve(legacyPath),
1655
+ reason: `backed off: ${path4.basename(legacyPath)} is held by another writer (one from before #3476, or a holder past the generation lease)`
1656
+ });
1657
+ }
1658
+ function releaseGeneration(hold) {
1561
1659
  try {
1562
- const content = fs4.readFileSync(lockPath, "utf8");
1563
- return content ? `legacy ${content}` : void 0;
1660
+ fs4.writeFileSync(path4.join(hold.dir, releasedName(hold.generation)), "");
1564
1661
  } catch {
1565
- return void 0;
1566
1662
  }
1567
1663
  }
1568
- function acquireBoundedPidFileLock(lockPath, options) {
1569
- const token = `${process.pid}:${Date.now()}:${randomUUID()}`;
1570
- const deadline = Date.now() + options.waitMs;
1571
- const dir = generationDir(lockPath);
1572
- const timedOutHolder = timedOutHolders2.get(dir);
1573
- let legacyHeldRecorded = false;
1664
+ function heartbeatIntervalMs(leaseMs) {
1665
+ return Math.max(1e3, Math.floor(leaseMs / 4));
1666
+ }
1667
+ function startGenerationHeartbeat(hold, intervalMs) {
1668
+ const file = generationPath(hold.dir, hold.generation);
1669
+ const timer = setInterval(() => {
1670
+ try {
1671
+ const now = /* @__PURE__ */ new Date();
1672
+ fs4.utimesSync(file, now, now);
1673
+ } catch {
1674
+ }
1675
+ }, intervalMs);
1676
+ timer.unref();
1677
+ return { stop: () => clearInterval(timer) };
1678
+ }
1679
+ function ownsTopGeneration(hold) {
1680
+ try {
1681
+ const entries = fs4.readdirSync(hold.dir);
1682
+ if (entries.includes(releasedName(hold.generation)))
1683
+ return false;
1684
+ return topGeneration(entries) === hold.generation;
1685
+ } catch {
1686
+ return false;
1687
+ }
1688
+ }
1689
+ function tryAcquireGeneration(dir, staleMs) {
1690
+ fs4.mkdirSync(dir, { recursive: true });
1691
+ const listed = fs4.readdirSync(dir);
1692
+ const top = topGeneration(listed);
1693
+ const free = top === 0 || listed.includes(releasedName(top));
1694
+ if (!free && !pidFileIsStale(generationPath(dir, top), staleMs)) {
1695
+ return void 0;
1696
+ }
1697
+ const hold = { dir, generation: top + 1, tookOverStale: !free };
1698
+ try {
1699
+ fs4.writeFileSync(generationPath(dir, hold.generation), `${process.pid} ${Date.now()}
1700
+ `, { flag: "wx" });
1701
+ } catch (error) {
1702
+ if (isLockContention(error))
1703
+ return void 0;
1704
+ throw error;
1705
+ }
1706
+ let entries;
1707
+ try {
1708
+ entries = fs4.readdirSync(dir);
1709
+ } catch (cause) {
1710
+ releaseGeneration(hold);
1711
+ throw cause;
1712
+ }
1713
+ if (topGeneration(entries) > hold.generation) {
1714
+ releaseGeneration(hold);
1715
+ return void 0;
1716
+ }
1717
+ removeBelowPredecessor(dir, entries, hold.generation);
1718
+ return hold;
1719
+ }
1720
+ var timedOutHolders = new BoundedFifoMap(16);
1721
+ function topGenerationHolder(dir) {
1722
+ try {
1723
+ const top = topGeneration(fs4.readdirSync(dir));
1724
+ return `lock.${top} ${fs4.readFileSync(generationPath(dir, top), "utf8").trim()}`;
1725
+ } catch {
1726
+ return void 0;
1727
+ }
1728
+ }
1729
+ function withGenerationLockSync(dir, timing, op) {
1730
+ const deadline = Date.now() + timing.waitMs;
1731
+ const timedOutHolder = timedOutHolders.get(dir);
1574
1732
  for (; ; ) {
1575
- const hold = tryAcquireBoundedLock(lockPath, token);
1576
- if (typeof hold === "object") {
1577
- return () => {
1578
- releaseLegacyBoundedLock(lockPath, token);
1579
- releaseGeneration(hold);
1580
- };
1733
+ let hold;
1734
+ try {
1735
+ hold = tryAcquireGeneration(dir, timing.staleMs);
1736
+ } catch (cause) {
1737
+ return { held: false, cause };
1581
1738
  }
1582
- if (hold === "legacy-held" && !legacyHeldRecorded) {
1583
- legacyHeldRecorded = true;
1584
- recordLegacyLockHeld(lockPath);
1739
+ if (hold) {
1740
+ if (hold.tookOverStale)
1741
+ recordGenerationTakeover(hold);
1742
+ try {
1743
+ return { held: true, value: op() };
1744
+ } finally {
1745
+ releaseGeneration(hold);
1746
+ }
1585
1747
  }
1586
- if (timedOutHolder !== void 0 && currentHolderIdentity(dir, lockPath, hold) === timedOutHolder) {
1748
+ if (timedOutHolder !== void 0 && topGenerationHolder(dir) === timedOutHolder) {
1587
1749
  recordDegradationOnce({
1588
- kind: "bounded-pid-lock-wait-skipped",
1589
- subject: path4.resolve(dir),
1750
+ kind: "generation-lock-wait-skipped",
1751
+ subject: dir,
1590
1752
  reason: `did not wait: ${timedOutHolder} still holds the lock after an earlier wait ran out`
1591
1753
  });
1592
- if (options.onContention === "skip-log") {
1593
- options.logContention();
1594
- return null;
1595
- }
1596
- throw new Error(options.timeoutMessage);
1754
+ return { held: false };
1597
1755
  }
1598
1756
  if (Date.now() >= deadline) {
1599
- timedOutHolders2.set(dir, currentHolderIdentity(dir, lockPath, hold));
1600
- if (options.onContention === "skip-log") {
1601
- options.logContention();
1602
- return null;
1603
- }
1604
- throw new Error(options.timeoutMessage);
1757
+ timedOutHolders.set(dir, topGenerationHolder(dir));
1758
+ return { held: false };
1605
1759
  }
1606
- Atomics.wait(waitArray, 0, 0, options.retryMs);
1760
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, randomInt(5, 26));
1607
1761
  }
1608
1762
  }
1609
1763
 
1610
- // dist/clients/child-unref.js
1611
- import { spawn as nodeSpawn } from "node:child_process";
1612
- function unrefChildAndPipes(child) {
1764
+ // dist/clients/bounded-pid-file-lock.js
1765
+ var waitArray = new Int32Array(new SharedArrayBuffer(4));
1766
+ var UNREADABLE_LOCK_STALE_MS = 5e3;
1767
+ function generationDir(lockPath) {
1768
+ return `${lockPath}s`;
1769
+ }
1770
+ function boundedLockIsStale(lockPath) {
1771
+ const [pidText] = fs5.readFileSync(lockPath, "utf8").split(":", 1);
1772
+ const pid = Number.parseInt(pidText ?? "", 10);
1773
+ if (Number.isSafeInteger(pid) && pid > 0)
1774
+ return !ownerPidIsLive(pid);
1775
+ return Date.now() - fs5.statSync(lockPath).mtimeMs > UNREADABLE_LOCK_STALE_MS;
1776
+ }
1777
+ function ownerPidIsLive(pid) {
1778
+ if (!Number.isSafeInteger(pid) || pid <= 0)
1779
+ return false;
1613
1780
  try {
1614
- child.unref();
1615
- for (const stream of [child.stdout, child.stderr, child.stdin]) {
1616
- stream?.unref?.();
1617
- }
1781
+ process.kill(pid, 0);
1782
+ return true;
1783
+ } catch (error) {
1784
+ return error.code === "EPERM";
1785
+ }
1786
+ }
1787
+ function quarantinePath(lockPath, token) {
1788
+ return `${lockPath}.quarantine-${process.pid}-${token}`;
1789
+ }
1790
+ async function restoreQuarantinedLock(lockPath, quarantined) {
1791
+ try {
1792
+ await fsp.rename(quarantined, lockPath);
1618
1793
  } catch {
1619
1794
  }
1620
1795
  }
1621
- function spawnCollectStdoutResult(command, args, options, collectOptions = {}) {
1622
- return new Promise((resolve7) => {
1623
- let settled = false;
1624
- let timer;
1625
- const settle = (result) => {
1626
- if (settled)
1627
- return;
1628
- settled = true;
1629
- if (timer)
1630
- clearTimeout(timer);
1631
- resolve7(result);
1632
- };
1796
+ async function releaseQuarantineLock(lockPath, token) {
1797
+ const quarantined = quarantinePath(lockPath, `release-${token}`);
1798
+ let renamed = false;
1799
+ for (let attempt = 0; attempt < 3; attempt += 1) {
1633
1800
  try {
1634
- const child = nodeSpawn(command, args, options);
1635
- unrefChildAndPipes(child);
1636
- const out = createBoundedOutputSink();
1637
- child.stdout?.on("data", (chunk) => out.append(chunk));
1638
- child.once("error", (error) => settle({ stdout: "", status: "spawn-error", error }));
1639
- child.once("close", (code, signal) => settle(code === 0 && signal === null ? { stdout: out.text, status: "ok" } : {
1640
- stdout: "",
1641
- status: "exit-error",
1642
- exitCode: code,
1643
- exitSignal: signal
1644
- }));
1645
- const timeoutMs = collectOptions.timeoutMs;
1646
- if (typeof timeoutMs === "number" && timeoutMs > 0) {
1647
- timer = setTimeout(() => {
1648
- void terminateTimedOutChild(child, collectOptions.onTimeout).then((timeoutKill) => settle({ stdout: out.text, status: "timeout", timeoutKill }));
1649
- }, timeoutMs);
1650
- timer.unref();
1651
- }
1801
+ await fsp.rename(lockPath, quarantined);
1802
+ renamed = true;
1803
+ break;
1652
1804
  } catch (error) {
1653
- settle({ stdout: "", status: "spawn-error", error });
1654
- }
1655
- });
1656
- }
1657
- async function terminateTimedOutChild(child, onTimeout) {
1658
- if (onTimeout) {
1659
- try {
1660
- return await onTimeout(child);
1661
- } catch {
1662
- return "unverified";
1805
+ if (error.code !== "ENOENT" || attempt === 2)
1806
+ return;
1807
+ await new Promise((resolve7) => setImmediate(resolve7));
1663
1808
  }
1664
1809
  }
1810
+ if (!renamed)
1811
+ return;
1665
1812
  try {
1666
- child.kill();
1813
+ const owner = JSON.parse(await fsp.readFile(path5.join(quarantined, "owner.json"), "utf8"));
1814
+ if (owner.token === token) {
1815
+ await fsp.rm(quarantined, { recursive: true, force: true });
1816
+ } else {
1817
+ await restoreQuarantinedLock(lockPath, quarantined);
1818
+ }
1667
1819
  } catch {
1820
+ await restoreQuarantinedLock(lockPath, quarantined);
1668
1821
  }
1669
- return "unverified";
1670
- }
1671
-
1672
- // dist/clients/file-utils.js
1673
- import * as fs5 from "node:fs";
1674
- import { createHash, randomBytes } from "node:crypto";
1675
- import * as os3 from "node:os";
1676
- import * as path8 from "node:path";
1677
-
1678
- // dist/clients/spawn-timeout-cooldown.js
1679
- import path5 from "node:path";
1680
- var COOLDOWN_STATE_KEY = /* @__PURE__ */ Symbol.for("pi-lens:spawn-timeout-cooldown");
1681
- var _global = globalThis;
1682
- if (!_global[COOLDOWN_STATE_KEY]) {
1683
- _global[COOLDOWN_STATE_KEY] = { timedOutByCommand: /* @__PURE__ */ new Map() };
1684
1822
  }
1685
- var timedOutByCommand = _global[COOLDOWN_STATE_KEY].timedOutByCommand;
1686
- function wrapperKindOf(command) {
1687
- const ext = path5.extname(command);
1688
- return ext ? ext.slice(1) : "bare";
1823
+ function quarantineOwnerIsStale(owner, staleMs) {
1824
+ const pidUsable = Number.isInteger(owner.pid) && owner.pid > 0;
1825
+ if (pidUsable && !ownerPidIsLive(owner.pid))
1826
+ return true;
1827
+ return Number.isFinite(owner.createdAt) && Date.now() - owner.createdAt > staleMs;
1689
1828
  }
1690
- function cooldownKey(command) {
1691
- return path5.basename(command).replace(/\.[^.]+$/, "").toLowerCase();
1829
+ async function reclaimQuarantineLock(lockPath, staleMs) {
1830
+ const quarantined = quarantinePath(lockPath, `reclaim-${Date.now()}-${randomUUID()}`);
1831
+ try {
1832
+ await fsp.rename(lockPath, quarantined);
1833
+ } catch {
1834
+ return false;
1835
+ }
1836
+ let stale = false;
1837
+ try {
1838
+ const owner = JSON.parse(await fsp.readFile(path5.join(quarantined, "owner.json"), "utf8"));
1839
+ stale = quarantineOwnerIsStale(owner, staleMs);
1840
+ } catch {
1841
+ try {
1842
+ stale = Date.now() - (await fsp.stat(quarantined)).mtimeMs > staleMs;
1843
+ } catch {
1844
+ stale = false;
1845
+ }
1846
+ }
1847
+ if (stale) {
1848
+ await fsp.rm(quarantined, { recursive: true, force: true });
1849
+ return true;
1850
+ }
1851
+ await restoreQuarantinedLock(lockPath, quarantined);
1852
+ return false;
1692
1853
  }
1693
- function noteSpawnTimeout(input) {
1694
- const key = cooldownKey(input.command);
1695
- timedOutByCommand.set(key, {
1696
- tool: input.tool,
1697
- command: input.command,
1698
- phase: input.phase,
1699
- atMs: Date.now()
1700
- });
1701
- logLatency({
1702
- type: "phase",
1703
- toolName: input.tool,
1704
- phase: "spawn_timeout_cooldown",
1705
- filePath: normalizeLoggedPath(input.command),
1854
+ async function tryAcquireQuarantineLock(lockPath, staleMs) {
1855
+ const owner = {
1856
+ pid: process.pid,
1857
+ createdAt: Date.now(),
1858
+ token: `${process.pid}-${Date.now()}-${randomUUID()}`
1859
+ };
1860
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1861
+ try {
1862
+ await fsp.mkdir(lockPath);
1863
+ try {
1864
+ await fsp.writeFile(path5.join(lockPath, "owner.json"), JSON.stringify(owner), "utf8");
1865
+ } catch (error) {
1866
+ await fsp.rm(lockPath, { recursive: true, force: true }).catch(() => {
1867
+ });
1868
+ throw error;
1869
+ }
1870
+ return () => releaseQuarantineLock(lockPath, owner.token);
1871
+ } catch (error) {
1872
+ if (error.code !== "EEXIST")
1873
+ throw error;
1874
+ }
1875
+ let stale;
1876
+ try {
1877
+ const existing = JSON.parse(await fsp.readFile(path5.join(lockPath, "owner.json"), "utf8"));
1878
+ stale = quarantineOwnerIsStale(existing, staleMs);
1879
+ } catch {
1880
+ try {
1881
+ stale = Date.now() - (await fsp.stat(lockPath)).mtimeMs > staleMs;
1882
+ } catch {
1883
+ stale = true;
1884
+ }
1885
+ }
1886
+ if (!stale || !await reclaimQuarantineLock(lockPath, staleMs))
1887
+ return null;
1888
+ }
1889
+ return null;
1890
+ }
1891
+ async function tryAcquireQuarantineGeneration(lockPath, staleMs) {
1892
+ const hold = tryAcquireGeneration(generationDir(lockPath), staleMs);
1893
+ if (!hold)
1894
+ return "busy";
1895
+ if (hold.tookOverStale)
1896
+ recordGenerationTakeover(hold);
1897
+ let releaseLegacy;
1898
+ try {
1899
+ releaseLegacy = await tryAcquireQuarantineLock(lockPath, staleMs);
1900
+ } catch (cause) {
1901
+ releaseGeneration(hold);
1902
+ throw cause;
1903
+ }
1904
+ if (releaseLegacy) {
1905
+ const heartbeat = startGenerationHeartbeat(hold, heartbeatIntervalMs(staleMs));
1906
+ return async () => {
1907
+ heartbeat.stop();
1908
+ await releaseLegacy();
1909
+ releaseGeneration(hold);
1910
+ };
1911
+ }
1912
+ releaseGeneration(hold);
1913
+ return "legacy-held";
1914
+ }
1915
+ async function acquireQuarantinePidFileLock(lockPath, options) {
1916
+ const deadline = Date.now() + options.waitMs;
1917
+ let legacyHeldRecorded = false;
1918
+ for (; ; ) {
1919
+ const release2 = await tryAcquireQuarantineGeneration(lockPath, options.staleMs);
1920
+ if (typeof release2 === "function")
1921
+ return release2;
1922
+ if (release2 === "legacy-held" && !legacyHeldRecorded) {
1923
+ legacyHeldRecorded = true;
1924
+ recordLegacyLockHeld(lockPath);
1925
+ }
1926
+ const remaining = deadline - Date.now();
1927
+ if (remaining <= 0) {
1928
+ if (options.onContention === "skip-log") {
1929
+ options.logContention();
1930
+ return null;
1931
+ }
1932
+ throw new Error(options.timeoutMessage);
1933
+ }
1934
+ await new Promise((resolve7) => setTimeout(resolve7, Math.min(options.retryMs, remaining)));
1935
+ }
1936
+ }
1937
+ function createLegacyBoundedLock(lockPath, token) {
1938
+ try {
1939
+ fs5.writeFileSync(lockPath, token, { encoding: "utf8", flag: "wx" });
1940
+ return true;
1941
+ } catch (cause) {
1942
+ if (isLockContention(cause))
1943
+ return false;
1944
+ throw cause;
1945
+ }
1946
+ }
1947
+ function takeLegacyBoundedLock(lockPath, token) {
1948
+ if (createLegacyBoundedLock(lockPath, token))
1949
+ return true;
1950
+ try {
1951
+ if (!boundedLockIsStale(lockPath))
1952
+ return false;
1953
+ fs5.unlinkSync(lockPath);
1954
+ } catch {
1955
+ return false;
1956
+ }
1957
+ return createLegacyBoundedLock(lockPath, token);
1958
+ }
1959
+ function releaseLegacyBoundedLock(lockPath, token) {
1960
+ try {
1961
+ if (fs5.readFileSync(lockPath, "utf8") === token)
1962
+ fs5.unlinkSync(lockPath);
1963
+ } catch {
1964
+ }
1965
+ }
1966
+ function tryAcquireBoundedLock(lockPath, token) {
1967
+ const hold = tryAcquireGeneration(generationDir(lockPath), UNREADABLE_LOCK_STALE_MS);
1968
+ if (!hold)
1969
+ return "busy";
1970
+ if (hold.tookOverStale)
1971
+ recordGenerationTakeover(hold);
1972
+ let took;
1973
+ try {
1974
+ took = takeLegacyBoundedLock(lockPath, token);
1975
+ } catch (cause) {
1976
+ releaseGeneration(hold);
1977
+ throw cause;
1978
+ }
1979
+ if (took)
1980
+ return hold;
1981
+ releaseGeneration(hold);
1982
+ return "legacy-held";
1983
+ }
1984
+ var timedOutHolders2 = new BoundedFifoMap(16);
1985
+ function currentHolderIdentity(dir, lockPath, hold) {
1986
+ if (hold === "busy")
1987
+ return topGenerationHolder(dir);
1988
+ try {
1989
+ const content = fs5.readFileSync(lockPath, "utf8");
1990
+ return content ? `legacy ${content}` : void 0;
1991
+ } catch {
1992
+ return void 0;
1993
+ }
1994
+ }
1995
+ function acquireBoundedPidFileLock(lockPath, options) {
1996
+ const token = `${process.pid}:${Date.now()}:${randomUUID()}`;
1997
+ const deadline = Date.now() + options.waitMs;
1998
+ const dir = generationDir(lockPath);
1999
+ const timedOutHolder = timedOutHolders2.get(dir);
2000
+ let legacyHeldRecorded = false;
2001
+ for (; ; ) {
2002
+ const hold = tryAcquireBoundedLock(lockPath, token);
2003
+ if (typeof hold === "object") {
2004
+ return () => {
2005
+ releaseLegacyBoundedLock(lockPath, token);
2006
+ releaseGeneration(hold);
2007
+ };
2008
+ }
2009
+ if (hold === "legacy-held" && !legacyHeldRecorded) {
2010
+ legacyHeldRecorded = true;
2011
+ recordLegacyLockHeld(lockPath);
2012
+ }
2013
+ if (timedOutHolder !== void 0 && currentHolderIdentity(dir, lockPath, hold) === timedOutHolder) {
2014
+ recordDegradationOnce({
2015
+ kind: "bounded-pid-lock-wait-skipped",
2016
+ subject: path5.resolve(dir),
2017
+ reason: `did not wait: ${timedOutHolder} still holds the lock after an earlier wait ran out`
2018
+ });
2019
+ if (options.onContention === "skip-log") {
2020
+ options.logContention();
2021
+ return null;
2022
+ }
2023
+ throw new Error(options.timeoutMessage);
2024
+ }
2025
+ if (Date.now() >= deadline) {
2026
+ timedOutHolders2.set(dir, currentHolderIdentity(dir, lockPath, hold));
2027
+ if (options.onContention === "skip-log") {
2028
+ options.logContention();
2029
+ return null;
2030
+ }
2031
+ throw new Error(options.timeoutMessage);
2032
+ }
2033
+ Atomics.wait(waitArray, 0, 0, options.retryMs);
2034
+ }
2035
+ }
2036
+
2037
+ // dist/clients/file-utils.js
2038
+ import * as fs6 from "node:fs";
2039
+ import { createHash, randomBytes } from "node:crypto";
2040
+ import * as os3 from "node:os";
2041
+ import * as path9 from "node:path";
2042
+
2043
+ // dist/clients/spawn-timeout-cooldown.js
2044
+ import path6 from "node:path";
2045
+ var COOLDOWN_STATE_KEY = /* @__PURE__ */ Symbol.for("pi-lens:spawn-timeout-cooldown");
2046
+ var _global = globalThis;
2047
+ if (!_global[COOLDOWN_STATE_KEY]) {
2048
+ _global[COOLDOWN_STATE_KEY] = { timedOutByCommand: /* @__PURE__ */ new Map() };
2049
+ }
2050
+ var timedOutByCommand = _global[COOLDOWN_STATE_KEY].timedOutByCommand;
2051
+ function wrapperKindOf(command) {
2052
+ const ext = path6.extname(command);
2053
+ return ext ? ext.slice(1) : "bare";
2054
+ }
2055
+ function cooldownKey(command) {
2056
+ return path6.basename(command).replace(/\.[^.]+$/, "").toLowerCase();
2057
+ }
2058
+ function noteSpawnTimeout(input) {
2059
+ const key = cooldownKey(input.command);
2060
+ timedOutByCommand.set(key, {
2061
+ tool: input.tool,
2062
+ command: input.command,
2063
+ phase: input.phase,
2064
+ atMs: Date.now()
2065
+ });
2066
+ logLatency({
2067
+ type: "phase",
2068
+ toolName: input.tool,
2069
+ phase: "spawn_timeout_cooldown",
2070
+ filePath: normalizeLoggedPath(input.command),
1706
2071
  durationMs: input.durationMs ?? 0,
1707
2072
  status: "cooldown_armed",
1708
2073
  metadata: {
@@ -1727,7 +2092,7 @@ function resetSpawnTimeoutCooldowns() {
1727
2092
  }
1728
2093
 
1729
2094
  // dist/clients/git-tracked-ignore.js
1730
- import * as path6 from "node:path";
2095
+ import * as path7 from "node:path";
1731
2096
  function recordTruncatedLsFiles(parseSite) {
1732
2097
  recordDegradationOnce({
1733
2098
  kind: "git-tracked-ignore-truncated",
@@ -1745,7 +2110,7 @@ function parseUntrackedIgnoredOutput(stdout, cwd) {
1745
2110
  const dirSegments = rel.split("/").slice(0, -1);
1746
2111
  if (dirSegments.some((segment) => isExcludedDirName(segment)))
1747
2112
  continue;
1748
- ids.add(normalizeMapKey(path6.join(cwd, rel)));
2113
+ ids.add(normalizeMapKey(path7.join(cwd, rel)));
1749
2114
  }
1750
2115
  return ids;
1751
2116
  }
@@ -1790,7 +2155,7 @@ function parseTrackedFilesOutput(stdout, cwd) {
1790
2155
  const dirSegments = rel.split("/").slice(0, -1);
1791
2156
  if (dirSegments.some((segment) => isExcludedDirName(segment)))
1792
2157
  continue;
1793
- ids.add(normalizeEphemeralMapKey(path6.join(base, rel)));
2158
+ ids.add(normalizeEphemeralMapKey(path7.join(base, rel)));
1794
2159
  }
1795
2160
  return ids;
1796
2161
  }
@@ -2077,12 +2442,12 @@ function resolvePiLensFlag(name, value, config, projectConfig, editedFilePath, p
2077
2442
 
2078
2443
  // dist/clients/ephemeral-root.js
2079
2444
  import * as os2 from "node:os";
2080
- import * as path7 from "node:path";
2445
+ import * as path8 from "node:path";
2081
2446
  var NOT_EPHEMERAL = { checkout: false };
2082
2447
  var classified = new BoundedFifoMap(1024);
2083
2448
  function classifyTmpDir(dir) {
2084
2449
  const tmpSpelling = os2.tmpdir();
2085
- const key = `${normalizeEphemeralMapKey(tmpSpelling)}\0${normalizeEphemeralMapKey(path7.resolve(dir))}`;
2450
+ const key = `${normalizeEphemeralMapKey(tmpSpelling)}\0${normalizeEphemeralMapKey(path8.resolve(dir))}`;
2086
2451
  const memo = classified.get(key);
2087
2452
  if (memo)
2088
2453
  return memo;
@@ -2093,18 +2458,18 @@ function classifyTmpDir(dir) {
2093
2458
  for (const current of walkUpDirs(real)) {
2094
2459
  if (current === tmpRoot)
2095
2460
  break;
2096
- if (isRealGitMarker(path7.join(current, ".git"))) {
2461
+ if (isRealGitMarker(path8.join(current, ".git"))) {
2097
2462
  result = { checkout: true };
2098
2463
  break;
2099
2464
  }
2100
2465
  }
2101
2466
  if (!result.checkout) {
2102
- const segments = path7.relative(tmpRoot, real).split(path7.sep);
2467
+ const segments = path8.relative(tmpRoot, real).split(path8.sep);
2103
2468
  const index = segments.findIndex((segment) => /^pi-agent(?:-|$)/i.test(segment));
2104
2469
  if (index >= 0) {
2105
2470
  result = {
2106
2471
  checkout: false,
2107
- stagingRoot: path7.join(tmpRoot, ...segments.slice(0, index + 1))
2472
+ stagingRoot: path8.join(tmpRoot, ...segments.slice(0, index + 1))
2108
2473
  };
2109
2474
  }
2110
2475
  }
@@ -2113,17 +2478,17 @@ function classifyTmpDir(dir) {
2113
2478
  return result;
2114
2479
  }
2115
2480
  function ephemeralStagingRoot(filePath) {
2116
- return classifyTmpDir(path7.dirname(path7.resolve(filePath))).stagingRoot;
2481
+ return classifyTmpDir(path8.dirname(path8.resolve(filePath))).stagingRoot;
2117
2482
  }
2118
2483
  function isPiOwnedTempPath(filePath) {
2119
2484
  const tmpRoot = realpathOrResolve(os2.tmpdir());
2120
2485
  const real = realpathOrResolve(filePath);
2121
2486
  if (!isUnderDir(real, tmpRoot))
2122
2487
  return false;
2123
- const relative3 = path7.relative(tmpRoot, real);
2124
- if (relative3.length === 0 || path7.isAbsolute(relative3))
2488
+ const relative3 = path8.relative(tmpRoot, real);
2489
+ if (relative3.length === 0 || path8.isAbsolute(relative3))
2125
2490
  return false;
2126
- const segments = relative3.split(path7.sep);
2491
+ const segments = relative3.split(path8.sep);
2127
2492
  return segments.length === 1 || /^pi-/i.test(segments[0] ?? "");
2128
2493
  }
2129
2494
  function isEphemeralCheckoutRoot(dir) {
@@ -2132,14 +2497,14 @@ function isEphemeralCheckoutRoot(dir) {
2132
2497
 
2133
2498
  // dist/clients/file-utils.js
2134
2499
  function getProjectDataDir(cwd) {
2135
- const legacyProjectDir = path8.join(cwd, ".pi-lens");
2500
+ const legacyProjectDir = path9.join(cwd, ".pi-lens");
2136
2501
  const configuredBase = process.env.PILENS_DATA_DIR?.trim();
2137
2502
  const resolvedBase = projectDataBase();
2138
- const memoKey = `${resolvedBase}\0${path8.resolve(cwd)}`;
2503
+ const memoKey = `${resolvedBase}\0${path9.resolve(cwd)}`;
2139
2504
  const cached = settledDataDirs.get(memoKey);
2140
2505
  if (cached !== void 0)
2141
2506
  return cached;
2142
- if (!configuredBase && fs5.existsSync(legacyProjectDir)) {
2507
+ if (!configuredBase && fs6.existsSync(legacyProjectDir)) {
2143
2508
  return legacyProjectDir;
2144
2509
  }
2145
2510
  const canonical = dataDirCanonicalRoot(cwd);
@@ -2147,13 +2512,13 @@ function getProjectDataDir(cwd) {
2147
2512
  const hash = projectDataDirRootHash(canonical.root);
2148
2513
  const slug = `${readable || "default"}-${hash}`;
2149
2514
  const base = isEphemeralCheckoutRoot(cwd) ? ephemeralDataBase(resolvedBase) : resolvedBase;
2150
- const dir = path8.join(base, slug);
2515
+ const dir = path9.join(base, slug);
2151
2516
  if (base !== resolvedBase && pendingDataDirMigrations.length < 32) {
2152
2517
  pendingDataDirMigrations.push({ to: dir, outcome: "ephemeral" });
2153
2518
  }
2154
2519
  const settled = settleProjectDataDir(base, readable || "default", dir, memoKey, canonical.fallback);
2155
2520
  if (settled === dir) {
2156
- adoptSpelledDataDirs(path8.resolve(cwd), base, dir, readable || "default");
2521
+ adoptSpelledDataDirs(path9.resolve(cwd), base, dir, readable || "default");
2157
2522
  }
2158
2523
  return settled;
2159
2524
  }
@@ -2179,18 +2544,18 @@ function adoptSpelledDataDirs(spelledRoot, base, dir, settledOldSlug) {
2179
2544
  }
2180
2545
  }
2181
2546
  function adoptSource(base, source, dir) {
2182
- const from = path8.join(base, source);
2547
+ const from = path9.join(base, source);
2183
2548
  if (from === dir || !isDirectory(from))
2184
2549
  return { copied: 0, failed: 0 };
2185
- const marker = path8.join(dir, `${ADOPTED_MARKER_PREFIX}${source}`);
2186
- if (fs5.existsSync(marker))
2550
+ const marker = path9.join(dir, `${ADOPTED_MARKER_PREFIX}${source}`);
2551
+ if (fs6.existsSync(marker))
2187
2552
  return { copied: 0, failed: 0 };
2188
2553
  const { copied, failed } = copyMissingFiles(from, dir);
2189
2554
  return { copied, failed: failed + (markAdopted(marker) ? 0 : 1) };
2190
2555
  }
2191
2556
  function markAdopted(marker) {
2192
2557
  try {
2193
- fs5.mkdirSync(path8.dirname(marker), { recursive: true });
2558
+ fs6.mkdirSync(path9.dirname(marker), { recursive: true });
2194
2559
  writeFileAtomic(marker, "", { bestEffort: false });
2195
2560
  return true;
2196
2561
  } catch {
@@ -2199,7 +2564,7 @@ function markAdopted(marker) {
2199
2564
  }
2200
2565
  function isDirectory(dir) {
2201
2566
  try {
2202
- return fs5.statSync(dir).isDirectory();
2567
+ return fs6.statSync(dir).isDirectory();
2203
2568
  } catch {
2204
2569
  return false;
2205
2570
  }
@@ -2213,7 +2578,7 @@ function copyMissingFiles(from, to) {
2213
2578
  const rel = pending.pop() ?? "";
2214
2579
  let entries;
2215
2580
  try {
2216
- entries = fs5.readdirSync(path8.join(from, rel), { withFileTypes: true });
2581
+ entries = fs6.readdirSync(path9.join(from, rel), { withFileTypes: true });
2217
2582
  } catch {
2218
2583
  failed++;
2219
2584
  continue;
@@ -2226,7 +2591,7 @@ function copyMissingFiles(from, to) {
2226
2591
  continue;
2227
2592
  if (name.startsWith(ADOPTED_MARKER_PREFIX))
2228
2593
  continue;
2229
- const child = path8.join(rel, name);
2594
+ const child = path9.join(rel, name);
2230
2595
  if (entry.isDirectory()) {
2231
2596
  if (++seen > ADOPT_MAX_ENTRIES)
2232
2597
  return { copied, failed: failed + 1 };
@@ -2237,7 +2602,7 @@ function copyMissingFiles(from, to) {
2237
2602
  continue;
2238
2603
  if (++seen > ADOPT_MAX_ENTRIES)
2239
2604
  return { copied, failed: failed + 1 };
2240
- const outcome = copyIfMissing(path8.join(from, child), path8.join(to, child));
2605
+ const outcome = copyIfMissing(path9.join(from, child), path9.join(to, child));
2241
2606
  if (outcome === "copied")
2242
2607
  copied++;
2243
2608
  else if (outcome === "failed")
@@ -2250,21 +2615,21 @@ function copyIfMissing(source, target) {
2250
2615
  const stage = stagePathFor(target);
2251
2616
  let staged = false;
2252
2617
  try {
2253
- fs5.mkdirSync(path8.dirname(target), { recursive: true });
2618
+ fs6.mkdirSync(path9.dirname(target), { recursive: true });
2254
2619
  staged = true;
2255
- fs5.copyFileSync(source, stage);
2256
- fs5.linkSync(stage, target);
2620
+ fs6.copyFileSync(source, stage);
2621
+ fs6.linkSync(stage, target);
2257
2622
  return "copied";
2258
2623
  } catch (cause) {
2259
2624
  return staged && cause.code === "EEXIST" ? "present" : "failed";
2260
2625
  } finally {
2261
2626
  if (staged)
2262
- fs5.rmSync(stage, { force: true });
2627
+ fs6.rmSync(stage, { force: true });
2263
2628
  }
2264
2629
  }
2265
2630
  function projectDataBase() {
2266
2631
  const configuredBase = process.env.PILENS_DATA_DIR?.trim();
2267
- return configuredBase || path8.join(getGlobalPiLensDir(), "projects");
2632
+ return configuredBase || path9.join(getGlobalPiLensDir(), "projects");
2268
2633
  }
2269
2634
  var EPHEMERAL_DATA_DIR_NAME = ".ephemeral";
2270
2635
  var EPHEMERAL_TOKEN_PATTERN = /^(\d+)-[0-9a-f]{8}$/;
@@ -2280,20 +2645,20 @@ function ephemeralDataBase(resolvedBase) {
2280
2645
  state.exitHook = true;
2281
2646
  process.once("exit", removeEphemeralDataDirs);
2282
2647
  }
2283
- return path8.join(resolvedBase, EPHEMERAL_DATA_DIR_NAME, state.token);
2648
+ return path9.join(resolvedBase, EPHEMERAL_DATA_DIR_NAME, state.token);
2284
2649
  }
2285
2650
  function removeEphemeralDataDirs() {
2286
- const dir = path8.join(projectDataBase(), EPHEMERAL_DATA_DIR_NAME, ephemeralDataToken().token);
2651
+ const dir = path9.join(projectDataBase(), EPHEMERAL_DATA_DIR_NAME, ephemeralDataToken().token);
2287
2652
  try {
2288
- fs5.rmSync(dir, { recursive: true, force: true });
2653
+ fs6.rmSync(dir, { recursive: true, force: true });
2289
2654
  } catch {
2290
2655
  }
2291
2656
  }
2292
2657
  async function sweepDeadEphemeralDataDirs(options) {
2293
- const parent = path8.join(projectDataBase(), EPHEMERAL_DATA_DIR_NAME);
2658
+ const parent = path9.join(projectDataBase(), EPHEMERAL_DATA_DIR_NAME);
2294
2659
  let handle;
2295
2660
  try {
2296
- handle = await fs5.promises.opendir(parent);
2661
+ handle = await fs6.promises.opendir(parent);
2297
2662
  } catch {
2298
2663
  return 0;
2299
2664
  }
@@ -2307,7 +2672,7 @@ async function sweepDeadEphemeralDataDirs(options) {
2307
2672
  if (pid === void 0 || options.isPidAlive(Number(pid)))
2308
2673
  continue;
2309
2674
  try {
2310
- await fs5.promises.rm(path8.join(parent, entry.name), {
2675
+ await fs6.promises.rm(path9.join(parent, entry.name), {
2311
2676
  recursive: true,
2312
2677
  force: true
2313
2678
  });
@@ -2327,14 +2692,9 @@ function projectDataDirReadableSlug(canonicalRoot) {
2327
2692
  return normalized.replace(/^[a-z]:/i, "").replace(/\/+/g, "-").replace(/[^A-Za-z0-9-]/g, "").replace(/^-+/, "").replace(/-+$/, "");
2328
2693
  }
2329
2694
  function dataDirCanonicalRoot(cwd, platform = process.platform) {
2330
- const resolved = path8.resolve(cwd);
2695
+ const resolved = path9.resolve(cwd);
2331
2696
  const root = platform === "win32" ? resolved : realpathOrResolve(resolved);
2332
- try {
2333
- fs5.realpathSync(resolved);
2334
- } catch {
2335
- return { root, fallback: true };
2336
- }
2337
- return { root, fallback: false };
2697
+ return { root, fallback: !fs6.existsSync(resolved) };
2338
2698
  }
2339
2699
  function projectDataDirRootHash(canonicalRoot) {
2340
2700
  return createHash("sha256").update(canonicalRoot).digest("hex").slice(0, 8);
@@ -2345,9 +2705,9 @@ function resetProjectDataDirSessionState() {
2345
2705
  pendingDataDirMigrations.splice(0);
2346
2706
  }
2347
2707
  function settleProjectDataDir(base, oldSlug, dir, memoKey, identityFallback) {
2348
- const oldDir = path8.join(base, oldSlug);
2349
- const newExists = fs5.existsSync(dir);
2350
- const oldExists = fs5.existsSync(oldDir);
2708
+ const oldDir = path9.join(base, oldSlug);
2709
+ const newExists = fs6.existsSync(dir);
2710
+ const oldExists = fs6.existsSync(oldDir);
2351
2711
  if (!oldExists) {
2352
2712
  if (identityFallback && pendingDataDirMigrations.length < 32) {
2353
2713
  pendingDataDirMigrations.push({
@@ -2360,14 +2720,14 @@ function settleProjectDataDir(base, oldSlug, dir, memoKey, identityFallback) {
2360
2720
  }
2361
2721
  if (!newExists) {
2362
2722
  try {
2363
- fs5.renameSync(oldDir, dir);
2723
+ fs6.renameSync(oldDir, dir);
2364
2724
  } catch (error) {
2365
2725
  if (error.code === "ENOENT") {
2366
- if (fs5.existsSync(dir)) {
2726
+ if (fs6.existsSync(dir)) {
2367
2727
  settledDataDirs.set(memoKey, dir);
2368
2728
  return dir;
2369
2729
  }
2370
- if (fs5.existsSync(oldDir))
2730
+ if (fs6.existsSync(oldDir))
2371
2731
  return oldDir;
2372
2732
  return dir;
2373
2733
  }
@@ -2394,8 +2754,8 @@ function drainProjectDataDirMigrations() {
2394
2754
  return pendingDataDirMigrations.splice(0);
2395
2755
  }
2396
2756
  function displayProjectDataPath(cwd, ...segments) {
2397
- const absolute = path8.resolve(getProjectDataDir(cwd), ...segments);
2398
- const absolutePosix = absolute.replace(/\\/g, "/");
2757
+ const absolute = path9.resolve(getProjectDataDir(cwd), ...segments);
2758
+ const absolutePosix = toPosix(absolute);
2399
2759
  const relative3 = toProjectRelativePath(absolute, cwd);
2400
2760
  if (relative3 !== absolutePosix) {
2401
2761
  return relative3;
@@ -2406,13 +2766,13 @@ function getGlobalPiLensDir() {
2406
2766
  return machineStateDir();
2407
2767
  }
2408
2768
  function isPiLensInternalPath(filePath, projectRoot) {
2409
- const absolute = path8.resolve(filePath);
2410
- const home = path8.resolve(os3.homedir());
2769
+ const absolute = path9.resolve(filePath);
2770
+ const home = path9.resolve(os3.homedir());
2411
2771
  const candidates = [
2412
2772
  getGlobalPiLensDir(),
2413
2773
  getProjectDataDir(projectRoot),
2414
- path8.join(home, ".pi"),
2415
- path8.join(home, ".pi-lens")
2774
+ path9.join(home, ".pi"),
2775
+ path9.join(home, ".pi-lens")
2416
2776
  ];
2417
2777
  if (candidates.some((dir) => isUnderDir(absolute, dir)))
2418
2778
  return true;
@@ -2476,16 +2836,11 @@ var EXCLUDED_DIRS = [
2476
2836
  "vendors"
2477
2837
  ];
2478
2838
  function resolveGitIgnoreRoot(startDir) {
2479
- const fallback = realpathOrResolve(startDir);
2480
- let current = fallback;
2481
- while (true) {
2482
- if (fs5.existsSync(path8.join(current, ".git")))
2839
+ for (const current of walkUpDirs(startDir)) {
2840
+ if (fs6.existsSync(path9.join(current, ".git")))
2483
2841
  return current;
2484
- const parent = path8.dirname(current);
2485
- if (parent === current)
2486
- return fallback;
2487
- current = parent;
2488
2842
  }
2843
+ return realpathOrResolve(startDir);
2489
2844
  }
2490
2845
  function collapseSlashes(value) {
2491
2846
  let out = "";
@@ -2584,10 +2939,40 @@ function matchesGitignorePattern(pattern, relativePath, isDirectory2, matchExpan
2584
2939
  return candidates.some((value) => matchExpanded(value, expanded));
2585
2940
  });
2586
2941
  }
2942
+ function lastMatchingPattern(patterns, relativePath, isDirectory2, matchExpanded) {
2943
+ let winner;
2944
+ for (const pattern of patterns) {
2945
+ if (matchesGitignorePattern(pattern, relativePath, isDirectory2, matchExpanded))
2946
+ winner = pattern;
2947
+ }
2948
+ return winner;
2949
+ }
2950
+ var gitignoreGlobOptions = {
2951
+ dot: true,
2952
+ nocase: process.platform === "win32"
2953
+ };
2954
+ function createExpandedGlobMatcher() {
2955
+ const compiledGlobs = /* @__PURE__ */ new Map();
2956
+ return (value, expanded) => {
2957
+ let compiled = compiledGlobs.get(expanded);
2958
+ if (compiled === void 0) {
2959
+ compiled = new Minimatch(expanded, gitignoreGlobOptions);
2960
+ compiledGlobs.set(expanded, compiled);
2961
+ }
2962
+ return compiled.match(value);
2963
+ };
2964
+ }
2965
+ function isIgnoredByGitignoreLines(lines, baseDir, filePath, isDirectory2 = false) {
2966
+ const relative3 = relativeInside(baseDir, filePath);
2967
+ if (relative3 === void 0)
2968
+ return false;
2969
+ const winner = lastMatchingPattern(parseGitignoreContent(lines.join("\n"), "pilens"), normalizeIgnorePath(relative3), isDirectory2, createExpandedGlobMatcher());
2970
+ return winner !== void 0 && !winner.negated;
2971
+ }
2587
2972
  function readGitignorePatterns(rootDir, layer = "gitignore") {
2588
- const gitignorePath = path8.join(rootDir, ".gitignore");
2973
+ const gitignorePath = path9.join(rootDir, ".gitignore");
2589
2974
  try {
2590
- return parseGitignoreContent(fs5.readFileSync(gitignorePath, "utf-8"), layer);
2975
+ return parseGitignoreContent(fs6.readFileSync(gitignorePath, "utf-8"), layer);
2591
2976
  } catch {
2592
2977
  return [];
2593
2978
  }
@@ -2601,13 +2986,13 @@ function isWithinPathForm(child, parent) {
2601
2986
  function ancestorDirsBetween(rootDir, targetDir) {
2602
2987
  if (!isWithinPathForm(targetDir, rootDir))
2603
2988
  return [];
2604
- const relative3 = path8.relative(rootDir, targetDir);
2989
+ const relative3 = path9.relative(rootDir, targetDir);
2605
2990
  const dirs = [rootDir];
2606
2991
  if (!relative3)
2607
2992
  return dirs;
2608
2993
  let current = rootDir;
2609
- for (const segment of relative3.split(path8.sep).filter(Boolean)) {
2610
- current = path8.join(current, segment);
2994
+ for (const segment of relative3.split(path9.sep).filter(Boolean)) {
2995
+ current = path9.join(current, segment);
2611
2996
  dirs.push(current);
2612
2997
  }
2613
2998
  return dirs;
@@ -2617,7 +3002,7 @@ function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
2617
3002
  const rememberIgnoreSource = (filePath, signature = fileFreshnessSignature(filePath)) => {
2618
3003
  consumedIgnoreSources.set(filePath, { path: filePath, ...signature });
2619
3004
  };
2620
- rememberIgnoreSource(path8.join(resolvedRoot, ".gitignore"));
3005
+ rememberIgnoreSource(path9.join(resolvedRoot, ".gitignore"));
2621
3006
  const nestedCache = /* @__PURE__ */ new Map();
2622
3007
  const patternsForDir = (dir) => {
2623
3008
  if (dir === resolvedRoot)
@@ -2628,7 +3013,7 @@ function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
2628
3013
  return cached.patterns;
2629
3014
  }
2630
3015
  const gitignoreSig = gitignoreSignature(dir);
2631
- rememberIgnoreSource(path8.join(dir, ".gitignore"), gitignoreSig);
3016
+ rememberIgnoreSource(path9.join(dir, ".gitignore"), gitignoreSig);
2632
3017
  const pilensInfo = findPiLensConfigInDir(dir);
2633
3018
  const pilensMtime = pilensInfo?.mtimeMs ?? -1;
2634
3019
  const pilensSize = pilensInfo?.size ?? -1;
@@ -2655,7 +3040,7 @@ function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
2655
3040
  };
2656
3041
  const patternMemo = /* @__PURE__ */ new Map();
2657
3042
  function dropVerdictsUnder(subtree) {
2658
- const subtreeForm = path8.resolve(subtree);
3043
+ const subtreeForm = path9.resolve(subtree);
2659
3044
  for (const key of patternMemo.keys()) {
2660
3045
  const memoPath = key.slice(2);
2661
3046
  if (isWithinPathForm(memoPath, subtreeForm)) {
@@ -2674,20 +3059,20 @@ function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
2674
3059
  };
2675
3060
  const hasDotSegment = (spelling) => /(^|[\\/])\.\.?([\\/]|$)/.test(spelling);
2676
3061
  const projectPathKey = (spelling) => {
2677
- const absolute = path8.resolve(spelling);
3062
+ const absolute = path9.resolve(spelling);
2678
3063
  if (!hasDotSegment(spelling)) {
2679
3064
  if (isUnderRootText(absolute))
2680
3065
  return absolute;
2681
- return path8.join(identityOfDir(path8.dirname(absolute)), path8.basename(absolute));
3066
+ return path9.join(identityOfDir(path9.dirname(absolute)), path9.basename(absolute));
2682
3067
  }
2683
- const tail = path8.basename(spelling);
3068
+ const tail = path9.basename(spelling);
2684
3069
  if (tail === "." || tail === "..")
2685
3070
  return identityOfDir(spelling);
2686
- return path8.join(identityOfDir(path8.dirname(spelling)), tail);
3071
+ return path9.join(identityOfDir(path9.dirname(spelling)), tail);
2687
3072
  };
2688
3073
  const isUnderRootText = (absolute) => isWithinPathForm(absolute, resolvedRoot);
2689
3074
  const invalidateSubtree = (subtree) => {
2690
- const absolute = path8.resolve(subtree);
3075
+ const absolute = path9.resolve(subtree);
2691
3076
  let local = absolute;
2692
3077
  if (hasDotSegment(subtree))
2693
3078
  local = identityOfDir(subtree);
@@ -2696,19 +3081,7 @@ function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
2696
3081
  dropVerdictsUnder(local);
2697
3082
  nestedCache.delete(local);
2698
3083
  };
2699
- const gitignoreGlobOptions = {
2700
- dot: true,
2701
- nocase: process.platform === "win32"
2702
- };
2703
- const compiledGlobs = /* @__PURE__ */ new Map();
2704
- const matchExpanded = (value, expanded) => {
2705
- let compiled = compiledGlobs.get(expanded);
2706
- if (compiled === void 0) {
2707
- compiled = new Minimatch(expanded, gitignoreGlobOptions);
2708
- compiledGlobs.set(expanded, compiled);
2709
- }
2710
- return compiled.match(value);
2711
- };
3084
+ const matchExpanded = createExpandedGlobMatcher();
2712
3085
  function isTrackedAndRescued(resolved) {
2713
3086
  const snapshot = getTrackedFilesSnapshot(resolvedRoot);
2714
3087
  if (!snapshot)
@@ -2737,18 +3110,17 @@ function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
2737
3110
  } else {
2738
3111
  let ignored = false;
2739
3112
  let layer;
2740
- const patternDirs = ancestorDirsBetween(resolvedRoot, path8.dirname(resolved));
3113
+ const patternDirs = ancestorDirsBetween(resolvedRoot, path9.dirname(resolved));
2741
3114
  for (const dir of patternDirs) {
2742
3115
  const dirPatterns = patternsForDir(dir);
2743
3116
  if (dirPatterns.length === 0)
2744
3117
  continue;
2745
- const relative3 = path8.relative(dir, resolved);
3118
+ const relative3 = path9.relative(dir, resolved);
2746
3119
  const normalized = normalizeIgnorePath(relative3);
2747
- for (const pattern of dirPatterns) {
2748
- if (!matchesGitignorePattern(pattern, normalized, isDirectory2, matchExpanded))
2749
- continue;
2750
- ignored = !pattern.negated;
2751
- layer = pattern.layer;
3120
+ const winner = lastMatchingPattern(dirPatterns, normalized, isDirectory2, matchExpanded);
3121
+ if (winner) {
3122
+ ignored = !winner.negated;
3123
+ layer = winner.layer;
2752
3124
  }
2753
3125
  }
2754
3126
  verdict = { ignored, layer };
@@ -2777,7 +3149,7 @@ var projectIgnoreMatcherCache = /* @__PURE__ */ new Map();
2777
3149
  var PROJECT_IGNORE_FRESHNESS_CADENCE_MS = FRESHNESS_CADENCE_MS;
2778
3150
  function fileFreshnessSignature(filePath) {
2779
3151
  try {
2780
- const stat = fs5.statSync(filePath);
3152
+ const stat = fs6.statSync(filePath);
2781
3153
  return { mtimeMs: stat.mtimeMs, size: stat.size };
2782
3154
  } catch {
2783
3155
  return { mtimeMs: -1, size: -1 };
@@ -2787,7 +3159,7 @@ function globalConfigSignature() {
2787
3159
  return fileFreshnessSignature(getPiLensGlobalConfigPath());
2788
3160
  }
2789
3161
  function gitignoreSignature(rootDir) {
2790
- return fileFreshnessSignature(path8.join(rootDir, ".gitignore"));
3162
+ return fileFreshnessSignature(path9.join(rootDir, ".gitignore"));
2791
3163
  }
2792
3164
  function hasIgnoreSourceDrift(sources) {
2793
3165
  return sources.some((source) => {
@@ -2848,17 +3220,17 @@ function getProjectIgnoreMatcher(rootDir) {
2848
3220
  return matcher;
2849
3221
  }
2850
3222
  function invalidateProjectIgnoreMatcherForPath(filePath) {
2851
- const resolvedPath = path8.resolve(filePath);
2852
- if (path8.basename(resolvedPath).toLowerCase() !== ".gitignore")
3223
+ const resolvedPath = path9.resolve(filePath);
3224
+ if (path9.basename(resolvedPath).toLowerCase() !== ".gitignore")
2853
3225
  return;
2854
3226
  for (const [cachedRoot, cached] of projectIgnoreMatcherCache) {
2855
3227
  if (!isUnderDir(resolvedPath, cachedRoot))
2856
3228
  continue;
2857
- if (normalizeFilePath(resolvedPath) === normalizeFilePath(path8.join(cachedRoot, ".gitignore"))) {
3229
+ if (normalizeFilePath(resolvedPath) === normalizeFilePath(path9.join(cachedRoot, ".gitignore"))) {
2858
3230
  projectIgnoreMatcherCache.delete(cachedRoot);
2859
3231
  continue;
2860
3232
  }
2861
- cached.matcher.invalidateSubtree(path8.dirname(filePath));
3233
+ cached.matcher.invalidateSubtree(path9.dirname(filePath));
2862
3234
  }
2863
3235
  }
2864
3236
  function isPathIgnoredByProject(filePath, rootDir, isDirectory2 = false) {
@@ -2873,7 +3245,7 @@ function isRecordableProjectPath(filePath, projectRoot) {
2873
3245
  }
2874
3246
  var projectIgnoreGlobsCache = /* @__PURE__ */ new Map();
2875
3247
  function getProjectIgnoreGlobs(rootDir) {
2876
- const resolvedRoot = path8.resolve(rootDir);
3248
+ const resolvedRoot = path9.resolve(rootDir);
2877
3249
  const signature = gitignoreSignature(resolvedRoot);
2878
3250
  const cached = projectIgnoreGlobsCache.get(resolvedRoot);
2879
3251
  if (cached && cached.mtimeMs === signature.mtimeMs && cached.size === signature.size) {
@@ -2928,7 +3300,7 @@ function getKnipIgnorePatterns() {
2928
3300
  function isTestFile(filePath) {
2929
3301
  if (detectFileRole(filePath) === "test")
2930
3302
  return true;
2931
- const normalized = filePath.replace(/\\/g, "/");
3303
+ const normalized = toPosix(filePath);
2932
3304
  return normalized.includes("test-utils") || normalized.startsWith("test-") || normalized.includes(".fixture.") || normalized.includes(".mock.");
2933
3305
  }
2934
3306
 
@@ -2989,569 +3361,205 @@ function makeHandle(sourceName, generation, read, tallyName) {
2989
3361
  return write();
2990
3362
  }
2991
3363
  };
2992
- }
2993
- function createGenerationSource(name, store) {
2994
- declare(name);
2995
- const local = { generation: 0 };
2996
- const cell = store ?? (() => local);
2997
- const read = () => cell().generation;
2998
- return {
2999
- name,
3000
- current: read,
3001
- bump() {
3002
- const held = cell();
3003
- held.generation += 1;
3004
- return held.generation;
3005
- },
3006
- capture() {
3007
- return makeHandle(name, read(), read, name);
3008
- }
3009
- };
3010
- }
3011
- var DEFAULT_MAX_KEYS = 512;
3012
- function createGenerationMap(name, options = {}) {
3013
- declare(name);
3014
- const normalize = options.normalizeKey ?? ((key) => key);
3015
- const maxKeys = Math.max(1, options.maxKeys ?? DEFAULT_MAX_KEYS);
3016
- const stamps = new BoundedFifoMap(maxKeys);
3017
- let nextTicket = 0;
3018
- let invalidations = 0;
3019
- const read = (key) => stamps.get(key) ?? 0;
3020
- function issue(key) {
3021
- nextTicket += 1;
3022
- stamps.delete(key);
3023
- const evicted = stamps.set(key, nextTicket);
3024
- invalidations += evicted.length;
3025
- return nextTicket;
3026
- }
3027
- return {
3028
- name,
3029
- current(key) {
3030
- return read(normalize(key));
3031
- },
3032
- bump(key) {
3033
- invalidations += 1;
3034
- return issue(normalize(key));
3035
- },
3036
- capture(key) {
3037
- const normalized = normalize(key);
3038
- const stamp = read(normalized) || issue(normalized);
3039
- const capturedInvalidations = invalidations;
3040
- return makeHandle(`${name}[${normalized}]`, stamp, () => {
3041
- if (invalidations === capturedInvalidations)
3042
- return stamp;
3043
- return read(normalize(key));
3044
- }, name);
3045
- },
3046
- forget(key) {
3047
- invalidations += 1;
3048
- stamps.delete(normalize(key));
3049
- },
3050
- clear() {
3051
- invalidations += 1;
3052
- stamps.clear();
3053
- },
3054
- size() {
3055
- return stamps.size;
3056
- }
3057
- };
3058
- }
3059
-
3060
- // dist/clients/instance-registry-lock.js
3061
- import * as fs6 from "node:fs";
3062
- import { randomInt as randomInt2 } from "node:crypto";
3063
- import * as path9 from "node:path";
3064
- var OWN_HOLDS_FAMILY = "instance-registry.lock-own-holds";
3065
- var OWN_HOLDS_VERSION = 1;
3066
- function ownAsyncHolds() {
3067
- return getProcessSingleton(OWN_HOLDS_FAMILY, OWN_HOLDS_VERSION, () => ({
3068
- count: 0
3069
- }));
3070
- }
3071
- var LOCK_STALE_MS = 5e3;
3072
- var LOCK_WAIT_MS = 500;
3073
- var LOCK_MIN_BACKOFF_MS = 5;
3074
- var LOCK_MAX_BACKOFF_MS = 25;
3075
- function generationDir2(target) {
3076
- return `${target}.locks`;
3077
- }
3078
- function legacyLockPath(target) {
3079
- return `${target}.lock`;
3080
- }
3081
- function createLegacyLock(lock) {
3082
- try {
3083
- fs6.writeFileSync(lock, `${process.pid} ${Date.now()}
3084
- `, { flag: "wx" });
3085
- return true;
3086
- } catch (error) {
3087
- if (isLockContention(error))
3088
- return false;
3089
- throw error;
3090
- }
3091
- }
3092
- function takeLegacyLock(lock) {
3093
- if (createLegacyLock(lock))
3094
- return true;
3095
- if (!pidFileIsStale(lock, LOCK_STALE_MS))
3096
- return false;
3097
- try {
3098
- fs6.unlinkSync(lock);
3099
- } catch {
3100
- }
3101
- return createLegacyLock(lock);
3102
- }
3103
- function releaseLegacyLock(lock) {
3104
- if (pidFileOwner(lock) !== process.pid)
3105
- return;
3106
- try {
3107
- fs6.unlinkSync(lock);
3108
- } catch {
3109
- }
3110
- }
3111
- function tryAcquire(target) {
3112
- let hold;
3113
- try {
3114
- hold = tryAcquireGeneration(generationDir2(target), LOCK_STALE_MS);
3115
- if (!hold)
3116
- return "busy";
3117
- if (hold.tookOverStale)
3118
- recordStaleTakeover(target, hold);
3119
- if (takeLegacyLock(legacyLockPath(target)))
3120
- return hold;
3121
- recordLegacyHeld(target);
3122
- releaseGeneration(hold);
3123
- return "busy";
3124
- } catch (cause) {
3125
- recordLockFailure(target, cause);
3126
- if (hold)
3127
- releaseGeneration(hold);
3128
- return "failed";
3129
- }
3130
- }
3131
- function release(target, hold) {
3132
- releaseLegacyLock(legacyLockPath(target));
3133
- releaseGeneration(hold);
3134
- }
3135
- function recordLockFailure(target, cause) {
3136
- const code = cause?.code ?? "unknown";
3137
- incrementDegradationCount({
3138
- kind: "instance-registry-lock-failed",
3139
- subject: path9.resolve(target),
3140
- reason: `lock acquisition failed for ${path9.basename(target)} (${code}); the registry write was skipped`
3141
- });
3142
- }
3143
- function recordStaleTakeover(target, hold) {
3144
- incrementDegradationCount({
3145
- kind: "instance-registry-lock-stale-takeover",
3146
- subject: path9.resolve(target),
3147
- reason: `took over lock generation ${hold.generation - 1} from a dead or aged-out holder`
3148
- });
3149
- }
3150
- function recordLegacyHeld(target) {
3151
- const lock = legacyLockPath(target);
3152
- incrementDegradationCount({
3153
- kind: "instance-registry-lock-legacy-held",
3154
- subject: path9.resolve(lock),
3155
- reason: `backed off: ${path9.basename(lock)} is held by pid ${pidFileOwner(lock) ?? "unknown"}, a writer from before #3476`
3156
- });
3157
- }
3158
- function recordLockTimeout(target) {
3159
- incrementDegradationCount({
3160
- kind: "instance-registry-lock-timeout",
3161
- subject: path9.resolve(target),
3162
- reason: `lock acquisition exhausted for ${path9.basename(target)}`
3163
- });
3164
- }
3165
- function backoffMs() {
3166
- return randomInt2(LOCK_MIN_BACKOFF_MS, LOCK_MAX_BACKOFF_MS + 1);
3167
- }
3168
- var LOCK_WAIT_THROUGH_LEASE_MS = LOCK_STALE_MS + LOCK_WAIT_MS;
3169
- async function withInstanceRegistryLock(target, op, waitMs = LOCK_WAIT_MS) {
3170
- const deadline = Date.now() + waitMs;
3171
- while (Date.now() <= deadline) {
3172
- const hold = tryAcquire(target);
3173
- if (hold === "failed")
3174
- return void 0;
3175
- if (hold === "busy") {
3176
- if (Date.now() <= deadline)
3177
- await new Promise((resolve7) => setTimeout(resolve7, backoffMs()));
3178
- continue;
3179
- }
3180
- const holds = ownAsyncHolds();
3181
- holds.count += 1;
3182
- try {
3183
- return await op();
3184
- } finally {
3185
- holds.count -= 1;
3186
- release(target, hold);
3187
- }
3188
- }
3189
- recordLockTimeout(target);
3190
- return void 0;
3191
- }
3192
-
3193
- // dist/scripts/lib/process-scan.mjs
3194
- import fs7 from "node:fs";
3195
- import path10 from "node:path";
3196
- function runningOnWindows() {
3197
- return process.platform === "win32";
3198
- }
3199
- var FIELD_COLUMNS = Object.freeze({
3200
- pid: { wmi: "ProcessId", ps: "pid", token: "int" },
3201
- ppid: { wmi: "ParentProcessId", ps: "ppid", token: "int" },
3202
- ageMs: { wmi: "CreationDate", ps: "etime", token: "age" },
3203
- rssBytes: { wmi: "WorkingSetSize", ps: null, token: "int" },
3204
- cpuKernel100ns: { wmi: "KernelModeTime", ps: null, token: "int" },
3205
- cpuUser100ns: { wmi: "UserModeTime", ps: null, token: "int" },
3206
- startedAt: { wmi: "CreationDate", ps: "lstart", token: "lstart" },
3207
- command: { wmi: "CommandLine", ps: "args", token: "tail" }
3208
- });
3209
- var FIELD_ORDER = Object.freeze(Object.keys(FIELD_COLUMNS));
3210
- var ALL_PROCESS_FIELDS = Object.freeze(["pid", "ppid", "command"]);
3211
- var FILTERABLE_COLUMNS = /* @__PURE__ */ new Set(["ProcessId", "Name", "CommandLine"]);
3212
- function windowsExe(name) {
3213
- return path10.join(process.env.SystemRoot ?? path10.join("C:", "Windows"), "System32", name);
3214
- }
3215
- function posixPsPath() {
3216
- try {
3217
- if (fs7.existsSync("/bin/ps"))
3218
- return "/bin/ps";
3219
- if (fs7.existsSync("/usr/bin/ps"))
3220
- return "/usr/bin/ps";
3221
- } catch {
3222
- }
3223
- return "/bin/ps";
3224
- }
3225
- function normalizeProcessFields(fields) {
3226
- const requested = new Set((fields ?? ALL_PROCESS_FIELDS).filter((field) => field in FIELD_COLUMNS));
3227
- requested.add("pid");
3228
- return FIELD_ORDER.filter((field) => requested.has(field));
3229
- }
3230
- function escapeWqlLikeValue(value) {
3231
- return String(value).replaceAll("'", "''").replaceAll(/[%_]/g, (ch) => `[${ch}]`);
3232
- }
3233
- function escapeWqlStringValue(value) {
3234
- return String(value).replaceAll("'", "''");
3235
- }
3236
- function assertPid(value) {
3237
- const pid = Number(value);
3238
- if (!Number.isInteger(pid) || pid <= 0) {
3239
- throw new Error(`process filter: invalid pid ${String(value)}`);
3240
- }
3241
- return pid;
3242
- }
3243
- function wqlFilterExpression(filter) {
3244
- const { column, op, values } = filter;
3245
- if (!FILTERABLE_COLUMNS.has(column)) {
3246
- throw new Error(`process filter: unsupported column ${String(column)}`);
3247
- }
3248
- const list = [...values];
3249
- if (list.length === 0) {
3250
- throw new Error(`process filter: ${column} filter has no values`);
3251
- }
3252
- if (column === "ProcessId") {
3253
- return list.map((value) => `ProcessId=${assertPid(value)}`).join(" OR ");
3254
- }
3255
- if (op === "like") {
3256
- return list.map((value) => `${column} LIKE '%${escapeWqlLikeValue(value)}%'`).join(" OR ");
3257
- }
3258
- return list.map((value) => `${column} = '${escapeWqlStringValue(value)}'`).join(" OR ");
3259
- }
3260
- function buildProcessQuery(fields = ALL_PROCESS_FIELDS, options = {}) {
3261
- const layout = normalizeProcessFields(fields);
3262
- const filter = options.filter;
3263
- if (runningOnWindows()) {
3264
- const columns2 = [
3265
- ...new Set(layout.map((field) => FIELD_COLUMNS[field].wmi))
3266
- ];
3267
- const where = filter ? ` WHERE ${wqlFilterExpression(filter)}` : "";
3268
- const excludeSelf = options.excludeSelfPid ? " | Where-Object { $_.ProcessId -ne $PID }" : "";
3269
- const prelude = (layout.includes("ageMs") ? "$age = if ($_.CreationDate -is [datetime]) { [int64]((Get-Date) - $_.CreationDate).TotalMilliseconds } else { '' }; " : "") + (layout.includes("startedAt") ? "$st = if ($_.CreationDate -is [datetime]) { $_.CreationDate.ToUniversalTime().ToString('o') } else { '' }; " : "");
3270
- const row = layout.map((field) => {
3271
- if (field === "ageMs")
3272
- return "$age";
3273
- if (field === "startedAt")
3274
- return "$st";
3275
- return `$($_.${FIELD_COLUMNS[field].wmi})`;
3276
- }).join("`t");
3277
- return {
3278
- command: windowsExe("WindowsPowerShell\\v1.0\\powershell.exe"),
3279
- args: [
3280
- "-NoProfile",
3281
- "-NonInteractive",
3282
- "-Command",
3283
- `Get-CimInstance -Query "SELECT ${columns2.join(",")} FROM Win32_Process${where}"${excludeSelf} | ForEach-Object { ${prelude}"${row}" }`
3284
- ],
3285
- tabSeparated: true,
3286
- fields: layout,
3287
- serverSideFiltered: Boolean(filter)
3288
- };
3289
- }
3290
- const unsupported = layout.filter((field) => !FIELD_COLUMNS[field].ps);
3291
- if (unsupported.length > 0) {
3292
- throw new Error(`process query: ${unsupported.join(", ")} has no POSIX ps column`);
3293
- }
3294
- if (layout.includes("startedAt") && process.platform === "linux") {
3295
- throw new Error("process query: startedAt on Linux is read from /proc, not ps");
3296
- }
3297
- const columns = layout.map((field) => `${FIELD_COLUMNS[field].ps}=`).join(",");
3298
- const pidFilter = filter && filter.column === "ProcessId" && filter.op === "eq" ? [...filter.values].map((value) => assertPid(value)) : null;
3299
- return {
3300
- command: posixPsPath(),
3301
- args: pidFilter ? ["-p", pidFilter.join(","), "-o", columns] : ["-eo", columns],
3302
- tabSeparated: false,
3303
- fields: layout,
3304
- serverSideFiltered: Boolean(pidFilter),
3305
- // BSD `ps` formats `lstart` with strftime("%c") in the local zone, so
3306
- // two readers with different locales or zones would print one process
3307
- // two ways. Pinned, every reader prints the same text.
3308
- ...layout.includes("startedAt") ? { env: posixStartEnv() } : {}
3309
- };
3310
- }
3311
- function posixStartEnv() {
3312
- return { ...process.env, LC_ALL: "C", TZ: "UTC0" };
3313
- }
3314
- function readLinuxProcessStart(pid) {
3315
- try {
3316
- const ticks = parseLinuxStatStart(fs7.readFileSync(`/proc/${assertPid(pid)}/stat`, "utf8"));
3317
- const boot = fs7.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
3318
- const offset = readBoottimeOffsetTicks();
3319
- return ticks === void 0 || offset === void 0 || !/^[0-9a-f-]{36}$/.test(boot) ? void 0 : `${Number(ticks) - offset}@${boot}`;
3320
- } catch {
3321
- return void 0;
3322
- }
3323
- }
3324
- var USER_HZ = 100;
3325
- var NSEC_PER_TICK = 1e9 / USER_HZ;
3326
- function readBoottimeOffsetTicks() {
3327
- let text;
3328
- try {
3329
- text = fs7.readFileSync("/proc/self/timens_offsets", "utf8");
3330
- } catch (error) {
3331
- return (
3332
- /** @type {NodeJS.ErrnoException} */
3333
- error.code === "ENOENT" ? 0 : void 0
3334
- );
3335
- }
3336
- const match = /^boottime\s+(-?\d+)\s+(\d+)\s*$/m.exec(String(text));
3337
- if (!match)
3338
- return void 0;
3339
- const nsec = Number(match[2]);
3340
- if (nsec % NSEC_PER_TICK !== 0)
3341
- return void 0;
3342
- return Number(match[1]) * USER_HZ + nsec / NSEC_PER_TICK;
3343
- }
3344
- function parseLinuxStatStart(stat) {
3345
- const fields = String(stat).slice(stat.lastIndexOf(")") + 2).split(" ");
3346
- const start = fields[19];
3347
- return /^\d+$/.test(start ?? "") ? start : void 0;
3348
- }
3349
- function readLinuxPidNamespace(pid) {
3350
- try {
3351
- return fs7.readlinkSync(`/proc/${assertPid(pid)}/ns/pid`);
3352
- } catch {
3353
- return void 0;
3354
- }
3355
- }
3356
- function parseNonNegativeInt(raw) {
3357
- const token = String(raw ?? "").trim();
3358
- if (!/^\d+$/.test(token))
3359
- return void 0;
3360
- const value = Number(token);
3361
- return Number.isFinite(value) ? value : void 0;
3362
- }
3363
- function ageMsFromPosixEtime(raw) {
3364
- const token = String(raw ?? "").trim();
3365
- if (!/^(?:\d+-)?(?:\d+:)?\d+:\d+$/.test(token))
3366
- return void 0;
3367
- let days = 0;
3368
- let rest = token;
3369
- const dash = rest.indexOf("-");
3370
- if (dash >= 0) {
3371
- days = Number(rest.slice(0, dash));
3372
- rest = rest.slice(dash + 1);
3373
- }
3374
- const parts = rest.split(":").map(Number);
3375
- if (parts.some((part) => !Number.isFinite(part)))
3376
- return void 0;
3377
- const [hours, minutes, seconds] = parts.length === 3 ? parts : [0, parts[0], parts[1]];
3378
- return ((days * 24 + hours) * 60 * 60 + minutes * 60 + seconds) * 1e3;
3379
- }
3380
- function posixTokenPattern(field) {
3381
- const token = FIELD_COLUMNS[field].token;
3382
- if (token === "age")
3383
- return "(\\S+)";
3384
- if (token === "lstart")
3385
- return "(\\S+\\s+\\S+\\s+\\d+\\s+\\d+:\\d+:\\d+\\s+\\d+)";
3386
- return "(\\d+)";
3387
- }
3388
- var LSTART_MONTHS = [
3389
- "Jan",
3390
- "Feb",
3391
- "Mar",
3392
- "Apr",
3393
- "May",
3394
- "Jun",
3395
- "Jul",
3396
- "Aug",
3397
- "Sep",
3398
- "Oct",
3399
- "Nov",
3400
- "Dec"
3401
- ];
3402
- function isoFromLstart(raw) {
3403
- const match = /^\w{3}\s+(\w{3})\s+(\d{1,2})\s+(\d{1,2}):(\d{2}):(\d{2})\s+(\d{4})$/.exec(String(raw ?? "").trim());
3404
- if (!match)
3405
- return void 0;
3406
- const month = LSTART_MONTHS.indexOf(match[1]);
3407
- if (month === -1)
3408
- return void 0;
3409
- const [day, hours, minutes, seconds, year] = [2, 3, 4, 5, 6].map((i) => Number(match[i]));
3410
- return new Date(Date.UTC(year, month, day, hours, minutes, seconds)).toISOString();
3411
- }
3412
- function parseProcessTable(out, tabSeparated, fields = ALL_PROCESS_FIELDS) {
3413
- const layout = normalizeProcessFields(fields);
3414
- const commandIndex = layout.indexOf("command");
3415
- const positional = tabSeparated ? null : new RegExp(`^\\s*${layout.filter((field) => field !== "command").map((field) => posixTokenPattern(field)).join("\\s+")}${commandIndex === -1 ? "\\s*$" : "\\s+(.*)$"}`);
3416
- const rows = [];
3417
- for (const line of String(out ?? "").split(/\r?\n/)) {
3418
- if (!line.trim())
3419
- continue;
3420
- let parts;
3421
- if (tabSeparated) {
3422
- const split = line.split(" ");
3423
- if (split.length < layout.length - (commandIndex === -1 ? 0 : 1))
3424
- continue;
3425
- parts = commandIndex === -1 ? split : [
3426
- ...split.slice(0, commandIndex),
3427
- split.slice(commandIndex).join(" ")
3428
- ];
3429
- } else {
3430
- const match = positional?.exec(line);
3431
- if (!match)
3432
- continue;
3433
- parts = match.slice(1);
3434
- }
3435
- const value = (field) => {
3436
- const at = layout.indexOf(field);
3437
- return at === -1 ? void 0 : parts[at];
3438
- };
3439
- const pid = Number(value("pid"));
3440
- if (!Number.isInteger(pid) || pid <= 0)
3441
- continue;
3442
- const ppid = Number(value("ppid"));
3443
- const row = {
3444
- pid,
3445
- ppid: Number.isInteger(ppid) && ppid > 0 ? ppid : 0,
3446
- command: value("command") ?? ""
3447
- };
3448
- for (const field of layout) {
3449
- if (field === "pid" || field === "ppid" || field === "command")
3450
- continue;
3451
- const raw = value(field);
3452
- if (field === "ageMs") {
3453
- row.ageMs = tabSeparated ? parseNonNegativeInt(raw) : ageMsFromPosixEtime(raw ?? "");
3454
- } else if (field === "startedAt") {
3455
- row.startedAt = tabSeparated ? String(raw ?? "").trim() : isoFromLstart(raw ?? "");
3456
- } else {
3457
- row[field] = parseNonNegativeInt(raw);
3458
- }
3364
+ }
3365
+ function createGenerationSource(name, store) {
3366
+ declare(name);
3367
+ const local = { generation: 0 };
3368
+ const cell = store ?? (() => local);
3369
+ const read = () => cell().generation;
3370
+ return {
3371
+ name,
3372
+ current: read,
3373
+ bump() {
3374
+ const held = cell();
3375
+ held.generation += 1;
3376
+ return held.generation;
3377
+ },
3378
+ capture() {
3379
+ return makeHandle(name, read(), read, name);
3459
3380
  }
3460
- rows.push(row);
3381
+ };
3382
+ }
3383
+ var DEFAULT_MAX_KEYS = 512;
3384
+ function createGenerationMap(name, options = {}) {
3385
+ declare(name);
3386
+ const normalize = options.normalizeKey ?? ((key) => key);
3387
+ const maxKeys = Math.max(1, options.maxKeys ?? DEFAULT_MAX_KEYS);
3388
+ const stamps = new BoundedFifoMap(maxKeys);
3389
+ let nextTicket = 0;
3390
+ let invalidations = 0;
3391
+ const read = (key) => stamps.get(key) ?? 0;
3392
+ function issue(key) {
3393
+ nextTicket += 1;
3394
+ stamps.delete(key);
3395
+ const evicted = stamps.set(key, nextTicket);
3396
+ invalidations += evicted.length;
3397
+ return nextTicket;
3461
3398
  }
3462
- return rows;
3399
+ return {
3400
+ name,
3401
+ current(key) {
3402
+ return read(normalize(key));
3403
+ },
3404
+ bump(key) {
3405
+ invalidations += 1;
3406
+ return issue(normalize(key));
3407
+ },
3408
+ capture(key) {
3409
+ const normalized = normalize(key);
3410
+ const stamp = read(normalized) || issue(normalized);
3411
+ const capturedInvalidations = invalidations;
3412
+ return makeHandle(`${name}[${normalized}]`, stamp, () => {
3413
+ if (invalidations === capturedInvalidations)
3414
+ return stamp;
3415
+ return read(normalize(key));
3416
+ }, name);
3417
+ },
3418
+ forget(key) {
3419
+ invalidations += 1;
3420
+ stamps.delete(normalize(key));
3421
+ },
3422
+ clear() {
3423
+ invalidations += 1;
3424
+ stamps.clear();
3425
+ },
3426
+ size() {
3427
+ return stamps.size;
3428
+ }
3429
+ };
3463
3430
  }
3464
3431
 
3465
- // dist/clients/process-snapshot.js
3466
- async function queryProcessTable(request, options) {
3467
- let query;
3432
+ // dist/clients/instance-registry-lock.js
3433
+ import * as fs7 from "node:fs";
3434
+ import { randomInt as randomInt2 } from "node:crypto";
3435
+ import * as path10 from "node:path";
3436
+ var OWN_HOLDS_FAMILY = "instance-registry.lock-own-holds";
3437
+ var OWN_HOLDS_VERSION = 1;
3438
+ function ownAsyncHolds() {
3439
+ return getProcessSingleton(OWN_HOLDS_FAMILY, OWN_HOLDS_VERSION, () => ({
3440
+ count: 0
3441
+ }));
3442
+ }
3443
+ var LOCK_STALE_MS = 5e3;
3444
+ var LOCK_WAIT_MS = 500;
3445
+ var LOCK_MIN_BACKOFF_MS = 5;
3446
+ var LOCK_MAX_BACKOFF_MS = 25;
3447
+ function generationDir2(target) {
3448
+ return `${target}.locks`;
3449
+ }
3450
+ function legacyLockPath(target) {
3451
+ return `${target}.lock`;
3452
+ }
3453
+ function createLegacyLock(lock) {
3468
3454
  try {
3469
- query = buildProcessQuery(request.fields, {
3470
- filter: request.filter,
3471
- excludeSelfPid: request.excludeSelfPid
3472
- });
3455
+ fs7.writeFileSync(lock, `${process.pid} ${Date.now()}
3456
+ `, { flag: "wx" });
3457
+ return true;
3458
+ } catch (error) {
3459
+ if (isLockContention(error))
3460
+ return false;
3461
+ throw error;
3462
+ }
3463
+ }
3464
+ function takeLegacyLock(lock) {
3465
+ if (createLegacyLock(lock))
3466
+ return true;
3467
+ if (!pidFileIsStale(lock, LOCK_STALE_MS))
3468
+ return false;
3469
+ try {
3470
+ fs7.unlinkSync(lock);
3473
3471
  } catch {
3474
- return { rows: [], status: "spawn-error", serverSideFiltered: false };
3475
3472
  }
3476
- const result = await spawnCollectStdoutResult(query.command, query.args, {
3477
- shell: false,
3478
- windowsHide: true,
3479
- stdio: ["ignore", "pipe", "ignore"],
3480
- env: query.env
3481
- }, { timeoutMs: options.timeoutMs, onTimeout: options.onTimeout });
3482
- return {
3483
- // Whatever the collector kept is parsed rather than discarded here: it
3484
- // drops stdout on a non-zero exit (that output is not evidence of what
3485
- // is NOT running) but KEEPS the partial table from a timed-out child,
3486
- // and the caller decides what a partial table is worth by reading
3487
- // `status`. Re-deciding that here would be a second policy.
3488
- rows: parseProcessTable(result.stdout, query.tabSeparated, query.fields),
3489
- status: result.status,
3490
- exitCode: result.exitCode,
3491
- timeoutKill: result.timeoutKill,
3492
- serverSideFiltered: query.serverSideFiltered
3493
- };
3473
+ return createLegacyLock(lock);
3494
3474
  }
3495
- function validPids(pids) {
3496
- return [...new Set(pids.filter((p) => Number.isInteger(p) && p > 0))];
3475
+ function releaseLegacyLock(lock) {
3476
+ if (pidFileOwner(lock) !== process.pid)
3477
+ return;
3478
+ try {
3479
+ fs7.unlinkSync(lock);
3480
+ } catch {
3481
+ }
3497
3482
  }
3498
- async function queryProcessIdentities(pids, options) {
3499
- const valid = validPids(pids);
3500
- const identities = /* @__PURE__ */ new Map();
3501
- if (valid.length === 0)
3502
- return { identities, status: "ok" };
3503
- const linux = process.platform === "linux";
3504
- const result = await queryProcessTable({
3505
- fields: linux ? ["pid", "command"] : ["pid", "startedAt", "command"],
3506
- filter: { column: "ProcessId", op: "eq", values: valid }
3507
- }, options);
3508
- for (const row of result.rows) {
3509
- const start = linux ? readLinuxProcessStart(row.pid) : row.startedAt;
3510
- identities.set(row.pid, {
3511
- command: row.command,
3512
- start: start ? start : void 0
3513
- });
3483
+ function tryAcquire(target) {
3484
+ let hold;
3485
+ try {
3486
+ hold = tryAcquireGeneration(generationDir2(target), LOCK_STALE_MS);
3487
+ if (!hold)
3488
+ return "busy";
3489
+ if (hold.tookOverStale)
3490
+ recordStaleTakeover(target, hold);
3491
+ if (takeLegacyLock(legacyLockPath(target)))
3492
+ return hold;
3493
+ recordLegacyHeld(target);
3494
+ releaseGeneration(hold);
3495
+ return "busy";
3496
+ } catch (cause) {
3497
+ recordLockFailure(target, cause);
3498
+ if (hold)
3499
+ releaseGeneration(hold);
3500
+ return "failed";
3514
3501
  }
3515
- return { identities, status: result.status };
3516
3502
  }
3517
- var OWNER_TAG_ENV = "PI_LENS_OWNER";
3518
- function formatOwnerTag(tag) {
3519
- return `${tag.pid}:${tag.start}`;
3503
+ function release(target, hold) {
3504
+ releaseLegacyLock(legacyLockPath(target));
3505
+ releaseGeneration(hold);
3520
3506
  }
3521
- async function ownerTagForChildren(options) {
3522
- if (process.platform === "win32")
3523
- return void 0;
3524
- const start = await ownProcessStart(options);
3525
- return start === void 0 ? void 0 : formatOwnerTag({ pid: process.pid, start });
3507
+ function recordLockFailure(target, cause) {
3508
+ const code = cause?.code ?? "unknown";
3509
+ incrementDegradationCount({
3510
+ kind: "instance-registry-lock-failed",
3511
+ subject: path10.resolve(target),
3512
+ reason: `lock acquisition failed for ${path10.basename(target)} (${code}); the registry write was skipped`
3513
+ });
3526
3514
  }
3527
- function isInPidNamespace(entry, namespace) {
3528
- return entry.pidNamespace === void 0 || entry.pidNamespace === namespace;
3515
+ function recordStaleTakeover(target, hold) {
3516
+ incrementDegradationCount({
3517
+ kind: "instance-registry-lock-stale-takeover",
3518
+ subject: path10.resolve(target),
3519
+ reason: `took over lock generation ${hold.generation - 1} from a dead or aged-out holder`
3520
+ });
3529
3521
  }
3530
- function ownPidNamespace() {
3531
- return process.platform === "linux" ? readLinuxPidNamespace(process.pid) : void 0;
3522
+ function recordLegacyHeld(target) {
3523
+ const lock = legacyLockPath(target);
3524
+ incrementDegradationCount({
3525
+ kind: "instance-registry-lock-legacy-held",
3526
+ subject: path10.resolve(lock),
3527
+ reason: `backed off: ${path10.basename(lock)} is held by pid ${pidFileOwner(lock) ?? "unknown"}, a writer from before #3476`
3528
+ });
3532
3529
  }
3533
- var ownStart = null;
3534
- function ownProcessStart(options) {
3535
- if (process.platform === "linux")
3536
- return Promise.resolve(readLinuxProcessStart(process.pid));
3537
- if (ownStart)
3538
- return ownStart.promise;
3539
- const cell = {
3540
- promise: readProcessStart(process.pid, options).then((start) => {
3541
- if (start === void 0)
3542
- ownStart = null;
3543
- else
3544
- cell.value = start;
3545
- return start;
3546
- })
3547
- };
3548
- ownStart = cell;
3549
- return cell.promise;
3530
+ function recordLockTimeout(target) {
3531
+ incrementDegradationCount({
3532
+ kind: "instance-registry-lock-timeout",
3533
+ subject: path10.resolve(target),
3534
+ reason: `lock acquisition exhausted for ${path10.basename(target)}`
3535
+ });
3550
3536
  }
3551
- async function readProcessStart(pid, options) {
3552
- if (process.platform === "linux")
3553
- return readLinuxProcessStart(pid);
3554
- return (await queryProcessIdentities([pid], options)).identities.get(pid)?.start;
3537
+ function backoffMs() {
3538
+ return randomInt2(LOCK_MIN_BACKOFF_MS, LOCK_MAX_BACKOFF_MS + 1);
3539
+ }
3540
+ var LOCK_WAIT_THROUGH_LEASE_MS = LOCK_STALE_MS + LOCK_WAIT_MS;
3541
+ async function withInstanceRegistryLock(target, op, waitMs = LOCK_WAIT_MS) {
3542
+ const deadline = Date.now() + waitMs;
3543
+ while (Date.now() <= deadline) {
3544
+ const hold = tryAcquire(target);
3545
+ if (hold === "failed")
3546
+ return void 0;
3547
+ if (hold === "busy") {
3548
+ if (Date.now() <= deadline)
3549
+ await new Promise((resolve7) => setTimeout(resolve7, backoffMs()));
3550
+ continue;
3551
+ }
3552
+ const holds = ownAsyncHolds();
3553
+ holds.count += 1;
3554
+ try {
3555
+ return await op();
3556
+ } finally {
3557
+ holds.count -= 1;
3558
+ release(target, hold);
3559
+ }
3560
+ }
3561
+ recordLockTimeout(target);
3562
+ return void 0;
3555
3563
  }
3556
3564
 
3557
3565
  // dist/clients/instance-registry-tail.js
@@ -4724,7 +4732,7 @@ function isOwnLiveChild(pid, site, handle) {
4724
4732
  function killPidTreeSync(pid) {
4725
4733
  if (process.platform === "win32") {
4726
4734
  try {
4727
- const taskkill = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\taskkill.exe`;
4735
+ const taskkill = windowsExe("taskkill.exe");
4728
4736
  spawnSync(taskkill, ["/F", "/T", "/PID", String(pid)], {
4729
4737
  shell: false,
4730
4738
  windowsHide: true,
@@ -4799,7 +4807,7 @@ function cmdEscapeArg(arg) {
4799
4807
  return `"${arg.replace(/"/g, '""')}"`;
4800
4808
  }
4801
4809
  function buildWindowsShellCommand(command, args) {
4802
- const chcp = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\chcp.com`;
4810
+ const chcp = windowsExe("chcp.com");
4803
4811
  return `${chcp} 65001 >nul 2>&1 & ${[command, ...args].map(cmdEscapeArg).join(" ")}`;
4804
4812
  }
4805
4813
  var WINDOWS_DIRECT_RESOLVABLE_EXTS = /* @__PURE__ */ new Set([
@@ -5005,7 +5013,8 @@ function resolveWindowsCommand(command, cwd, env) {
5005
5013
  return resolveWindowsCommandForEnvironment(command, cwd, env);
5006
5014
  }
5007
5015
  function getSpawnEnvironment(overrides, stripNpmConfig) {
5008
- const merged = process.platform === "win32" ? mergeWindowsEnvironment(process.env, overrides) : { ...process.env, ...overrides };
5016
+ const ambient = { ...process.env, GIT_OPTIONAL_LOCKS: "0" };
5017
+ const merged = process.platform === "win32" ? mergeWindowsEnvironment(ambient, overrides) : { ...ambient, ...overrides };
5009
5018
  if (!stripNpmConfig)
5010
5019
  return merged;
5011
5020
  const stripped = {};
@@ -5141,7 +5150,7 @@ function ensureUtf8ConsoleCodePageOnce() {
5141
5150
  return;
5142
5151
  utf8ConsoleCodePageApplied = true;
5143
5152
  try {
5144
- const cmdExe = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\cmd.exe`;
5153
+ const cmdExe = windowsExe("cmd.exe");
5145
5154
  spawnSync(cmdExe, ["/d", "/s", "/c", "chcp 65001 >nul 2>&1"], {
5146
5155
  shell: false,
5147
5156
  windowsHide: true,
@@ -5336,7 +5345,7 @@ async function safeSpawnAsync(command, args, options) {
5336
5345
  if (unsafeValue !== void 0) {
5337
5346
  resolutionError = new Error(`Refusing to spawn "${resolved2.resolvedPath}" via cmd.exe: ${JSON.stringify(unsafeValue)} contains a character (", %, !, or CR/LF) that cannot be safely escaped on a cmd.exe /c command line (CWE-78, #817). Rename/quote the value or invoke the tool without going through cmd.exe.`);
5338
5347
  } else {
5339
- spawnCmd = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\cmd.exe`;
5348
+ spawnCmd = windowsExe("cmd.exe");
5340
5349
  spawnArgs = [
5341
5350
  "/d",
5342
5351
  "/s",
@@ -5436,7 +5445,7 @@ async function safeSpawnAsync(command, args, options) {
5436
5445
  };
5437
5446
  const killTree = async (phase) => {
5438
5447
  if (isWindows2 && child.pid && child.pid > 0) {
5439
- const taskkill = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\taskkill.exe`;
5448
+ const taskkill = windowsExe("taskkill.exe");
5440
5449
  try {
5441
5450
  await new Promise((done) => {
5442
5451
  const killer = spawn(taskkill, ["/F", "/T", "/PID", String(child.pid)], {
@@ -5845,7 +5854,7 @@ function safeSpawn(command, args, options) {
5845
5854
  })
5846
5855
  };
5847
5856
  }
5848
- spawnCmd = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\cmd.exe`;
5857
+ spawnCmd = windowsExe("cmd.exe");
5849
5858
  spawnArgs = [
5850
5859
  "/d",
5851
5860
  "/s",
@@ -5928,6 +5937,9 @@ export {
5928
5937
  isUntrustedProjectPath,
5929
5938
  recordProjectCommandRefusal,
5930
5939
  admittedLookupAnswer,
5940
+ windowsExe,
5941
+ OWNER_TAG_ENV,
5942
+ ownerTagForChildren,
5931
5943
  isLockContention,
5932
5944
  recordGenerationTakeover,
5933
5945
  recordLegacyLockHeld,
@@ -5941,8 +5953,6 @@ export {
5941
5953
  acquireBoundedPidFileLock,
5942
5954
  createGenerationSource,
5943
5955
  createGenerationMap,
5944
- OWNER_TAG_ENV,
5945
- ownerTagForChildren,
5946
5956
  isSubagentSession,
5947
5957
  getSubagentIdentity,
5948
5958
  subagentLightModeNotice,
@@ -5998,6 +6008,8 @@ export {
5998
6008
  getGlobalPiLensDir,
5999
6009
  isPiLensInternalPath,
6000
6010
  EXCLUDED_DIRS,
6011
+ isIgnoredByGitignoreLines,
6012
+ isWithinPathForm,
6001
6013
  getProjectIgnoreMatcher,
6002
6014
  isPathIgnoredByProject,
6003
6015
  isRecordableProjectPath,