pi-lens 4.4.7 → 4.4.9

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 (186) hide show
  1. package/CHANGELOG-USER.md +31 -0
  2. package/CHANGELOG.md +327 -0
  3. package/README.md +13 -2
  4. package/config/dependency-cruiser-eager-allowlist.json +1 -1
  5. package/config/markdownlint/run-no-fix.mjs +36 -0
  6. package/dist/{chunk-4LM3VAZH.js → chunk-2VZ3VN3N.js} +2 -2
  7. package/dist/{chunk-PUZ3E2J4.js → chunk-3HTZDY3C.js} +8 -6
  8. package/dist/{chunk-RORGS5II.js → chunk-3NPWO5UO.js} +7 -13
  9. package/dist/{chunk-MNJIXFX4.js → chunk-47UCC4MM.js} +1 -1
  10. package/dist/chunk-4ENEJHF4.js +198 -0
  11. package/dist/chunk-5GEYJJHG.js +22 -0
  12. package/dist/{chunk-U6VN4NVL.js → chunk-5YSEQHJN.js} +3 -3
  13. package/dist/{chunk-6IR3ZYIB.js → chunk-6GPB3JLL.js} +3 -3
  14. package/dist/{chunk-MB6PXBUA.js → chunk-7R5GZIA6.js} +7 -15
  15. package/dist/{chunk-DH5JPM3K.js → chunk-7UTSNTWM.js} +10 -9
  16. package/dist/{chunk-24BILSZW.js → chunk-7YTRG6YW.js} +2 -2
  17. package/dist/{chunk-KW5JQPO5.js → chunk-AACN5GNE.js} +2 -2
  18. package/dist/{chunk-PKES3ISE.js → chunk-ACRJ2GZ5.js} +2 -2
  19. package/dist/{chunk-4ZYJHQMB.js → chunk-C3YRO3EU.js} +10 -12
  20. package/dist/{chunk-PQJFG24Z.js → chunk-CB7PEVOJ.js} +1300 -946
  21. package/dist/{chunk-ABPKUVA4.js → chunk-CDFJF5YD.js} +1 -1
  22. package/dist/{chunk-T7A2HK2B.js → chunk-CJS6WE66.js} +17 -18
  23. package/dist/{chunk-3YY7IXIL.js → chunk-CM6BDY4E.js} +14 -60
  24. package/dist/{chunk-RZOXUSPC.js → chunk-CZCAZVTD.js} +16 -2
  25. package/dist/chunk-DGKFWQK4.js +23 -0
  26. package/dist/{chunk-NA7SEXHE.js → chunk-E65WJVI5.js} +7 -9
  27. package/dist/{chunk-2TF6RXWB.js → chunk-EKNYSXFB.js} +8 -10
  28. package/dist/{chunk-RRV3FNNM.js → chunk-EY6LY2HO.js} +27 -30
  29. package/dist/{chunk-LBLBAFG3.js → chunk-F6BEQWAK.js} +17 -5
  30. package/dist/{chunk-4L36HG27.js → chunk-FGNSESAC.js} +12 -14
  31. package/dist/{chunk-3FRLWYBG.js → chunk-FRUBVFXV.js} +39 -42
  32. package/dist/{chunk-FB5SCCPT.js → chunk-G22UNQID.js} +14 -15
  33. package/dist/{chunk-LV4UMYVH.js → chunk-GQTQUNCG.js} +26 -27
  34. package/dist/{chunk-E7HJ56Y7.js → chunk-H3BVMK47.js} +64 -73
  35. package/dist/chunk-H6FLQ5NW.js +28 -0
  36. package/dist/{chunk-QHSNL7B2.js → chunk-HEA3EM23.js} +15 -19
  37. package/dist/{chunk-AWDSEDER.js → chunk-HSOBIN22.js} +2 -2
  38. package/dist/{chunk-EAOK7MIZ.js → chunk-HYSKJMZK.js} +17 -4
  39. package/dist/{chunk-VUZWQ7UG.js → chunk-IICERRFF.js} +46 -72
  40. package/dist/{chunk-OXOI55RU.js → chunk-IILEH3ZC.js} +8 -10
  41. package/dist/{chunk-ZKXQKGWZ.js → chunk-J3Q2NYJR.js} +4 -3
  42. package/dist/{chunk-YHC2O2WO.js → chunk-JUZ67QZQ.js} +20 -9
  43. package/dist/chunk-KR5VGMVT.js +25 -0
  44. package/dist/{chunk-F7K5IBZG.js → chunk-KV6GQOGN.js} +41 -44
  45. package/dist/{chunk-SNDXCFRS.js → chunk-KXMJLOZF.js} +25 -23
  46. package/dist/{chunk-CB4WHS4H.js → chunk-L4Y3ROKQ.js} +3 -3
  47. package/dist/{chunk-3F6BMY53.js → chunk-L6WBJGQS.js} +1 -1
  48. package/dist/{chunk-MPKRJBPK.js → chunk-L7O774U7.js} +30 -32
  49. package/dist/{chunk-URCQWAQ4.js → chunk-LAHHGNAY.js} +21 -21
  50. package/dist/{chunk-V63BC55Q.js → chunk-LT62P654.js} +1 -1
  51. package/dist/{chunk-ZMAUPOMG.js → chunk-LWOM6LVS.js} +34 -34
  52. package/dist/{chunk-HO6LWE2E.js → chunk-MKPDIAZH.js} +21 -1
  53. package/dist/{chunk-2PHMIAKO.js → chunk-MN635QYA.js} +3 -4
  54. package/dist/{chunk-KDX35VXP.js → chunk-MQ4PPCJB.js} +166 -149
  55. package/dist/{chunk-QOE342SU.js → chunk-MRLH4MYU.js} +2 -2
  56. package/dist/{chunk-CE6VMBCB.js → chunk-N56BNAA6.js} +20 -21
  57. package/dist/{chunk-L3CMBQMH.js → chunk-N5CEGQPG.js} +14 -17
  58. package/dist/{chunk-7E2563GA.js → chunk-NCLO6E6N.js} +13 -33
  59. package/dist/{chunk-J6JP25XU.js → chunk-NL5LSKVD.js} +4 -3
  60. package/dist/{chunk-U7BD2QL7.js → chunk-NMUSOZ2D.js} +10 -12
  61. package/dist/{chunk-BZARLRJW.js → chunk-NOWH2VA2.js} +8 -33
  62. package/dist/{chunk-U2SDMG7C.js → chunk-NUSXS6YB.js} +6 -5
  63. package/dist/{chunk-ZJTT47IG.js → chunk-OSEKJEUU.js} +2 -2
  64. package/dist/{chunk-FZKFVUEC.js → chunk-OUYAUXAT.js} +647 -355
  65. package/dist/{chunk-ZE3KXHS7.js → chunk-PBZNYHMM.js} +84 -4
  66. package/dist/{chunk-U5HPROLA.js → chunk-PIIUNJIT.js} +2 -4
  67. package/dist/chunk-PKLB2XJL.js +8 -0
  68. package/dist/{chunk-RC2Z6K47.js → chunk-PRHYIA6X.js} +15 -6
  69. package/dist/{chunk-RQS4QQSD.js → chunk-PXQ45SGD.js} +2 -2
  70. package/dist/chunk-Q6JQKWPK.js +25 -0
  71. package/dist/{chunk-F6X3YJWD.js → chunk-QB7T2PHK.js} +2 -2
  72. package/dist/{chunk-TIQJPRDD.js → chunk-QGITU23N.js} +3 -2
  73. package/dist/chunk-QJJKOHLH.js +57 -0
  74. package/dist/{chunk-4LOE5R5P.js → chunk-QP33NKYC.js} +18 -15
  75. package/dist/{chunk-N5WSK2K7.js → chunk-QVBOXT3L.js} +12 -17
  76. package/dist/{chunk-DPGEAHZT.js → chunk-RNJFRXEN.js} +10 -18
  77. package/dist/{chunk-EKWX4WD3.js → chunk-RNXOWDM6.js} +10 -10
  78. package/dist/{chunk-O4BJFESU.js → chunk-RTFMDIKV.js} +1 -1
  79. package/dist/{chunk-LS3QJRUB.js → chunk-SIQHOB6P.js} +11 -13
  80. package/dist/{chunk-3K2F6UDZ.js → chunk-SLSMJPEF.js} +43 -42
  81. package/dist/chunk-T5QSLSMM.js +50 -0
  82. package/dist/chunk-TGQDAG4B.js +88 -0
  83. package/dist/{chunk-4YHYPW2G.js → chunk-THYHUIDR.js} +44 -13
  84. package/dist/{chunk-YVHBNSME.js → chunk-TMNUTMT5.js} +1099 -1100
  85. package/dist/{chunk-WDBICWH3.js → chunk-TOE2RRCS.js} +1 -1
  86. package/dist/chunk-TYHPVE5H.js +25 -0
  87. package/dist/chunk-UAKO2M6B.js +73 -0
  88. package/dist/chunk-UC5AXW5Z.js +20 -0
  89. package/dist/chunk-UTJP6WOS.js +28 -0
  90. package/dist/{chunk-DQZFQSR5.js → chunk-UXTQ3QPD.js} +4 -4
  91. package/dist/chunk-UYXV5NIS.js +20 -0
  92. package/dist/{chunk-KKCK636N.js → chunk-V2WDBOLZ.js} +10 -12
  93. package/dist/{chunk-PR6PO3ES.js → chunk-V67D6TMU.js} +22 -20
  94. package/dist/{chunk-VSFLRN5Y.js → chunk-VCRVNLE7.js} +135 -2
  95. package/dist/{chunk-CPSR3AVL.js → chunk-VO4JFPTV.js} +2 -2
  96. package/dist/{chunk-XT2HTCJ5.js → chunk-VWLSU3XV.js} +6 -5
  97. package/dist/{chunk-WME2OQST.js → chunk-W5E72HJA.js} +66 -24
  98. package/dist/{chunk-LLS45EWB.js → chunk-W7TY6HYX.js} +6 -8
  99. package/dist/{chunk-CCV2EU7T.js → chunk-WSSLVMDA.js} +12 -13
  100. package/dist/{chunk-YISME6ON.js → chunk-WTB4GKMH.js} +10 -1
  101. package/dist/{chunk-KPPJTH44.js → chunk-X5BJ3G2P.js} +64 -35
  102. package/dist/{chunk-JMEKXFOL.js → chunk-XKFO2SZV.js} +39 -34
  103. package/dist/{chunk-HR3OJ3TH.js → chunk-XLAI7UYY.js} +84 -31
  104. package/dist/{chunk-H7OR7DFZ.js → chunk-XO756WE5.js} +53 -37
  105. package/dist/{chunk-F5Z6URKM.js → chunk-XVB3Q2PG.js} +2 -4
  106. package/dist/{chunk-R5MOQM2H.js → chunk-YOXCCJDF.js} +607 -366
  107. package/dist/{chunk-ZGSJDWQU.js → chunk-ZCQBNPRH.js} +2 -2
  108. package/dist/chunk-ZD4KVFXI.js +234 -0
  109. package/dist/{chunk-WGRJOXED.js → chunk-ZDMFGACN.js} +1295 -966
  110. package/dist/{chunk-OSTKYB55.js → chunk-ZMMHHXSW.js} +1 -1
  111. package/dist/{chunk-75GAYVNO.js → chunk-ZPM7ZIFL.js} +6 -6
  112. package/dist/{chunk-LUBPZN36.js → chunk-ZVCDHYWZ.js} +9 -11
  113. package/dist/{chunk-Y7F7IEE3.js → chunk-ZZN74OGD.js} +102 -7
  114. package/dist/{chunk-L5JYIU47.js → chunk-ZZSJAR76.js} +39 -20
  115. package/dist/index.js +10933 -8644
  116. package/dist/mcp/analyze-cli.js +12 -17
  117. package/dist/mcp/cli.js +43 -42
  118. package/dist/mcp/server.js +3073 -1147
  119. package/dist/mcp/worker.js +61 -61
  120. package/dist/probes/installer.js +18 -19
  121. package/docs/adr/0003-git-guard-latch-writer.md +11 -6
  122. package/docs/agent-tools.md +58 -16
  123. package/docs/alignment-families.md +29 -0
  124. package/docs/analysisall.md +1 -1
  125. package/docs/ast-grep_rules_catalog.md +6 -4
  126. package/docs/ci-bot-pr-checks.md +128 -0
  127. package/docs/configuration.md +150 -12
  128. package/docs/defect-shapes.md +107 -15
  129. package/docs/engineering-principles.md +27 -2
  130. package/docs/environment-variables.md +18 -1
  131. package/docs/features.md +14 -7
  132. package/docs/globalconfig.md +11 -3
  133. package/docs/invariants/git-guard-host.md +7 -3
  134. package/docs/invariants/language-config.md +15 -4
  135. package/docs/invariants/lsp-trust-exec.md +25 -4
  136. package/docs/invariants/paths-os.md +4 -2
  137. package/docs/invariants/session-telemetry.md +2 -2
  138. package/docs/language-coverage.md +1 -0
  139. package/docs/lsp-capability-matrix.md +167 -65
  140. package/docs/lsp-idle-eviction.md +4 -1
  141. package/docs/merge-queue-rollout.md +10 -8
  142. package/docs/module-report-read-symbol.md +34 -23
  143. package/docs/pi-lens-fixer.md +34 -17
  144. package/docs/pi-lens-investigator.md +3 -0
  145. package/docs/pi-lens-merge-policy.md +34 -17
  146. package/docs/pi-lens-monitor.md +9 -0
  147. package/docs/pi-lens-orchestration.md +4 -1
  148. package/docs/pi-lens-reviewer.md +6 -6
  149. package/docs/pi-lens-subagent.md +19 -3
  150. package/docs/public-api-stability.md +57 -7
  151. package/docs/release-qa-baseline.md +7 -4
  152. package/docs/schema/pi-lens-config-v1.json +21 -2
  153. package/docs/servercapabilities.md +3 -1
  154. package/docs/settings.md +11 -7
  155. package/docs/word-index.md +20 -7
  156. package/package.json +11 -4
  157. package/rules/ast-grep-rules/rule-tests/no-accumulating-spread-js-test.yml +37 -0
  158. package/rules/ast-grep-rules/rule-tests/ts-redundant-filter-map-test.yml +12 -1
  159. package/rules/ast-grep-rules/rule-tests-disabled/filter-then-map-js-test.yml +12 -0
  160. package/rules/ast-grep-rules/rule-tests-disabled/filter-then-map-test.yml +25 -0
  161. package/rules/ast-grep-rules/rules/no-accumulating-spread-js.yml +49 -1
  162. package/rules/ast-grep-rules/rules/no-sql-in-code-execute-js.yml +1 -2
  163. package/rules/ast-grep-rules/rules/no-sql-in-code-execute.yml +1 -2
  164. package/rules/ast-grep-rules/rules/ts-redundant-filter-map.yml +9 -1
  165. package/rules/ast-grep-rules/rules-disabled/filter-then-map-js.yml +17 -0
  166. package/rules/ast-grep-rules/rules-disabled/filter-then-map.yml +36 -0
  167. package/rules/ast-grep-rules/self-scan-baseline.json +1 -1
  168. package/scripts/download-grammars.js +3 -2
  169. package/skills/pi-lens-lsp-navigation/SKILL.md +5 -1
  170. package/dist/chunk-46TNM7XZ.js +0 -88
  171. package/dist/chunk-72OKUXSD.js +0 -31
  172. package/dist/chunk-7GLOLOSH.js +0 -57
  173. package/dist/chunk-AKUUMGD5.js +0 -26
  174. package/dist/chunk-ASUXV767.js +0 -22
  175. package/dist/chunk-CTADOKYM.js +0 -25
  176. package/dist/chunk-GNSIWBAT.js +0 -106
  177. package/dist/chunk-HWDAVBFU.js +0 -49
  178. package/dist/chunk-JJ2RRESP.js +0 -58
  179. package/dist/chunk-KXF5R4UN.js +0 -48
  180. package/dist/chunk-LSC3VADM.js +0 -23
  181. package/dist/chunk-OE5ZBP7F.js +0 -443
  182. package/dist/chunk-SHLDT3OI.js +0 -27
  183. package/dist/chunk-UF7RTZSO.js +0 -27
  184. package/dist/chunk-W4WP2ERB.js +0 -30
  185. package/dist/chunk-YES5CACN.js +0 -73
  186. package/dist/chunk-Z2XAOKHK.js +0 -136
