@modootoday/pmcp 0.22.12 → 0.23.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (154) hide show
  1. package/.agents/plugins/marketplace.json +1 -1
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/.claude-plugin/plugin.json +1 -1
  4. package/.mcp.json +1 -1
  5. package/dist/affected-D6FRJPPI.js +836 -0
  6. package/dist/{apply-LPKZZ6EL.js → apply-3PWUO4J5.js} +27 -22
  7. package/dist/{available-BFXLII4A.js → available-74CMIBPD.js} +9 -9
  8. package/dist/{broadcast-DZGMSZRG.js → broadcast-VKZY7WSD.js} +6 -5
  9. package/dist/chunk-2GZKA33O.js +173 -0
  10. package/dist/chunk-2HL2MFNI.js +159 -0
  11. package/dist/{chunk-OAX6MIOZ.js → chunk-2K4WYN4C.js} +2 -2
  12. package/dist/{chunk-PEMMV5YQ.js → chunk-2MX5C7B2.js} +3 -3
  13. package/dist/{chunk-7I7O7ZNT.js → chunk-3V37OZQH.js} +5 -3
  14. package/dist/chunk-43MXRTKH.js +134 -0
  15. package/dist/chunk-4VVQLWTS.js +93 -0
  16. package/dist/{chunk-DYZVHO2L.js → chunk-5HNLHI5F.js} +2 -2
  17. package/dist/{chunk-JEL35P7S.js → chunk-5NDUWEMW.js} +2 -2
  18. package/dist/chunk-65BW7Y6O.js +40 -0
  19. package/dist/{chunk-HUBJWC7T.js → chunk-6NRLBSEG.js} +7 -7
  20. package/dist/chunk-6QJ3F445.js +166 -0
  21. package/dist/{chunk-2OOWAGBE.js → chunk-72V6U7CZ.js} +3 -3
  22. package/dist/{chunk-RPCIROW7.js → chunk-7CHUMF3E.js} +2 -2
  23. package/dist/{chunk-INT7QLEU.js → chunk-7DJQASH3.js} +25 -6
  24. package/dist/chunk-7IRXUPM2.js +7 -0
  25. package/dist/{chunk-UDVYVRGJ.js → chunk-DNSHJIS4.js} +2 -2
  26. package/dist/{chunk-UMQLIRSU.js → chunk-DZTSCJOZ.js} +3 -3
  27. package/dist/{chunk-KEHB4FZP.js → chunk-E2E4HIEN.js} +49 -3
  28. package/dist/{chunk-SUJCVEBM.js → chunk-EQF64INS.js} +3 -3
  29. package/dist/chunk-F3R5HEUB.js +39 -0
  30. package/dist/chunk-FOLA4EUJ.js +261 -0
  31. package/dist/chunk-FQLCD4HU.js +24 -0
  32. package/dist/{chunk-OEH47H6A.js → chunk-GUHOEIHP.js} +3 -20
  33. package/dist/{chunk-B2WRYGHJ.js → chunk-HES44LTA.js} +5 -5
  34. package/dist/{chunk-RHJEGLYM.js → chunk-HF5D6B2U.js} +45 -6
  35. package/dist/{chunk-R5MT42JS.js → chunk-HYXOJYVR.js} +2 -2
  36. package/dist/chunk-JANBBPKP.js +50 -0
  37. package/dist/{chunk-ITOTOC6Y.js → chunk-JJFPSFDU.js} +3 -3
  38. package/dist/{chunk-XNML2KIC.js → chunk-JPYQDOEW.js} +3 -3
  39. package/dist/{chunk-SPZQRLL5.js → chunk-KYGGQPAH.js} +18 -6
  40. package/dist/{chunk-EX4YXPVW.js → chunk-LGRFYN5T.js} +2 -2
  41. package/dist/{chunk-DP326AER.js → chunk-LO54UUDE.js} +2 -2
  42. package/dist/{chunk-5QKXEWDB.js → chunk-MHKY6TNF.js} +6 -4
  43. package/dist/chunk-N7ANFMA5.js +171 -0
  44. package/dist/{chunk-KPKMEUUH.js → chunk-OGCJO6HQ.js} +9 -8
  45. package/dist/{chunk-N63QCJHX.js → chunk-P25V6NEX.js} +5 -5
  46. package/dist/{chunk-PUIWESU3.js → chunk-Q6V274OB.js} +8 -6
  47. package/dist/chunk-QR6A3TYP.js +315 -0
  48. package/dist/{chunk-EIDIVIAD.js → chunk-QYLOIM4U.js} +9 -2
  49. package/dist/{chunk-MIFPPUWY.js → chunk-RRKA3GF5.js} +4 -4
  50. package/dist/{chunk-7CSUKCU7.js → chunk-RZYZILU4.js} +17 -96
  51. package/dist/{chunk-FODUHLZM.js → chunk-SDQYZDHS.js} +2 -2
  52. package/dist/chunk-SGFTHKKS.js +86 -0
  53. package/dist/chunk-T6C3TSTO.js +99 -0
  54. package/dist/chunk-UVTGY2R3.js +78 -0
  55. package/dist/{chunk-LLT5FQBE.js → chunk-VBVNOLRR.js} +7 -3
  56. package/dist/{chunk-ABTJQ4QV.js → chunk-WBPVNCQO.js} +20 -5
  57. package/dist/{chunk-63RZGEVI.js → chunk-WQBKQTNT.js} +98 -26
  58. package/dist/{chunk-YGOWIJPE.js → chunk-WZYGM3FR.js} +6 -2
  59. package/dist/chunk-Y6NFETNG.js +232 -0
  60. package/dist/{chunk-D5MIZM6L.js → chunk-YRNFMPZB.js} +7 -8
  61. package/dist/{chunk-2GRECE6B.js → chunk-ZXMECZBI.js} +4 -4
  62. package/dist/{cli-34EDFXJA.js → cli-GFDT4YXM.js} +14 -15
  63. package/dist/{cli-JXPJFHUA.js → cli-YWV7FLYO.js} +24 -12
  64. package/dist/cli.js +317 -51
  65. package/dist/{completion-KTECNPVY.js → completion-OKGNN7DE.js} +25 -21
  66. package/dist/{diagnostics-I5VZHK42.js → diagnostics-N4XRRCQG.js} +10 -6
  67. package/dist/{doctor-JJ2VUNHT.js → doctor-3H6UYNEA.js} +27 -23
  68. package/dist/{entry-OT7BN3ID.js → entry-KDLLG6ED.js} +19 -15
  69. package/dist/{exec-mcp-3E4SRJUY.js → exec-mcp-AENALAHJ.js} +15 -11
  70. package/dist/{harness-Q236VJSU.js → harness-GRYTNUF2.js} +26 -44
  71. package/dist/harness-launch-gate.js +8 -4
  72. package/dist/harness-worker.js +10 -6
  73. package/dist/heavy-BGXKJKYB.js +1965 -0
  74. package/dist/hook-body.js +69 -21
  75. package/dist/hooks-V25ANQ4Q.js +24 -0
  76. package/dist/{host-LT5JMUFJ.js → host-4EGPADOJ.js} +11 -7
  77. package/dist/{host-UDC4HVX3.js → host-MLSWY7D7.js} +24 -17
  78. package/dist/{host-run-LD63JGN7.js → host-run-VI52IUKF.js} +10 -6
  79. package/dist/http.js +1 -1
  80. package/dist/{import-mcp-URVONIZ3.js → import-mcp-FIXFLUDM.js} +18 -14
  81. package/dist/index.d.ts +1 -1
  82. package/dist/index.js +17 -12
  83. package/dist/init-ALTBFUPP.js +14 -0
  84. package/dist/{install-7V6NIA7W.js → install-5JH4DSFF.js} +10 -10
  85. package/dist/{invoke-JW5OC2HO.js → invoke-7T7UY57O.js} +12 -8
  86. package/dist/{list-UM4DYJRL.js → list-JFZ7UZLV.js} +18 -14
  87. package/dist/{list-WK2IYUK7.js → list-LV5EKCF6.js} +11 -7
  88. package/dist/{logout-H5X4D26I.js → logout-7CNBO76Z.js} +15 -11
  89. package/dist/{logs-UHJM7ZCL.js → logs-2JEMSNSG.js} +11 -10
  90. package/dist/{mailbox-NIMBOQPA.js → mailbox-5FVFMQ2J.js} +12 -44
  91. package/dist/{mailbox-YN6PG66A.js → mailbox-ZHZWZMAY.js} +14 -21
  92. package/dist/{mainline-74WCH4T4.js → mainline-6PBT3VNR.js} +75 -126
  93. package/dist/{marketplace-G4VQET5W.js → marketplace-2X3OOEPW.js} +10 -9
  94. package/dist/{mcp-6P3MVT4V.js → mcp-MVQVMAKJ.js} +4 -4
  95. package/dist/{mcp-AXHV547W.js → mcp-PBTQ5SJW.js} +2 -2
  96. package/dist/{models-ISU4DCMA.js → models-XSF45MCD.js} +9 -5
  97. package/dist/{pause-CBZ3BTJL.js → pause-CMZOIHTJ.js} +6 -5
  98. package/dist/{preview-DT7DWG5F.js → preview-465CQJBQ.js} +4 -4
  99. package/dist/{project-6QUIC73W.js → project-FZGJRG2U.js} +14 -12
  100. package/dist/{reindex-I7RYWCUR.js → reindex-D62HQAN2.js} +7 -7
  101. package/dist/{report-ZHOHQ4PZ.js → report-UB7MXAUB.js} +14 -13
  102. package/dist/{resume-UJEWQ66P.js → resume-PAKIT4TT.js} +6 -5
  103. package/dist/{run-HQTB7N2R.js → run-TOP37ZQC.js} +14 -10
  104. package/dist/run-VGJDMA2O.js +23 -0
  105. package/dist/{serve-APEVIJD2.js → serve-LR7SJHNH.js} +13 -13
  106. package/dist/{session-YZVX4NGN.js → session-3YVVO2GR.js} +6 -6
  107. package/dist/{setup-SOUBEZ3H.js → setup-6AQUOWOH.js} +7 -4
  108. package/dist/{smoke-2FI5D74B.js → smoke-6X6IXQIQ.js} +4 -4
  109. package/dist/{start-login-ER7DEGYN.js → start-login-X37KGCCB.js} +16 -12
  110. package/dist/{status-KN2ZE64O.js → status-4PYPTYUB.js} +7 -6
  111. package/dist/{status-7NYXRZ3R.js → status-E4AFUOQO.js} +24 -13
  112. package/dist/{status-OGABWCPO.js → status-LBRK37GA.js} +35 -30
  113. package/dist/stdio.js +2 -2
  114. package/dist/{sweep-EPZCW63Q.js → sweep-VURZU6DI.js} +6 -5
  115. package/dist/{test-WRZQERYC.js → test-D2EEFUN2.js} +18 -14
  116. package/dist/{tui-YUHQ36FC.js → tui-D7E3MD3X.js} +45 -19
  117. package/dist/{unbroadcast-N6LXHAMT.js → unbroadcast-7AMLURCG.js} +6 -5
  118. package/dist/{validate-KFBCUFI4.js → validate-YXR7FJJX.js} +11 -9
  119. package/dist/wait-HEODT7KV.js +141 -0
  120. package/dist/{worker-OKBJNDEI.js → worker-WTBC6VYO.js} +12 -8
  121. package/dist/{worktree-create-KMXPQXIQ.js → worktree-create-FTSLMZWS.js} +2 -2
  122. package/docs/commands.md +108 -36
  123. package/docs/git-workflow.md +51 -0
  124. package/docs/hooks.md +11 -4
  125. package/docs/project-configuration.md +136 -20
  126. package/docs/terminal-workspace.md +2 -0
  127. package/docs/upgrading.md +54 -0
  128. package/gemini-extension.json +2 -2
  129. package/mcp.json +1 -1
  130. package/package.json +5 -5
  131. package/plugin.json +1 -1
  132. package/plugins/pmcp/.claude-plugin/plugin.json +1 -1
  133. package/plugins/pmcp/.mcp.json +1 -1
  134. package/plugins/pmcp/gemini-extension.json +2 -2
  135. package/plugins/pmcp/mcp.json +1 -1
  136. package/plugins/pmcp/plugin.json +1 -1
  137. package/plugins/pmcp/skills/headless-agents-ci-scaffold/SKILL.md +1 -1
  138. package/plugins/pmcp/skills/pmcp-project-init/SKILL.md +1 -1
  139. package/plugins/pmcp/skills/pmcp-sessions-and-git/SKILL.md +3 -2
  140. package/skills/headless-agents-ci-scaffold/SKILL.md +1 -1
  141. package/skills/pmcp-project-init/SKILL.md +1 -1
  142. package/skills/pmcp-sessions-and-git/SKILL.md +3 -2
  143. package/dist/chunk-2P4Z2NUX.js +0 -28
  144. package/dist/chunk-3C5FVHQ3.js +0 -7
  145. package/dist/chunk-3Y3HDMHA.js +0 -108
  146. package/dist/chunk-A4PKLESO.js +0 -112
  147. package/dist/chunk-E3DQB5LS.js +0 -48
  148. package/dist/chunk-GFOQDLPL.js +0 -35
  149. package/dist/chunk-JWRZDYB5.js +0 -59
  150. package/dist/chunk-LMUBBIE2.js +0 -83
  151. package/dist/chunk-SMZPYJQI.js +0 -151
  152. package/dist/hooks-PABOEQO6.js +0 -24
  153. package/dist/init-4O24ZNUQ.js +0 -14
  154. package/dist/run-GZK3XJ62.js +0 -19
