@modootoday/pmcp 0.26.0 → 0.27.0

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