@@ -13,7 +13,7 @@ import {
13
13
  reportPiLensConfigRecords,
14
14
  resolveOnePiLensConfigDocument,
15
15
  warnIgnoredConfigOnce
16
- } from "./chunk-KPPJTH44.js";
16
+ } from "./chunk-X5BJ3G2P.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-NL5LSKVD.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-U5HPROLA.js";
34
+ } from "./chunk-PIIUNJIT.js";
35
35
  import {
36
36
  GLOBAL_NON_FLAG_CONFIG_SECTIONS,
37
37
  LENS_FLAGS,
@@ -42,22 +42,19 @@ import {
42
42
  flagValueFromConfig,
43
43
  getLensFlagSpec,
44
44
  incrementDegradationCount,
45
+ logExtension,
45
46
  readFlagConfigValue,
46
47
  readLazyToolsSetting,
47
48
  readToolConfig,
48
49
  recordDegradation,
49
50
  recordDegradationOnce
50
- } from "./chunk-WME2OQST.js";
51
- import {
52
- logExtension
53
- } from "./chunk-KXF5R4UN.js";
54
- import {
55
- logLatency
56
- } from "./chunk-Z2XAOKHK.js";
51
+ } from "./chunk-W5E72HJA.js";
57
52
  import {
58
53
  getProcessSingleton,
54
+ isToolInstallDisabled,
55
+ logLatency,
59
56
  machineStateDir
60
- } from "./chunk-VSFLRN5Y.js";
57
+ } from "./chunk-VCRVNLE7.js";
61
58
  import {
62
59
  STAGE_TMP_PATTERN,
63
60
  stagePathFor,
@@ -82,10 +79,11 @@ import {
82
79
  normalizePathSpelling,
83
80
  pathsEqual,
84
81
  realpathOrResolve,
82
+ relativeInside,
85
83
  toPosix,
86
84
  toProjectRelativePath,
87
85
  walkUpDirs
88
- } from "./chunk-PQJFG24Z.js";
86
+ } from "./chunk-CB7PEVOJ.js";
89
87
  import {
90
88
  __commonJS,
91
89
  __require,
@@ -1138,413 +1136,843 @@ function admittedLookupAnswer(stdout) {
1138
1136
  return null;
1139
1137
  }
1140
1138
 
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) {
1139
+ // dist/clients/child-unref.js
1140
+ import { spawn as nodeSpawn } from "node:child_process";
1141
+ function unrefChildAndPipes(child) {
1159
1142
  try {
1160
- const pid = Number(fs3.readFileSync(file, "utf8").trim().split(/\s+/)[0]);
1161
- return Number.isInteger(pid) && pid > 0 ? pid : void 0;
1143
+ child.unref();
1144
+ for (const stream of [child.stdout, child.stderr, child.stdin]) {
1145
+ stream?.unref?.();
1146
+ }
1162
1147
  } catch {
1163
- return void 0;
1164
1148
  }
1165
1149
  }
1166
- function isPidAlive(pid) {
1167
- if (pid === void 0)
1168
- return false;
1150
+ function spawnCollectStdoutResult(command, args, options, collectOptions = {}) {
1151
+ return new Promise((resolve7) => {
1152
+ let settled = false;
1153
+ let timer;
1154
+ const settle = (result) => {
1155
+ if (settled)
1156
+ return;
1157
+ settled = true;
1158
+ if (timer)
1159
+ clearTimeout(timer);
1160
+ resolve7(result);
1161
+ };
1162
+ try {
1163
+ const child = nodeSpawn(command, args, options);
1164
+ unrefChildAndPipes(child);
1165
+ const out = createBoundedOutputSink();
1166
+ child.stdout?.on("data", (chunk) => out.append(chunk));
1167
+ child.once("error", (error) => settle({ stdout: "", status: "spawn-error", error }));
1168
+ child.once("close", (code, signal) => settle(code === 0 && signal === null ? { stdout: out.text, status: "ok" } : {
1169
+ stdout: "",
1170
+ status: "exit-error",
1171
+ exitCode: code,
1172
+ exitSignal: signal
1173
+ }));
1174
+ const timeoutMs = collectOptions.timeoutMs;
1175
+ if (typeof timeoutMs === "number" && timeoutMs > 0) {
1176
+ timer = setTimeout(() => {
1177
+ void terminateTimedOutChild(child, collectOptions.onTimeout).then((timeoutKill) => settle({ stdout: out.text, status: "timeout", timeoutKill }));
1178
+ }, timeoutMs);
1179
+ timer.unref();
1180
+ }
1181
+ } catch (error) {
1182
+ settle({ stdout: "", status: "spawn-error", error });
1183
+ }
1184
+ });
1185
+ }
1186
+ async function terminateTimedOutChild(child, onTimeout) {
1187
+ if (onTimeout) {
1188
+ try {
1189
+ return await onTimeout(child);
1190
+ } catch {
1191
+ return "unverified";
1192
+ }
1193
+ }
1169
1194
  try {
1170
- process.kill(pid, 0);
1171
- return true;
1172
- } catch (error) {
1173
- return error?.code !== "ESRCH";
1195
+ child.kill();
1196
+ } catch {
1174
1197
  }
1198
+ return "unverified";
1175
1199
  }
1176
- function pidFileIsStale(file, staleMs) {
1200
+
1201
+ // dist/scripts/lib/process-scan.mjs
1202
+ import fs3 from "node:fs";
1203
+ import path3 from "node:path";
1204
+ function runningOnWindows() {
1205
+ return process.platform === "win32";
1206
+ }
1207
+ var FIELD_COLUMNS = Object.freeze({
1208
+ pid: { wmi: "ProcessId", ps: "pid", token: "int" },
1209
+ ppid: { wmi: "ParentProcessId", ps: "ppid", token: "int" },
1210
+ ageMs: { wmi: "CreationDate", ps: "etime", token: "age" },
1211
+ rssBytes: { wmi: "WorkingSetSize", ps: null, token: "int" },
1212
+ cpuKernel100ns: { wmi: "KernelModeTime", ps: null, token: "int" },
1213
+ cpuUser100ns: { wmi: "UserModeTime", ps: null, token: "int" },
1214
+ startedAt: { wmi: "CreationDate", ps: "lstart", token: "lstart" },
1215
+ command: { wmi: "CommandLine", ps: "args", token: "tail" }
1216
+ });
1217
+ var FIELD_ORDER = Object.freeze(Object.keys(FIELD_COLUMNS));
1218
+ var ALL_PROCESS_FIELDS = Object.freeze(["pid", "ppid", "command"]);
1219
+ var FILTERABLE_COLUMNS = /* @__PURE__ */ new Set(["ProcessId", "Name", "CommandLine"]);
1220
+ function windowsExe(name) {
1221
+ return path3.win32.join(process.env.SystemRoot ?? path3.win32.join("C:", "Windows"), "System32", name);
1222
+ }
1223
+ function posixPsPath() {
1177
1224
  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);
1225
+ if (fs3.existsSync("/bin/ps"))
1226
+ return "/bin/ps";
1227
+ if (fs3.existsSync("/usr/bin/ps"))
1228
+ return "/usr/bin/ps";
1183
1229
  } catch {
1184
- return false;
1185
1230
  }
1231
+ return "/bin/ps";
1186
1232
  }
1187
- function isLockContention(error) {
1188
- const code = error?.code;
1189
- return code === "EEXIST" || code === "EPERM" || code === "EBUSY";
1233
+ function normalizeProcessFields(fields) {
1234
+ const requested = new Set((fields ?? ALL_PROCESS_FIELDS).filter((field) => field in FIELD_COLUMNS));
1235
+ requested.add("pid");
1236
+ return FIELD_ORDER.filter((field) => requested.has(field));
1190
1237
  }
1191
- function generationPath(dir, generation) {
1192
- return path3.join(dir, `lock.${generation}`);
1238
+ function escapeWqlLikeValue(value) {
1239
+ return String(value).replaceAll("'", "''").replaceAll(/[%_]/g, (ch) => `[${ch}]`);
1193
1240
  }
1194
- function releasedName(generation) {
1195
- return `lock.${generation}.released`;
1241
+ function escapeWqlStringValue(value) {
1242
+ return String(value).replaceAll("'", "''");
1196
1243
  }
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]));
1244
+ function assertPid(value) {
1245
+ const pid = Number(value);
1246
+ if (!Number.isInteger(pid) || pid <= 0) {
1247
+ throw new Error(`process filter: invalid pid ${String(value)}`);
1203
1248
  }
1204
- return top;
1249
+ return pid;
1205
1250
  }
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
- }
1251
+ function wqlFilterExpression(filter) {
1252
+ const { column, op, values } = filter;
1253
+ if (!FILTERABLE_COLUMNS.has(column)) {
1254
+ throw new Error(`process filter: unsupported column ${String(column)}`);
1215
1255
  }
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 {
1256
+ const list = [...values];
1257
+ if (list.length === 0) {
1258
+ throw new Error(`process filter: ${column} filter has no values`);
1259
+ }
1260
+ if (column === "ProcessId") {
1261
+ return list.map((value) => `ProcessId=${assertPid(value)}`).join(" OR ");
1262
+ }
1263
+ if (op === "like") {
1264
+ return list.map((value) => `${column} LIKE '%${escapeWqlLikeValue(value)}%'`).join(" OR ");
1235
1265
  }
1266
+ return list.map((value) => `${column} = '${escapeWqlStringValue(value)}'`).join(" OR ");
1236
1267
  }
1237
- function heartbeatIntervalMs(leaseMs) {
1238
- return Math.max(1e3, Math.floor(leaseMs / 4));
1268
+ function buildProcessQuery(fields = ALL_PROCESS_FIELDS, options = {}) {
1269
+ const layout = normalizeProcessFields(fields);
1270
+ const filter = options.filter;
1271
+ if (runningOnWindows()) {
1272
+ const columns2 = [
1273
+ ...new Set(layout.map((field) => FIELD_COLUMNS[field].wmi))
1274
+ ];
1275
+ const where = filter ? ` WHERE ${wqlFilterExpression(filter)}` : "";
1276
+ const excludeSelf = options.excludeSelfPid ? " | Where-Object { $_.ProcessId -ne $PID }" : "";
1277
+ 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 { '' }; " : "");
1278
+ const row = layout.map((field) => {
1279
+ if (field === "ageMs")
1280
+ return "$age";
1281
+ if (field === "startedAt")
1282
+ return "$st";
1283
+ return `$($_.${FIELD_COLUMNS[field].wmi})`;
1284
+ }).join("`t");
1285
+ return {
1286
+ command: windowsExe("WindowsPowerShell\\v1.0\\powershell.exe"),
1287
+ args: [
1288
+ "-NoProfile",
1289
+ "-NonInteractive",
1290
+ "-Command",
1291
+ `Get-CimInstance -Query "SELECT ${columns2.join(",")} FROM Win32_Process${where}"${excludeSelf} | ForEach-Object { ${prelude}"${row}" }`
1292
+ ],
1293
+ tabSeparated: true,
1294
+ fields: layout,
1295
+ serverSideFiltered: Boolean(filter)
1296
+ };
1297
+ }
1298
+ const unsupported = layout.filter((field) => !FIELD_COLUMNS[field].ps);
1299
+ if (unsupported.length > 0) {
1300
+ throw new Error(`process query: ${unsupported.join(", ")} has no POSIX ps column`);
1301
+ }
1302
+ if (layout.includes("startedAt") && process.platform === "linux") {
1303
+ throw new Error("process query: startedAt on Linux is read from /proc, not ps");
1304
+ }
1305
+ const columns = layout.map((field) => `${FIELD_COLUMNS[field].ps}=`).join(",");
1306
+ const pidFilter = filter && filter.column === "ProcessId" && filter.op === "eq" ? [...filter.values].map((value) => assertPid(value)) : null;
1307
+ return {
1308
+ command: posixPsPath(),
1309
+ args: pidFilter ? ["-p", pidFilter.join(","), "-o", columns] : ["-eo", columns],
1310
+ tabSeparated: false,
1311
+ fields: layout,
1312
+ serverSideFiltered: Boolean(pidFilter),
1313
+ // BSD `ps` formats `lstart` with strftime("%c") in the local zone, so
1314
+ // two readers with different locales or zones would print one process
1315
+ // two ways. Pinned, every reader prints the same text.
1316
+ ...layout.includes("startedAt") ? { env: posixStartEnv() } : {}
1317
+ };
1239
1318
  }
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) };
1319
+ function posixStartEnv() {
1320
+ return { ...process.env, LC_ALL: "C", TZ: "UTC0" };
1251
1321
  }
1252
- function ownsTopGeneration(hold) {
1322
+ function readLinuxProcessStart(pid) {
1253
1323
  try {
1254
- const entries = fs3.readdirSync(hold.dir);
1255
- if (entries.includes(releasedName(hold.generation)))
1256
- return false;
1257
- return topGeneration(entries) === hold.generation;
1324
+ const ticks = parseLinuxStatStart(fs3.readFileSync(`/proc/${assertPid(pid)}/stat`, "utf8"));
1325
+ const boot = fs3.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
1326
+ const offset = readBoottimeOffsetTicks();
1327
+ return ticks === void 0 || offset === void 0 || !/^[0-9a-f-]{36}$/.test(boot) ? void 0 : `${Number(ticks) - offset}@${boot}`;
1258
1328
  } 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
1329
  return void 0;
1269
1330
  }
1270
- const hold = { dir, generation: top + 1, tookOverStale: !free };
1331
+ }
1332
+ var USER_HZ = 100;
1333
+ var NSEC_PER_TICK = 1e9 / USER_HZ;
1334
+ function readBoottimeOffsetTicks() {
1335
+ let text;
1271
1336
  try {
1272
- fs3.writeFileSync(generationPath(dir, hold.generation), `${process.pid} ${Date.now()}
1273
- `, { flag: "wx" });
1337
+ text = fs3.readFileSync("/proc/self/timens_offsets", "utf8");
1274
1338
  } 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;
1339
+ return (
1340
+ /** @type {NodeJS.ErrnoException} */
1341
+ error.code === "ENOENT" ? 0 : void 0
1342
+ );
1285
1343
  }
1286
- if (topGeneration(entries) > hold.generation) {
1287
- releaseGeneration(hold);
1344
+ const match = /^boottime\s+(-?\d+)\s+(\d+)\s*$/m.exec(String(text));
1345
+ if (!match)
1288
1346
  return void 0;
1289
- }
1290
- removeBelowPredecessor(dir, entries, hold.generation);
1291
- return hold;
1347
+ const nsec = Number(match[2]);
1348
+ if (nsec % NSEC_PER_TICK !== 0)
1349
+ return void 0;
1350
+ return Number(match[1]) * USER_HZ + nsec / NSEC_PER_TICK;
1292
1351
  }
1293
- var timedOutHolders = new BoundedFifoMap(16);
1294
- function topGenerationHolder(dir) {
1352
+ function parseLinuxStatStart(stat) {
1353
+ const fields = String(stat).slice(stat.lastIndexOf(")") + 2).split(" ");
1354
+ const start = fields[19];
1355
+ return /^\d+$/.test(start ?? "") ? start : void 0;
1356
+ }
1357
+ function readLinuxPidNamespace(pid) {
1295
1358
  try {
1296
- const top = topGeneration(fs3.readdirSync(dir));
1297
- return `lock.${top} ${fs3.readFileSync(generationPath(dir, top), "utf8").trim()}`;
1359
+ return fs3.readlinkSync(`/proc/${assertPid(pid)}/ns/pid`);
1298
1360
  } catch {
1299
1361
  return void 0;
1300
1362
  }
1301
1363
  }
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 };
1364
+ function parseNonNegativeInt(raw) {
1365
+ const token = String(raw ?? "").trim();
1366
+ if (!/^\d+$/.test(token))
1367
+ return void 0;
1368
+ const value = Number(token);
1369
+ return Number.isFinite(value) ? value : void 0;
1370
+ }
1371
+ function ageMsFromPosixEtime(raw) {
1372
+ const token = String(raw ?? "").trim();
1373
+ if (!/^(?:\d+-)?(?:\d+:)?\d+:\d+$/.test(token))
1374
+ return void 0;
1375
+ let days = 0;
1376
+ let rest = token;
1377
+ const dash = rest.indexOf("-");
1378
+ if (dash >= 0) {
1379
+ days = Number(rest.slice(0, dash));
1380
+ rest = rest.slice(dash + 1);
1381
+ }
1382
+ const parts = rest.split(":").map(Number);
1383
+ if (parts.some((part) => !Number.isFinite(part)))
1384
+ return void 0;
1385
+ const [hours, minutes, seconds] = parts.length === 3 ? parts : [0, parts[0], parts[1]];
1386
+ return ((days * 24 + hours) * 60 * 60 + minutes * 60 + seconds) * 1e3;
1387
+ }
1388
+ function posixTokenPattern(field) {
1389
+ const token = FIELD_COLUMNS[field].token;
1390
+ if (token === "age")
1391
+ return "(\\S+)";
1392
+ if (token === "lstart")
1393
+ return "(\\S+\\s+\\S+\\s+\\d+\\s+\\d+:\\d+:\\d+\\s+\\d+)";
1394
+ return "(\\d+)";
1395
+ }
1396
+ var LSTART_MONTHS = [
1397
+ "Jan",
1398
+ "Feb",
1399
+ "Mar",
1400
+ "Apr",
1401
+ "May",
1402
+ "Jun",
1403
+ "Jul",
1404
+ "Aug",
1405
+ "Sep",
1406
+ "Oct",
1407
+ "Nov",
1408
+ "Dec"
1409
+ ];
1410
+ function isoFromLstart(raw) {
1411
+ 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());
1412
+ if (!match)
1413
+ return void 0;
1414
+ const month = LSTART_MONTHS.indexOf(match[1]);
1415
+ if (month === -1)
1416
+ return void 0;
1417
+ const [day, hours, minutes, seconds, year] = [2, 3, 4, 5, 6].map((i) => Number(match[i]));
1418
+ return new Date(Date.UTC(year, month, day, hours, minutes, seconds)).toISOString();
1419
+ }
1420
+ function parseProcessTable(out, tabSeparated, fields = ALL_PROCESS_FIELDS) {
1421
+ const layout = normalizeProcessFields(fields);
1422
+ const commandIndex = layout.indexOf("command");
1423
+ const positional = tabSeparated ? null : new RegExp(`^\\s*${layout.filter((field) => field !== "command").map((field) => posixTokenPattern(field)).join("\\s+")}${commandIndex === -1 ? "\\s*$" : "\\s+(.*)$"}`);
1424
+ const rows = [];
1425
+ for (const line of String(out ?? "").split(/\r?\n/)) {
1426
+ if (!line.trim())
1427
+ continue;
1428
+ let parts;
1429
+ if (tabSeparated) {
1430
+ const split = line.split(" ");
1431
+ if (split.length < layout.length - (commandIndex === -1 ? 0 : 1))
1432
+ continue;
1433
+ parts = commandIndex === -1 ? split : [
1434
+ ...split.slice(0, commandIndex),
1435
+ split.slice(commandIndex).join(" ")
1436
+ ];
1437
+ } else {
1438
+ const match = positional?.exec(line);
1439
+ if (!match)
1440
+ continue;
1441
+ parts = match.slice(1);
1311
1442
  }
1312
- if (hold) {
1313
- if (hold.tookOverStale)
1314
- recordGenerationTakeover(hold);
1315
- try {
1316
- return { held: true, value: op() };
1317
- } finally {
1318
- releaseGeneration(hold);
1443
+ const value = (field) => {
1444
+ const at = layout.indexOf(field);
1445
+ return at === -1 ? void 0 : parts[at];
1446
+ };
1447
+ const pid = Number(value("pid"));
1448
+ if (!Number.isInteger(pid) || pid <= 0)
1449
+ continue;
1450
+ const ppid = Number(value("ppid"));
1451
+ const row = {
1452
+ pid,
1453
+ ppid: Number.isInteger(ppid) && ppid > 0 ? ppid : 0,
1454
+ command: value("command") ?? ""
1455
+ };
1456
+ for (const field of layout) {
1457
+ if (field === "pid" || field === "ppid" || field === "command")
1458
+ continue;
1459
+ const raw = value(field);
1460
+ if (field === "ageMs") {
1461
+ row.ageMs = tabSeparated ? parseNonNegativeInt(raw) : ageMsFromPosixEtime(raw ?? "");
1462
+ } else if (field === "startedAt") {
1463
+ row.startedAt = tabSeparated ? String(raw ?? "").trim() : isoFromLstart(raw ?? "");
1464
+ } else {
1465
+ row[field] = parseNonNegativeInt(raw);
1319
1466
  }
1320
1467
  }
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));
1468
+ rows.push(row);
1334
1469
  }
1470
+ return rows;
1335
1471
  }