@@ -0,0 +1,1965 @@
1
+ import {
2
+ flock
3
+ } from "./chunk-SGFTHKKS.js";
4
+ import {
5
+ inferSession
6
+ } from "./chunk-65BW7Y6O.js";
7
+ import {
8
+ flockAvailable
9
+ } from "./chunk-DZ2MRTYT.js";
10
+ import {
11
+ heavySpec
12
+ } from "./chunk-43MXRTKH.js";
13
+ import "./chunk-JPYQDOEW.js";
14
+ import {
15
+ ArgumentError,
16
+ EXIT,
17
+ one
18
+ } from "./chunk-Y6NFETNG.js";
19
+ import {
20
+ BUSY_EXIT,
21
+ DISABLE_ENV,
22
+ NOW_ENV,
23
+ leaseSettingsFor
24
+ } from "./chunk-FOLA4EUJ.js";
25
+ import {
26
+ LANES,
27
+ describeRecord,
28
+ epoch,
29
+ leaseHeld,
30
+ leasePaths,
31
+ liveRecords,
32
+ liveWaiters,
33
+ logEvent,
34
+ newId,
35
+ nowUtc,
36
+ oneLine,
37
+ pidAlive,
38
+ readRecord,
39
+ removeRecord,
40
+ writeRecord
41
+ } from "./chunk-N7ANFMA5.js";
42
+ import "./chunk-T6C3TSTO.js";
43
+ import "./chunk-GUHOEIHP.js";
44
+ import "./chunk-IJBSOWHK.js";
45
+ import {
46
+ ConfigError,
47
+ findConfig
48
+ } from "./chunk-GJXOFDJT.js";
49
+ import "./chunk-PMJG2CXF.js";
50
+
51
+ // src/commands/heavy.ts
52
+ import { dirname } from "path";
53
+
54
+ // src/lease/run.ts
55
+ import { spawn } from "child_process";
56
+ import { constants } from "os";
57
+
58
+ // src/lease/scope.ts
59
+ import { spawnSync as spawnSync2 } from "child_process";
60
+ import { existsSync } from "fs";
61
+ import { join as join2 } from "path";
62
+
63
+ // src/lease/iocontrol.ts
64
+ import { spawnSync } from "child_process";
65
+ import { readFileSync, writeFileSync } from "fs";
66
+ import { join } from "path";
67
+ function cgroupHost() {
68
+ let self = "";
69
+ try {
70
+ const line = readFileSync("/proc/self/cgroup", "utf8").split("\n").find((entry) => entry.startsWith("0::"));
71
+ self = line?.slice(3) ?? "";
72
+ } catch {
73
+ }
74
+ return { root: "/sys/fs/cgroup", self };
75
+ }
76
+ function controllers(dir) {
77
+ try {
78
+ return readFileSync(join(dir, "cgroup.controllers"), "utf8").trim().split(/\s+/u);
79
+ } catch {
80
+ return [];
81
+ }
82
+ }
83
+ function ioDelegated(host) {
84
+ const parts = host.self.split("/").filter(Boolean);
85
+ const at = parts.findIndex((part) => /^user@\d+\.service$/u.test(part));
86
+ if (at < 0) return false;
87
+ const manager = join(host.root, ...parts.slice(0, at + 1));
88
+ return controllers(manager).includes("io");
89
+ }
90
+ function enable(dir) {
91
+ const file = join(dir, "cgroup.subtree_control");
92
+ try {
93
+ if (readFileSync(file, "utf8").split(/\s+/u).includes("io")) return;
94
+ writeFileSync(file, "+io");
95
+ } catch {
96
+ }
97
+ }
98
+ function applyIo(host, scope, weight, max) {
99
+ const parts = scope.split("/").filter(Boolean);
100
+ for (let at = 1; at < parts.length; at += 1)
101
+ enable(join(host.root, ...parts.slice(0, at)));
102
+ const dir = join(host.root, ...parts);
103
+ if (!controllers(dir).includes("io")) return false;
104
+ try {
105
+ writeFileSync(join(dir, "io.weight"), `default ${weight}`);
106
+ if (max) writeFileSync(join(dir, "io.max"), max);
107
+ return true;
108
+ } catch {
109
+ return false;
110
+ }
111
+ }
112
+ function scopeCgroup(unit) {
113
+ const run2 = spawnSync(
114
+ "systemctl",
115
+ ["--user", "show", unit, "-p", "ControlGroup", "--value"],
116
+ { encoding: "utf8" }
117
+ );
118
+ const path = run2.status === 0 ? run2.stdout.trim() : "";
119
+ return path || null;
120
+ }
121
+
122
+ // src/lease/scope.ts
123
+ var BUS_FAILURE = /Failed to connect to (?:the )?bus/u;
124
+ var installed;
125
+ var probed = /* @__PURE__ */ new Map();
126
+ function probeScope(env) {
127
+ const run2 = spawnSync2("systemd-run", ["--user", "--scope", "-q", "true"], {
128
+ env,
129
+ encoding: "utf8",
130
+ stdio: ["ignore", "ignore", "pipe"],
131
+ timeout: 1e4
132
+ });
133
+ if (run2.status === 0) return null;
134
+ const line = (run2.stderr ?? "").trim().split("\n")[0];
135
+ return line || `systemd-run --user exited ${run2.status ?? "on a signal"}`;
136
+ }
137
+ function systemdRun() {
138
+ installed ??= spawnSync2("systemd-run", ["--user", "--version"], { stdio: "ignore" }).status === 0;
139
+ return installed;
140
+ }
141
+ function userManager(exists = existsSync, probe = probeScope, platform = process.platform, present = systemdRun) {
142
+ return {
143
+ unreachable(env) {
144
+ if (platform !== "linux") return "not Linux";
145
+ if (!present()) return "systemd-run is not installed";
146
+ const runtime = env["XDG_RUNTIME_DIR"];
147
+ if (!runtime) return "XDG_RUNTIME_DIR is not set";
148
+ const socket = exists(join2(runtime, "systemd", "private")) || exists(join2(runtime, "bus")) || Boolean(env["DBUS_SESSION_BUS_ADDRESS"]);
149
+ if (!socket) return `no user manager socket in ${runtime}`;
150
+ if (!probed.has(runtime)) probed.set(runtime, probe(env));
151
+ return probed.get(runtime) ?? null;
152
+ }
153
+ };
154
+ }
155
+ function lost(memoryMax, io2) {
156
+ const parts = [
157
+ ...memoryMax === void 0 ? [] : [`MemoryMax=${memoryMax}`],
158
+ ...io2 ? ["io.weight"] : []
159
+ ];
160
+ return parts.join(" and ");
161
+ }
162
+ function wantsIo(settings2, lane, host) {
163
+ if (lane === null || settings2.io.enabled === false) return false;
164
+ return ioDelegated(host);
165
+ }
166
+ async function weigh(unit, settings2, lane, host, say, onCgroup) {
167
+ for (let tries = 0; tries < 30; tries += 1) {
168
+ const scope = scopeCgroup(unit);
169
+ if (scope !== null) {
170
+ onCgroup(join2(host.root, scope));
171
+ const set = applyIo(
172
+ host,
173
+ scope,
174
+ settings2.io.weights[lane],
175
+ settings2.io.max[lane]
176
+ );
177
+ if (!set && settings2.io.enabled === true)
178
+ say(`io control did not reach ${scope}; running without io.weight`);
179
+ return;
180
+ }
181
+ await new Promise((resolve) => setTimeout(resolve, 100));
182
+ }
183
+ }
184
+ function scoped(argv, settings2, lane, memoryMax, say, onCgroup = () => {
185
+ }, host = cgroupHost(), manager = userManager(), env = process.env) {
186
+ const io2 = wantsIo(settings2, lane, host);
187
+ if (memoryMax === void 0 && !io2) return { argv };
188
+ const reason2 = manager.unreachable(env);
189
+ if (reason2 !== null) {
190
+ say(
191
+ `no systemd user scope (${reason2}); running without ${lost(memoryMax, io2)}`
192
+ );
193
+ return { argv };
194
+ }
195
+ const unit = `pmcp-heavy-${process.pid}-${Date.now()}`;
196
+ const limits = memoryMax === void 0 ? [] : ["-p", `MemoryMax=${memoryMax}`, "-p", "MemorySwapMax=0"];
197
+ return {
198
+ argv: [
199
+ "systemd-run",
200
+ "--user",
201
+ "--scope",
202
+ "-q",
203
+ `--unit=${unit}`,
204
+ ...limits,
205
+ "--",
206
+ ...argv
207
+ ],
208
+ unscoped: argv,
209
+ ...io2 && lane !== null ? { started: () => weigh(unit, settings2, lane, host, say, onCgroup) } : {}
210
+ };
211
+ }
212
+
213
+ // src/lease/acquire.ts
214
+ import {
215
+ closeSync as closeSync2,
216
+ mkdirSync,
217
+ openSync as openSync2,
218
+ readFileSync as readFileSync4,
219
+ rmSync,
220
+ writeFileSync as writeFileSync3
221
+ } from "fs";
222
+
223
+ // src/lease/admit.ts
224
+ import { closeSync, openSync } from "fs";
225
+ import { join as join3 } from "path";
226
+ function admissible(settings2, running, waiters) {
227
+ const free = { ...settings2.slots };
228
+ let budget = settings2.budget;
229
+ for (const job2 of running) {
230
+ if (job2.weight === 0) continue;
231
+ free[job2.lane] -= 1;
232
+ budget -= job2.weight;
233
+ }
234
+ const found = new Set(
235
+ waiters.filter((waiter) => waiter.weight === 0).map((w) => w.pid)
236
+ );
237
+ for (const waiter of waiters) {
238
+ if (waiter.weight === 0 || free[waiter.lane] <= 0) continue;
239
+ if (waiter.weight > budget) break;
240
+ free[waiter.lane] -= 1;
241
+ budget -= waiter.weight;
242
+ found.add(waiter.pid);
243
+ }
244
+ return found;
245
+ }
246
+ function runningWeight(running) {
247
+ return running.reduce((sum, job2) => sum + job2.weight, 0);
248
+ }
249
+ function laneUse(settings2, running) {
250
+ const used = (lane) => running.filter((job2) => job2.lane === lane).length;
251
+ const lanes = LANES.map(
252
+ (lane) => `${lane} ${used(lane)}/${settings2.slots[lane]}`
253
+ ).join(" ");
254
+ return `${lanes}, weight ${runningWeight(running)}/${settings2.budget}`;
255
+ }
256
+ function underAdmitLock(paths, act) {
257
+ const fd = openSync(paths.admit, "a");
258
+ try {
259
+ if (flock(fd, ["-w", "10"]) !== 0) return null;
260
+ return act();
261
+ } finally {
262
+ closeSync(fd);
263
+ }
264
+ }
265
+ function readQueue(paths, prune2 = true) {
266
+ return {
267
+ running: liveRecords(paths.running, prune2),
268
+ waiters: liveRecords(paths.waiters, prune2)
269
+ };
270
+ }
271
+ function runningFile(paths, pid) {
272
+ return join3(paths.running, String(pid));
273
+ }
274
+ function waiterFile(paths, pid) {
275
+ return join3(paths.waiters, String(pid));
276
+ }
277
+
278
+ // src/lease/host.ts
279
+ import { readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
280
+ function hostSources(env) {
281
+ return {
282
+ loadavg: env["PMCP_HEAVY_LOADAVG_FILE"] || "/proc/loadavg",
283
+ pressure: env["PMCP_HEAVY_PRESSURE_FILE"] || "/proc/pressure/io"
284
+ };
285
+ }
286
+ function read(file) {
287
+ try {
288
+ return readFileSync2(file, "utf8");
289
+ } catch {
290
+ return null;
291
+ }
292
+ }
293
+ function readHost(sources) {
294
+ const load = read(sources.loadavg)?.split(" ")[0]?.trim() || null;
295
+ const some = read(sources.pressure)?.match(/^some (.*)$/mu)?.[1] ?? "";
296
+ const pressure = {};
297
+ for (const [, key, value] of some.matchAll(/(avg\d+)=([0-9.]+)/gu))
298
+ pressure[key] = value;
299
+ return { load, io: pressure["avg10"] ?? null, pressure };
300
+ }
301
+ function hostNow(reading) {
302
+ return `load ${reading.load ?? "n/a"} io ${reading.io ?? "n/a"}`;
303
+ }
304
+ function below(value, max) {
305
+ return value === null || Number(value) < max;
306
+ }
307
+ function hostSettled(settings2, paths, sources) {
308
+ const reading = readHost(sources);
309
+ if (!below(reading.load, settings2.maxLoad)) return false;
310
+ const io2 = reading.pressure[settings2.ioWindow] ?? reading.io;
311
+ if (!below(io2, settings2.maxIo)) return false;
312
+ try {
313
+ writeFileSync2(paths.settled, `${nowUtc()}
314
+ `);
315
+ } catch {
316
+ }
317
+ return true;
318
+ }
319
+ function sleepSeconds(seconds) {
320
+ if (seconds <= 0) return;
321
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, seconds * 1e3);
322
+ }
323
+
324
+ // src/lease/queue.ts
325
+ import { readFileSync as readFileSync3 } from "fs";
326
+ function sessionOf(env, cwd) {
327
+ const inferred = inferSession(env, [], []).session;
328
+ if (inferred) return inferred;
329
+ try {
330
+ const stat = readFileSync3("/proc/self/stat", "utf8");
331
+ const group = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[2];
332
+ if (group) return `pgid:${group}`;
333
+ } catch {
334
+ }
335
+ return `cwd:${cwd}`;
336
+ }
337
+ var CAPPED = ["interactive", "bulk"];
338
+ function parkForSession(park) {
339
+ if (park.cap === 0 || !CAPPED.includes(park.lane)) return 0;
340
+ const started = epoch();
341
+ const queued = () => liveWaiters(park.paths).filter(
342
+ (record2) => record2.session === park.session && record2.lane === park.lane
343
+ ).length;
344
+ let count = queued();
345
+ if (count < park.cap) return 0;
346
+ park.say(
347
+ `parked outside the queue: this session already has ${count} queued ${park.lane} job(s) (per_session ${park.cap})`
348
+ );
349
+ for (; ; ) {
350
+ if (epoch() - started >= park.maxWait) return null;
351
+ sleepSeconds(1);
352
+ count = queued();
353
+ if (count < park.cap) return epoch() - started;
354
+ }
355
+ }
356
+
357
+ // src/lease/settle.ts
358
+ function io(settings2, reading) {
359
+ return reading.pressure[settings2.ioWindow] ?? reading.io;
360
+ }
361
+ function over(value, max) {
362
+ return value !== null && Number(value) >= max;
363
+ }
364
+ function settled(settings2, reading) {
365
+ return !over(reading.load, settings2.maxLoad) && !over(io(settings2, reading), settings2.maxIo);
366
+ }
367
+ function severe(settings2, reading) {
368
+ const factor = settings2.hardFactor;
369
+ return over(reading.load, settings2.maxLoad * factor) || over(io(settings2, reading), settings2.maxIo * factor);
370
+ }
371
+ function hostVerdict(settings2, reading, waiting) {
372
+ if (settled(settings2, reading)) return "settled";
373
+ if (severe(settings2, reading)) return "severe";
374
+ if (waiting.lane === "hook") return "hook";
375
+ if (waiting.weight === 0) return "tiny";
376
+ const window = settings2.settleWindow;
377
+ if (window > 0 && waiting.sinceRelease !== null && waiting.sinceRelease >= window)
378
+ return "settle";
379
+ if (waiting.grace > 0 && waiting.waited >= waiting.grace && waiting.runningWeight === 0)
380
+ return "grace";
381
+ return "wait";
382
+ }
383
+
384
+ // src/lease/acquire.ts
385
+ var STEP_SECONDS = 1;
386
+ function skipReason(settings2, env) {
387
+ const own = env[DISABLE_ENV];
388
+ if (own) return own;
389
+ const legacy = settings2.legacySkipEnv ? env[settings2.legacySkipEnv] : "";
390
+ return legacy || null;
391
+ }
392
+ function reentrant(settings2, env) {
393
+ const paths = leasePaths(settings2.dir);
394
+ const names = [settings2.markerEnv, settings2.legacyMarkerEnv];
395
+ const markers = names.flatMap(
396
+ (name) => name && env[name] ? [env[name]] : []
397
+ );
398
+ if (markers.length === 0) return false;
399
+ if (liveRecords(paths.running).some((job2) => markers.includes(String(job2.pid))))
400
+ return true;
401
+ const holder = readRecord(paths.holder);
402
+ if (holder === null || !markers.includes(String(holder.pid))) return false;
403
+ return pidAlive(holder.pid) && leaseHeld(paths);
404
+ }
405
+ function profileLane(profile) {
406
+ if (profile === "gate" || profile === "hook") return profile;
407
+ return "interactive";
408
+ }
409
+ function position(paths, pid) {
410
+ const index = liveRecords(paths.waiters).findIndex((r) => r.pid === pid);
411
+ return index < 0 ? 0 : index + 1;
412
+ }
413
+ function tryAdmit(options, paths, fd, start, registered) {
414
+ let fields = start;
415
+ const pid = process.pid;
416
+ const outcome = underAdmitLock(paths, () => {
417
+ const mine = readRecord(waiterFile(paths, pid));
418
+ if (mine === null || mine.cancel)
419
+ return {
420
+ admitted: false,
421
+ verdict: "cancelled",
422
+ reason: mine?.cancel || "removed"
423
+ };
424
+ fields = { ...fields, lane: mine.lane };
425
+ if (mine.promote) {
426
+ flock(fd, ["-s", "-n"]);
427
+ writeRecord(runningFile(paths, pid), pid, {
428
+ ...fields,
429
+ bypass: mine.promote
430
+ });
431
+ writeRecord(paths.holder, pid, fields);
432
+ rmSync(waiterFile(paths, pid), { force: true });
433
+ logEvent(
434
+ paths,
435
+ pid,
436
+ "bypass",
437
+ `reason=${mine.promote} cwd=${fields.cwd} label=${fields.label} lane=${fields.lane} weight=${fields.weight} id=${fields.id}`
438
+ );
439
+ return { admitted: true, verdict: "promoted", lane: fields.lane };
440
+ }
441
+ const { running, waiters } = readQueue(paths);
442
+ if (!admissible(options.settings, running, waiters).has(pid))
443
+ return { admitted: false, verdict: "queue" };
444
+ const grace = options.settings.profiles[options.profile].loadGrace;
445
+ const reading = readHost(hostSources(options.env));
446
+ const released = lastRelease(paths);
447
+ const verdict = hostVerdict(options.settings, reading, {
448
+ lane: fields.lane,
449
+ weight: fields.weight,
450
+ grace,
451
+ waited: epoch() - registered,
452
+ // Only a release while this job waited counts: older ones explain nothing now.
453
+ sinceRelease: released !== null && released >= registered ? epoch() - released : null,
454
+ runningWeight: runningWeight(running)
455
+ });
456
+ if (verdict === "wait" || verdict === "severe")
457
+ return { admitted: false, verdict };
458
+ if (flock(fd, ["-s", "-n"]) !== 0)
459
+ return { admitted: false, verdict: "legacy" };
460
+ writeRecord(runningFile(paths, pid), pid, {
461
+ ...fields,
462
+ queued: Date.now(),
463
+ grace: verdict === "grace"
464
+ });
465
+ writeRecord(paths.holder, pid, fields);
466
+ rmSync(waiterFile(paths, pid), { force: true });
467
+ if (verdict !== "settled")
468
+ logEvent(
469
+ paths,
470
+ pid,
471
+ verdict,
472
+ `waited=${epoch() - registered} ${hostNow(reading)} label=${fields.label}`
473
+ );
474
+ return { admitted: true, verdict, lane: fields.lane };
475
+ });
476
+ return outcome ?? { admitted: false, verdict: "queue" };
477
+ }
478
+ function lastRelease(paths) {
479
+ try {
480
+ return Number(readFileSync4(paths.released, "utf8").trim()) || null;
481
+ } catch {
482
+ return null;
483
+ }
484
+ }
485
+ function markRelease(paths) {
486
+ try {
487
+ writeFileSync3(paths.released, `${epoch()}
488
+ `);
489
+ } catch {
490
+ }
491
+ }
492
+ function release(paths, pid, fd, rc, ran) {
493
+ underAdmitLock(paths, () => {
494
+ rmSync(runningFile(paths, pid), { force: true });
495
+ removeRecord(paths.holder, pid);
496
+ markRelease(paths);
497
+ const next = liveRecords(paths.running)[0];
498
+ if (next && readRecord(paths.holder) === null)
499
+ writeRecord(paths.holder, next.pid, { ...next, queued: next.queued });
500
+ });
501
+ logEvent(paths, pid, "released", `ran=${ran} rc=${rc}`);
502
+ closeSync2(fd);
503
+ }
504
+ function held(options, paths, fd, start) {
505
+ const { settings: settings2 } = options;
506
+ const pid = String(process.pid);
507
+ const env = { [settings2.markerEnv]: pid };
508
+ if (settings2.legacyMarkerEnv) env[settings2.legacyMarkerEnv] = pid;
509
+ if (settings2.legacySkipEnv)
510
+ env[settings2.legacySkipEnv] = `inside pmcp heavy ${pid}`;
511
+ let open = true;
512
+ return {
513
+ kind: "held",
514
+ env,
515
+ start,
516
+ release(rc, ran) {
517
+ if (!open) return;
518
+ open = false;
519
+ release(paths, process.pid, fd, rc, ran);
520
+ }
521
+ };
522
+ }
523
+ function acquireLease(options) {
524
+ const { settings: settings2, env, label, say } = options;
525
+ if (!settings2.enabled) return { kind: "disabled" };
526
+ const paths = leasePaths(settings2.dir);
527
+ const skip = skipReason(settings2, env);
528
+ if (skip !== null) {
529
+ say(`running without the host lease: ${skip}`);
530
+ logEvent(
531
+ paths,
532
+ process.pid,
533
+ "skip",
534
+ `reason=${skip} cwd=${options.cwd} label=${label}`
535
+ );
536
+ return { kind: "skipped", reason: skip };
537
+ }
538
+ if (!flockAvailable()) {
539
+ say("flock is not installed; running without the host lease");
540
+ return { kind: "skipped", reason: "flock is not installed" };
541
+ }
542
+ if (reentrant(settings2, env)) return { kind: "reentrant" };
543
+ const profile = settings2.profiles[options.profile];
544
+ if (profile === void 0)
545
+ throw new Error(`unknown profile ${options.profile}`);
546
+ const lane = options.lane ?? profileLane(options.profile);
547
+ const weight = Math.min(
548
+ options.weight ?? settings2.weights[lane],
549
+ settings2.budget
550
+ );
551
+ const session = sessionOf(env, options.cwd);
552
+ const fields = {
553
+ cwd: options.cwd,
554
+ label,
555
+ lane,
556
+ weight,
557
+ session,
558
+ id: options.id ?? newId()
559
+ };
560
+ mkdirSync(paths.waiters, { recursive: true });
561
+ mkdirSync(paths.running, { recursive: true });
562
+ if (options.now) return bypass(options, paths, fields);
563
+ const started = epoch();
564
+ const deadline = started + profile.maxWait;
565
+ const parked = parkForSession({
566
+ paths,
567
+ lane,
568
+ session,
569
+ cap: settings2.perSession,
570
+ maxWait: profile.maxWait,
571
+ say
572
+ });
573
+ if (parked === null) return busy(options, paths, lane, 0, "parked", started);
574
+ const fd = openSync2(paths.lock, "a");
575
+ writeRecord(waiterFile(paths, process.pid), process.pid, fields);
576
+ const registered = epoch();
577
+ let beat = 0;
578
+ let last = "queue";
579
+ let admittedLane = lane;
580
+ try {
581
+ for (; ; ) {
582
+ const attempt = tryAdmit(options, paths, fd, fields, registered);
583
+ if (attempt.admitted) {
584
+ last = attempt.verdict;
585
+ admittedLane = attempt.lane ?? lane;
586
+ break;
587
+ }
588
+ if (attempt.verdict === "cancelled") {
589
+ closeSync2(fd);
590
+ say(`cancelled in the queue: ${attempt.reason}`);
591
+ return { kind: "cancelled", reason: attempt.reason ?? "" };
592
+ }
593
+ if (last === "queue" && attempt.verdict !== "queue")
594
+ say(
595
+ `next in line; ${describeWait(attempt.verdict, hostNow(readHost(hostSources(env))))}`
596
+ );
597
+ last = attempt.verdict;
598
+ if (epoch() >= deadline) {
599
+ closeSync2(fd);
600
+ const place = position(paths, process.pid);
601
+ const reason2 = last === "severe" ? "host" : last === "legacy" ? "legacy" : "queue";
602
+ return busy(options, paths, lane, place, reason2, started);
603
+ }
604
+ if (epoch() - beat >= settings2.heartbeat) {
605
+ const { running } = readQueue(paths);
606
+ say(
607
+ `waiting ${epoch() - started}s; ${lane} position ${position(paths, process.pid)}, running weight ${runningWeight(running)}/${settings2.budget}, ${hostNow(readHost(hostSources(env)))}`
608
+ );
609
+ beat = epoch();
610
+ }
611
+ sleepSeconds(Math.min(STEP_SECONDS, deadline - epoch()));
612
+ }
613
+ } finally {
614
+ rmSync(waiterFile(paths, process.pid), { force: true });
615
+ }
616
+ hostSettled(settings2, paths, hostSources(env));
617
+ logEvent(
618
+ paths,
619
+ process.pid,
620
+ "acquired",
621
+ `waited=${epoch() - started} cwd=${options.cwd} label=${label} lane=${admittedLane} weight=${weight}`
622
+ );
623
+ const start = last === "promoted" ? "bypass" : last === "grace" ? "grace" : "queue";
624
+ return held(options, paths, fd, start);
625
+ }
626
+ function bypass(options, paths, fields) {
627
+ const fd = openSync2(paths.lock, "a");
628
+ const reason2 = options.now;
629
+ underAdmitLock(paths, () => {
630
+ flock(fd, ["-s", "-n"]);
631
+ writeRecord(runningFile(paths, process.pid), process.pid, {
632
+ ...fields,
633
+ bypass: reason2
634
+ });
635
+ });
636
+ options.say(
637
+ `BYPASS: running now, outside the queue and the host check: ${reason2}`
638
+ );
639
+ logEvent(
640
+ paths,
641
+ process.pid,
642
+ "bypass",
643
+ `reason=${reason2} cwd=${fields.cwd} label=${fields.label} lane=${fields.lane} weight=${fields.weight}`
644
+ );
645
+ return held(options, paths, fd, "bypass");
646
+ }
647
+ function describeWait(verdict, host) {
648
+ if (verdict === "severe")
649
+ return `the host is at hard_factor x a limit (${host})`;
650
+ if (verdict === "wait") return `waiting for the host to settle (${host})`;
651
+ if (verdict === "legacy") return "a shell wrapper holds the whole lease";
652
+ return "waiting";
653
+ }
654
+ function busy(options, paths, lane, place, reason2, started) {
655
+ const profile = options.settings.profiles[options.profile];
656
+ const host = hostNow(readHost(hostSources(options.env)));
657
+ logEvent(
658
+ paths,
659
+ process.pid,
660
+ "timeout",
661
+ `waited=${profile.maxWait} label=${options.label} lane=${lane} position=${place} reason=${reason2}`
662
+ );
663
+ return {
664
+ kind: "busy",
665
+ waited: epoch() - started,
666
+ lane,
667
+ position: place,
668
+ reason: reason2,
669
+ host
670
+ };
671
+ }
672
+
673
+ // src/lease/usage.ts
674
+ import {
675
+ appendFileSync,
676
+ readFileSync as readFileSync5,
677
+ readdirSync,
678
+ renameSync,
679
+ statSync
680
+ } from "fs";
681
+ import { join as join4, relative } from "path";
682
+ var WORD = /^[a-z][a-z0-9:_-]{0,39}$/u;
683
+ function signature(argv) {
684
+ const [program = "", ...rest] = argv;
685
+ const words = [program.slice(program.lastIndexOf("/") + 1)];
686
+ for (const word of rest) {
687
+ if (!WORD.test(word)) break;
688
+ words.push(word);
689
+ }
690
+ return words.join(" ");
691
+ }
692
+ function packageDir(cwd, root) {
693
+ const path = relative(root, cwd);
694
+ return path === "" ? "." : path.startsWith("..") ? "(outside)" : path;
695
+ }
696
+ function appendUsage(file, usage, cap) {
697
+ try {
698
+ if (statSync(file).size >= cap) renameSync(file, `${file}.1`);
699
+ } catch {
700
+ }
701
+ try {
702
+ appendFileSync(file, `${JSON.stringify(usage)}
703
+ `);
704
+ } catch {
705
+ }
706
+ }
707
+ function readUsage(file) {
708
+ const found = [];
709
+ for (const path of [`${file}.1`, file]) {
710
+ let text = "";
711
+ try {
712
+ text = readFileSync5(path, "utf8");
713
+ } catch {
714
+ continue;
715
+ }
716
+ for (const line of text.split("\n")) {
717
+ if (!line.trim()) continue;
718
+ try {
719
+ found.push(JSON.parse(line));
720
+ } catch {
721
+ }
722
+ }
723
+ }
724
+ return found;
725
+ }
726
+ var METRICS = [
727
+ "wall_s",
728
+ "user_s",
729
+ "sys_s",
730
+ "max_rss_kb",
731
+ "read_bytes",
732
+ "write_bytes"
733
+ ];
734
+ function percentile(values, share) {
735
+ const sorted = [...values].sort((a, b) => a - b);
736
+ return sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * share))] ?? 0;
737
+ }
738
+ function usageStats(records) {
739
+ const groups = /* @__PURE__ */ new Map();
740
+ for (const record2 of records) {
741
+ const key = `${record2.signature} @ ${record2.dir}`;
742
+ groups.set(key, [...groups.get(key) ?? [], record2]);
743
+ }
744
+ return [...groups.entries()].map(([key, list]) => {
745
+ const ran = list.filter((record2) => record2.outcome === "ran");
746
+ const pick = (share) => Object.fromEntries(
747
+ METRICS.map((metric) => [
748
+ metric,
749
+ percentile(
750
+ ran.map((record2) => record2[metric]),
751
+ share
752
+ )
753
+ ])
754
+ );
755
+ return {
756
+ signature: key,
757
+ samples: ran.length,
758
+ failed: ran.filter((record2) => record2.exit !== 0).length,
759
+ timeouts: list.length - ran.length,
760
+ p50: pick(0.5),
761
+ p90: pick(0.9)
762
+ };
763
+ }).sort(
764
+ (a, b) => b.samples - a.samples || a.signature.localeCompare(b.signature)
765
+ );
766
+ }
767
+ var Sampler = class {
768
+ constructor(proc = "/proc") {
769
+ this.proc = proc;
770
+ this.before = this.children();
771
+ }
772
+ proc;
773
+ ticks = 100;
774
+ before;
775
+ peakRss = 0;
776
+ io = /* @__PURE__ */ new Map();
777
+ cgroup = null;
778
+ cgroupIo = { read: 0, write: 0 };
779
+ cgroupPeak = 0;
780
+ children() {
781
+ try {
782
+ const stat = readFileSync5(`${this.proc}/self/stat`, "utf8");
783
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
784
+ return { user: Number(fields[13]), sys: Number(fields[14]) };
785
+ } catch {
786
+ return { user: 0, sys: 0 };
787
+ }
788
+ }
789
+ useCgroup(dir) {
790
+ this.cgroup = dir;
791
+ }
792
+ sample(root) {
793
+ if (this.cgroup) this.sampleCgroup(this.cgroup);
794
+ if (root === void 0) return;
795
+ const parents = /* @__PURE__ */ new Map();
796
+ let names = [];
797
+ try {
798
+ names = readdirSync(this.proc).filter((name) => /^\d+$/u.test(name));
799
+ } catch {
800
+ return;
801
+ }
802
+ for (const name of names) {
803
+ try {
804
+ const stat = readFileSync5(`${this.proc}/${name}/stat`, "utf8");
805
+ parents.set(
806
+ Number(name),
807
+ Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1])
808
+ );
809
+ } catch {
810
+ }
811
+ }
812
+ const inTree = (pid) => {
813
+ for (let at = pid, hops = 0; at > 1 && hops < 64; hops += 1) {
814
+ if (at === root) return true;
815
+ at = parents.get(at) ?? 0;
816
+ }
817
+ return false;
818
+ };
819
+ let rss = 0;
820
+ for (const pid of parents.keys()) {
821
+ if (!inTree(pid)) continue;
822
+ try {
823
+ const status = readFileSync5(`${this.proc}/${pid}/status`, "utf8");
824
+ rss += Number(status.match(/^VmRSS:\s+(\d+)/mu)?.[1] ?? 0);
825
+ const io2 = readFileSync5(`${this.proc}/${pid}/io`, "utf8");
826
+ const value = (key) => Number(io2.match(new RegExp(`^${key}: (\\d+)`, "mu"))?.[1] ?? 0);
827
+ this.io.set(pid, {
828
+ read: value("read_bytes"),
829
+ write: value("write_bytes")
830
+ });
831
+ } catch {
832
+ }
833
+ }
834
+ this.peakRss = Math.max(this.peakRss, rss);
835
+ }
836
+ sampleCgroup(dir) {
837
+ try {
838
+ const peak = Number(
839
+ readFileSync5(join4(dir, "memory.peak"), "utf8").trim()
840
+ );
841
+ if (peak > 0)
842
+ this.cgroupPeak = Math.max(this.cgroupPeak, Math.round(peak / 1024));
843
+ } catch {
844
+ }
845
+ try {
846
+ let read3 = 0;
847
+ let write = 0;
848
+ for (const line of readFileSync5(join4(dir, "io.stat"), "utf8").split(
849
+ "\n"
850
+ )) {
851
+ read3 += Number(line.match(/rbytes=(\d+)/u)?.[1] ?? 0);
852
+ write += Number(line.match(/wbytes=(\d+)/u)?.[1] ?? 0);
853
+ }
854
+ this.cgroupIo = { read: read3, write };
855
+ } catch {
856
+ }
857
+ }
858
+ finish() {
859
+ const after = this.children();
860
+ const cpu = {
861
+ user_s: Math.max(0, after.user - this.before.user) / this.ticks,
862
+ sys_s: Math.max(0, after.sys - this.before.sys) / this.ticks
863
+ };
864
+ if (this.cgroup && (this.cgroupPeak > 0 || this.cgroupIo.read + this.cgroupIo.write > 0))
865
+ return {
866
+ ...cpu,
867
+ max_rss_kb: this.cgroupPeak || this.peakRss,
868
+ read_bytes: this.cgroupIo.read,
869
+ write_bytes: this.cgroupIo.write,
870
+ source: "cgroup"
871
+ };
872
+ let read3 = 0;
873
+ let write = 0;
874
+ for (const value of this.io.values()) {
875
+ read3 += value.read;
876
+ write += value.write;
877
+ }
878
+ return {
879
+ ...cpu,
880
+ max_rss_kb: this.peakRss,
881
+ read_bytes: read3,
882
+ write_bytes: write,
883
+ source: "proc"
884
+ };
885
+ }
886
+ };
887
+
888
+ // src/lease/run.ts
889
+ function prefixed(argv, prefix) {
890
+ const name = (word = "") => word.slice(word.lastIndexOf("/") + 1);
891
+ return argv.length >= prefix.length && prefix.every((word, at) => (at === 0 ? name(argv[0]) : argv[at]) === word);
892
+ }
893
+ function laneFor(run2) {
894
+ const command = run2.settings.commands.find(
895
+ (entry) => prefixed(run2.argv, entry.argv)
896
+ );
897
+ const fromProfile = run2.profile === "gate" || run2.profile === "hook";
898
+ const lane = run2.lane ?? (fromProfile ? profileLane(run2.profile) : command?.lane ?? "interactive");
899
+ const tiny = run2.settings.tiny.some((prefix) => prefixed(run2.argv, prefix));
900
+ const weight = run2.weight ?? command?.weight ?? (tiny ? 0 : run2.settings.weights[lane]);
901
+ return { lane, weight };
902
+ }
903
+ var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
904
+ var HEAD = 2048;
905
+ function execute(argv, run2, extra, watch) {
906
+ const [bin, ...rest] = argv;
907
+ return new Promise((resolve) => {
908
+ const child = spawn(bin ?? "true", rest, {
909
+ cwd: run2.cwd,
910
+ env: { ...run2.env, ...extra },
911
+ stdio: ["inherit", "inherit", watch.stderrHead ? "pipe" : "inherit"]
912
+ });
913
+ let head = "";
914
+ child.stderr?.on("data", (chunk) => {
915
+ process.stderr.write(chunk);
916
+ if (head.length >= HEAD) return;
917
+ head += chunk.toString("utf8");
918
+ watch.stderrHead?.(head.slice(0, HEAD));
919
+ });
920
+ void watch.started?.();
921
+ const forward = (signal) => child.kill(signal);
922
+ for (const signal of SIGNALS) process.on(signal, forward);
923
+ const timer = setInterval(() => watch.tick(child.pid), 1e3);
924
+ const done = (code) => {
925
+ clearInterval(timer);
926
+ for (const signal of SIGNALS) process.off(signal, forward);
927
+ resolve(code);
928
+ };
929
+ child.on("error", (error) => {
930
+ run2.say(`${bin}: ${error.message}`);
931
+ done(127);
932
+ });
933
+ child.on("exit", (code, signal) => {
934
+ if (code !== null) return done(code);
935
+ done(128 + (signal && constants.signals[signal] || 15));
936
+ });
937
+ });
938
+ }
939
+ function holdWarner(run2, since) {
940
+ let warned = false;
941
+ return () => {
942
+ const held2 = epoch() - since;
943
+ if (warned || held2 < run2.settings.holdWarn) return;
944
+ warned = true;
945
+ run2.say(
946
+ `holding the host lease for ${held2}s (hold_warn ${run2.settings.holdWarn}s); others may be waiting`
947
+ );
948
+ };
949
+ }
950
+ var BECAUSE = {
951
+ queue: "the jobs ahead kept the budget",
952
+ parked: "this session already had a job queued in the lane (per_session)",
953
+ host: "the host stayed at hard_factor x a limit or more",
954
+ legacy: "a shell wrapper kept the whole lease"
955
+ };
956
+ function busyReason(busy2) {
957
+ return `gave up after ${busy2.waited}s in the ${busy2.lane} lane (position ${busy2.position}): ${BECAUSE[busy2.reason]}; ${busy2.host}`;
958
+ }
959
+ function record(run2, fields) {
960
+ const usage = {
961
+ at: (/* @__PURE__ */ new Date()).toISOString(),
962
+ signature: signature(run2.argv),
963
+ dir: packageDir(run2.cwd, run2.root ?? run2.cwd),
964
+ ...fields
965
+ };
966
+ appendUsage(leasePaths(run2.settings.dir).usage, usage, run2.settings.usageCap);
967
+ run2.onUsage?.(usage);
968
+ }
969
+ var CANCELLED_EXIT = 130;
970
+ var NOTHING = {
971
+ wall_s: 0,
972
+ user_s: 0,
973
+ sys_s: 0,
974
+ max_rss_kb: 0,
975
+ read_bytes: 0,
976
+ write_bytes: 0,
977
+ source: "none"
978
+ };
979
+ async function runHeavy(run2) {
980
+ const label = oneLine(run2.label || run2.argv.join(" "));
981
+ const { lane, weight } = laneFor(run2);
982
+ let outcome;
983
+ if (!run2.settings.enabled) {
984
+ run2.say("lease disabled ([host.lease] enabled = false); running now");
985
+ outcome = { kind: "disabled" };
986
+ } else {
987
+ outcome = acquireLease({ ...run2, label, lane, weight });
988
+ }
989
+ if (outcome.kind === "cancelled") {
990
+ record(run2, {
991
+ ...NOTHING,
992
+ lane,
993
+ weight,
994
+ start: "none",
995
+ outcome: "cancelled",
996
+ exit: CANCELLED_EXIT
997
+ });
998
+ return CANCELLED_EXIT;
999
+ }
1000
+ if (outcome.kind === "busy") {
1001
+ run2.say(`not run: host busy; ${busyReason(outcome)}`);
1002
+ if (outcome.lane === "bulk" && outcome.reason === "queue")
1003
+ run2.say(
1004
+ "a bulk job waits behind every gate, hook and interactive job; this one reached its max_wait"
1005
+ );
1006
+ run2.say(
1007
+ `run it again later, or set ${DISABLE_ENV}=<reason> to run beside it`
1008
+ );
1009
+ record(run2, {
1010
+ ...NOTHING,
1011
+ lane,
1012
+ weight,
1013
+ start: "none",
1014
+ outcome: "timeout",
1015
+ exit: BUSY_EXIT
1016
+ });
1017
+ return BUSY_EXIT;
1018
+ }
1019
+ const memoryMax = run2.settings.profiles[run2.profile]?.memoryMax;
1020
+ const held2 = outcome.kind === "held" ? outcome : null;
1021
+ const sampler = new Sampler();
1022
+ const { argv, started, unscoped } = scoped(
1023
+ run2.argv,
1024
+ run2.settings,
1025
+ held2 ? lane : null,
1026
+ memoryMax,
1027
+ run2.say,
1028
+ (dir) => sampler.useCgroup(dir),
1029
+ void 0,
1030
+ void 0,
1031
+ run2.env
1032
+ );
1033
+ const warn = held2 ? holdWarner(run2, epoch()) : () => {
1034
+ };
1035
+ const tick = (pid) => {
1036
+ warn();
1037
+ sampler.sample(pid);
1038
+ };
1039
+ const begun = Date.now();
1040
+ let code = 1;
1041
+ let head = "";
1042
+ try {
1043
+ code = await execute(argv, run2, held2?.env ?? {}, {
1044
+ tick,
1045
+ ...started ? { started } : {},
1046
+ ...unscoped ? { stderrHead: (text) => head = text } : {}
1047
+ });
1048
+ if (code !== 0 && unscoped && BUS_FAILURE.test(head.split("\n")[0] ?? "")) {
1049
+ run2.say(
1050
+ "systemd-run could not reach the user manager; running the command again without the scope"
1051
+ );
1052
+ code = await execute(unscoped, run2, held2?.env ?? {}, { tick });
1053
+ }
1054
+ } finally {
1055
+ const wall = Math.round((Date.now() - begun) / 100) / 10;
1056
+ held2?.release(code, Math.round(wall));
1057
+ if (outcome.kind !== "disabled")
1058
+ record(run2, {
1059
+ ...sampler.finish(),
1060
+ wall_s: wall,
1061
+ lane,
1062
+ weight,
1063
+ start: held2 ? held2.start : "none",
1064
+ outcome: "ran",
1065
+ exit: code
1066
+ });
1067
+ }
1068
+ return code;
1069
+ }
1070
+
1071
+ // src/lease/status.ts
1072
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync7 } from "fs";
1073
+
1074
+ // src/lease/estimate.ts
1075
+ import { closeSync as closeSync3, fstatSync, openSync as openSync3, readSync } from "fs";
1076
+ var TAIL_BYTES = 512 * 1024;
1077
+ function tail(file) {
1078
+ let fd;
1079
+ try {
1080
+ fd = openSync3(file, "r");
1081
+ } catch {
1082
+ return "";
1083
+ }
1084
+ try {
1085
+ const size = fstatSync(fd).size;
1086
+ const length = Math.min(size, TAIL_BYTES);
1087
+ const buffer = Buffer.alloc(length);
1088
+ readSync(fd, buffer, 0, length, size - length);
1089
+ return buffer.toString("utf8");
1090
+ } finally {
1091
+ closeSync3(fd);
1092
+ }
1093
+ }
1094
+ function median(values) {
1095
+ if (values.length === 0) return void 0;
1096
+ const sorted = [...values].sort((a, b) => a - b);
1097
+ return sorted[Math.floor(sorted.length / 2)];
1098
+ }
1099
+ function logLines(log) {
1100
+ return tail(log).split("\n").map((line) => line.split(" ")).filter((fields) => fields.length >= 4);
1101
+ }
1102
+ function runMedians(lines) {
1103
+ const open = /* @__PURE__ */ new Map();
1104
+ const runs = { all: [] };
1105
+ for (const [, pid = "", event, detail = ""] of lines) {
1106
+ if (event === "acquired") {
1107
+ const named = detail.match(/ lane=(\w+)/u)?.[1];
1108
+ open.set(pid, LANES.includes(named) ? named : "interactive");
1109
+ } else if (event === "released") {
1110
+ const lane = open.get(pid);
1111
+ const ran = Number(detail.match(/^ran=(\d+)/u)?.[1]);
1112
+ if (lane === void 0 || !Number.isFinite(ran)) continue;
1113
+ open.delete(pid);
1114
+ (runs[lane] ??= []).push(ran);
1115
+ runs["all"].push(ran);
1116
+ }
1117
+ }
1118
+ const found = {};
1119
+ for (const [key, values] of Object.entries(runs)) {
1120
+ const value = median(values);
1121
+ if (value !== void 0) found[key] = value;
1122
+ }
1123
+ return found;
1124
+ }
1125
+ function graceRuns(lines, now = Date.now()) {
1126
+ const recent = lines.filter(
1127
+ ([stamp = "", , event]) => event === "grace" && now - Date.parse(stamp) <= 864e5
1128
+ );
1129
+ const last = recent.at(-1);
1130
+ return {
1131
+ count: recent.length,
1132
+ last: last ? `${last[0]} (${last[3]})` : null
1133
+ };
1134
+ }
1135
+ function etas(medians, budget, running, waiters, now) {
1136
+ if (medians["all"] === void 0) return waiters.map(() => null);
1137
+ const typical = (lane) => medians[lane] ?? medians["all"] ?? 0;
1138
+ let work = running.reduce(
1139
+ (sum, job2) => sum + Math.max(0, typical(job2.lane) - (now - job2.since)) * job2.weight,
1140
+ 0
1141
+ );
1142
+ return waiters.map((waiter) => {
1143
+ const mine = Math.round(work / Math.max(1, budget));
1144
+ work += typical(waiter.lane) * waiter.weight;
1145
+ return mine;
1146
+ });
1147
+ }
1148
+
1149
+ // src/lease/procs.ts
1150
+ import { readFileSync as readFileSync6, readdirSync as readdirSync2 } from "fs";
1151
+ var TICKS_PER_SECOND = 100;
1152
+ function read2(file) {
1153
+ try {
1154
+ return readFileSync6(file, "utf8");
1155
+ } catch {
1156
+ return null;
1157
+ }
1158
+ }
1159
+ function sample(proc) {
1160
+ const found = /* @__PURE__ */ new Map();
1161
+ let names;
1162
+ try {
1163
+ names = readdirSync2(proc);
1164
+ } catch {
1165
+ return found;
1166
+ }
1167
+ for (const name of names) {
1168
+ if (!/^\d+$/u.test(name)) continue;
1169
+ const stat = read2(`${proc}/${name}/stat`);
1170
+ if (stat === null) continue;
1171
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
1172
+ const io2 = read2(`${proc}/${name}/io`) ?? "";
1173
+ const bytes = (key) => Number(io2.match(new RegExp(`^${key}: (\\d+)`, "mu"))?.[1] ?? 0);
1174
+ found.set(Number(name), {
1175
+ ppid: Number(fields[1]),
1176
+ ticks: Number(fields[11]) + Number(fields[12]),
1177
+ bytes: bytes("read_bytes") + bytes("write_bytes")
1178
+ });
1179
+ }
1180
+ return found;
1181
+ }
1182
+ function under(pid, roots, all) {
1183
+ for (let at = pid, hops = 0; at > 1 && hops < 64; hops += 1) {
1184
+ if (roots.has(at)) return true;
1185
+ at = all.get(at)?.ppid ?? 0;
1186
+ }
1187
+ return false;
1188
+ }
1189
+ function outsideLease(options) {
1190
+ const proc = options.proc ?? "/proc";
1191
+ const interval = options.interval ?? 1;
1192
+ const before = sample(proc);
1193
+ if (before.size === 0) return [];
1194
+ sleepSeconds(interval);
1195
+ const after = sample(proc);
1196
+ const roots = /* @__PURE__ */ new Set([process.pid]);
1197
+ for (const pid of options.holders) roots.add(pid);
1198
+ const found = [];
1199
+ for (const [pid, now] of after) {
1200
+ const then = before.get(pid);
1201
+ if (then === void 0 || now.ppid === 2 || pid === 2) continue;
1202
+ if (under(pid, roots, after)) continue;
1203
+ const cpu = (now.ticks - then.ticks) / TICKS_PER_SECOND / interval * 100;
1204
+ const ioMbps = (now.bytes - then.bytes) / interval / 1e6;
1205
+ if (cpu < 20 && ioMbps < 5) continue;
1206
+ const command = (read2(`${proc}/${pid}/cmdline`) ?? "").split("\0").join(" ").trim().slice(0, 100);
1207
+ found.push({ pid, cpu, ioMbps, command });
1208
+ }
1209
+ return found.sort((a, b) => b.cpu + b.ioMbps * 10 - (a.cpu + a.ioMbps * 10)).slice(0, options.limit ?? 5);
1210
+ }
1211
+
1212
+ // src/lease/status.ts
1213
+ function hostLine(settings2, load, io2) {
1214
+ return `host: load1 ${load ?? "n/a"} (max ${settings2.maxLoad}), io some avg10 ${io2 ?? "n/a"} (max ${settings2.maxIo})`;
1215
+ }
1216
+ function holdLine(settings2, job2) {
1217
+ const held2 = epoch() - job2.since;
1218
+ const limits = `warn ${settings2.holdWarn}s${settings2.holdMax ? `, max ${settings2.holdMax}s` : ""}`;
1219
+ let verdict = "ok";
1220
+ if (held2 >= settings2.holdWarn) verdict = "warning: over hold_warn";
1221
+ if (settings2.holdMax && held2 >= settings2.holdMax)
1222
+ verdict = "over-limit: over hold_max";
1223
+ return `hold: pid ${job2.pid} ${held2}s (${limits}) ${verdict} lane ${job2.lane} weight ${job2.weight}`;
1224
+ }
1225
+ function outsideLines(found) {
1226
+ if (found.length === 0) return ["outside: none"];
1227
+ return found.map(
1228
+ (item) => `outside: pid ${item.pid} cpu ${item.cpu.toFixed(0)}% io ${item.ioMbps.toFixed(1)}MB/s ${item.command}`
1229
+ );
1230
+ }
1231
+ function settledLine(settings2, env) {
1232
+ const paths = leasePaths(settings2.dir);
1233
+ if (hostSettled(settings2, paths, hostSources(env))) return "settled: now";
1234
+ let last = "never";
1235
+ try {
1236
+ last = readFileSync7(paths.settled, "utf8").trim() || "never";
1237
+ } catch {
1238
+ }
1239
+ return `settled: last seen ${last}`;
1240
+ }
1241
+ function leaseStatus(options) {
1242
+ const { settings: settings2, env } = options;
1243
+ const paths = leasePaths(settings2.dir);
1244
+ const reading = readHost(hostSources(env));
1245
+ const host = hostLine(settings2, reading.load, reading.io);
1246
+ if (!settings2.enabled)
1247
+ return ["lease: disabled ([host.lease] enabled = false)", host];
1248
+ try {
1249
+ mkdirSync2(paths.dir, { recursive: true });
1250
+ } catch {
1251
+ }
1252
+ const lines = [`lease: ${paths.lock}`, host, settledLine(settings2, env)];
1253
+ const held2 = leaseHeld(paths);
1254
+ lines.push(
1255
+ held2 ? `holder: ${describeRecord(readRecord(paths.holder))}` : "holder: none"
1256
+ );
1257
+ const { running, waiters } = readQueue(paths);
1258
+ const log = logLines(paths.log);
1259
+ const eta = etas(runMedians(log), settings2.budget, running, waiters, epoch());
1260
+ waiters.forEach((waiter, at) => {
1261
+ const guess = eta[at];
1262
+ const tail2 = guess === null || guess === void 0 ? "" : ` eta ~${guess}s`;
1263
+ lines.push(
1264
+ `waiter: ${describeRecord(waiter)} lane ${waiter.lane} weight ${waiter.weight} position ${at + 1}${tail2}${waiter.id ? ` id ${waiter.id}` : ""}`
1265
+ );
1266
+ });
1267
+ if (waiters.length === 0) lines.push("waiters: none");
1268
+ lines.push(`lanes: ${laneUse(settings2, running)}`);
1269
+ for (const job2 of running) lines.push(`running: ${describeRecord(job2)}`);
1270
+ for (const job2 of running.filter((entry) => entry.bypass))
1271
+ lines.push(
1272
+ `bypass running: pid ${job2.pid}, reason ${job2.bypass}, since ${epoch() - job2.since}s`
1273
+ );
1274
+ for (const job2 of running) lines.push(holdLine(settings2, job2));
1275
+ const window = reading.pressure[settings2.ioWindow] ?? "n/a";
1276
+ lines.push(
1277
+ `io: the host check reads some ${settings2.ioWindow} ${window} (max ${settings2.maxIo}, hard ${settings2.maxIo * settings2.hardFactor})`
1278
+ );
1279
+ const grace = graceRuns(log);
1280
+ lines.push(
1281
+ grace.count === 0 ? "grace: no job started on load_grace in the last 24h" : `grace: ${grace.count} job(s) started on load_grace in the last 24h, last ${grace.last}`
1282
+ );
1283
+ const outside = options.outside ?? ((pids) => outsideLease({ holders: pids }));
1284
+ lines.push(...outsideLines(outside(running.map((job2) => job2.pid))));
1285
+ const skip = skipReason(settings2, env);
1286
+ if (skip !== null)
1287
+ lines.push(
1288
+ `skip: this shell runs without the lease (${DISABLE_ENV}): ${skip}`
1289
+ );
1290
+ return lines;
1291
+ }
1292
+
1293
+ // src/lease/tickets.ts
1294
+ import { randomBytes } from "crypto";
1295
+ import {
1296
+ mkdirSync as mkdirSync3,
1297
+ openSync as openSync4,
1298
+ closeSync as closeSync4,
1299
+ readFileSync as readFileSync8,
1300
+ readdirSync as readdirSync3,
1301
+ renameSync as renameSync2,
1302
+ rmSync as rmSync2,
1303
+ statSync as statSync2,
1304
+ writeFileSync as writeFileSync4
1305
+ } from "fs";
1306
+ import { join as join5 } from "path";
1307
+ import { spawn as spawn2 } from "child_process";
1308
+ function ticketExists(dir, id) {
1309
+ try {
1310
+ return readJson(join5(ticketDir(dir, id), "request.json")) !== null;
1311
+ } catch {
1312
+ return false;
1313
+ }
1314
+ }
1315
+ var ID = /^\d{10}-[0-9a-f]{6}$/u;
1316
+ var KEEP_MS = 7 * 864e5;
1317
+ function ticketsDir(dir) {
1318
+ return join5(dir, "tickets");
1319
+ }
1320
+ function ticketDir(dir, id) {
1321
+ if (!ID.test(id)) throw new Error(`not a ticket id: ${id}`);
1322
+ return join5(ticketsDir(dir), id);
1323
+ }
1324
+ function readJson(file) {
1325
+ try {
1326
+ return JSON.parse(readFileSync8(file, "utf8"));
1327
+ } catch {
1328
+ return null;
1329
+ }
1330
+ }
1331
+ function writeJson(file, value) {
1332
+ const temporary = `${file}.tmp.${process.pid}`;
1333
+ writeFileSync4(temporary, `${JSON.stringify(value)}
1334
+ `);
1335
+ renameSync2(temporary, file);
1336
+ }
1337
+ function writeResult(dir, id, result, keepExisting = false) {
1338
+ const file = join5(ticketDir(dir, id), "result.json");
1339
+ if (keepExisting && readJson(file) !== null) return;
1340
+ writeJson(file, result);
1341
+ }
1342
+ function prune(dir) {
1343
+ let names = [];
1344
+ try {
1345
+ names = readdirSync3(ticketsDir(dir));
1346
+ } catch {
1347
+ return;
1348
+ }
1349
+ for (const name of names) {
1350
+ const path = join5(ticketsDir(dir), name);
1351
+ try {
1352
+ const done = statSync2(join5(path, "result.json"));
1353
+ if (Date.now() - done.mtimeMs > KEEP_MS)
1354
+ rmSync2(path, { recursive: true, force: true });
1355
+ } catch {
1356
+ }
1357
+ }
1358
+ }
1359
+ function submit(request) {
1360
+ prune(request.dir);
1361
+ const id = `${Math.floor(Date.now() / 1e3)}-${randomBytes(3).toString("hex")}`;
1362
+ const path = ticketDir(request.dir, id);
1363
+ mkdirSync3(path, { recursive: true });
1364
+ writeJson(join5(path, "request.json"), {
1365
+ version: 1,
1366
+ ticket: id,
1367
+ label: request.label,
1368
+ cwd: request.cwd,
1369
+ created: (/* @__PURE__ */ new Date()).toISOString()
1370
+ });
1371
+ const log = openSync4(join5(path, "log"), "a");
1372
+ const [bin, ...args] = request.runner(id);
1373
+ const child = spawn2(bin, args, {
1374
+ cwd: request.cwd,
1375
+ env: request.env,
1376
+ detached: true,
1377
+ stdio: ["ignore", log, log]
1378
+ });
1379
+ closeSync4(log);
1380
+ writeFileSync4(join5(path, "pid"), `${child.pid}
1381
+ `);
1382
+ child.unref();
1383
+ return id;
1384
+ }
1385
+ function ticketView(dir, id) {
1386
+ const path = ticketDir(dir, id);
1387
+ const request = readJson(join5(path, "request.json"));
1388
+ if (request === null) return null;
1389
+ const result = readJson(join5(path, "result.json"));
1390
+ const pidText = readJson(join5(path, "pid"));
1391
+ const pid = typeof pidText === "number" && pidText > 0 ? pidText : null;
1392
+ const base = { id, label: request.label, pid, result };
1393
+ if (result) return { ...base, state: "done", position: null };
1394
+ if (pid === null) return { ...base, state: "queued", position: null };
1395
+ if (!pidAlive(pid)) return { ...base, state: "lost", position: null };
1396
+ const paths = leasePaths(dir);
1397
+ const waiting = liveRecords(paths.waiters, false).findIndex(
1398
+ (r) => r.pid === pid
1399
+ );
1400
+ if (waiting >= 0) return { ...base, state: "queued", position: waiting + 1 };
1401
+ const running = liveRecords(paths.running, false).some((r) => r.pid === pid);
1402
+ return { ...base, state: running ? "running" : "queued", position: null };
1403
+ }
1404
+ function recentTickets(dir) {
1405
+ let names = [];
1406
+ try {
1407
+ names = readdirSync3(ticketsDir(dir)).filter((name) => ID.test(name));
1408
+ } catch {
1409
+ return [];
1410
+ }
1411
+ return names.sort().map((name) => ticketView(dir, name)).filter((view) => {
1412
+ if (view === null) return false;
1413
+ if (view.state !== "done") return true;
1414
+ try {
1415
+ const done = statSync2(join5(ticketDir(dir, view.id), "result.json"));
1416
+ return Date.now() - done.mtimeMs < 36e5;
1417
+ } catch {
1418
+ return false;
1419
+ }
1420
+ });
1421
+ }
1422
+ function logTail(dir, id, lines = 20) {
1423
+ try {
1424
+ const text = readFileSync8(join5(ticketDir(dir, id), "log"), "utf8");
1425
+ return text.split("\n").slice(-lines - 1).join("\n");
1426
+ } catch {
1427
+ return "";
1428
+ }
1429
+ }
1430
+ function cancel(dir, id, force) {
1431
+ const view = ticketView(dir, id);
1432
+ if (view === null) return "unknown";
1433
+ if (view.state === "done") return "done";
1434
+ if (view.state === "running" && !force) return "running";
1435
+ if (view.pid !== null && pidAlive(view.pid)) {
1436
+ try {
1437
+ process.kill(-view.pid, "SIGTERM");
1438
+ } catch {
1439
+ process.kill(view.pid, "SIGTERM");
1440
+ }
1441
+ }
1442
+ writeResult(dir, id, {
1443
+ version: 1,
1444
+ ticket: id,
1445
+ exit: 130,
1446
+ outcome: "cancelled"
1447
+ });
1448
+ return "cancelled";
1449
+ }
1450
+
1451
+ // src/lease/status-json.ts
1452
+ var STATUS_SCHEMA = "pmcp.heavy.status.v1";
1453
+ function flags(settings2, job2, now) {
1454
+ const held2 = now - job2.since;
1455
+ return [
1456
+ ...job2.grace ? ["grace"] : [],
1457
+ ...job2.bypass ? ["bypass"] : [],
1458
+ ...held2 >= settings2.holdWarn ? ["over_hold_warn"] : [],
1459
+ ...settings2.holdMax && held2 >= settings2.holdMax ? ["over_hold_max"] : []
1460
+ ];
1461
+ }
1462
+ function job(settings2, record2, now) {
1463
+ return {
1464
+ id: record2.id || null,
1465
+ pid: record2.pid,
1466
+ label: record2.label,
1467
+ cwd: record2.cwd,
1468
+ lane: record2.lane,
1469
+ weight: record2.weight,
1470
+ session: record2.session || null,
1471
+ started: record2.started,
1472
+ running_s: now - record2.since,
1473
+ flags: flags(settings2, record2, now),
1474
+ bypass_reason: record2.bypass || null
1475
+ };
1476
+ }
1477
+ function number(value) {
1478
+ return value === null || value === void 0 ? null : Number(value);
1479
+ }
1480
+ function statusJson(settings2, env, outside = (pids) => outsideLease({ holders: pids, interval: 0.25 })) {
1481
+ const paths = leasePaths(settings2.dir);
1482
+ const reading = readHost(hostSources(env));
1483
+ const now = epoch();
1484
+ const { running, waiters } = settings2.enabled ? readQueue(paths, false) : { running: [], waiters: [] };
1485
+ const log = settings2.enabled ? logLines(paths.log) : [];
1486
+ const eta = etas(runMedians(log), settings2.budget, running, waiters, now);
1487
+ return {
1488
+ version: 1,
1489
+ schema: STATUS_SCHEMA,
1490
+ enabled: settings2.enabled,
1491
+ dir: settings2.dir,
1492
+ budget: settings2.budget,
1493
+ running_weight: runningWeight(running),
1494
+ // A shell wrapper holds the lock file exclusively and counts as the whole budget.
1495
+ legacy_holder: settings2.enabled && running.length === 0 && leaseHeld(paths),
1496
+ host: {
1497
+ load1: number(reading.load),
1498
+ io_some_avg10: number(reading.pressure["avg10"]),
1499
+ io_some_avg60: number(reading.pressure["avg60"]),
1500
+ io_some_avg300: number(reading.pressure["avg300"]),
1501
+ io_window: settings2.ioWindow,
1502
+ max_load: settings2.maxLoad,
1503
+ max_io: settings2.maxIo,
1504
+ hard_factor: settings2.hardFactor,
1505
+ settled: settled(settings2, reading)
1506
+ },
1507
+ lanes: LANES.map((lane) => ({
1508
+ lane,
1509
+ slots: settings2.slots[lane],
1510
+ running: running.filter((record2) => record2.lane === lane).map((record2) => job(settings2, record2, now))
1511
+ })),
1512
+ waiters: waiters.map((record2, at) => ({
1513
+ id: record2.id || null,
1514
+ pid: record2.pid,
1515
+ label: record2.label,
1516
+ cwd: record2.cwd,
1517
+ lane: record2.lane,
1518
+ weight: record2.weight,
1519
+ session: record2.session || null,
1520
+ position: at + 1,
1521
+ waited_s: now - record2.since,
1522
+ eta_s: eta[at] ?? null
1523
+ })),
1524
+ tickets: settings2.enabled ? recentTickets(settings2.dir).map((view) => ({
1525
+ id: view.id,
1526
+ state: view.state,
1527
+ position: view.position,
1528
+ label: view.label,
1529
+ pid: view.pid,
1530
+ exit: view.result?.exit ?? null
1531
+ })) : [],
1532
+ grace_24h: graceRuns(log),
1533
+ outside: settings2.enabled ? outside(running.map((record2) => record2.pid)).map((item) => ({
1534
+ pid: item.pid,
1535
+ cpu_percent: Math.round(item.cpu),
1536
+ io_mbps: Math.round(item.ioMbps * 10) / 10,
1537
+ command: item.command
1538
+ })) : [],
1539
+ skip: skipReason(settings2, env)
1540
+ };
1541
+ }
1542
+
1543
+ // src/lease/control.ts
1544
+ import { readdirSync as readdirSync4 } from "fs";
1545
+ import { join as join6 } from "path";
1546
+ function find(paths, dir, id) {
1547
+ let names = [];
1548
+ try {
1549
+ names = readdirSync4(dir).filter((name) => /^\d+$/u.test(name));
1550
+ } catch {
1551
+ return null;
1552
+ }
1553
+ for (const name of names) {
1554
+ const record2 = readRecord(join6(dir, name));
1555
+ if (record2?.id === id) return { file: join6(dir, name), record: record2 };
1556
+ }
1557
+ return null;
1558
+ }
1559
+ function findRunning(paths, id) {
1560
+ return liveRecords(paths.running, false).find((r) => r.id === id) ?? null;
1561
+ }
1562
+ function rewrite(file, record2, change2) {
1563
+ const next = { ...record2, ...change2 };
1564
+ writeRecord(file, next.pid, {
1565
+ cwd: next.cwd,
1566
+ label: next.label,
1567
+ lane: next.lane,
1568
+ weight: next.weight,
1569
+ session: next.session,
1570
+ queued: next.queued,
1571
+ since: next.since,
1572
+ started: next.started,
1573
+ ...next.id ? { id: next.id } : {},
1574
+ ...next.promote ? { promote: next.promote } : {},
1575
+ ...next.cancel ? { cancel: next.cancel } : {}
1576
+ });
1577
+ return next;
1578
+ }
1579
+ function logged(paths, record2, who2, what, reason2) {
1580
+ const by = `uid:${who2.uid ?? "?"}${who2.session ? ` session=${who2.session}` : ""}`;
1581
+ logEvent(
1582
+ paths,
1583
+ record2.pid,
1584
+ "control",
1585
+ `id=${record2.id} ${what} by=${by} reason=${reason2}`
1586
+ );
1587
+ }
1588
+ function change(paths, id, who2, reason2, what) {
1589
+ const done = underAdmitLock(paths, () => {
1590
+ const found = find(paths, paths.waiters, id);
1591
+ if (found === null) return { ok: false, why: `no waiting job ${id}` };
1592
+ const waiters = liveRecords(paths.waiters);
1593
+ if (!waiters.some((r) => r.pid === found.record.pid))
1594
+ return { ok: false, why: `${id} had died; its record was removed` };
1595
+ const decided = what(found.record, waiters);
1596
+ if (typeof decided === "string") return { ok: false, why: decided };
1597
+ const [fields, description] = decided;
1598
+ const record2 = rewrite(found.file, found.record, fields);
1599
+ logged(paths, record2, who2, description, reason2);
1600
+ return { ok: true, record: record2 };
1601
+ });
1602
+ return done ?? { ok: false, why: "the admission lock stayed busy" };
1603
+ }
1604
+ function promote(paths, id, who2, reason2) {
1605
+ return change(paths, id, who2, reason2, () => [
1606
+ { promote: reason2 },
1607
+ "action=promote"
1608
+ ]);
1609
+ }
1610
+ function cancelWaiter(paths, id, who2, reason2) {
1611
+ return change(paths, id, who2, reason2, () => [
1612
+ { cancel: reason2 },
1613
+ "action=cancel"
1614
+ ]);
1615
+ }
1616
+ function reprioritize(paths, id, to, who2, reason2) {
1617
+ return change(paths, id, who2, reason2, (record2, waiters) => {
1618
+ if (LANES.includes(to))
1619
+ return [
1620
+ { lane: to, queued: Date.now() },
1621
+ `action=priority from=${record2.lane} to=${to}`
1622
+ ];
1623
+ const step = /^[+-]\d+$/u.test(to) ? Number(to) : NaN;
1624
+ if (!Number.isInteger(step) || step === 0)
1625
+ return `priority is a lane (${LANES.join(", ")}) or +N/-N, not ${to}`;
1626
+ const lane = waiters.filter((r) => r.lane === record2.lane);
1627
+ const at = lane.findIndex((r) => r.pid === record2.pid);
1628
+ const target = Math.max(0, Math.min(lane.length - 1, at - step));
1629
+ if (target === at) return [{}, `action=priority ${to} (already there)`];
1630
+ const other = lane[target];
1631
+ const queued = target < at ? other.queued - 1 : other.queued + 1;
1632
+ return [
1633
+ { queued },
1634
+ `action=priority ${to} position=${at + 1}->${target + 1}`
1635
+ ];
1636
+ });
1637
+ }
1638
+
1639
+ // src/commands/heavy-queue.ts
1640
+ function who(context) {
1641
+ return {
1642
+ uid: process.getuid?.() ?? null,
1643
+ session: sessionOf(context.env, context.cwd)
1644
+ };
1645
+ }
1646
+ function reason(context, required) {
1647
+ const text = one(context.args, "reason")?.trim() ?? "";
1648
+ if (required && !text)
1649
+ throw new ArgumentError("say why with --reason <text>");
1650
+ return text || "none given";
1651
+ }
1652
+ function report(context, result) {
1653
+ if (!result.ok) {
1654
+ context.ui.error(result.why);
1655
+ return EXIT.failure;
1656
+ }
1657
+ context.ui.data(
1658
+ `${result.record.id} ${result.record.lane} ${result.record.label}
1659
+ `
1660
+ );
1661
+ return EXIT.ok;
1662
+ }
1663
+ function queueList(context, settings2) {
1664
+ const snapshot = statusJson(settings2, context.env, () => []);
1665
+ if (context.args.flags.has("json")) {
1666
+ const { version, schema, waiters } = snapshot;
1667
+ context.ui.data(`${JSON.stringify({ version, schema, waiters })}
1668
+ `);
1669
+ return EXIT.ok;
1670
+ }
1671
+ if (snapshot.waiters.length === 0) context.ui.data("queue: empty\n");
1672
+ for (const w of snapshot.waiters)
1673
+ context.ui.data(
1674
+ `${w.id} ${w.lane} position ${w.position} waited ${w.waited_s}s eta ${w.eta_s ?? "?"}s weight ${w.weight} pid ${w.pid} ${w.session ?? "-"} ${w.label}
1675
+ `
1676
+ );
1677
+ return EXIT.ok;
1678
+ }
1679
+ function queuePromote(context, settings2, id) {
1680
+ if (id === void 0) throw new ArgumentError("name the job id");
1681
+ if (!context.args.flags.has("now"))
1682
+ throw new ArgumentError(
1683
+ "promote starts a job at once: pass --now --reason <text>"
1684
+ );
1685
+ const paths = leasePaths(settings2.dir);
1686
+ return report(
1687
+ context,
1688
+ promote(paths, id, who(context), reason(context, true))
1689
+ );
1690
+ }
1691
+ function queuePriority(context, settings2, id, to) {
1692
+ if (id === void 0 || to === void 0)
1693
+ throw new ArgumentError(
1694
+ "pmcp heavy priority <id> <lane|+N|-N> --reason <text>"
1695
+ );
1696
+ const paths = leasePaths(settings2.dir);
1697
+ return report(
1698
+ context,
1699
+ reprioritize(paths, id, to, who(context), reason(context, true))
1700
+ );
1701
+ }
1702
+ function queueCancel(context, settings2, id) {
1703
+ if (id === void 0) throw new ArgumentError("name the job id");
1704
+ const paths = leasePaths(settings2.dir);
1705
+ const because = reason(context, false);
1706
+ const ticket = /^\d{10}-[0-9a-f]{6}$/u.test(id) && ticketExists(settings2.dir, id);
1707
+ const waiting = cancelWaiter(paths, id, who(context), because);
1708
+ if (waiting.ok) {
1709
+ if (ticket)
1710
+ writeResult(settings2.dir, id, {
1711
+ version: 1,
1712
+ ticket: id,
1713
+ exit: 130,
1714
+ outcome: "cancelled"
1715
+ });
1716
+ context.ui.data(`${id} cancelled
1717
+ `);
1718
+ return EXIT.ok;
1719
+ }
1720
+ const running = findRunning(paths, id);
1721
+ if (running !== null && !ticket) {
1722
+ if (!context.args.flags.has("force")) {
1723
+ context.ui.error(`${id} is running; --force stops it`);
1724
+ return EXIT.failure;
1725
+ }
1726
+ process.kill(running.pid, "SIGTERM");
1727
+ context.ui.data(`${id} stopped
1728
+ `);
1729
+ return EXIT.ok;
1730
+ }
1731
+ if (!ticket) {
1732
+ context.ui.error(waiting.why);
1733
+ return EXIT.failure;
1734
+ }
1735
+ const done = cancel(settings2.dir, id, context.args.flags.has("force"));
1736
+ if (done === "running") {
1737
+ context.ui.error(`${id} is running; --force stops it`);
1738
+ return EXIT.failure;
1739
+ }
1740
+ context.ui.data(`${id} ${done}
1741
+ `);
1742
+ return done === "cancelled" ? EXIT.ok : EXIT.failure;
1743
+ }
1744
+
1745
+ // src/commands/heavy-tickets.ts
1746
+ var PASSED = ["config", "label", "profile", "lane", "weight"];
1747
+ function submitTicket(context, settings2, command) {
1748
+ const flags2 = PASSED.flatMap((name) => {
1749
+ const value = one(context.args, name);
1750
+ return value === void 0 ? [] : [`--${name}`, value];
1751
+ });
1752
+ const self = [process.execPath, ...process.execArgv, process.argv[1] ?? ""];
1753
+ const id = submit({
1754
+ dir: settings2.dir,
1755
+ label: one(context.args, "label") ?? command.join(" "),
1756
+ runner: (ticket) => [
1757
+ ...self,
1758
+ "heavy",
1759
+ ...flags2,
1760
+ "--ticket",
1761
+ ticket,
1762
+ "--",
1763
+ ...command
1764
+ ],
1765
+ cwd: context.cwd,
1766
+ env: context.env
1767
+ });
1768
+ context.ui.data(`${id}
1769
+ `);
1770
+ return EXIT.ok;
1771
+ }
1772
+ function describe(view) {
1773
+ const where = view.position === null ? "" : ` position ${view.position}`;
1774
+ const result = view.result ? ` exit ${view.result.exit} (${view.result.outcome})` : "";
1775
+ return `${view.id} ${view.state}${where}${result} ${view.label}`;
1776
+ }
1777
+ function viewOf(settings2, id) {
1778
+ if (id === void 0) throw new ArgumentError("name the ticket");
1779
+ let view;
1780
+ try {
1781
+ view = ticketView(settings2.dir, id);
1782
+ } catch (error) {
1783
+ throw new ArgumentError(error.message);
1784
+ }
1785
+ if (view === null) throw new ArgumentError(`no ticket ${id}`);
1786
+ return view;
1787
+ }
1788
+ function ticketResult(context, settings2, id) {
1789
+ const view = viewOf(settings2, id);
1790
+ if (context.args.flags.has("json"))
1791
+ context.ui.data(`${JSON.stringify({ version: 1, ...view })}
1792
+ `);
1793
+ else context.ui.data(`${describe(view)}
1794
+ `);
1795
+ return EXIT.ok;
1796
+ }
1797
+ async function ticketWait(context, settings2, id) {
1798
+ const text = one(context.args, "timeout");
1799
+ const timeout = text === void 0 ? Infinity : Number(text);
1800
+ if (!(timeout > 0)) throw new ArgumentError("--timeout must be positive");
1801
+ const deadline = Date.now() + timeout * 1e3;
1802
+ let view = viewOf(settings2, id);
1803
+ while (view.state === "queued" || view.state === "running") {
1804
+ if (Date.now() >= deadline) {
1805
+ context.ui.error(`${view.id} is still ${view.state}`);
1806
+ return BUSY_EXIT;
1807
+ }
1808
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
1809
+ view = viewOf(settings2, view.id);
1810
+ }
1811
+ const tail2 = logTail(settings2.dir, view.id);
1812
+ if (tail2.trim()) process.stderr.write(`${tail2}
1813
+ `);
1814
+ context.ui.data(`${describe(view)}
1815
+ `);
1816
+ if (view.state === "lost") return EXIT.failure;
1817
+ return view.result?.exit ?? EXIT.failure;
1818
+ }
1819
+
1820
+ // src/commands/heavy.ts
1821
+ function settings(context) {
1822
+ try {
1823
+ return leaseSettingsFor(context.cwd, one(context.args, "config"));
1824
+ } catch (error) {
1825
+ if (error instanceof ConfigError) throw new ArgumentError(error.message);
1826
+ throw error;
1827
+ }
1828
+ }
1829
+ function statLine(stat) {
1830
+ const pair = (key, scale = 1, unit = "") => `${Math.round(stat.p50[key] / scale)}/${Math.round(stat.p90[key] / scale)}${unit}`;
1831
+ const cpu = {
1832
+ p50: stat.p50.user_s + stat.p50.sys_s,
1833
+ p90: stat.p90.user_s + stat.p90.sys_s
1834
+ };
1835
+ return [
1836
+ stat.signature,
1837
+ `samples ${stat.samples} (failed ${stat.failed}, timeouts ${stat.timeouts})`,
1838
+ `wall ${pair("wall_s", 1, "s")}`,
1839
+ `cpu ${Math.round(cpu.p50)}/${Math.round(cpu.p90)}s`,
1840
+ `rss ${pair("max_rss_kb", 1024, "MB")}`,
1841
+ `read ${pair("read_bytes", 1e6, "MB")}`,
1842
+ `write ${pair("write_bytes", 1e6, "MB")}`
1843
+ ].join(" ");
1844
+ }
1845
+ function stats(context) {
1846
+ const found = usageStats(readUsage(leasePaths(settings(context).dir).usage));
1847
+ if (context.args.flags.has("json")) {
1848
+ context.ui.data(`${JSON.stringify(found)}
1849
+ `);
1850
+ return EXIT.ok;
1851
+ }
1852
+ if (found.length === 0) context.ui.data("no usage recorded yet\n");
1853
+ context.ui.data(
1854
+ "signature @ dir samples p50/p90 of wall, cpu, rss, read, write\n"
1855
+ );
1856
+ for (const stat of found) context.ui.data(`${statLine(stat)}
1857
+ `);
1858
+ return EXIT.ok;
1859
+ }
1860
+ function verbs(context) {
1861
+ const { positional, passthrough } = context.args;
1862
+ return positional.slice(0, positional.length - (passthrough?.length ?? 0));
1863
+ }
1864
+ function subcommand(context) {
1865
+ const [verb, ticket, to, ...rest] = verbs(context);
1866
+ const lease = settings(context);
1867
+ if (verb === "priority" && rest.length === 0)
1868
+ return queuePriority(context, lease, ticket, to);
1869
+ if (to !== void 0) throw new ArgumentError(`unexpected ${to}`);
1870
+ if (verb === "result") return ticketResult(context, lease, ticket);
1871
+ if (verb === "wait") return ticketWait(context, lease, ticket);
1872
+ if (verb === "cancel") return queueCancel(context, lease, ticket);
1873
+ if (verb === "promote") return queuePromote(context, lease, ticket);
1874
+ if (ticket !== void 0 && verb !== "queue")
1875
+ throw new ArgumentError(`unexpected ${ticket}`);
1876
+ if (verb === "queue") return queueList(context, lease);
1877
+ if (verb !== "status" && verb !== "stats")
1878
+ throw new ArgumentError(
1879
+ "put the command after --, or use pmcp heavy status | stats | queue | submit | wait | result | promote | priority | cancel"
1880
+ );
1881
+ if (verb === "stats") return stats(context);
1882
+ if (context.args.flags.has("json")) {
1883
+ const snapshot = statusJson(lease, context.env);
1884
+ context.ui.data(`${JSON.stringify(snapshot)}
1885
+ `);
1886
+ return EXIT.ok;
1887
+ }
1888
+ for (const line of leaseStatus({ settings: lease, env: context.env }))
1889
+ context.ui.data(`${line}
1890
+ `);
1891
+ return EXIT.ok;
1892
+ }
1893
+ async function run(context) {
1894
+ const { args } = context;
1895
+ const say = (line) => process.stderr.write(`pmcp heavy: ${line}
1896
+ `);
1897
+ const [verb, ...extra] = verbs(context);
1898
+ if (args.passthrough === void 0 || verb !== void 0) {
1899
+ if (verb !== "submit") return subcommand(context);
1900
+ if (extra.length > 0) throw new ArgumentError(`unexpected ${extra[0]}`);
1901
+ }
1902
+ if (args.passthrough === void 0 || args.passthrough.length === 0)
1903
+ throw new ArgumentError("no command after --");
1904
+ const lease = settings(context);
1905
+ const profile = one(args, "profile") ?? "default";
1906
+ if (lease.profiles[profile] === void 0)
1907
+ throw new ArgumentError(
1908
+ `unknown profile ${profile}; known: ${Object.keys(lease.profiles).join(", ")}`
1909
+ );
1910
+ const label = one(args, "label");
1911
+ const reason2 = one(args, "reason") ?? context.env[NOW_ENV];
1912
+ const now = args.flags.has("now") || Boolean(context.env[NOW_ENV]);
1913
+ if (now && !reason2?.trim())
1914
+ throw new ArgumentError(
1915
+ "--now needs --reason <text>: say why it cannot wait"
1916
+ );
1917
+ if (!now && one(args, "reason") !== void 0)
1918
+ throw new ArgumentError("--reason goes with --now");
1919
+ const lane = one(args, "lane");
1920
+ if (lane !== void 0 && !LANES.includes(lane))
1921
+ throw new ArgumentError(`--lane is ${LANES.join(", ")}`);
1922
+ const weightText = one(args, "weight");
1923
+ const weight = weightText === void 0 ? void 0 : Number(weightText);
1924
+ if (weight !== void 0 && !(Number.isInteger(weight) && weight >= 0))
1925
+ throw new ArgumentError("--weight is a whole number (0 for a tiny job)");
1926
+ if (verb === "submit") {
1927
+ if (now) throw new ArgumentError("--now runs at once; it is not submitted");
1928
+ return submitTicket(context, lease, args.passthrough);
1929
+ }
1930
+ const ticket = one(args, "ticket");
1931
+ let result = null;
1932
+ const config = one(args, "config") ?? findConfig(context.cwd);
1933
+ const code = await runHeavy({
1934
+ settings: lease,
1935
+ profile,
1936
+ ...label ? { label } : {},
1937
+ ...lane ? { lane } : {},
1938
+ ...weight !== void 0 ? { weight } : {},
1939
+ ...now ? { now: reason2 } : {},
1940
+ root: config ? dirname(config) : context.cwd,
1941
+ ...ticket ? { id: ticket } : {},
1942
+ argv: args.passthrough,
1943
+ cwd: context.cwd,
1944
+ env: context.env,
1945
+ say,
1946
+ ...ticket ? {
1947
+ onUsage: (usage) => {
1948
+ result = { version: 1, ticket, ...usage };
1949
+ }
1950
+ } : {}
1951
+ });
1952
+ if (ticket)
1953
+ writeResult(
1954
+ lease.dir,
1955
+ ticket,
1956
+ result ?? { version: 1, ticket, exit: code, outcome: "ran" },
1957
+ true
1958
+ );
1959
+ return code;
1960
+ }
1961
+ var heavyCommand = { ...heavySpec, run };
1962
+ export {
1963
+ heavyCommand
1964
+ };
1965
+ //# sourceMappingURL=heavy-BGXKJKYB.js.map