1336
1472
 
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;
1349
- }
1350
- function ownerPidIsLive(pid) {
1351
- if (!Number.isSafeInteger(pid) || pid <= 0)
1352
- return false;
1473
+ // dist/clients/process-snapshot.js
1474
+ async function queryProcessTable(request, options) {
1475
+ let query;
1353
1476
  try {
1354
- process.kill(pid, 0);
1355
- return true;
1356
- } catch (error) {
1357
- return error.code === "EPERM";
1477
+ query = buildProcessQuery(request.fields, {
1478
+ filter: request.filter,
1479
+ excludeSelfPid: request.excludeSelfPid
1480
+ });
1481
+ } catch {
1482
+ return { rows: [], status: "spawn-error", serverSideFiltered: false };
1358
1483
  }
1484
+ const result = await spawnCollectStdoutResult(query.command, query.args, {
1485
+ shell: false,
1486
+ windowsHide: true,
1487
+ stdio: ["ignore", "pipe", "ignore"],
1488
+ env: query.env
1489
+ }, { timeoutMs: options.timeoutMs, onTimeout: options.onTimeout });
1490
+ return {
1491
+ // Whatever the collector kept is parsed rather than discarded here: it
1492
+ // drops stdout on a non-zero exit (that output is not evidence of what
1493
+ // is NOT running) but KEEPS the partial table from a timed-out child,
1494
+ // and the caller decides what a partial table is worth by reading
1495
+ // `status`. Re-deciding that here would be a second policy.
1496
+ rows: parseProcessTable(result.stdout, query.tabSeparated, query.fields),
1497
+ status: result.status,
1498
+ exitCode: result.exitCode,
1499
+ timeoutKill: result.timeoutKill,
1500
+ serverSideFiltered: query.serverSideFiltered
1501
+ };
1359
1502
  }
1360
- function quarantinePath(lockPath, token) {
1361
- return `${lockPath}.quarantine-${process.pid}-${token}`;
1503
+ function validPids(pids) {
1504
+ return [...new Set(pids.filter((p) => Number.isInteger(p) && p > 0))];
1362
1505
  }
1363
- async function restoreQuarantinedLock(lockPath, quarantined) {
1364
- try {
1365
- await fsp.rename(quarantined, lockPath);
1366
- } catch {
1506
+ async function queryProcessIdentities(pids, options) {
1507
+ const valid = validPids(pids);
1508
+ const identities = /* @__PURE__ */ new Map();
1509
+ if (valid.length === 0)
1510
+ return { identities, status: "ok" };
1511
+ const linux = process.platform === "linux";
1512
+ const result = await queryProcessTable({
1513
+ fields: linux ? ["pid", "command"] : ["pid", "startedAt", "command"],
1514
+ filter: { column: "ProcessId", op: "eq", values: valid }
1515
+ }, options);
1516
+ for (const row of result.rows) {
1517
+ const start = linux ? readLinuxProcessStart(row.pid) : row.startedAt;
1518
+ identities.set(row.pid, {
1519
+ command: row.command,
1520
+ start: start ? start : void 0
1521
+ });
1367
1522
  }
1523
+ return { identities, status: result.status };
1368
1524
  }
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 });
1389
- } else {
1390
- await restoreQuarantinedLock(lockPath, quarantined);
1391
- }
1392
- } catch {
1393
- await restoreQuarantinedLock(lockPath, quarantined);
1394
- }
1525
+ var OWNER_TAG_ENV = "PI_LENS_OWNER";
1526
+ function formatOwnerTag(tag) {
1527
+ return `${tag.pid}:${tag.start}`;
1395
1528
  }
1396
- function quarantineOwnerIsStale(owner, staleMs) {
1397
- const pidUsable = Number.isInteger(owner.pid) && owner.pid > 0;
1398
- if (pidUsable && !ownerPidIsLive(owner.pid))
1529
+ async function ownerTagForChildren(options) {
1530
+ if (process.platform === "win32")
1531
+ return void 0;
1532
+ const start = await ownProcessStart(options);
1533
+ return start === void 0 ? void 0 : formatOwnerTag({ pid: process.pid, start });
1534
+ }
1535
+ function isInPidNamespace(entry, namespace) {
1536
+ return entry.pidNamespace === void 0 || entry.pidNamespace === namespace;
1537
+ }
1538
+ function ownPidNamespace() {
1539
+ return process.platform === "linux" ? readLinuxPidNamespace(process.pid) : void 0;
1540
+ }
1541
+ var ownStart = null;
1542
+ function ownProcessStart(options) {
1543
+ if (process.platform === "linux")
1544
+ return Promise.resolve(readLinuxProcessStart(process.pid));
1545
+ if (ownStart)
1546
+ return ownStart.promise;
1547
+ const cell = {
1548
+ promise: readProcessStart(process.pid, options).then((start) => {
1549
+ if (start === void 0)
1550
+ ownStart = null;
1551
+ else
1552
+ cell.value = start;
1553
+ return start;
1554
+ })
1555
+ };
1556
+ ownStart = cell;
1557
+ return cell.promise;
1558
+ }
1559
+ async function readProcessStart(pid, options) {
1560
+ if (process.platform === "linux")
1561
+ return readLinuxProcessStart(pid);
1562
+ return (await queryProcessIdentities([pid], options)).identities.get(pid)?.start;
1563
+ }
1564
+
1565
+ // dist/clients/resource-sampler.js
1566
+ var import_pidusage = __toESM(require_pidusage(), 1);
1567
+
1568
+ // dist/clients/instance-reaper.js
1569
+ import { spawn as nodeSpawn2 } from "node:child_process";
1570
+
1571
+ // dist/clients/bounded-pid-file-lock.js
1572
+ import { randomUUID } from "node:crypto";
1573
+ import * as fs5 from "node:fs";
1574
+ import fsp from "node:fs/promises";
1575
+ import path5 from "node:path";
1576
+
1577
+ // dist/clients/generation-lock.js
1578
+ import { randomInt } from "node:crypto";
1579
+ import * as fs4 from "node:fs";
1580
+ import * as path4 from "node:path";
1581
+
1582
+ // dist/clients/pid-liveness.js
1583
+ function realIsPidAlive(pid) {
1584
+ if (!Number.isFinite(pid) || pid <= 0)
1585
+ return false;
1586
+ try {
1587
+ process.kill(pid, 0);
1399
1588
  return true;
1400
- return Number.isFinite(owner.createdAt) && Date.now() - owner.createdAt > staleMs;
1589
+ } catch (err) {
1590
+ const code = err?.code;
1591
+ if (code === "ESRCH")
1592
+ return false;
1593
+ if (code !== "EPERM") {
1594
+ recordDegradationOnce({
1595
+ kind: "pid-liveness-unprobeable",
1596
+ subject: String(code ?? "unknown"),
1597
+ reason: `process.kill(pid, 0) threw ${String(code ?? "an error without a code")}; read as alive`
1598
+ });
1599
+ }
1600
+ return true;
1601
+ }
1401
1602
  }
1402
- async function reclaimQuarantineLock(lockPath, staleMs) {
1403
- const quarantined = quarantinePath(lockPath, `reclaim-${Date.now()}-${randomUUID()}`);
1603
+
1604
+ // dist/clients/generation-lock.js
1605
+ var GENERATION = /^lock\.(\d+)(\.released)?$/;
1606
+ function pidFileOwner(file) {
1404
1607
  try {
1405
- await fsp.rename(lockPath, quarantined);
1608
+ const pid = Number(fs4.readFileSync(file, "utf8").trim().split(/\s+/)[0]);
1609
+ return Number.isInteger(pid) && pid > 0 ? pid : void 0;
1406
1610
  } catch {
1407
- return false;
1611
+ return void 0;
1408
1612
  }
1409
- let stale = false;
1613
+ }
1614
+ function pidFileIsStale(file, staleMs) {
1410
1615
  try {
1411
- const owner = JSON.parse(await fsp.readFile(path4.join(quarantined, "owner.json"), "utf8"));
1412
- stale = quarantineOwnerIsStale(owner, staleMs);
1616
+ const stat = fs4.statSync(file);
1617
+ if (Date.now() - stat.mtimeMs > staleMs)
1618
+ return true;
1619
+ const pid = pidFileOwner(file);
1620
+ return pid !== void 0 && !realIsPidAlive(pid);
1413
1621
  } catch {
1414
- try {
1415
- stale = Date.now() - (await fsp.stat(quarantined)).mtimeMs > staleMs;
1416
- } catch {
1417
- stale = false;
1418
- }
1622
+ return false;
1419
1623
  }
1420
- if (stale) {
1421
- await fsp.rm(quarantined, { recursive: true, force: true });
1422
- return true;
1624
+ }
1625
+ function isLockContention(error) {
1626
+ const code = error?.code;
1627
+ return code === "EEXIST" || code === "EPERM" || code === "EBUSY";
1628
+ }
1629
+ function generationPath(dir, generation) {
1630
+ return path4.join(dir, `lock.${generation}`);
1631
+ }
1632
+ function releasedName(generation) {
1633
+ return `lock.${generation}.released`;
1634
+ }
1635
+ function topGeneration(entries) {
1636
+ let top = 0;
1637
+ for (const name of entries) {
1638
+ const match = GENERATION.exec(name);
1639
+ if (match && !match[2])
1640
+ top = Math.max(top, Number(match[1]));
1423
1641
  }
1424
- await restoreQuarantinedLock(lockPath, quarantined);
1425
- return false;
1642
+ return top;
1426
1643
  }
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;
1644
+ function removeBelowPredecessor(dir, entries, generation) {
1645
+ for (const name of entries) {
1646
+ const match = GENERATION.exec(name);
1647
+ if (!match || Number(match[1]) + 1 >= generation)
1648
+ continue;
1449
1649
  try {
1450
- const existing = JSON.parse(await fsp.readFile(path4.join(lockPath, "owner.json"), "utf8"));
1451
- stale = quarantineOwnerIsStale(existing, staleMs);
1650
+ fs4.unlinkSync(path4.join(dir, name));
1452
1651
  } catch {
1453
- try {
1454
- stale = Date.now() - (await fsp.stat(lockPath)).mtimeMs > staleMs;
1455
- } catch {
1456
- stale = true;
1457
- }
1458
1652
  }
1459
- if (!stale || !await reclaimQuarantineLock(lockPath, staleMs))
1460
- return null;
1461
1653
  }
1462
- return null;
1463
1654
  }
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
- };
1484
- }
1485
- releaseGeneration(hold);
1486
- return "legacy-held";
1655
+ function recordGenerationTakeover(hold) {
1656
+ incrementDegradationCount({
1657
+ kind: "generation-lock-stale-takeover",
1658
+ subject: path4.resolve(hold.dir),
1659
+ reason: `took over lock generation ${hold.generation - 1} from a dead or aged-out holder`
1660
+ });
1487
1661
  }
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)));
1508
- }
1662
+ function recordLegacyLockHeld(legacyPath) {
1663
+ incrementDegradationCount({
1664
+ kind: "generation-lock-legacy-held",
1665
+ subject: path4.resolve(legacyPath),
1666
+ reason: `backed off: ${path4.basename(legacyPath)} is held by another writer (one from before #3476, or a holder past the generation lease)`
1667
+ });
1509
1668
  }
1510
- function createLegacyBoundedLock(lockPath, token) {
1669
+ function releaseGeneration(hold) {
1511
1670
  try {
1512
- fs4.writeFileSync(lockPath, token, { encoding: "utf8", flag: "wx" });
1513
- return true;
1514
- } catch (cause) {
1515
- if (isLockContention(cause))
1516
- return false;
1517
- throw cause;
1671
+ fs4.writeFileSync(path4.join(hold.dir, releasedName(hold.generation)), "");
1672
+ } catch {
1518
1673
  }
1519
1674
  }
1520
- function takeLegacyBoundedLock(lockPath, token) {
1521
- if (createLegacyBoundedLock(lockPath, token))
1522
- return true;
1675
+ function heartbeatIntervalMs(leaseMs) {
1676
+ return Math.max(1e3, Math.floor(leaseMs / 4));
1677
+ }
1678
+ function startGenerationHeartbeat(hold, intervalMs) {
1679
+ const file = generationPath(hold.dir, hold.generation);
1680
+ const timer = setInterval(() => {
1681
+ try {
1682
+ const now = /* @__PURE__ */ new Date();
1683
+ fs4.utimesSync(file, now, now);
1684
+ } catch {
1685
+ }
1686
+ }, intervalMs);
1687
+ timer.unref();
1688
+ return { stop: () => clearInterval(timer) };
1689
+ }
1690
+ function ownsTopGeneration(hold) {
1523
1691
  try {
1524
- if (!boundedLockIsStale(lockPath))
1692
+ const entries = fs4.readdirSync(hold.dir);
1693
+ if (entries.includes(releasedName(hold.generation)))
1525
1694
  return false;
1526
- fs4.unlinkSync(lockPath);
1695
+ return topGeneration(entries) === hold.generation;
1527
1696
  } catch {
1528
1697
  return false;
1529
1698
  }
1530
- return createLegacyBoundedLock(lockPath, token);
1531
1699
  }
1532
- function releaseLegacyBoundedLock(lockPath, token) {
1700
+ function tryAcquireGeneration(dir, staleMs) {
1701
+ fs4.mkdirSync(dir, { recursive: true });
1702
+ const listed = fs4.readdirSync(dir);
1703
+ const top = topGeneration(listed);
1704
+ const free = top === 0 || listed.includes(releasedName(top));
1705
+ if (!free && !pidFileIsStale(generationPath(dir, top), staleMs)) {
1706
+ return void 0;
1707
+ }
1708
+ const hold = { dir, generation: top + 1, tookOverStale: !free };
1533
1709
  try {
1534
- if (fs4.readFileSync(lockPath, "utf8") === token)
1535
- fs4.unlinkSync(lockPath);
1536
- } catch {
1710
+ fs4.writeFileSync(generationPath(dir, hold.generation), `${process.pid} ${Date.now()}
1711
+ `, { flag: "wx" });
1712
+ } catch (error) {
1713
+ if (isLockContention(error))
1714
+ return void 0;
1715
+ throw error;
1537
1716
  }
1538
- }
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;
1717
+ let entries;
1546
1718
  try {
1547
- took = takeLegacyBoundedLock(lockPath, token);
1719
+ entries = fs4.readdirSync(dir);
1720
+ } catch (cause) {
1721
+ releaseGeneration(hold);
1722
+ throw cause;
1723
+ }
1724
+ if (topGeneration(entries) > hold.generation) {
1725
+ releaseGeneration(hold);
1726
+ return void 0;
1727
+ }
1728
+ removeBelowPredecessor(dir, entries, hold.generation);
1729
+ return hold;
1730
+ }
1731
+ var timedOutHolders = new BoundedFifoMap(16);
1732
+ function topGenerationHolder(dir) {
1733
+ try {
1734
+ const top = topGeneration(fs4.readdirSync(dir));
1735
+ return `lock.${top} ${fs4.readFileSync(generationPath(dir, top), "utf8").trim()}`;
1736
+ } catch {
1737
+ return void 0;
1738
+ }
1739
+ }
1740
+ function withGenerationLockSync(dir, timing, op) {
1741
+ const deadline = Date.now() + timing.waitMs;
1742
+ const timedOutHolder = timedOutHolders.get(dir);
1743
+ for (; ; ) {
1744
+ let hold;
1745
+ try {
1746
+ hold = tryAcquireGeneration(dir, timing.staleMs);
1747
+ } catch (cause) {
1748
+ return { held: false, cause };
1749
+ }
1750
+ if (hold) {
1751
+ if (hold.tookOverStale)
1752
+ recordGenerationTakeover(hold);
1753
+ try {
1754
+ return { held: true, value: op() };
1755
+ } finally {
1756
+ releaseGeneration(hold);
1757
+ }
1758
+ }
1759
+ if (timedOutHolder !== void 0 && topGenerationHolder(dir) === timedOutHolder) {
1760
+ recordDegradationOnce({
1761
+ kind: "generation-lock-wait-skipped",
1762
+ subject: dir,
1763
+ reason: `did not wait: ${timedOutHolder} still holds the lock after an earlier wait ran out`
1764
+ });
1765
+ return { held: false };
1766
+ }
1767
+ if (Date.now() >= deadline) {
1768
+ timedOutHolders.set(dir, topGenerationHolder(dir));
1769
+ return { held: false };
1770
+ }
1771
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, randomInt(5, 26));
1772
+ }
1773
+ }
1774
+
1775
+ // dist/clients/bounded-pid-file-lock.js
1776
+ var waitArray = new Int32Array(new SharedArrayBuffer(4));
1777
+ var UNREADABLE_LOCK_STALE_MS = 5e3;
1778
+ function generationDir(lockPath) {
1779
+ return `${lockPath}s`;
1780
+ }
1781
+ function boundedLockIsStale(lockPath) {
1782
+ const [pidText] = fs5.readFileSync(lockPath, "utf8").split(":", 1);
1783
+ const pid = Number.parseInt(pidText ?? "", 10);
1784
+ if (Number.isSafeInteger(pid) && pid > 0)
1785
+ return !realIsPidAlive(pid);
1786
+ return Date.now() - fs5.statSync(lockPath).mtimeMs > UNREADABLE_LOCK_STALE_MS;
1787
+ }
1788
+ function quarantinePath(lockPath, token) {
1789
+ return `${lockPath}.quarantine-${process.pid}-${token}`;
1790
+ }
1791
+ async function restoreQuarantinedLock(lockPath, quarantined) {
1792
+ try {
1793
+ await fsp.rename(quarantined, lockPath);
1794
+ } catch {
1795
+ }
1796
+ }
1797
+ async function releaseQuarantineLock(lockPath, token) {
1798
+ const quarantined = quarantinePath(lockPath, `release-${token}`);
1799
+ let renamed = false;
1800
+ for (let attempt = 0; attempt < 3; attempt += 1) {
1801
+ try {
1802
+ await fsp.rename(lockPath, quarantined);
1803
+ renamed = true;
1804
+ break;
1805
+ } catch (error) {
1806
+ if (error.code !== "ENOENT" || attempt === 2)
1807
+ return;
1808
+ await new Promise((resolve7) => setImmediate(resolve7));
1809
+ }
1810
+ }
1811
+ if (!renamed)
1812
+ return;
1813
+ try {
1814
+ const owner = JSON.parse(await fsp.readFile(path5.join(quarantined, "owner.json"), "utf8"));
1815
+ if (owner.token === token) {
1816
+ await fsp.rm(quarantined, { recursive: true, force: true });
1817
+ } else {
1818
+ await restoreQuarantinedLock(lockPath, quarantined);
1819
+ }
1820
+ } catch {
1821
+ await restoreQuarantinedLock(lockPath, quarantined);
1822
+ }
1823
+ }
1824
+ function quarantineOwnerIsStale(owner, staleMs) {
1825
+ const pidUsable = Number.isInteger(owner.pid) && owner.pid > 0;
1826
+ if (pidUsable && !realIsPidAlive(owner.pid))
1827
+ return true;
1828
+ return Number.isFinite(owner.createdAt) && Date.now() - owner.createdAt > staleMs;
1829
+ }
1830
+ async function reclaimQuarantineLock(lockPath, staleMs) {
1831
+ const quarantined = quarantinePath(lockPath, `reclaim-${Date.now()}-${randomUUID()}`);
1832
+ try {
1833
+ await fsp.rename(lockPath, quarantined);
1834
+ } catch {
1835
+ return false;
1836
+ }
1837
+ let stale = false;
1838
+ try {
1839
+ const owner = JSON.parse(await fsp.readFile(path5.join(quarantined, "owner.json"), "utf8"));
1840
+ stale = quarantineOwnerIsStale(owner, staleMs);
1841
+ } catch {
1842
+ try {
1843
+ stale = Date.now() - (await fsp.stat(quarantined)).mtimeMs > staleMs;
1844
+ } catch {
1845
+ stale = false;
1846
+ }
1847
+ }
1848
+ if (stale) {
1849
+ await fsp.rm(quarantined, { recursive: true, force: true });
1850
+ return true;
1851
+ }
1852
+ await restoreQuarantinedLock(lockPath, quarantined);
1853
+ return false;
1854
+ }
1855
+ async function tryAcquireQuarantineLock(lockPath, staleMs) {
1856
+ const owner = {
1857
+ pid: process.pid,
1858
+ createdAt: Date.now(),
1859
+ token: `${process.pid}-${Date.now()}-${randomUUID()}`
1860
+ };
1861
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1862
+ try {
1863
+ await fsp.mkdir(lockPath);
1864
+ try {
1865
+ await fsp.writeFile(path5.join(lockPath, "owner.json"), JSON.stringify(owner), "utf8");
1866
+ } catch (error) {
1867
+ await fsp.rm(lockPath, { recursive: true, force: true }).catch(() => {
1868
+ });
1869
+ throw error;
1870
+ }
1871
+ return () => releaseQuarantineLock(lockPath, owner.token);
1872
+ } catch (error) {
1873
+ if (error.code !== "EEXIST")
1874
+ throw error;
1875
+ }
1876
+ let stale;
1877
+ try {
1878
+ const existing = JSON.parse(await fsp.readFile(path5.join(lockPath, "owner.json"), "utf8"));
1879
+ stale = quarantineOwnerIsStale(existing, staleMs);
1880
+ } catch {
1881
+ try {
1882
+ stale = Date.now() - (await fsp.stat(lockPath)).mtimeMs > staleMs;
1883
+ } catch {
1884
+ stale = true;
1885
+ }
1886
+ }
1887
+ if (!stale || !await reclaimQuarantineLock(lockPath, staleMs))
1888
+ return null;
1889
+ }
1890
+ return null;
1891
+ }
1892
+ async function tryAcquireQuarantineGeneration(lockPath, staleMs) {
1893
+ const hold = tryAcquireGeneration(generationDir(lockPath), staleMs);
1894
+ if (!hold)
1895
+ return "busy";
1896
+ if (hold.tookOverStale)
1897
+ recordGenerationTakeover(hold);
1898
+ let releaseLegacy;
1899
+ try {
1900
+ releaseLegacy = await tryAcquireQuarantineLock(lockPath, staleMs);
1901
+ } catch (cause) {
1902
+ releaseGeneration(hold);
1903
+ throw cause;
1904
+ }
1905
+ if (releaseLegacy) {
1906
+ const heartbeat = startGenerationHeartbeat(hold, heartbeatIntervalMs(staleMs));
1907
+ return async () => {
1908
+ heartbeat.stop();
1909
+ await releaseLegacy();
1910
+ releaseGeneration(hold);
1911
+ };
1912
+ }
1913
+ releaseGeneration(hold);
1914
+ return "legacy-held";
1915
+ }
1916
+ async function acquireQuarantinePidFileLock(lockPath, options) {
1917
+ const deadline = Date.now() + options.waitMs;
1918
+ let legacyHeldRecorded = false;
1919
+ for (; ; ) {
1920
+ const release2 = await tryAcquireQuarantineGeneration(lockPath, options.staleMs);
1921
+ if (typeof release2 === "function")
1922
+ return release2;
1923
+ if (release2 === "legacy-held" && !legacyHeldRecorded) {
1924
+ legacyHeldRecorded = true;
1925
+ recordLegacyLockHeld(lockPath);
1926
+ }
1927
+ const remaining = deadline - Date.now();
1928
+ if (remaining <= 0) {
1929
+ if (options.onContention === "skip-log") {
1930
+ options.logContention();
1931
+ return null;
1932
+ }
1933
+ throw new Error(options.timeoutMessage);
1934
+ }
1935
+ await new Promise((resolve7) => setTimeout(resolve7, Math.min(options.retryMs, remaining)));
1936
+ }
1937
+ }
1938
+ function createLegacyBoundedLock(lockPath, token) {
1939
+ try {
1940
+ fs5.writeFileSync(lockPath, token, { encoding: "utf8", flag: "wx" });
1941
+ return true;
1942
+ } catch (cause) {
1943
+ if (isLockContention(cause))
1944
+ return false;
1945
+ throw cause;
1946
+ }
1947
+ }
1948
+ function takeLegacyBoundedLock(lockPath, token) {
1949
+ if (createLegacyBoundedLock(lockPath, token))
1950
+ return true;
1951
+ try {
1952
+ if (!boundedLockIsStale(lockPath))
1953
+ return false;
1954
+ fs5.unlinkSync(lockPath);
1955
+ } catch {
1956
+ return false;
1957
+ }
1958
+ return createLegacyBoundedLock(lockPath, token);
1959
+ }
1960
+ function releaseLegacyBoundedLock(lockPath, token) {
1961
+ try {
1962
+ if (fs5.readFileSync(lockPath, "utf8") === token)
1963
+ fs5.unlinkSync(lockPath);
1964
+ } catch {
1965
+ }
1966
+ }
1967
+ function tryAcquireBoundedLock(lockPath, token) {
1968
+ const hold = tryAcquireGeneration(generationDir(lockPath), UNREADABLE_LOCK_STALE_MS);
1969
+ if (!hold)
1970
+ return "busy";
1971
+ if (hold.tookOverStale)
1972
+ recordGenerationTakeover(hold);
1973
+ let took;
1974
+ try {
1975
+ took = takeLegacyBoundedLock(lockPath, token);
1548
1976
  } catch (cause) {
1549
1977
  releaseGeneration(hold);
1550
1978
  throw cause;
@@ -1559,7 +1987,7 @@ function currentHolderIdentity(dir, lockPath, hold) {
1559
1987
  if (hold === "busy")
1560
1988
  return topGenerationHolder(dir);
1561
1989
  try {
1562
- const content = fs4.readFileSync(lockPath, "utf8");
1990
+ const content = fs5.readFileSync(lockPath, "utf8");
1563
1991
  return content ? `legacy ${content}` : void 0;
1564
1992
  } catch {
1565
1993
  return void 0;
@@ -1586,7 +2014,7 @@ function acquireBoundedPidFileLock(lockPath, options) {
1586
2014
  if (timedOutHolder !== void 0 && currentHolderIdentity(dir, lockPath, hold) === timedOutHolder) {
1587
2015
  recordDegradationOnce({
1588
2016
  kind: "bounded-pid-lock-wait-skipped",
1589
- subject: path4.resolve(dir),
2017
+ subject: path5.resolve(dir),
1590
2018
  reason: `did not wait: ${timedOutHolder} still holds the lock after an earlier wait ran out`
1591
2019
  });
1592
2020
  if (options.onContention === "skip-log") {
@@ -1607,76 +2035,14 @@ function acquireBoundedPidFileLock(lockPath, options) {
1607
2035
  }
1608
2036
  }
1609
2037
 
1610
- // dist/clients/child-unref.js
1611
- import { spawn as nodeSpawn } from "node:child_process";
1612
- function unrefChildAndPipes(child) {
1613
- try {
1614
- child.unref();
1615
- for (const stream of [child.stdout, child.stderr, child.stdin]) {
1616
- stream?.unref?.();
1617
- }
1618
- } catch {
1619
- }
1620
- }
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
- };
1633
- 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
- }
1652
- } 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";
1663
- }
1664
- }
1665
- try {
1666
- child.kill();
1667
- } catch {
1668
- }
1669
- return "unverified";
1670
- }
1671
-
1672
2038
  // dist/clients/file-utils.js
1673
- import * as fs5 from "node:fs";
2039
+ import * as fs6 from "node:fs";
1674
2040
  import { createHash, randomBytes } from "node:crypto";
1675
2041
  import * as os3 from "node:os";
1676
- import * as path8 from "node:path";
2042
+ import * as path9 from "node:path";
1677
2043
 
1678
2044
  // dist/clients/spawn-timeout-cooldown.js
1679
- import path5 from "node:path";
2045
+ import path6 from "node:path";
1680
2046
  var COOLDOWN_STATE_KEY = /* @__PURE__ */ Symbol.for("pi-lens:spawn-timeout-cooldown");
1681
2047
  var _global = globalThis;
1682
2048
  if (!_global[COOLDOWN_STATE_KEY]) {
@@ -1684,11 +2050,11 @@ if (!_global[COOLDOWN_STATE_KEY]) {
1684
2050
  }
1685
2051
  var timedOutByCommand = _global[COOLDOWN_STATE_KEY].timedOutByCommand;
1686
2052
  function wrapperKindOf(command) {
1687
- const ext = path5.extname(command);
2053
+ const ext = path6.extname(command);
1688
2054
  return ext ? ext.slice(1) : "bare";
1689
2055
  }
1690
2056
  function cooldownKey(command) {
1691
- return path5.basename(command).replace(/\.[^.]+$/, "").toLowerCase();
2057
+ return path6.basename(command).replace(/\.[^.]+$/, "").toLowerCase();
1692
2058
  }
1693
2059
  function noteSpawnTimeout(input) {
1694
2060
  const key = cooldownKey(input.command);
@@ -1727,7 +2093,7 @@ function resetSpawnTimeoutCooldowns() {
1727
2093
  }
1728
2094
 
1729
2095
  // dist/clients/git-tracked-ignore.js
1730
- import * as path6 from "node:path";
2096
+ import * as path7 from "node:path";
1731
2097
  function recordTruncatedLsFiles(parseSite) {
1732
2098
  recordDegradationOnce({
1733
2099
  kind: "git-tracked-ignore-truncated",
@@ -1745,7 +2111,7 @@ function parseUntrackedIgnoredOutput(stdout, cwd) {
1745
2111
  const dirSegments = rel.split("/").slice(0, -1);
1746
2112
  if (dirSegments.some((segment) => isExcludedDirName(segment)))
1747
2113
  continue;
1748
- ids.add(normalizeMapKey(path6.join(cwd, rel)));
2114
+ ids.add(normalizeMapKey(path7.join(cwd, rel)));
1749
2115
  }
1750
2116
  return ids;
1751
2117
  }
@@ -1790,7 +2156,7 @@ function parseTrackedFilesOutput(stdout, cwd) {
1790
2156
  const dirSegments = rel.split("/").slice(0, -1);
1791
2157
  if (dirSegments.some((segment) => isExcludedDirName(segment)))
1792
2158
  continue;
1793
- ids.add(normalizeEphemeralMapKey(path6.join(base, rel)));
2159
+ ids.add(normalizeEphemeralMapKey(path7.join(base, rel)));
1794
2160
  }
1795
2161
  return ids;
1796
2162
  }
@@ -1912,7 +2278,7 @@ function loadPiLensGlobalConfig(configPath) {
1912
2278
  try {
1913
2279
  const parsed = outcome.value;
1914
2280
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1915
- note("top-level value must be an object");
2281
+ note("top-level value must be an object", "PILENS_CFG_0001");
1916
2282
  return void 0;
1917
2283
  }
1918
2284
  const document = {
@@ -1933,7 +2299,7 @@ function loadPiLensGlobalConfig(configPath) {
1933
2299
  if (toolsSection && "lazy" in toolsSection) {
1934
2300
  const lazy = readLazyToolsSetting(raw);
1935
2301
  if (lazy === void 0)
1936
- warnInvalid('tools.lazy must be "auto", true, or false');
2302
+ warnInvalid('tools.lazy must be "auto", true, or false', "PILENS_CFG_0005");
1937
2303
  else
1938
2304
  config.tools = { ...config.tools, lazy };
1939
2305
  }
@@ -1953,12 +2319,12 @@ function loadPiLensGlobalConfig(configPath) {
1953
2319
  if (mode === "quick" || mode === "full" || mode === "minimal")
1954
2320
  startupConfig.mode = mode;
1955
2321
  else if ("mode" in startup)
1956
- warnInvalid('startup.mode must be "quick", "full", or "minimal"');
2322
+ warnInvalid('startup.mode must be "quick", "full", or "minimal"', "PILENS_CFG_0005");
1957
2323
  if (scans) {
1958
2324
  if (typeof scans.enabled === "boolean") {
1959
2325
  startupConfig.scans = { enabled: scans.enabled };
1960
2326
  } else if ("enabled" in scans)
1961
- warnInvalid("startup.scans.enabled must be a boolean");
2327
+ warnInvalid("startup.scans.enabled must be a boolean", "PILENS_CFG_0005");
1962
2328
  }
1963
2329
  if (startupConfig.mode !== void 0 || startupConfig.scans !== void 0)
1964
2330
  config.startup = startupConfig;
@@ -1970,7 +2336,7 @@ function loadPiLensGlobalConfig(configPath) {
1970
2336
  config.dispatch = { runnerTimeoutFloorMs: floor };
1971
2337
  } else {
1972
2338
  if ("runnerTimeoutFloorMs" in dispatch) {
1973
- warnInvalid("dispatch.runnerTimeoutFloorMs must be a positive finite number");
2339
+ warnInvalid("dispatch.runnerTimeoutFloorMs must be a positive finite number", "PILENS_CFG_0005");
1974
2340
  }
1975
2341
  config.dispatch = { runnerTimeoutFloorMs: void 0 };
1976
2342
  }
@@ -1983,7 +2349,7 @@ function loadPiLensGlobalConfig(configPath) {
1983
2349
  warnings.autoFix ??= {};
1984
2350
  warnings.autoFix.maxFixes = Math.floor(autoFix.maxFixes);
1985
2351
  } else {
1986
- warnInvalid("actionableWarnings.autoFix.maxFixes must be a non-negative finite number");
2352
+ warnInvalid("actionableWarnings.autoFix.maxFixes must be a non-negative finite number", "PILENS_CFG_0005");
1987
2353
  }
1988
2354
  }
1989
2355
  const contextInjection = asConfigObject(raw.contextInjection);
@@ -1992,7 +2358,7 @@ function loadPiLensGlobalConfig(configPath) {
1992
2358
  config.contextInjection ??= {};
1993
2359
  config.contextInjection.requirePreExistingFixes = contextInjection.requirePreExistingFixes;
1994
2360
  } else {
1995
- warnInvalid("contextInjection.requirePreExistingFixes must be a boolean");
2361
+ warnInvalid("contextInjection.requirePreExistingFixes must be a boolean", "PILENS_CFG_0005");
1996
2362
  }
1997
2363
  }
1998
2364
  const widget = asConfigObject(raw.widget);
@@ -2001,7 +2367,7 @@ function loadPiLensGlobalConfig(configPath) {
2001
2367
  config.widget = { visible: widget.visible };
2002
2368
  } else {
2003
2369
  if ("visible" in widget) {
2004
- warnInvalid("widget.visible must be a boolean");
2370
+ warnInvalid("widget.visible must be a boolean", "PILENS_CFG_0005");
2005
2371
  }
2006
2372
  config.widget = { visible: void 0 };
2007
2373
  }
@@ -2014,7 +2380,7 @@ function loadPiLensGlobalConfig(configPath) {
2014
2380
  formatSection.mode = format.mode;
2015
2381
  } else {
2016
2382
  if ("mode" in format) {
2017
- warnInvalid('format.mode must be "immediate" or "deferred"');
2383
+ warnInvalid('format.mode must be "immediate" or "deferred"', "PILENS_CFG_0005");
2018
2384
  }
2019
2385
  formatSection.mode = void 0;
2020
2386
  }
@@ -2026,7 +2392,7 @@ function loadPiLensGlobalConfig(configPath) {
2026
2392
  ]);
2027
2393
  for (const key of Object.keys(raw)) {
2028
2394
  if (!knownGlobalConfigKeys.has(key)) {
2029
- warnInvalid(PROJECT_NON_FLAG_CONFIG_SECTIONS.includes(key) ? `"${key}" is a project-scoped pi-lens setting; set it in <project>/.pi-lens.json, not in the global config; ignored` : `unknown key "${key}" is not a recognized pi-lens setting (check for a typo); ignored`);
2395
+ warnInvalid(PROJECT_NON_FLAG_CONFIG_SECTIONS.includes(key) ? `"${key}" is a project-scoped pi-lens setting; set it in <project>/.pi-lens.json, not in the global config; ignored` : `unknown key "${key}" is not a recognized pi-lens setting (check for a typo); ignored`, "PILENS_CFG_0004");
2030
2396
  }
2031
2397
  }
2032
2398
  return config;
@@ -2077,12 +2443,12 @@ function resolvePiLensFlag(name, value, config, projectConfig, editedFilePath, p
2077
2443
 
2078
2444
  // dist/clients/ephemeral-root.js
2079
2445
  import * as os2 from "node:os";
2080
- import * as path7 from "node:path";
2446
+ import * as path8 from "node:path";
2081
2447
  var NOT_EPHEMERAL = { checkout: false };
2082
2448
  var classified = new BoundedFifoMap(1024);
2083
2449
  function classifyTmpDir(dir) {
2084
2450
  const tmpSpelling = os2.tmpdir();
2085
- const key = `${normalizeEphemeralMapKey(tmpSpelling)}\0${normalizeEphemeralMapKey(path7.resolve(dir))}`;
2451
+ const key = `${normalizeEphemeralMapKey(tmpSpelling)}\0${normalizeEphemeralMapKey(path8.resolve(dir))}`;
2086
2452
  const memo = classified.get(key);
2087
2453
  if (memo)
2088
2454
  return memo;
@@ -2093,18 +2459,18 @@ function classifyTmpDir(dir) {
2093
2459
  for (const current of walkUpDirs(real)) {
2094
2460
  if (current === tmpRoot)
2095
2461
  break;
2096
- if (isRealGitMarker(path7.join(current, ".git"))) {
2462
+ if (isRealGitMarker(path8.join(current, ".git"))) {
2097
2463
  result = { checkout: true };
2098
2464
  break;
2099
2465
  }
2100
2466
  }
2101
2467
  if (!result.checkout) {
2102
- const segments = path7.relative(tmpRoot, real).split(path7.sep);
2468
+ const segments = path8.relative(tmpRoot, real).split(path8.sep);
2103
2469
  const index = segments.findIndex((segment) => /^pi-agent(?:-|$)/i.test(segment));
2104
2470
  if (index >= 0) {
2105
2471
  result = {
2106
2472
  checkout: false,
2107
- stagingRoot: path7.join(tmpRoot, ...segments.slice(0, index + 1))
2473
+ stagingRoot: path8.join(tmpRoot, ...segments.slice(0, index + 1))
2108
2474
  };
2109
2475
  }
2110
2476
  }
@@ -2113,17 +2479,17 @@ function classifyTmpDir(dir) {
2113
2479
  return result;
2114
2480
  }
2115
2481
  function ephemeralStagingRoot(filePath) {
2116
- return classifyTmpDir(path7.dirname(path7.resolve(filePath))).stagingRoot;
2482
+ return classifyTmpDir(path8.dirname(path8.resolve(filePath))).stagingRoot;
2117
2483
  }
2118
2484
  function isPiOwnedTempPath(filePath) {
2119
2485
  const tmpRoot = realpathOrResolve(os2.tmpdir());
2120
2486
  const real = realpathOrResolve(filePath);
2121
2487
  if (!isUnderDir(real, tmpRoot))
2122
2488
  return false;
2123
- const relative3 = path7.relative(tmpRoot, real);
2124
- if (relative3.length === 0 || path7.isAbsolute(relative3))
2489
+ const relative3 = path8.relative(tmpRoot, real);
2490
+ if (relative3.length === 0 || path8.isAbsolute(relative3))
2125
2491
  return false;
2126
- const segments = relative3.split(path7.sep);
2492
+ const segments = relative3.split(path8.sep);
2127
2493
  return segments.length === 1 || /^pi-/i.test(segments[0] ?? "");
2128
2494
  }
2129
2495
  function isEphemeralCheckoutRoot(dir) {
@@ -2132,14 +2498,14 @@ function isEphemeralCheckoutRoot(dir) {
2132
2498
 
2133
2499
  // dist/clients/file-utils.js
2134
2500
  function getProjectDataDir(cwd) {
2135
- const legacyProjectDir = path8.join(cwd, ".pi-lens");
2501
+ const legacyProjectDir = path9.join(cwd, ".pi-lens");
2136
2502
  const configuredBase = process.env.PILENS_DATA_DIR?.trim();
2137
2503
  const resolvedBase = projectDataBase();
2138
- const memoKey = `${resolvedBase}\0${path8.resolve(cwd)}`;
2504
+ const memoKey = `${resolvedBase}\0${path9.resolve(cwd)}`;
2139
2505
  const cached = settledDataDirs.get(memoKey);
2140
2506
  if (cached !== void 0)
2141
2507
  return cached;
2142
- if (!configuredBase && fs5.existsSync(legacyProjectDir)) {
2508
+ if (!configuredBase && fs6.existsSync(legacyProjectDir)) {
2143
2509
  return legacyProjectDir;
2144
2510
  }
2145
2511
  const canonical = dataDirCanonicalRoot(cwd);
@@ -2147,13 +2513,13 @@ function getProjectDataDir(cwd) {
2147
2513
  const hash = projectDataDirRootHash(canonical.root);
2148
2514
  const slug = `${readable || "default"}-${hash}`;
2149
2515
  const base = isEphemeralCheckoutRoot(cwd) ? ephemeralDataBase(resolvedBase) : resolvedBase;
2150
- const dir = path8.join(base, slug);
2516
+ const dir = path9.join(base, slug);
2151
2517
  if (base !== resolvedBase && pendingDataDirMigrations.length < 32) {
2152
2518
  pendingDataDirMigrations.push({ to: dir, outcome: "ephemeral" });
2153
2519
  }
2154
2520
  const settled = settleProjectDataDir(base, readable || "default", dir, memoKey, canonical.fallback);
2155
2521
  if (settled === dir) {
2156
- adoptSpelledDataDirs(path8.resolve(cwd), base, dir, readable || "default");
2522
+ adoptSpelledDataDirs(path9.resolve(cwd), base, dir, readable || "default");
2157
2523
  }
2158
2524
  return settled;
2159
2525
  }
@@ -2179,18 +2545,18 @@ function adoptSpelledDataDirs(spelledRoot, base, dir, settledOldSlug) {
2179
2545
  }
2180
2546
  }
2181
2547
  function adoptSource(base, source, dir) {
2182
- const from = path8.join(base, source);
2548
+ const from = path9.join(base, source);
2183
2549
  if (from === dir || !isDirectory(from))
2184
2550
  return { copied: 0, failed: 0 };
2185
- const marker = path8.join(dir, `${ADOPTED_MARKER_PREFIX}${source}`);
2186
- if (fs5.existsSync(marker))
2551
+ const marker = path9.join(dir, `${ADOPTED_MARKER_PREFIX}${source}`);
2552
+ if (fs6.existsSync(marker))
2187
2553
  return { copied: 0, failed: 0 };
2188
2554
  const { copied, failed } = copyMissingFiles(from, dir);
2189
2555
  return { copied, failed: failed + (markAdopted(marker) ? 0 : 1) };
2190
2556
  }
2191
2557
  function markAdopted(marker) {
2192
2558
  try {
2193
- fs5.mkdirSync(path8.dirname(marker), { recursive: true });
2559
+ fs6.mkdirSync(path9.dirname(marker), { recursive: true });
2194
2560
  writeFileAtomic(marker, "", { bestEffort: false });
2195
2561
  return true;
2196
2562
  } catch {
@@ -2199,7 +2565,7 @@ function markAdopted(marker) {
2199
2565
  }
2200
2566
  function isDirectory(dir) {
2201
2567
  try {
2202
- return fs5.statSync(dir).isDirectory();
2568
+ return fs6.statSync(dir).isDirectory();
2203
2569
  } catch {
2204
2570
  return false;
2205
2571
  }
@@ -2213,7 +2579,7 @@ function copyMissingFiles(from, to) {
2213
2579
  const rel = pending.pop() ?? "";
2214
2580
  let entries;
2215
2581
  try {
2216
- entries = fs5.readdirSync(path8.join(from, rel), { withFileTypes: true });
2582
+ entries = fs6.readdirSync(path9.join(from, rel), { withFileTypes: true });
2217
2583
  } catch {
2218
2584
  failed++;
2219
2585
  continue;
@@ -2226,7 +2592,7 @@ function copyMissingFiles(from, to) {
2226
2592
  continue;
2227
2593
  if (name.startsWith(ADOPTED_MARKER_PREFIX))
2228
2594
  continue;
2229
- const child = path8.join(rel, name);
2595
+ const child = path9.join(rel, name);
2230
2596
  if (entry.isDirectory()) {
2231
2597
  if (++seen > ADOPT_MAX_ENTRIES)
2232
2598
  return { copied, failed: failed + 1 };
@@ -2237,7 +2603,7 @@ function copyMissingFiles(from, to) {
2237
2603
  continue;
2238
2604
  if (++seen > ADOPT_MAX_ENTRIES)
2239
2605
  return { copied, failed: failed + 1 };
2240
- const outcome = copyIfMissing(path8.join(from, child), path8.join(to, child));
2606
+ const outcome = copyIfMissing(path9.join(from, child), path9.join(to, child));
2241
2607
  if (outcome === "copied")
2242
2608
  copied++;
2243
2609
  else if (outcome === "failed")
@@ -2250,21 +2616,21 @@ function copyIfMissing(source, target) {
2250
2616
  const stage = stagePathFor(target);
2251
2617
  let staged = false;
2252
2618
  try {
2253
- fs5.mkdirSync(path8.dirname(target), { recursive: true });
2619
+ fs6.mkdirSync(path9.dirname(target), { recursive: true });
2254
2620
  staged = true;
2255
- fs5.copyFileSync(source, stage);
2256
- fs5.linkSync(stage, target);
2621
+ fs6.copyFileSync(source, stage);
2622
+ fs6.linkSync(stage, target);
2257
2623
  return "copied";
2258
2624
  } catch (cause) {
2259
2625
  return staged && cause.code === "EEXIST" ? "present" : "failed";
2260
2626
  } finally {
2261
2627
  if (staged)
2262
- fs5.rmSync(stage, { force: true });
2628
+ fs6.rmSync(stage, { force: true });
2263
2629
  }
2264
2630
  }
2265
2631
  function projectDataBase() {
2266
2632
  const configuredBase = process.env.PILENS_DATA_DIR?.trim();
2267
- return configuredBase || path8.join(getGlobalPiLensDir(), "projects");
2633
+ return configuredBase || path9.join(getGlobalPiLensDir(), "projects");
2268
2634
  }
2269
2635
  var EPHEMERAL_DATA_DIR_NAME = ".ephemeral";
2270
2636
  var EPHEMERAL_TOKEN_PATTERN = /^(\d+)-[0-9a-f]{8}$/;
@@ -2280,20 +2646,20 @@ function ephemeralDataBase(resolvedBase) {
2280
2646
  state.exitHook = true;
2281
2647
  process.once("exit", removeEphemeralDataDirs);
2282
2648
  }
2283
- return path8.join(resolvedBase, EPHEMERAL_DATA_DIR_NAME, state.token);
2649
+ return path9.join(resolvedBase, EPHEMERAL_DATA_DIR_NAME, state.token);
2284
2650
  }
2285
2651
  function removeEphemeralDataDirs() {
2286
- const dir = path8.join(projectDataBase(), EPHEMERAL_DATA_DIR_NAME, ephemeralDataToken().token);
2652
+ const dir = path9.join(projectDataBase(), EPHEMERAL_DATA_DIR_NAME, ephemeralDataToken().token);
2287
2653
  try {
2288
- fs5.rmSync(dir, { recursive: true, force: true });
2654
+ fs6.rmSync(dir, { recursive: true, force: true });
2289
2655
  } catch {
2290
2656
  }
2291
2657
  }
2292
2658
  async function sweepDeadEphemeralDataDirs(options) {
2293
- const parent = path8.join(projectDataBase(), EPHEMERAL_DATA_DIR_NAME);
2659
+ const parent = path9.join(projectDataBase(), EPHEMERAL_DATA_DIR_NAME);
2294
2660
  let handle;
2295
2661
  try {
2296
- handle = await fs5.promises.opendir(parent);
2662
+ handle = await fs6.promises.opendir(parent);
2297
2663
  } catch {
2298
2664
  return 0;
2299
2665
  }
@@ -2307,7 +2673,7 @@ async function sweepDeadEphemeralDataDirs(options) {
2307
2673
  if (pid === void 0 || options.isPidAlive(Number(pid)))
2308
2674
  continue;
2309
2675
  try {
2310
- await fs5.promises.rm(path8.join(parent, entry.name), {
2676
+ await fs6.promises.rm(path9.join(parent, entry.name), {
2311
2677
  recursive: true,
2312
2678
  force: true
2313
2679
  });
@@ -2327,9 +2693,9 @@ function projectDataDirReadableSlug(canonicalRoot) {
2327
2693
  return normalized.replace(/^[a-z]:/i, "").replace(/\/+/g, "-").replace(/[^A-Za-z0-9-]/g, "").replace(/^-+/, "").replace(/-+$/, "");
2328
2694
  }
2329
2695
  function dataDirCanonicalRoot(cwd, platform = process.platform) {
2330
- const resolved = path8.resolve(cwd);
2696
+ const resolved = path9.resolve(cwd);
2331
2697
  const root = platform === "win32" ? resolved : realpathOrResolve(resolved);
2332
- return { root, fallback: !fs5.existsSync(resolved) };
2698
+ return { root, fallback: !fs6.existsSync(resolved) };
2333
2699
  }
2334
2700
  function projectDataDirRootHash(canonicalRoot) {
2335
2701
  return createHash("sha256").update(canonicalRoot).digest("hex").slice(0, 8);
@@ -2340,9 +2706,9 @@ function resetProjectDataDirSessionState() {
2340
2706
  pendingDataDirMigrations.splice(0);
2341
2707
  }
2342
2708
  function settleProjectDataDir(base, oldSlug, dir, memoKey, identityFallback) {
2343
- const oldDir = path8.join(base, oldSlug);
2344
- const newExists = fs5.existsSync(dir);
2345
- const oldExists = fs5.existsSync(oldDir);
2709
+ const oldDir = path9.join(base, oldSlug);
2710
+ const newExists = fs6.existsSync(dir);
2711
+ const oldExists = fs6.existsSync(oldDir);
2346
2712
  if (!oldExists) {
2347
2713
  if (identityFallback && pendingDataDirMigrations.length < 32) {
2348
2714
  pendingDataDirMigrations.push({
@@ -2355,14 +2721,14 @@ function settleProjectDataDir(base, oldSlug, dir, memoKey, identityFallback) {
2355
2721
  }
2356
2722
  if (!newExists) {
2357
2723
  try {
2358
- fs5.renameSync(oldDir, dir);
2724
+ fs6.renameSync(oldDir, dir);
2359
2725
  } catch (error) {
2360
2726
  if (error.code === "ENOENT") {
2361
- if (fs5.existsSync(dir)) {
2727
+ if (fs6.existsSync(dir)) {
2362
2728
  settledDataDirs.set(memoKey, dir);
2363
2729
  return dir;
2364
2730
  }
2365
- if (fs5.existsSync(oldDir))
2731
+ if (fs6.existsSync(oldDir))
2366
2732
  return oldDir;
2367
2733
  return dir;
2368
2734
  }
@@ -2389,8 +2755,8 @@ function drainProjectDataDirMigrations() {
2389
2755
  return pendingDataDirMigrations.splice(0);
2390
2756
  }
2391
2757
  function displayProjectDataPath(cwd, ...segments) {
2392
- const absolute = path8.resolve(getProjectDataDir(cwd), ...segments);
2393
- const absolutePosix = absolute.replace(/\\/g, "/");
2758
+ const absolute = path9.resolve(getProjectDataDir(cwd), ...segments);
2759
+ const absolutePosix = toPosix(absolute);
2394
2760
  const relative3 = toProjectRelativePath(absolute, cwd);
2395
2761
  if (relative3 !== absolutePosix) {
2396
2762
  return relative3;
@@ -2401,13 +2767,13 @@ function getGlobalPiLensDir() {
2401
2767
  return machineStateDir();
2402
2768
  }
2403
2769
  function isPiLensInternalPath(filePath, projectRoot) {
2404
- const absolute = path8.resolve(filePath);
2405
- const home = path8.resolve(os3.homedir());
2770
+ const absolute = path9.resolve(filePath);
2771
+ const home = path9.resolve(os3.homedir());
2406
2772
  const candidates = [
2407
2773
  getGlobalPiLensDir(),
2408
2774
  getProjectDataDir(projectRoot),
2409
- path8.join(home, ".pi"),
2410
- path8.join(home, ".pi-lens")
2775
+ path9.join(home, ".pi"),
2776
+ path9.join(home, ".pi-lens")
2411
2777
  ];
2412
2778
  if (candidates.some((dir) => isUnderDir(absolute, dir)))
2413
2779
  return true;
@@ -2471,16 +2837,11 @@ var EXCLUDED_DIRS = [
2471
2837
  "vendors"
2472
2838
  ];
2473
2839
  function resolveGitIgnoreRoot(startDir) {
2474
- const fallback = realpathOrResolve(startDir);
2475
- let current = fallback;
2476
- while (true) {
2477
- if (fs5.existsSync(path8.join(current, ".git")))
2840
+ for (const current of walkUpDirs(startDir)) {
2841
+ if (fs6.existsSync(path9.join(current, ".git")))
2478
2842
  return current;
2479
- const parent = path8.dirname(current);
2480
- if (parent === current)
2481
- return fallback;
2482
- current = parent;
2483
2843
  }
2844
+ return realpathOrResolve(startDir);
2484
2845
  }
2485
2846
  function collapseSlashes(value) {
2486
2847
  let out = "";
@@ -2579,10 +2940,40 @@ function matchesGitignorePattern(pattern, relativePath, isDirectory2, matchExpan
2579
2940
  return candidates.some((value) => matchExpanded(value, expanded));
2580
2941
  });
2581
2942
  }
2943
+ function lastMatchingPattern(patterns, relativePath, isDirectory2, matchExpanded) {
2944
+ let winner;
2945
+ for (const pattern of patterns) {
2946
+ if (matchesGitignorePattern(pattern, relativePath, isDirectory2, matchExpanded))
2947
+ winner = pattern;
2948
+ }
2949
+ return winner;
2950
+ }
2951
+ var gitignoreGlobOptions = {
2952
+ dot: true,
2953
+ nocase: process.platform === "win32"
2954
+ };
2955
+ function createExpandedGlobMatcher() {
2956
+ const compiledGlobs = /* @__PURE__ */ new Map();
2957
+ return (value, expanded) => {
2958
+ let compiled = compiledGlobs.get(expanded);
2959
+ if (compiled === void 0) {
2960
+ compiled = new Minimatch(expanded, gitignoreGlobOptions);
2961
+ compiledGlobs.set(expanded, compiled);
2962
+ }
2963
+ return compiled.match(value);
2964
+ };
2965
+ }
2966
+ function isIgnoredByGitignoreLines(lines, baseDir, filePath, isDirectory2 = false) {
2967
+ const relative3 = relativeInside(baseDir, filePath);
2968
+ if (relative3 === void 0)
2969
+ return false;
2970
+ const winner = lastMatchingPattern(parseGitignoreContent(lines.join("\n"), "pilens"), normalizeIgnorePath(relative3), isDirectory2, createExpandedGlobMatcher());
2971
+ return winner !== void 0 && !winner.negated;
2972
+ }
2582
2973
  function readGitignorePatterns(rootDir, layer = "gitignore") {
2583
- const gitignorePath = path8.join(rootDir, ".gitignore");
2974
+ const gitignorePath = path9.join(rootDir, ".gitignore");
2584
2975
  try {
2585
- return parseGitignoreContent(fs5.readFileSync(gitignorePath, "utf-8"), layer);
2976
+ return parseGitignoreContent(fs6.readFileSync(gitignorePath, "utf-8"), layer);
2586
2977
  } catch {
2587
2978
  return [];
2588
2979
  }
@@ -2596,13 +2987,13 @@ function isWithinPathForm(child, parent) {
2596
2987
  function ancestorDirsBetween(rootDir, targetDir) {
2597
2988
  if (!isWithinPathForm(targetDir, rootDir))
2598
2989
  return [];
2599
- const relative3 = path8.relative(rootDir, targetDir);
2990
+ const relative3 = path9.relative(rootDir, targetDir);
2600
2991
  const dirs = [rootDir];
2601
2992
  if (!relative3)
2602
2993
  return dirs;
2603
2994
  let current = rootDir;
2604
- for (const segment of relative3.split(path8.sep).filter(Boolean)) {
2605
- current = path8.join(current, segment);
2995
+ for (const segment of relative3.split(path9.sep).filter(Boolean)) {
2996
+ current = path9.join(current, segment);
2606
2997
  dirs.push(current);
2607
2998
  }
2608
2999
  return dirs;
@@ -2612,7 +3003,7 @@ function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
2612
3003
  const rememberIgnoreSource = (filePath, signature = fileFreshnessSignature(filePath)) => {
2613
3004
  consumedIgnoreSources.set(filePath, { path: filePath, ...signature });
2614
3005
  };
2615
- rememberIgnoreSource(path8.join(resolvedRoot, ".gitignore"));
3006
+ rememberIgnoreSource(path9.join(resolvedRoot, ".gitignore"));
2616
3007
  const nestedCache = /* @__PURE__ */ new Map();
2617
3008
  const patternsForDir = (dir) => {
2618
3009
  if (dir === resolvedRoot)
@@ -2623,7 +3014,7 @@ function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
2623
3014
  return cached.patterns;
2624
3015
  }
2625
3016
  const gitignoreSig = gitignoreSignature(dir);
2626
- rememberIgnoreSource(path8.join(dir, ".gitignore"), gitignoreSig);
3017
+ rememberIgnoreSource(path9.join(dir, ".gitignore"), gitignoreSig);
2627
3018
  const pilensInfo = findPiLensConfigInDir(dir);
2628
3019
  const pilensMtime = pilensInfo?.mtimeMs ?? -1;
2629
3020
  const pilensSize = pilensInfo?.size ?? -1;
@@ -2650,7 +3041,7 @@ function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
2650
3041
  };
2651
3042
  const patternMemo = /* @__PURE__ */ new Map();
2652
3043
  function dropVerdictsUnder(subtree) {
2653
- const subtreeForm = path8.resolve(subtree);
3044
+ const subtreeForm = path9.resolve(subtree);
2654
3045
  for (const key of patternMemo.keys()) {
2655
3046
  const memoPath = key.slice(2);
2656
3047
  if (isWithinPathForm(memoPath, subtreeForm)) {
@@ -2669,20 +3060,20 @@ function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
2669
3060
  };
2670
3061
  const hasDotSegment = (spelling) => /(^|[\\/])\.\.?([\\/]|$)/.test(spelling);
2671
3062
  const projectPathKey = (spelling) => {
2672
- const absolute = path8.resolve(spelling);
3063
+ const absolute = path9.resolve(spelling);
2673
3064
  if (!hasDotSegment(spelling)) {
2674
3065
  if (isUnderRootText(absolute))
2675
3066
  return absolute;
2676
- return path8.join(identityOfDir(path8.dirname(absolute)), path8.basename(absolute));
3067
+ return path9.join(identityOfDir(path9.dirname(absolute)), path9.basename(absolute));
2677
3068
  }
2678
- const tail = path8.basename(spelling);
3069
+ const tail = path9.basename(spelling);
2679
3070
  if (tail === "." || tail === "..")
2680
3071
  return identityOfDir(spelling);
2681
- return path8.join(identityOfDir(path8.dirname(spelling)), tail);
3072
+ return path9.join(identityOfDir(path9.dirname(spelling)), tail);
2682
3073
  };
2683
3074
  const isUnderRootText = (absolute) => isWithinPathForm(absolute, resolvedRoot);
2684
3075
  const invalidateSubtree = (subtree) => {
2685
- const absolute = path8.resolve(subtree);
3076
+ const absolute = path9.resolve(subtree);
2686
3077
  let local = absolute;
2687
3078
  if (hasDotSegment(subtree))
2688
3079
  local = identityOfDir(subtree);
@@ -2691,19 +3082,7 @@ function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
2691
3082
  dropVerdictsUnder(local);
2692
3083
  nestedCache.delete(local);
2693
3084
  };
2694
- const gitignoreGlobOptions = {
2695
- dot: true,
2696
- nocase: process.platform === "win32"
2697
- };
2698
- const compiledGlobs = /* @__PURE__ */ new Map();
2699
- const matchExpanded = (value, expanded) => {
2700
- let compiled = compiledGlobs.get(expanded);
2701
- if (compiled === void 0) {
2702
- compiled = new Minimatch(expanded, gitignoreGlobOptions);
2703
- compiledGlobs.set(expanded, compiled);
2704
- }
2705
- return compiled.match(value);
2706
- };
3085
+ const matchExpanded = createExpandedGlobMatcher();
2707
3086
  function isTrackedAndRescued(resolved) {
2708
3087
  const snapshot = getTrackedFilesSnapshot(resolvedRoot);
2709
3088
  if (!snapshot)
@@ -2732,18 +3111,17 @@ function buildProjectIgnoreMatcher(resolvedRoot, patterns) {
2732
3111
  } else {
2733
3112
  let ignored = false;
2734
3113
  let layer;
2735
- const patternDirs = ancestorDirsBetween(resolvedRoot, path8.dirname(resolved));
3114
+ const patternDirs = ancestorDirsBetween(resolvedRoot, path9.dirname(resolved));
2736
3115
  for (const dir of patternDirs) {
2737
3116
  const dirPatterns = patternsForDir(dir);
2738
3117
  if (dirPatterns.length === 0)
2739
3118
  continue;
2740
- const relative3 = path8.relative(dir, resolved);
3119
+ const relative3 = path9.relative(dir, resolved);
2741
3120
  const normalized = normalizeIgnorePath(relative3);
2742
- for (const pattern of dirPatterns) {
2743
- if (!matchesGitignorePattern(pattern, normalized, isDirectory2, matchExpanded))
2744
- continue;
2745
- ignored = !pattern.negated;
2746
- layer = pattern.layer;
3121
+ const winner = lastMatchingPattern(dirPatterns, normalized, isDirectory2, matchExpanded);
3122
+ if (winner) {
3123
+ ignored = !winner.negated;
3124
+ layer = winner.layer;
2747
3125
  }
2748
3126
  }
2749
3127
  verdict = { ignored, layer };
@@ -2772,7 +3150,7 @@ var projectIgnoreMatcherCache = /* @__PURE__ */ new Map();
2772
3150
  var PROJECT_IGNORE_FRESHNESS_CADENCE_MS = FRESHNESS_CADENCE_MS;
2773
3151
  function fileFreshnessSignature(filePath) {
2774
3152
  try {
2775
- const stat = fs5.statSync(filePath);
3153
+ const stat = fs6.statSync(filePath);
2776
3154
  return { mtimeMs: stat.mtimeMs, size: stat.size };
2777
3155
  } catch {
2778
3156
  return { mtimeMs: -1, size: -1 };
@@ -2782,7 +3160,7 @@ function globalConfigSignature() {
2782
3160
  return fileFreshnessSignature(getPiLensGlobalConfigPath());
2783
3161
  }
2784
3162
  function gitignoreSignature(rootDir) {
2785
- return fileFreshnessSignature(path8.join(rootDir, ".gitignore"));
3163
+ return fileFreshnessSignature(path9.join(rootDir, ".gitignore"));
2786
3164
  }
2787
3165
  function hasIgnoreSourceDrift(sources) {
2788
3166
  return sources.some((source) => {
@@ -2843,17 +3221,17 @@ function getProjectIgnoreMatcher(rootDir) {
2843
3221
  return matcher;
2844
3222
  }
2845
3223
  function invalidateProjectIgnoreMatcherForPath(filePath) {
2846
- const resolvedPath = path8.resolve(filePath);
2847
- if (path8.basename(resolvedPath).toLowerCase() !== ".gitignore")
3224
+ const resolvedPath = path9.resolve(filePath);
3225
+ if (path9.basename(resolvedPath).toLowerCase() !== ".gitignore")
2848
3226
  return;
2849
3227
  for (const [cachedRoot, cached] of projectIgnoreMatcherCache) {
2850
3228
  if (!isUnderDir(resolvedPath, cachedRoot))
2851
3229
  continue;
2852
- if (normalizeFilePath(resolvedPath) === normalizeFilePath(path8.join(cachedRoot, ".gitignore"))) {
3230
+ if (normalizeFilePath(resolvedPath) === normalizeFilePath(path9.join(cachedRoot, ".gitignore"))) {
2853
3231
  projectIgnoreMatcherCache.delete(cachedRoot);
2854
3232
  continue;
2855
3233
  }
2856
- cached.matcher.invalidateSubtree(path8.dirname(filePath));
3234
+ cached.matcher.invalidateSubtree(path9.dirname(filePath));
2857
3235
  }
2858
3236
  }
2859
3237
  function isPathIgnoredByProject(filePath, rootDir, isDirectory2 = false) {
@@ -2868,7 +3246,7 @@ function isRecordableProjectPath(filePath, projectRoot) {
2868
3246
  }
2869
3247
  var projectIgnoreGlobsCache = /* @__PURE__ */ new Map();
2870
3248
  function getProjectIgnoreGlobs(rootDir) {
2871
- const resolvedRoot = path8.resolve(rootDir);
3249
+ const resolvedRoot = path9.resolve(rootDir);
2872
3250
  const signature = gitignoreSignature(resolvedRoot);
2873
3251
  const cached = projectIgnoreGlobsCache.get(resolvedRoot);
2874
3252
  if (cached && cached.mtimeMs === signature.mtimeMs && cached.size === signature.size) {
@@ -2923,7 +3301,7 @@ function getKnipIgnorePatterns() {
2923
3301
  function isTestFile(filePath) {
2924
3302
  if (detectFileRole(filePath) === "test")
2925
3303
  return true;
2926
- const normalized = filePath.replace(/\\/g, "/");
3304
+ const normalized = toPosix(filePath);
2927
3305
  return normalized.includes("test-utils") || normalized.startsWith("test-") || normalized.includes(".fixture.") || normalized.includes(".mock.");
2928
3306
  }
2929
3307
 
@@ -3004,549 +3382,185 @@ function createGenerationSource(name, store) {
3004
3382
  };
3005
3383
  }
3006
3384
  var DEFAULT_MAX_KEYS = 512;
3007
- function createGenerationMap(name, options = {}) {
3008
- declare(name);
3009
- const normalize = options.normalizeKey ?? ((key) => key);
3010
- const maxKeys = Math.max(1, options.maxKeys ?? DEFAULT_MAX_KEYS);
3011
- const stamps = new BoundedFifoMap(maxKeys);
3012
- let nextTicket = 0;
3013
- let invalidations = 0;
3014
- const read = (key) => stamps.get(key) ?? 0;
3015
- function issue(key) {
3016
- nextTicket += 1;
3017
- stamps.delete(key);
3018
- const evicted = stamps.set(key, nextTicket);
3019
- invalidations += evicted.length;
3020
- return nextTicket;
3021
- }
3022
- return {
3023
- name,
3024
- current(key) {
3025
- return read(normalize(key));
3026
- },
3027
- bump(key) {
3028
- invalidations += 1;
3029
- return issue(normalize(key));
3030
- },
3031
- capture(key) {
3032
- const normalized = normalize(key);
3033
- const stamp = read(normalized) || issue(normalized);
3034
- const capturedInvalidations = invalidations;
3035
- return makeHandle(`${name}[${normalized}]`, stamp, () => {
3036
- if (invalidations === capturedInvalidations)
3037
- return stamp;
3038
- return read(normalize(key));
3039
- }, name);
3040
- },
3041
- forget(key) {
3042
- invalidations += 1;
3043
- stamps.delete(normalize(key));
3044
- },
3045
- clear() {
3046
- invalidations += 1;
3047
- stamps.clear();
3048
- },
3049
- size() {
3050
- return stamps.size;
3051
- }
3052
- };
3053
- }
3054
-
3055
- // dist/clients/instance-registry-lock.js
3056
- import * as fs6 from "node:fs";
3057
- import { randomInt as randomInt2 } from "node:crypto";
3058
- import * as path9 from "node:path";
3059
- var OWN_HOLDS_FAMILY = "instance-registry.lock-own-holds";
3060
- var OWN_HOLDS_VERSION = 1;
3061
- function ownAsyncHolds() {
3062
- return getProcessSingleton(OWN_HOLDS_FAMILY, OWN_HOLDS_VERSION, () => ({
3063
- count: 0
3064
- }));
3065
- }
3066
- var LOCK_STALE_MS = 5e3;
3067
- var LOCK_WAIT_MS = 500;
3068
- var LOCK_MIN_BACKOFF_MS = 5;
3069
- var LOCK_MAX_BACKOFF_MS = 25;
3070
- function generationDir2(target) {
3071
- return `${target}.locks`;
3072
- }
3073
- function legacyLockPath(target) {
3074
- return `${target}.lock`;
3075
- }
3076
- function createLegacyLock(lock) {
3077
- try {
3078
- fs6.writeFileSync(lock, `${process.pid} ${Date.now()}
3079
- `, { flag: "wx" });
3080
- return true;
3081
- } catch (error) {
3082
- if (isLockContention(error))
3083
- return false;
3084
- throw error;
3085
- }
3086
- }
3087
- function takeLegacyLock(lock) {
3088
- if (createLegacyLock(lock))
3089
- return true;
3090
- if (!pidFileIsStale(lock, LOCK_STALE_MS))
3091
- return false;
3092
- try {
3093
- fs6.unlinkSync(lock);
3094
- } catch {
3095
- }
3096
- return createLegacyLock(lock);
3097
- }
3098
- function releaseLegacyLock(lock) {
3099
- if (pidFileOwner(lock) !== process.pid)
3100
- return;
3101
- try {
3102
- fs6.unlinkSync(lock);
3103
- } catch {
3104
- }
3105
- }
3106
- function tryAcquire(target) {
3107
- let hold;
3108
- try {
3109
- hold = tryAcquireGeneration(generationDir2(target), LOCK_STALE_MS);
3110
- if (!hold)
3111
- return "busy";
3112
- if (hold.tookOverStale)
3113
- recordStaleTakeover(target, hold);
3114
- if (takeLegacyLock(legacyLockPath(target)))
3115
- return hold;
3116
- recordLegacyHeld(target);
3117
- releaseGeneration(hold);
3118
- return "busy";
3119
- } catch (cause) {
3120
- recordLockFailure(target, cause);
3121
- if (hold)
3122
- releaseGeneration(hold);
3123
- return "failed";
3124
- }
3125
- }
3126
- function release(target, hold) {
3127
- releaseLegacyLock(legacyLockPath(target));
3128
- releaseGeneration(hold);
3129
- }
3130
- function recordLockFailure(target, cause) {
3131
- const code = cause?.code ?? "unknown";
3132
- incrementDegradationCount({
3133
- kind: "instance-registry-lock-failed",
3134
- subject: path9.resolve(target),
3135
- reason: `lock acquisition failed for ${path9.basename(target)} (${code}); the registry write was skipped`
3136
- });
3137
- }
3138
- function recordStaleTakeover(target, hold) {
3139
- incrementDegradationCount({
3140
- kind: "instance-registry-lock-stale-takeover",
3141
- subject: path9.resolve(target),
3142
- reason: `took over lock generation ${hold.generation - 1} from a dead or aged-out holder`
3143
- });
3144
- }
3145
- function recordLegacyHeld(target) {
3146
- const lock = legacyLockPath(target);
3147
- incrementDegradationCount({
3148
- kind: "instance-registry-lock-legacy-held",
3149
- subject: path9.resolve(lock),
3150
- reason: `backed off: ${path9.basename(lock)} is held by pid ${pidFileOwner(lock) ?? "unknown"}, a writer from before #3476`
3151
- });
3152
- }
3153
- function recordLockTimeout(target) {
3154
- incrementDegradationCount({
3155
- kind: "instance-registry-lock-timeout",
3156
- subject: path9.resolve(target),
3157
- reason: `lock acquisition exhausted for ${path9.basename(target)}`
3158
- });
3159
- }
3160
- function backoffMs() {
3161
- return randomInt2(LOCK_MIN_BACKOFF_MS, LOCK_MAX_BACKOFF_MS + 1);
3162
- }
3163
- var LOCK_WAIT_THROUGH_LEASE_MS = LOCK_STALE_MS + LOCK_WAIT_MS;
3164
- async function withInstanceRegistryLock(target, op, waitMs = LOCK_WAIT_MS) {
3165
- const deadline = Date.now() + waitMs;
3166
- while (Date.now() <= deadline) {
3167
- const hold = tryAcquire(target);
3168
- if (hold === "failed")
3169
- return void 0;
3170
- if (hold === "busy") {
3171
- if (Date.now() <= deadline)
3172
- await new Promise((resolve7) => setTimeout(resolve7, backoffMs()));
3173
- continue;
3174
- }
3175
- const holds = ownAsyncHolds();
3176
- holds.count += 1;
3177
- try {
3178
- return await op();
3179
- } finally {
3180
- holds.count -= 1;
3181
- release(target, hold);
3182
- }
3183
- }
3184
- recordLockTimeout(target);
3185
- return void 0;
3186
- }
3187
-
3188
- // dist/scripts/lib/process-scan.mjs
3189
- import fs7 from "node:fs";
3190
- import path10 from "node:path";
3191
- function runningOnWindows() {
3192
- return process.platform === "win32";
3193
- }
3194
- var FIELD_COLUMNS = Object.freeze({
3195
- pid: { wmi: "ProcessId", ps: "pid", token: "int" },
3196
- ppid: { wmi: "ParentProcessId", ps: "ppid", token: "int" },
3197
- ageMs: { wmi: "CreationDate", ps: "etime", token: "age" },
3198
- rssBytes: { wmi: "WorkingSetSize", ps: null, token: "int" },
3199
- cpuKernel100ns: { wmi: "KernelModeTime", ps: null, token: "int" },
3200
- cpuUser100ns: { wmi: "UserModeTime", ps: null, token: "int" },
3201
- startedAt: { wmi: "CreationDate", ps: "lstart", token: "lstart" },
3202
- command: { wmi: "CommandLine", ps: "args", token: "tail" }
3203
- });
3204
- var FIELD_ORDER = Object.freeze(Object.keys(FIELD_COLUMNS));
3205
- var ALL_PROCESS_FIELDS = Object.freeze(["pid", "ppid", "command"]);
3206
- var FILTERABLE_COLUMNS = /* @__PURE__ */ new Set(["ProcessId", "Name", "CommandLine"]);
3207
- function windowsExe(name) {
3208
- return path10.join(process.env.SystemRoot ?? path10.join("C:", "Windows"), "System32", name);
3209
- }
3210
- function posixPsPath() {
3211
- try {
3212
- if (fs7.existsSync("/bin/ps"))
3213
- return "/bin/ps";
3214
- if (fs7.existsSync("/usr/bin/ps"))
3215
- return "/usr/bin/ps";
3216
- } catch {
3217
- }
3218
- return "/bin/ps";
3219
- }
3220
- function normalizeProcessFields(fields) {
3221
- const requested = new Set((fields ?? ALL_PROCESS_FIELDS).filter((field) => field in FIELD_COLUMNS));
3222
- requested.add("pid");
3223
- return FIELD_ORDER.filter((field) => requested.has(field));
3224
- }
3225
- function escapeWqlLikeValue(value) {
3226
- return String(value).replaceAll("'", "''").replaceAll(/[%_]/g, (ch) => `[${ch}]`);
3227
- }
3228
- function escapeWqlStringValue(value) {
3229
- return String(value).replaceAll("'", "''");
3230
- }
3231
- function assertPid(value) {
3232
- const pid = Number(value);
3233
- if (!Number.isInteger(pid) || pid <= 0) {
3234
- throw new Error(`process filter: invalid pid ${String(value)}`);
3235
- }
3236
- return pid;
3237
- }
3238
- function wqlFilterExpression(filter) {
3239
- const { column, op, values } = filter;
3240
- if (!FILTERABLE_COLUMNS.has(column)) {
3241
- throw new Error(`process filter: unsupported column ${String(column)}`);
3242
- }
3243
- const list = [...values];
3244
- if (list.length === 0) {
3245
- throw new Error(`process filter: ${column} filter has no values`);
3246
- }
3247
- if (column === "ProcessId") {
3248
- return list.map((value) => `ProcessId=${assertPid(value)}`).join(" OR ");
3249
- }
3250
- if (op === "like") {
3251
- return list.map((value) => `${column} LIKE '%${escapeWqlLikeValue(value)}%'`).join(" OR ");
3252
- }
3253
- return list.map((value) => `${column} = '${escapeWqlStringValue(value)}'`).join(" OR ");
3254
- }
3255
- function buildProcessQuery(fields = ALL_PROCESS_FIELDS, options = {}) {
3256
- const layout = normalizeProcessFields(fields);
3257
- const filter = options.filter;
3258
- if (runningOnWindows()) {
3259
- const columns2 = [
3260
- ...new Set(layout.map((field) => FIELD_COLUMNS[field].wmi))
3261
- ];
3262
- const where = filter ? ` WHERE ${wqlFilterExpression(filter)}` : "";
3263
- const excludeSelf = options.excludeSelfPid ? " | Where-Object { $_.ProcessId -ne $PID }" : "";
3264
- 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 { '' }; " : "");
3265
- const row = layout.map((field) => {
3266
- if (field === "ageMs")
3267
- return "$age";
3268
- if (field === "startedAt")
3269
- return "$st";
3270
- return `$($_.${FIELD_COLUMNS[field].wmi})`;
3271
- }).join("`t");
3272
- return {
3273
- command: windowsExe("WindowsPowerShell\\v1.0\\powershell.exe"),
3274
- args: [
3275
- "-NoProfile",
3276
- "-NonInteractive",
3277
- "-Command",
3278
- `Get-CimInstance -Query "SELECT ${columns2.join(",")} FROM Win32_Process${where}"${excludeSelf} | ForEach-Object { ${prelude}"${row}" }`
3279
- ],
3280
- tabSeparated: true,
3281
- fields: layout,
3282
- serverSideFiltered: Boolean(filter)
3283
- };
3284
- }
3285
- const unsupported = layout.filter((field) => !FIELD_COLUMNS[field].ps);
3286
- if (unsupported.length > 0) {
3287
- throw new Error(`process query: ${unsupported.join(", ")} has no POSIX ps column`);
3288
- }
3289
- if (layout.includes("startedAt") && process.platform === "linux") {
3290
- throw new Error("process query: startedAt on Linux is read from /proc, not ps");
3291
- }
3292
- const columns = layout.map((field) => `${FIELD_COLUMNS[field].ps}=`).join(",");
3293
- const pidFilter = filter && filter.column === "ProcessId" && filter.op === "eq" ? [...filter.values].map((value) => assertPid(value)) : null;
3294
- return {
3295
- command: posixPsPath(),
3296
- args: pidFilter ? ["-p", pidFilter.join(","), "-o", columns] : ["-eo", columns],
3297
- tabSeparated: false,
3298
- fields: layout,
3299
- serverSideFiltered: Boolean(pidFilter),
3300
- // BSD `ps` formats `lstart` with strftime("%c") in the local zone, so
3301
- // two readers with different locales or zones would print one process
3302
- // two ways. Pinned, every reader prints the same text.
3303
- ...layout.includes("startedAt") ? { env: posixStartEnv() } : {}
3304
- };
3305
- }
3306
- function posixStartEnv() {
3307
- return { ...process.env, LC_ALL: "C", TZ: "UTC0" };
3308
- }
3309
- function readLinuxProcessStart(pid) {
3310
- try {
3311
- const ticks = parseLinuxStatStart(fs7.readFileSync(`/proc/${assertPid(pid)}/stat`, "utf8"));
3312
- const boot = fs7.readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
3313
- const offset = readBoottimeOffsetTicks();
3314
- return ticks === void 0 || offset === void 0 || !/^[0-9a-f-]{36}$/.test(boot) ? void 0 : `${Number(ticks) - offset}@${boot}`;
3315
- } catch {
3316
- return void 0;
3317
- }
3318
- }
3319
- var USER_HZ = 100;
3320
- var NSEC_PER_TICK = 1e9 / USER_HZ;
3321
- function readBoottimeOffsetTicks() {
3322
- let text;
3323
- try {
3324
- text = fs7.readFileSync("/proc/self/timens_offsets", "utf8");
3325
- } catch (error) {
3326
- return (
3327
- /** @type {NodeJS.ErrnoException} */
3328
- error.code === "ENOENT" ? 0 : void 0
3329
- );
3330
- }
3331
- const match = /^boottime\s+(-?\d+)\s+(\d+)\s*$/m.exec(String(text));
3332
- if (!match)
3333
- return void 0;
3334
- const nsec = Number(match[2]);
3335
- if (nsec % NSEC_PER_TICK !== 0)
3336
- return void 0;
3337
- return Number(match[1]) * USER_HZ + nsec / NSEC_PER_TICK;
3338
- }
3339
- function parseLinuxStatStart(stat) {
3340
- const fields = String(stat).slice(stat.lastIndexOf(")") + 2).split(" ");
3341
- const start = fields[19];
3342
- return /^\d+$/.test(start ?? "") ? start : void 0;
3343
- }
3344
- function readLinuxPidNamespace(pid) {
3345
- try {
3346
- return fs7.readlinkSync(`/proc/${assertPid(pid)}/ns/pid`);
3347
- } catch {
3348
- return void 0;
3349
- }
3350
- }
3351
- function parseNonNegativeInt(raw) {
3352
- const token = String(raw ?? "").trim();
3353
- if (!/^\d+$/.test(token))
3354
- return void 0;
3355
- const value = Number(token);
3356
- return Number.isFinite(value) ? value : void 0;
3357
- }
3358
- function ageMsFromPosixEtime(raw) {
3359
- const token = String(raw ?? "").trim();
3360
- if (!/^(?:\d+-)?(?:\d+:)?\d+:\d+$/.test(token))
3361
- return void 0;
3362
- let days = 0;
3363
- let rest = token;
3364
- const dash = rest.indexOf("-");
3365
- if (dash >= 0) {
3366
- days = Number(rest.slice(0, dash));
3367
- rest = rest.slice(dash + 1);
3368
- }
3369
- const parts = rest.split(":").map(Number);
3370
- if (parts.some((part) => !Number.isFinite(part)))
3371
- return void 0;
3372
- const [hours, minutes, seconds] = parts.length === 3 ? parts : [0, parts[0], parts[1]];
3373
- return ((days * 24 + hours) * 60 * 60 + minutes * 60 + seconds) * 1e3;
3374
- }
3375
- function posixTokenPattern(field) {
3376
- const token = FIELD_COLUMNS[field].token;
3377
- if (token === "age")
3378
- return "(\\S+)";
3379
- if (token === "lstart")
3380
- return "(\\S+\\s+\\S+\\s+\\d+\\s+\\d+:\\d+:\\d+\\s+\\d+)";
3381
- return "(\\d+)";
3382
- }
3383
- var LSTART_MONTHS = [
3384
- "Jan",
3385
- "Feb",
3386
- "Mar",
3387
- "Apr",
3388
- "May",
3389
- "Jun",
3390
- "Jul",
3391
- "Aug",
3392
- "Sep",
3393
- "Oct",
3394
- "Nov",
3395
- "Dec"
3396
- ];
3397
- function isoFromLstart(raw) {
3398
- 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());
3399
- if (!match)
3400
- return void 0;
3401
- const month = LSTART_MONTHS.indexOf(match[1]);
3402
- if (month === -1)
3403
- return void 0;
3404
- const [day, hours, minutes, seconds, year] = [2, 3, 4, 5, 6].map((i) => Number(match[i]));
3405
- return new Date(Date.UTC(year, month, day, hours, minutes, seconds)).toISOString();
3406
- }
3407
- function parseProcessTable(out, tabSeparated, fields = ALL_PROCESS_FIELDS) {
3408
- const layout = normalizeProcessFields(fields);
3409
- const commandIndex = layout.indexOf("command");
3410
- const positional = tabSeparated ? null : new RegExp(`^\\s*${layout.filter((field) => field !== "command").map((field) => posixTokenPattern(field)).join("\\s+")}${commandIndex === -1 ? "\\s*$" : "\\s+(.*)$"}`);
3411
- const rows = [];
3412
- for (const line of String(out ?? "").split(/\r?\n/)) {
3413
- if (!line.trim())
3414
- continue;
3415
- let parts;
3416
- if (tabSeparated) {
3417
- const split = line.split(" ");
3418
- if (split.length < layout.length - (commandIndex === -1 ? 0 : 1))
3419
- continue;
3420
- parts = commandIndex === -1 ? split : [
3421
- ...split.slice(0, commandIndex),
3422
- split.slice(commandIndex).join(" ")
3423
- ];
3424
- } else {
3425
- const match = positional?.exec(line);
3426
- if (!match)
3427
- continue;
3428
- parts = match.slice(1);
3429
- }
3430
- const value = (field) => {
3431
- const at = layout.indexOf(field);
3432
- return at === -1 ? void 0 : parts[at];
3433
- };
3434
- const pid = Number(value("pid"));
3435
- if (!Number.isInteger(pid) || pid <= 0)
3436
- continue;
3437
- const ppid = Number(value("ppid"));
3438
- const row = {
3439
- pid,
3440
- ppid: Number.isInteger(ppid) && ppid > 0 ? ppid : 0,
3441
- command: value("command") ?? ""
3442
- };
3443
- for (const field of layout) {
3444
- if (field === "pid" || field === "ppid" || field === "command")
3445
- continue;
3446
- const raw = value(field);
3447
- if (field === "ageMs") {
3448
- row.ageMs = tabSeparated ? parseNonNegativeInt(raw) : ageMsFromPosixEtime(raw ?? "");
3449
- } else if (field === "startedAt") {
3450
- row.startedAt = tabSeparated ? String(raw ?? "").trim() : isoFromLstart(raw ?? "");
3451
- } else {
3452
- row[field] = parseNonNegativeInt(raw);
3453
- }
3454
- }
3455
- rows.push(row);
3385
+ function createGenerationMap(name, options = {}) {
3386
+ declare(name);
3387
+ const normalize = options.normalizeKey ?? ((key) => key);
3388
+ const maxKeys = Math.max(1, options.maxKeys ?? DEFAULT_MAX_KEYS);
3389
+ const stamps = new BoundedFifoMap(maxKeys);
3390
+ let nextTicket = 0;
3391
+ let invalidations = 0;
3392
+ const read = (key) => stamps.get(key) ?? 0;
3393
+ function issue(key) {
3394
+ nextTicket += 1;
3395
+ stamps.delete(key);
3396
+ const evicted = stamps.set(key, nextTicket);
3397
+ invalidations += evicted.length;
3398
+ return nextTicket;
3456
3399
  }
3457
- return rows;
3400
+ return {
3401
+ name,
3402
+ current(key) {
3403
+ return read(normalize(key));
3404
+ },
3405
+ bump(key) {
3406
+ invalidations += 1;
3407
+ return issue(normalize(key));
3408
+ },
3409
+ capture(key) {
3410
+ const normalized = normalize(key);
3411
+ const stamp = read(normalized) || issue(normalized);
3412
+ const capturedInvalidations = invalidations;
3413
+ return makeHandle(`${name}[${normalized}]`, stamp, () => {
3414
+ if (invalidations === capturedInvalidations)
3415
+ return stamp;
3416
+ return read(normalize(key));
3417
+ }, name);
3418
+ },
3419
+ forget(key) {
3420
+ invalidations += 1;
3421
+ stamps.delete(normalize(key));
3422
+ },
3423
+ clear() {
3424
+ invalidations += 1;
3425
+ stamps.clear();
3426
+ },
3427
+ size() {
3428
+ return stamps.size;
3429
+ }
3430
+ };
3458
3431
  }
3459
3432
 
3460
- // dist/clients/process-snapshot.js
3461
- async function queryProcessTable(request, options) {
3462
- let query;
3433
+ // dist/clients/instance-registry-lock.js
3434
+ import * as fs7 from "node:fs";
3435
+ import { randomInt as randomInt2 } from "node:crypto";
3436
+ import * as path10 from "node:path";
3437
+ var OWN_HOLDS_FAMILY = "instance-registry.lock-own-holds";
3438
+ var OWN_HOLDS_VERSION = 1;
3439
+ function ownAsyncHolds() {
3440
+ return getProcessSingleton(OWN_HOLDS_FAMILY, OWN_HOLDS_VERSION, () => ({
3441
+ count: 0
3442
+ }));
3443
+ }
3444
+ var LOCK_STALE_MS = 5e3;
3445
+ var LOCK_WAIT_MS = 500;
3446
+ var LOCK_MIN_BACKOFF_MS = 5;
3447
+ var LOCK_MAX_BACKOFF_MS = 25;
3448
+ function generationDir2(target) {
3449
+ return `${target}.locks`;
3450
+ }
3451
+ function legacyLockPath(target) {
3452
+ return `${target}.lock`;
3453
+ }
3454
+ function createLegacyLock(lock) {
3463
3455
  try {
3464
- query = buildProcessQuery(request.fields, {
3465
- filter: request.filter,
3466
- excludeSelfPid: request.excludeSelfPid
3467
- });
3456
+ fs7.writeFileSync(lock, `${process.pid} ${Date.now()}
3457
+ `, { flag: "wx" });
3458
+ return true;
3459
+ } catch (error) {
3460
+ if (isLockContention(error))
3461
+ return false;
3462
+ throw error;
3463
+ }
3464
+ }
3465
+ function takeLegacyLock(lock) {
3466
+ if (createLegacyLock(lock))
3467
+ return true;
3468
+ if (!pidFileIsStale(lock, LOCK_STALE_MS))
3469
+ return false;
3470
+ try {
3471
+ fs7.unlinkSync(lock);
3468
3472
  } catch {
3469
- return { rows: [], status: "spawn-error", serverSideFiltered: false };
3470
3473
  }
3471
- const result = await spawnCollectStdoutResult(query.command, query.args, {
3472
- shell: false,
3473
- windowsHide: true,
3474
- stdio: ["ignore", "pipe", "ignore"],
3475
- env: query.env
3476
- }, { timeoutMs: options.timeoutMs, onTimeout: options.onTimeout });
3477
- return {
3478
- // Whatever the collector kept is parsed rather than discarded here: it
3479
- // drops stdout on a non-zero exit (that output is not evidence of what
3480
- // is NOT running) but KEEPS the partial table from a timed-out child,
3481
- // and the caller decides what a partial table is worth by reading
3482
- // `status`. Re-deciding that here would be a second policy.
3483
- rows: parseProcessTable(result.stdout, query.tabSeparated, query.fields),
3484
- status: result.status,
3485
- exitCode: result.exitCode,
3486
- timeoutKill: result.timeoutKill,
3487
- serverSideFiltered: query.serverSideFiltered
3488
- };
3474
+ return createLegacyLock(lock);
3489
3475
  }
3490
- function validPids(pids) {
3491
- return [...new Set(pids.filter((p) => Number.isInteger(p) && p > 0))];
3476
+ function releaseLegacyLock(lock) {
3477
+ if (pidFileOwner(lock) !== process.pid)
3478
+ return;
3479
+ try {
3480
+ fs7.unlinkSync(lock);
3481
+ } catch {
3482
+ }
3492
3483
  }
3493
- async function queryProcessIdentities(pids, options) {
3494
- const valid = validPids(pids);
3495
- const identities = /* @__PURE__ */ new Map();
3496
- if (valid.length === 0)
3497
- return { identities, status: "ok" };
3498
- const linux = process.platform === "linux";
3499
- const result = await queryProcessTable({
3500
- fields: linux ? ["pid", "command"] : ["pid", "startedAt", "command"],
3501
- filter: { column: "ProcessId", op: "eq", values: valid }
3502
- }, options);
3503
- for (const row of result.rows) {
3504
- const start = linux ? readLinuxProcessStart(row.pid) : row.startedAt;
3505
- identities.set(row.pid, {
3506
- command: row.command,
3507
- start: start ? start : void 0
3508
- });
3484
+ function tryAcquire(target) {
3485
+ let hold;
3486
+ try {
3487
+ hold = tryAcquireGeneration(generationDir2(target), LOCK_STALE_MS);
3488
+ if (!hold)
3489
+ return "busy";
3490
+ if (hold.tookOverStale)
3491
+ recordStaleTakeover(target, hold);
3492
+ if (takeLegacyLock(legacyLockPath(target)))
3493
+ return hold;
3494
+ recordLegacyHeld(target);
3495
+ releaseGeneration(hold);
3496
+ return "busy";
3497
+ } catch (cause) {
3498
+ recordLockFailure(target, cause);
3499
+ if (hold)
3500
+ releaseGeneration(hold);
3501
+ return "failed";
3509
3502
  }
3510
- return { identities, status: result.status };
3511
3503
  }
3512
- var OWNER_TAG_ENV = "PI_LENS_OWNER";
3513
- function formatOwnerTag(tag) {
3514
- return `${tag.pid}:${tag.start}`;
3504
+ function release(target, hold) {
3505
+ releaseLegacyLock(legacyLockPath(target));
3506
+ releaseGeneration(hold);
3515
3507
  }
3516
- async function ownerTagForChildren(options) {
3517
- if (process.platform === "win32")
3518
- return void 0;
3519
- const start = await ownProcessStart(options);
3520
- return start === void 0 ? void 0 : formatOwnerTag({ pid: process.pid, start });
3508
+ function recordLockFailure(target, cause) {
3509
+ const code = cause?.code ?? "unknown";
3510
+ incrementDegradationCount({
3511
+ kind: "instance-registry-lock-failed",
3512
+ subject: path10.resolve(target),
3513
+ reason: `lock acquisition failed for ${path10.basename(target)} (${code}); the registry write was skipped`
3514
+ });
3521
3515
  }
3522
- function isInPidNamespace(entry, namespace) {
3523
- return entry.pidNamespace === void 0 || entry.pidNamespace === namespace;
3516
+ function recordStaleTakeover(target, hold) {
3517
+ incrementDegradationCount({
3518
+ kind: "instance-registry-lock-stale-takeover",
3519
+ subject: path10.resolve(target),
3520
+ reason: `took over lock generation ${hold.generation - 1} from a dead or aged-out holder`
3521
+ });
3524
3522
  }
3525
- function ownPidNamespace() {
3526
- return process.platform === "linux" ? readLinuxPidNamespace(process.pid) : void 0;
3523
+ function recordLegacyHeld(target) {
3524
+ const lock = legacyLockPath(target);
3525
+ incrementDegradationCount({
3526
+ kind: "instance-registry-lock-legacy-held",
3527
+ subject: path10.resolve(lock),
3528
+ reason: `backed off: ${path10.basename(lock)} is held by pid ${pidFileOwner(lock) ?? "unknown"}, a writer from before #3476`
3529
+ });
3527
3530
  }
3528
- var ownStart = null;
3529
- function ownProcessStart(options) {
3530
- if (process.platform === "linux")
3531
- return Promise.resolve(readLinuxProcessStart(process.pid));
3532
- if (ownStart)
3533
- return ownStart.promise;
3534
- const cell = {
3535
- promise: readProcessStart(process.pid, options).then((start) => {
3536
- if (start === void 0)
3537
- ownStart = null;
3538
- else
3539
- cell.value = start;
3540
- return start;
3541
- })
3542
- };
3543
- ownStart = cell;
3544
- return cell.promise;
3531
+ function recordLockTimeout(target) {
3532
+ incrementDegradationCount({
3533
+ kind: "instance-registry-lock-timeout",
3534
+ subject: path10.resolve(target),
3535
+ reason: `lock acquisition exhausted for ${path10.basename(target)}`
3536
+ });
3545
3537
  }
3546
- async function readProcessStart(pid, options) {
3547
- if (process.platform === "linux")
3548
- return readLinuxProcessStart(pid);
3549
- return (await queryProcessIdentities([pid], options)).identities.get(pid)?.start;
3538
+ function backoffMs() {
3539
+ return randomInt2(LOCK_MIN_BACKOFF_MS, LOCK_MAX_BACKOFF_MS + 1);
3540
+ }
3541
+ var LOCK_WAIT_THROUGH_LEASE_MS = LOCK_STALE_MS + LOCK_WAIT_MS;
3542
+ async function withInstanceRegistryLock(target, op, waitMs = LOCK_WAIT_MS) {
3543
+ const deadline = Date.now() + waitMs;
3544
+ while (Date.now() <= deadline) {
3545
+ const hold = tryAcquire(target);
3546
+ if (hold === "failed")
3547
+ return void 0;
3548
+ if (hold === "busy") {
3549
+ if (Date.now() <= deadline)
3550
+ await new Promise((resolve7) => setTimeout(resolve7, backoffMs()));
3551
+ continue;
3552
+ }
3553
+ const holds = ownAsyncHolds();
3554
+ holds.count += 1;
3555
+ try {
3556
+ return await op();
3557
+ } finally {
3558
+ holds.count -= 1;
3559
+ release(target, hold);
3560
+ }
3561
+ }
3562
+ recordLockTimeout(target);
3563
+ return void 0;
3550
3564
  }
3551
3565
 
3552
3566
  // dist/clients/instance-registry-tail.js
@@ -3964,17 +3978,17 @@ function rootsOverlap(a, b) {
3964
3978
  const [shorter, longer] = a.length < b.length ? [a, b] : [b, a];
3965
3979
  return longer.startsWith(shorter.endsWith("/") ? shorter : `${shorter}/`);
3966
3980
  }
3967
- function selectLivePeerInstances(entries, root, now = Date.now(), isPidAlive2 = realIsPidAlive, match = "exact") {
3981
+ function selectLivePeerInstances(entries, root, now = Date.now(), isPidAlive = realIsPidAlive, match = "exact") {
3968
3982
  const normalizedRoot = normalizeFilePath(root);
3969
3983
  return entries.filter((entry) => entry.pid !== process.pid && // #2130: a host serves a SET of roots. Matching only
3970
3984
  // `entry.projectRoot` made every secondary root invisible, so a peer
3971
3985
  // working in the same checkout under its second root read as "no
3972
3986
  // peer" — and the shared-checkout guard then allowed the destructive
3973
3987
  // command it exists to block.
3974
- getInstanceRoots(entry).some((entryRoot) => match === "exact" ? entryRoot === normalizedRoot : rootsOverlap(entryRoot, normalizedRoot)) && isPidAlive2(entry.pid) && Number.isFinite(Date.parse(entry.heartbeatAt)) && now - Date.parse(entry.heartbeatAt) <= STALE_HEARTBEAT_MS).sort((a, b) => Date.parse(a.startedAt) - Date.parse(b.startedAt));
3988
+ getInstanceRoots(entry).some((entryRoot) => match === "exact" ? entryRoot === normalizedRoot : rootsOverlap(entryRoot, normalizedRoot)) && isPidAlive(entry.pid) && Number.isFinite(Date.parse(entry.heartbeatAt)) && now - Date.parse(entry.heartbeatAt) <= STALE_HEARTBEAT_MS).sort((a, b) => Date.parse(a.startedAt) - Date.parse(b.startedAt));
3975
3989
  }
3976
- function computeResourceFootprint(instances, isPidAlive2) {
3977
- const liveInstances = isPidAlive2 ? instances.filter((instance) => isPidAlive2(instance.pid)) : instances;
3990
+ function computeResourceFootprint(instances, isPidAlive) {
3991
+ const liveInstances = isPidAlive ? instances.filter((instance) => isPidAlive(instance.pid)) : instances;
3978
3992
  const perInstance = liveInstances.map((instance) => {
3979
3993
  const lspChildRssBytes = instance.lspChildren.reduce((sum, child) => sum + (child.rssBytes ?? 0), 0);
3980
3994
  const lspChildCpuPercent = instance.lspChildren.reduce((sum, child) => sum + (child.cpuPercent ?? 0), 0);
@@ -4006,10 +4020,10 @@ function computeResourceFootprint(instances, isPidAlive2) {
4006
4020
  perInstance
4007
4021
  };
4008
4022
  }
4009
- async function getResourceFootprint(isPidAlive2 = realIsPidAlive) {
4023
+ async function getResourceFootprint(isPidAlive = realIsPidAlive) {
4010
4024
  const instances = await readInstanceRegistry();
4011
4025
  const namespace = ownPidNamespace();
4012
- const dead = instances.filter((instance) => !isPidAlive2(instance.pid) && instance.lspChildren.length === 0 && isInPidNamespace(instance, namespace)).map((instance) => ({
4026
+ const dead = instances.filter((instance) => !isPidAlive(instance.pid) && instance.lspChildren.length === 0 && isInPidNamespace(instance, namespace)).map((instance) => ({
4013
4027
  pid: instance.pid,
4014
4028
  processStart: instance.processStart,
4015
4029
  pidNamespace: instance.pidNamespace
@@ -4018,7 +4032,7 @@ async function getResourceFootprint(isPidAlive2 = realIsPidAlive) {
4018
4032
  queueRegistryMutation(() => prunePids(dead)).catch(() => {
4019
4033
  });
4020
4034
  }
4021
- return computeResourceFootprint(instances, isPidAlive2);
4035
+ return computeResourceFootprint(instances, isPidAlive);
4022
4036
  }
4023
4037
  async function pruneDeadInstances(dead) {
4024
4038
  const result = await withInstanceRegistryLock(registryPath(), async () => {
@@ -4040,19 +4054,6 @@ async function prunePids(dead) {
4040
4054
  // dist/clients/instance-reaper.js
4041
4055
  var STALE_HEARTBEAT_MS = 6 * 60 * 60 * 1e3;
4042
4056
  var isWindows = process.platform === "win32";
4043
- function realIsPidAlive(pid) {
4044
- if (!Number.isFinite(pid) || pid <= 0)
4045
- return false;
4046
- try {
4047
- process.kill(pid, 0);
4048
- return true;
4049
- } catch (err) {
4050
- const code = err?.code;
4051
- if (code === "ESRCH")
4052
- return false;
4053
- return true;
4054
- }
4055
- }
4056
4057
  var STAGE_PID_PATTERN = /\.stage-(\d+)-/;
4057
4058
  function isStaleStageFile(entry, artifactPrefix) {
4058
4059
  if (!entry.startsWith(artifactPrefix))
@@ -4066,8 +4067,8 @@ var ATOMIC_STAGE_SWEEP_MAX_ENTRIES = 512;
4066
4067
  async function sweepAtomicWriteStages(directories, options = {}) {
4067
4068
  const requestedMax = options.maxEntries ?? ATOMIC_STAGE_SWEEP_MAX_ENTRIES;
4068
4069
  const maxEntries = Number.isFinite(requestedMax) ? Math.max(1, Math.floor(requestedMax)) : ATOMIC_STAGE_SWEEP_MAX_ENTRIES;
4069
- const isPidAlive2 = options.isPidAlive ?? realIsPidAlive;
4070
- return sweepOwnStagingFiles(directories, { maxEntries, isPidAlive: isPidAlive2 });
4070
+ const isPidAlive = options.isPidAlive ?? realIsPidAlive;
4071
+ return sweepOwnStagingFiles(directories, { maxEntries, isPidAlive });
4071
4072
  }
4072
4073
  var KILL_VERIFY_ATTEMPTS = 5;
4073
4074
  var KILL_VERIFY_INTERVAL_MS = 100;
@@ -4110,13 +4111,13 @@ async function killPidTree(pid, options = {}) {
4110
4111
  return await verifyPidGone(pid, options);
4111
4112
  }
4112
4113
  async function verifyPidGone(pid, options = {}) {
4113
- const isPidAlive2 = options.isPidAlive ?? realIsPidAlive;
4114
+ const isPidAlive = options.isPidAlive ?? realIsPidAlive;
4114
4115
  const attempts = Math.max(1, options.verifyAttempts ?? KILL_VERIFY_ATTEMPTS);
4115
4116
  const intervalMs = Math.max(0, options.verifyIntervalMs ?? KILL_VERIFY_INTERVAL_MS);
4116
4117
  for (let attempt = 0; attempt < attempts; attempt++) {
4117
4118
  let alive;
4118
4119
  try {
4119
- alive = isPidAlive2(pid);
4120
+ alive = isPidAlive(pid);
4120
4121
  } catch {
4121
4122
  alive = true;
4122
4123
  }
@@ -4719,7 +4720,7 @@ function isOwnLiveChild(pid, site, handle) {
4719
4720
  function killPidTreeSync(pid) {
4720
4721
  if (process.platform === "win32") {
4721
4722
  try {
4722
- const taskkill = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\taskkill.exe`;
4723
+ const taskkill = windowsExe("taskkill.exe");
4723
4724
  spawnSync(taskkill, ["/F", "/T", "/PID", String(pid)], {
4724
4725
  shell: false,
4725
4726
  windowsHide: true,
@@ -4794,7 +4795,7 @@ function cmdEscapeArg(arg) {
4794
4795
  return `"${arg.replace(/"/g, '""')}"`;
4795
4796
  }
4796
4797
  function buildWindowsShellCommand(command, args) {
4797
- const chcp = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\chcp.com`;
4798
+ const chcp = windowsExe("chcp.com");
4798
4799
  return `${chcp} 65001 >nul 2>&1 & ${[command, ...args].map(cmdEscapeArg).join(" ")}`;
4799
4800
  }
4800
4801
  var WINDOWS_DIRECT_RESOLVABLE_EXTS = /* @__PURE__ */ new Set([
@@ -4999,16 +5000,26 @@ function resolveWindowsCommandForEnvironment(command, cwd, env) {
4999
5000
  function resolveWindowsCommand(command, cwd, env) {
5000
5001
  return resolveWindowsCommandForEnvironment(command, cwd, env);
5001
5002
  }
5002
- function getSpawnEnvironment(overrides, stripNpmConfig) {
5003
+ function isNpxCommand(command) {
5004
+ const base = command.split(/[\\/]/).pop() ?? command;
5005
+ return /^npx(?:\.(?:cmd|exe|bat))?$/i.test(base);
5006
+ }
5007
+ function getSpawnEnvironment(command, overrides, stripNpmConfig) {
5003
5008
  const ambient = { ...process.env, GIT_OPTIONAL_LOCKS: "0" };
5004
5009
  const merged = process.platform === "win32" ? mergeWindowsEnvironment(ambient, overrides) : { ...ambient, ...overrides };
5005
- if (!stripNpmConfig)
5010
+ const offline = isToolInstallDisabled() && isNpxCommand(command);
5011
+ if (!stripNpmConfig) {
5012
+ if (offline)
5013
+ merged.npm_config_offline = "true";
5006
5014
  return merged;
5015
+ }
5007
5016
  const stripped = {};
5008
5017
  for (const [key, value] of Object.entries(merged)) {
5009
5018
  if (!/^npm_config_/i.test(key))
5010
5019
  stripped[key] = value;
5011
5020
  }
5021
+ if (offline)
5022
+ stripped.npm_config_offline = "true";
5012
5023
  return stripped;
5013
5024
  }
5014
5025
  function isSpawnLookup(command) {
@@ -5137,7 +5148,7 @@ function ensureUtf8ConsoleCodePageOnce() {
5137
5148
  return;
5138
5149
  utf8ConsoleCodePageApplied = true;
5139
5150
  try {
5140
- const cmdExe = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\cmd.exe`;
5151
+ const cmdExe = windowsExe("cmd.exe");
5141
5152
  spawnSync(cmdExe, ["/d", "/s", "/c", "chcp 65001 >nul 2>&1"], {
5142
5153
  shell: false,
5143
5154
  windowsHide: true,
@@ -5312,7 +5323,7 @@ async function safeSpawnAsync(command, args, options) {
5312
5323
  }
5313
5324
  };
5314
5325
  const isWindows2 = process.platform === "win32";
5315
- const admission = admitSpawn(command, options?.cwd, getSpawnEnvironment(options?.env, options?.stripNpmConfig));
5326
+ const admission = admitSpawn(command, options?.cwd, getSpawnEnvironment(command, options?.env, options?.stripNpmConfig));
5316
5327
  if (!admission.admitted) {
5317
5328
  resolve7(trustRefusalResult(command, admission.executable));
5318
5329
  return;
@@ -5332,7 +5343,7 @@ async function safeSpawnAsync(command, args, options) {
5332
5343
  if (unsafeValue !== void 0) {
5333
5344
  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.`);
5334
5345
  } else {
5335
- spawnCmd = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\cmd.exe`;
5346
+ spawnCmd = windowsExe("cmd.exe");
5336
5347
  spawnArgs = [
5337
5348
  "/d",
5338
5349
  "/s",
@@ -5432,7 +5443,7 @@ async function safeSpawnAsync(command, args, options) {
5432
5443
  };
5433
5444
  const killTree = async (phase) => {
5434
5445
  if (isWindows2 && child.pid && child.pid > 0) {
5435
- const taskkill = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\taskkill.exe`;
5446
+ const taskkill = windowsExe("taskkill.exe");
5436
5447
  try {
5437
5448
  await new Promise((done) => {
5438
5449
  const killer = spawn(taskkill, ["/F", "/T", "/PID", String(child.pid)], {
@@ -5779,15 +5790,6 @@ async function safeSpawnAsync(command, args, options) {
5779
5790
  });
5780
5791
  });
5781
5792
  }
5782
- async function safeSpawnBatch(commands, concurrency = 3) {
5783
- const results = [];
5784
- for (let i = 0; i < commands.length; i += concurrency) {
5785
- const batch = commands.slice(i, i + concurrency);
5786
- const batchResults = await Promise.all(batch.map(({ command, args, options }) => safeSpawnAsync(command, args, options)));
5787
- results.push(...batchResults);
5788
- }
5789
- return results;
5790
- }
5791
5793
  async function isCommandAvailableAsync(command) {
5792
5794
  const finder = process.platform === "win32" ? "where" : "which";
5793
5795
  const result = await safeSpawnAsync(finder, [command], { timeout: 5e3 });
@@ -5801,7 +5803,7 @@ async function findCommandAsync(command) {
5801
5803
  return admittedLookupAnswer(result.stdout);
5802
5804
  }
5803
5805
  function safeSpawn(command, args, options) {
5804
- const admission = admitSpawn(command, options?.cwd, getSpawnEnvironment(options?.env, options?.stripNpmConfig));
5806
+ const admission = admitSpawn(command, options?.cwd, getSpawnEnvironment(command, options?.env, options?.stripNpmConfig));
5805
5807
  if (!admission.admitted)
5806
5808
  return trustRefusalResult(command, admission.executable);
5807
5809
  const spawnEnv = admission.env;
@@ -5841,7 +5843,7 @@ function safeSpawn(command, args, options) {
5841
5843
  })
5842
5844
  };
5843
5845
  }
5844
- spawnCmd = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\cmd.exe`;
5846
+ spawnCmd = windowsExe("cmd.exe");
5845
5847
  spawnArgs = [
5846
5848
  "/d",
5847
5849
  "/s",
@@ -5894,10 +5896,6 @@ function safeSpawn(command, args, options) {
5894
5896
  ...spawnFailure ? { failure: "spawn", spawnFailure } : {}
5895
5897
  };
5896
5898
  }
5897
- function isCommandAvailable(command) {
5898
- const result = safeSpawn(process.platform === "win32" ? "where" : "which", [command], { timeout: 5e3 });
5899
- return result.status === 0;
5900
- }
5901
5899
  function findCommand(command) {
5902
5900
  const finder = process.platform === "win32" ? "where" : "which";
5903
5901
  const result = safeSpawn(finder, [command], { timeout: 5e3 });
@@ -5924,6 +5922,10 @@ export {
5924
5922
  isUntrustedProjectPath,
5925
5923
  recordProjectCommandRefusal,
5926
5924
  admittedLookupAnswer,
5925
+ windowsExe,
5926
+ OWNER_TAG_ENV,
5927
+ ownerTagForChildren,
5928
+ realIsPidAlive,
5927
5929
  isLockContention,
5928
5930
  recordGenerationTakeover,
5929
5931
  recordLegacyLockHeld,
@@ -5937,8 +5939,6 @@ export {
5937
5939
  acquireBoundedPidFileLock,
5938
5940
  createGenerationSource,
5939
5941
  createGenerationMap,
5940
- OWNER_TAG_ENV,
5941
- ownerTagForChildren,
5942
5942
  isSubagentSession,
5943
5943
  getSubagentIdentity,
5944
5944
  subagentLightModeNotice,
@@ -5948,7 +5948,6 @@ export {
5948
5948
  removeLspChild,
5949
5949
  selectLivePeerInstances,
5950
5950
  getResourceFootprint,
5951
- realIsPidAlive,
5952
5951
  isStaleStageFile,
5953
5952
  sweepAtomicWriteStages,
5954
5953
  sampleProcessTreeCpuPercent,
@@ -5974,11 +5973,9 @@ export {
5974
5973
  resetUtf8ConsoleCodePageStateForTests,
5975
5974
  spawnAbortScope,
5976
5975
  safeSpawnAsync,
5977
- safeSpawnBatch,
5978
5976
  isCommandAvailableAsync,
5979
5977
  findCommandAsync,
5980
5978
  safeSpawn,
5981
- isCommandAvailable,
5982
5979
  findCommand,
5983
5980
  collectUntrackedIgnoredIds,
5984
5981
  collectTrackedFiles,
@@ -5994,6 +5991,8 @@ export {
5994
5991
  getGlobalPiLensDir,
5995
5992
  isPiLensInternalPath,
5996
5993
  EXCLUDED_DIRS,
5994
+ isIgnoredByGitignoreLines,
5995
+ isWithinPathForm,
5997
5996
  getProjectIgnoreMatcher,
5998
5997
  isPathIgnoredByProject,
5999
5998
  isRecordableProjectPath,