@tekyzinc/gsd-t 3.29.10 → 4.0.12

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 (112) hide show
  1. package/CHANGELOG.md +176 -0
  2. package/bin/gsd-t-parallel.cjs +64 -13
  3. package/bin/gsd-t-test-data-adapters/file-json-array.cjs +27 -3
  4. package/bin/gsd-t-test-data-adapters/localstorage-key-prefix.cjs +6 -1
  5. package/bin/gsd-t-test-data-adapters/sqlite-table-where.cjs +16 -1
  6. package/bin/gsd-t-test-data-ledger.cjs +1 -0
  7. package/bin/gsd-t.js +48 -376
  8. package/bin/journey-coverage.cjs +6 -3
  9. package/bin/parallel-cli.cjs +13 -1
  10. package/commands/gsd-t-debug.md +47 -533
  11. package/commands/gsd-t-design-decompose.md +24 -497
  12. package/commands/gsd-t-doc-ripple.md +23 -139
  13. package/commands/gsd-t-execute.md +41 -958
  14. package/commands/gsd-t-help.md +0 -2
  15. package/commands/gsd-t-impact.md +26 -295
  16. package/commands/gsd-t-integrate.md +44 -369
  17. package/commands/gsd-t-milestone.md +25 -124
  18. package/commands/gsd-t-partition.md +28 -539
  19. package/commands/gsd-t-plan.md +26 -472
  20. package/commands/gsd-t-prd.md +25 -311
  21. package/commands/gsd-t-quick.md +1 -1
  22. package/commands/gsd-t-resume.md +0 -33
  23. package/commands/gsd-t-verify.md +52 -569
  24. package/commands/gsd-t-wave.md +41 -430
  25. package/package.json +1 -1
  26. package/scripts/gsd-t-calibration-hook.js +3 -1
  27. package/scripts/hooks/pre-commit-journey-coverage +0 -2
  28. package/scripts/hooks/pre-commit-playwright-gate +0 -2
  29. package/templates/CLAUDE-global.md +43 -173
  30. package/templates/CLAUDE-project.md +118 -104
  31. package/templates/prompts/design-verify-subagent.md +3 -0
  32. package/templates/prompts/qa-subagent.md +3 -0
  33. package/templates/prompts/red-team-subagent.md +5 -2
  34. package/templates/workflows/_lib.js +176 -0
  35. package/templates/workflows/gsd-t-debug.workflow.js +86 -0
  36. package/templates/workflows/gsd-t-execute.workflow.js +206 -0
  37. package/templates/workflows/gsd-t-integrate.workflow.js +71 -0
  38. package/templates/workflows/gsd-t-phase.workflow.js +94 -0
  39. package/templates/workflows/gsd-t-quick.workflow.js +72 -0
  40. package/templates/workflows/gsd-t-verify.workflow.js +348 -0
  41. package/templates/workflows/gsd-t-wave.workflow.js +43 -0
  42. package/bin/check-headless-sessions.js +0 -140
  43. package/bin/context-budget-audit.cjs +0 -447
  44. package/bin/context-meter-config.cjs +0 -101
  45. package/bin/context-meter-config.test.cjs +0 -101
  46. package/bin/event-stream.cjs +0 -205
  47. package/bin/gsd-t-benchmark-orchestrator.js +0 -437
  48. package/bin/gsd-t-capture-lint.cjs +0 -440
  49. package/bin/gsd-t-economics.cjs +0 -315
  50. package/bin/gsd-t-in-session-usage.cjs +0 -213
  51. package/bin/gsd-t-orchestrator-config.cjs +0 -161
  52. package/bin/gsd-t-orchestrator-queue.cjs +0 -180
  53. package/bin/gsd-t-orchestrator-recover.cjs +0 -231
  54. package/bin/gsd-t-orchestrator-worker.cjs +0 -219
  55. package/bin/gsd-t-orchestrator.js +0 -535
  56. package/bin/gsd-t-parallel-probe.cjs +0 -132
  57. package/bin/gsd-t-ratelimit-probe-worker.cjs +0 -237
  58. package/bin/gsd-t-ratelimit-probe.cjs +0 -648
  59. package/bin/gsd-t-report-tokens.cjs +0 -549
  60. package/bin/gsd-t-stream-feed-client.cjs +0 -151
  61. package/bin/gsd-t-token-backfill.cjs +0 -366
  62. package/bin/gsd-t-token-capture.cjs +0 -321
  63. package/bin/gsd-t-token-dashboard.cjs +0 -353
  64. package/bin/gsd-t-token-regenerate-log.cjs +0 -129
  65. package/bin/gsd-t-tool-attribution.cjs +0 -377
  66. package/bin/gsd-t-tool-cost.cjs +0 -195
  67. package/bin/gsd-t-transcript-tee.cjs +0 -246
  68. package/bin/gsd-t-unattended-heartbeat.cjs +0 -188
  69. package/bin/gsd-t-unattended-platform.cjs +0 -551
  70. package/bin/gsd-t-unattended-platform.js +0 -381
  71. package/bin/gsd-t-unattended-safety.cjs +0 -773
  72. package/bin/gsd-t-unattended-safety.js +0 -788
  73. package/bin/gsd-t-unattended.cjs +0 -2109
  74. package/bin/gsd-t-unattended.js +0 -1367
  75. package/bin/gsd-t-worker-dispatch.cjs +0 -211
  76. package/bin/handoff-lock.cjs +0 -249
  77. package/bin/handoff-lock.js +0 -249
  78. package/bin/headless-auto-spawn.cjs +0 -711
  79. package/bin/headless-auto-spawn.js +0 -373
  80. package/bin/headless-exit-codes.cjs +0 -67
  81. package/bin/live-activity-report.cjs +0 -615
  82. package/bin/log-tail.cjs +0 -81
  83. package/bin/m44-proof-measure.cjs +0 -285
  84. package/bin/m46-iter-proof.cjs +0 -149
  85. package/bin/m46-worker-proof.cjs +0 -201
  86. package/bin/m55-substrate-proof.cjs +0 -134
  87. package/bin/metrics-rollup.js +0 -200
  88. package/bin/model-windows.cjs +0 -99
  89. package/bin/model-windows.test.cjs +0 -75
  90. package/bin/parallelism-report.cjs +0 -535
  91. package/bin/runway-estimator.cjs +0 -242
  92. package/bin/spawn-plan-derive.cjs +0 -163
  93. package/bin/spawn-plan-status-updater.cjs +0 -292
  94. package/bin/spawn-plan-writer.cjs +0 -204
  95. package/bin/supervisor-pid-fingerprint.cjs +0 -126
  96. package/bin/token-budget.cjs +0 -265
  97. package/bin/unattended-watch-format.cjs +0 -178
  98. package/bin/watch-progress.js +0 -155
  99. package/commands/gsd-t-unattended-stop.md +0 -85
  100. package/commands/gsd-t-unattended-watch.md +0 -465
  101. package/commands/gsd-t-unattended.md +0 -476
  102. package/commands/gsd-t-visualize.md +0 -116
  103. package/scripts/gsd-t-context-meter.e2e.test.js +0 -364
  104. package/scripts/gsd-t-context-meter.js +0 -341
  105. package/scripts/gsd-t-context-meter.test.js +0 -471
  106. package/scripts/gsd-t-dashboard-server.js +0 -1203
  107. package/scripts/gsd-t-post-commit-spawn-plan.sh +0 -86
  108. package/scripts/gsd-t-transcript.html +0 -1821
  109. package/scripts/hooks/gsd-t-conversation-capture.js +0 -439
  110. package/scripts/hooks/gsd-t-in-session-usage-hook.js +0 -84
  111. package/scripts/spawn-plan-fmt-tokens.cjs +0 -80
  112. package/templates/hooks/post-commit-spawn-plan.sh +0 -85
@@ -1,551 +0,0 @@
1
- /**
2
- * gsd-t-unattended-platform.js
3
- *
4
- * Cross-platform helpers for the unattended supervisor (M36).
5
- *
6
- * This module is the SINGLE place where `process.platform` branches live.
7
- * Supervisor-core, watch-loop, and safety-rails import from here so that
8
- * the rest of the supervisor can stay platform-agnostic.
9
- *
10
- * Contract: .gsd-t/contracts/unattended-supervisor-contract.md v1.0.0
11
- * §5 Exit Code Table (timeout = 3, OS process-timeout = 124)
12
- * §7 Launch Handshake (spawn semantics)
13
- *
14
- * Task 1 of m36-cross-platform delivers:
15
- * - resolveClaudePath()
16
- * - isAlive(pid)
17
- * - spawnWorker(projectDir, timeoutMs, opts)
18
- * opts.onHeartbeatCheck? — async liveness watchdog (M43 D?)
19
- *
20
- * Cross-platform notes:
21
- * - darwin / linux paths are runtime-tested.
22
- * - win32 paths are implementation-complete but NOT runtime-tested on the
23
- * dev host (macOS). Spike C and the full Windows caveats matrix ship in
24
- * Task 3 (`docs/unattended-windows-caveats.md`).
25
- *
26
- * Zero external dependencies — Node built-ins only.
27
- */
28
-
29
- "use strict";
30
-
31
- const { spawnSync, spawn } = require("node:child_process");
32
-
33
- // ─── resolveClaudePath ───────────────────────────────────────────────────────
34
-
35
- /**
36
- * Resolve the executable name for the `claude` CLI on the current platform.
37
- *
38
- * Returns `'claude.cmd'` on win32 and `'claude'` everywhere else.
39
- *
40
- * This is intentionally a simple platform branch — it does NOT shell out to
41
- * `which` / `where`. The resolver assumes `claude` is on PATH; PATH lookup is
42
- * delegated to `spawnSync`, which is cross-platform and quoting-safe.
43
- *
44
- * Cross-platform:
45
- * - darwin / linux: returns `'claude'`. The macOS / Linux installer puts
46
- * `claude` on PATH via `/usr/local/bin` or `/opt/homebrew/bin`.
47
- * - win32: returns `'claude.cmd'`. The Anthropic Windows installer ships a
48
- * `.cmd` shim. Using the `.cmd` filename explicitly (instead of bare
49
- * `claude`) avoids `spawnSync` falling through to `cmd.exe /c claude`,
50
- * which would re-introduce the Spike C PowerShell quoting hazard.
51
- *
52
- * @returns {string} `'claude'` or `'claude.cmd'`
53
- */
54
- function resolveClaudePath() {
55
- return process.platform === "win32" ? "claude.cmd" : "claude";
56
- }
57
-
58
- // ─── isAlive ─────────────────────────────────────────────────────────────────
59
-
60
- /**
61
- * Cross-platform liveness check for a PID.
62
- *
63
- * Uses the POSIX trick `kill(pid, 0)` — sends signal 0, which performs all
64
- * permission and existence checks but delivers no signal. Node's
65
- * `process.kill` implements the same semantics on Windows.
66
- *
67
- * Errors:
68
- * - `ESRCH` → no such process. Returns `false`.
69
- * - `EPERM` → process exists but we don't own it. Returns `true` (we got
70
- * permission feedback, which proves the PID is live).
71
- * - other → unexpected; rethrown.
72
- *
73
- * @param {number} pid
74
- * @returns {boolean}
75
- */
76
- function isAlive(pid) {
77
- if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) {
78
- return false;
79
- }
80
- try {
81
- process.kill(pid, 0);
82
- return true;
83
- } catch (err) {
84
- if (err && err.code === "ESRCH") return false;
85
- if (err && err.code === "EPERM") return true; // exists, not ours
86
- throw err;
87
- }
88
- }
89
-
90
- // ─── spawnWorker ─────────────────────────────────────────────────────────────
91
-
92
- /**
93
- * Spawn a `claude -p '/gsd-t-resume'` worker iteration for the unattended
94
- * supervisor.
95
- *
96
- * Returns a normalized result object: `{ status, stdout, stderr, signal,
97
- * timedOut, staleHeartbeat, error }`. Never throws — spawn errors are
98
- * returned in `error`.
99
- *
100
- * Two kill paths:
101
- * 1. Heartbeat watchdog (M43 primary) — when `opts.onHeartbeatCheck` is
102
- * provided, the function polls every `opts.heartbeatPollMs` (default
103
- * 60_000). If the callback returns `{stale: true, ...}`, the child is
104
- * SIGTERM'd and `staleHeartbeat: true` is set on the result.
105
- * 2. Wall-clock timeout (absolute backstop) — `timeoutMs` is the hard cap
106
- * regardless of heartbeat. On expiry the child is SIGTERM'd and
107
- * `timedOut: true`. Default raised to 1 h in supervisor-core so a
108
- * healthy long-running worker is not cut.
109
- *
110
- * Exactly one path is used per iteration:
111
- * - opts.onHeartbeatCheck present → heartbeat path (async event loop)
112
- * - opts.onHeartbeatCheck absent → legacy spawnSync path (blocking)
113
- * The legacy path is preserved so callers that have no meaningful liveness
114
- * signal (test stubs, dry-run) keep the original semantics.
115
- *
116
- * Cross-platform:
117
- * - darwin / linux: runtime-tested.
118
- * - win32: implementation-complete; documented in
119
- * `docs/unattended-windows-caveats.md` (Task 3).
120
- *
121
- * @param {string} projectDir Absolute path to the project directory (cwd).
122
- * @param {number} timeoutMs Wall-clock backstop per worker iteration in ms.
123
- * @param {object} [opts] Optional overrides (test-mode hooks).
124
- * @param {string} [opts.bin] Override the resolved binary (test-mode only).
125
- * @param {string[]} [opts.args] Override args (defaults to `['-p', '/gsd-t-resume']`).
126
- * @param {object} [opts.env] Override env (defaults to `process.env`).
127
- * @param {Function} [opts.onHeartbeatCheck] Called every heartbeatPollMs
128
- * with no args; must return `{stale: boolean, reason?: string}` or a
129
- * Promise thereof. When stale, the child is SIGTERM'd.
130
- * @param {number} [opts.heartbeatPollMs] Poll cadence in ms. Default 60_000.
131
- * @param {Function} [opts.onHeartbeatSample] Optional observer; receives the
132
- * raw callback result each poll for logging.
133
- * @param {Function} [opts.onStdoutLine] Optional live stdout line callback.
134
- * When provided (heartbeat path only), invoked once per `\n`-terminated line
135
- * as stdout streams in. Trailing partial line is flushed on close. Errors
136
- * are swallowed (best-effort tee). Used by the supervisor to write each
137
- * worker line into the M42 transcript file in real time, instead of
138
- * appending the entire stdout buffer post-hoc at child exit.
139
- * @returns {{
140
- * status: number|null,
141
- * stdout: string,
142
- * stderr: string,
143
- * signal: string|null,
144
- * timedOut: boolean,
145
- * staleHeartbeat: boolean,
146
- * heartbeatReason: string|null,
147
- * error: Error|null
148
- * }|Promise<...>}
149
- * Returns a Promise when `opts.onHeartbeatCheck` is provided; otherwise a
150
- * synchronous result (legacy path).
151
- */
152
- function spawnWorker(projectDir, timeoutMs, opts = {}) {
153
- const bin = opts.bin || resolveClaudePath();
154
- const args = opts.args || [
155
- "-p",
156
- "/gsd-t-resume",
157
- "--output-format", "stream-json",
158
- "--verbose",
159
- "--dangerously-skip-permissions",
160
- ];
161
- const env = opts.env || process.env;
162
-
163
- if (typeof opts.onHeartbeatCheck === "function") {
164
- return _spawnWorkerAsyncHeartbeat({
165
- bin,
166
- args,
167
- env,
168
- cwd: projectDir,
169
- timeoutMs,
170
- onHeartbeatCheck: opts.onHeartbeatCheck,
171
- heartbeatPollMs: opts.heartbeatPollMs || 60 * 1000,
172
- onHeartbeatSample: opts.onHeartbeatSample,
173
- onStdoutLine: opts.onStdoutLine,
174
- spawnImpl: opts._spawnImpl || spawn,
175
- });
176
- }
177
-
178
- const result = spawnSync(bin, args, {
179
- cwd: projectDir,
180
- encoding: "utf8",
181
- timeout: timeoutMs,
182
- env,
183
- stdio: ["ignore", "pipe", "pipe"],
184
- shell: false,
185
- windowsHide: true,
186
- });
187
-
188
- const stdout = typeof result.stdout === "string" ? result.stdout : "";
189
- const stderr = typeof result.stderr === "string" ? result.stderr : "";
190
- const signal = result.signal || null;
191
- const status = typeof result.status === "number" ? result.status : null;
192
-
193
- const errCode = result.error && result.error.code;
194
- const timedOut =
195
- errCode === "ETIMEDOUT" || (status === null && signal !== null && !result.error);
196
-
197
- return {
198
- status,
199
- stdout,
200
- stderr,
201
- signal,
202
- timedOut,
203
- staleHeartbeat: false,
204
- heartbeatReason: null,
205
- error: errCode === "ETIMEDOUT" ? null : result.error || null,
206
- };
207
- }
208
-
209
- /**
210
- * Async spawn path used when a heartbeat callback is provided.
211
- *
212
- * Returns a Promise resolving to the same result shape as spawnWorker's
213
- * legacy path, plus `staleHeartbeat` and `heartbeatReason`.
214
- *
215
- * Kill precedence when both fire in the same tick: heartbeat wins (it is
216
- * the more specific signal). The loser is suppressed on the result.
217
- *
218
- * @private
219
- */
220
- function _spawnWorkerAsyncHeartbeat({
221
- bin,
222
- args,
223
- env,
224
- cwd,
225
- timeoutMs,
226
- onHeartbeatCheck,
227
- heartbeatPollMs,
228
- onHeartbeatSample,
229
- onStdoutLine,
230
- spawnImpl,
231
- }) {
232
- return new Promise((resolve) => {
233
- let child;
234
- try {
235
- child = spawnImpl(bin, args, {
236
- cwd,
237
- env,
238
- stdio: ["ignore", "pipe", "pipe"],
239
- shell: false,
240
- windowsHide: true,
241
- });
242
- } catch (err) {
243
- resolve({
244
- status: null,
245
- stdout: "",
246
- stderr: "",
247
- signal: null,
248
- timedOut: false,
249
- staleHeartbeat: false,
250
- heartbeatReason: null,
251
- error: err,
252
- });
253
- return;
254
- }
255
-
256
- const chunksOut = [];
257
- const chunksErr = [];
258
- let lineBuf = "";
259
- const emitLine = (line) => {
260
- if (typeof onStdoutLine !== "function" || line.length === 0) return;
261
- try { onStdoutLine(line); } catch (_) { /* tee is best-effort */ }
262
- };
263
- if (child.stdout) child.stdout.on("data", (d) => {
264
- chunksOut.push(d);
265
- if (typeof onStdoutLine !== "function") return;
266
- lineBuf += d.toString("utf8");
267
- let nl;
268
- while ((nl = lineBuf.indexOf("\n")) >= 0) {
269
- emitLine(lineBuf.slice(0, nl));
270
- lineBuf = lineBuf.slice(nl + 1);
271
- }
272
- });
273
- if (child.stderr) child.stderr.on("data", (d) => chunksErr.push(d));
274
-
275
- let resolved = false;
276
- let timedOut = false;
277
- let staleHeartbeat = false;
278
- let heartbeatReason = null;
279
- let spawnErr = null;
280
-
281
- const heartbeatTimer = setInterval(async () => {
282
- if (resolved) return;
283
- let sample;
284
- try {
285
- sample = await onHeartbeatCheck();
286
- } catch (err) {
287
- // Heartbeat check must not kill the worker on its own failures.
288
- // Surface via sample observer when provided and continue.
289
- sample = { stale: false, reason: `heartbeat check threw: ${err.message}` };
290
- }
291
- if (typeof onHeartbeatSample === "function") {
292
- try { onHeartbeatSample(sample); } catch (_) { /* observer best-effort */ }
293
- }
294
- if (sample && sample.stale) {
295
- staleHeartbeat = true;
296
- heartbeatReason = sample.reason || "stale heartbeat";
297
- try { child.kill("SIGTERM"); } catch (_) { /* child may already be gone */ }
298
- }
299
- }, heartbeatPollMs);
300
- if (typeof heartbeatTimer.unref === "function") heartbeatTimer.unref();
301
-
302
- const absoluteTimer = setTimeout(() => {
303
- if (resolved || staleHeartbeat) return;
304
- timedOut = true;
305
- try { child.kill("SIGTERM"); } catch (_) { /* child may already be gone */ }
306
- }, timeoutMs);
307
- if (typeof absoluteTimer.unref === "function") absoluteTimer.unref();
308
-
309
- child.on("error", (err) => {
310
- spawnErr = err;
311
- });
312
-
313
- child.on("close", (status, signal) => {
314
- if (resolved) return;
315
- resolved = true;
316
- clearInterval(heartbeatTimer);
317
- clearTimeout(absoluteTimer);
318
-
319
- if (lineBuf.length > 0) {
320
- emitLine(lineBuf);
321
- lineBuf = "";
322
- }
323
-
324
- const stdout = Buffer.concat(chunksOut).toString("utf8");
325
- const stderr = Buffer.concat(chunksErr).toString("utf8");
326
-
327
- resolve({
328
- status: typeof status === "number" ? status : null,
329
- stdout,
330
- stderr,
331
- signal: signal || null,
332
- timedOut,
333
- staleHeartbeat,
334
- heartbeatReason,
335
- error: spawnErr,
336
- });
337
- });
338
- });
339
- }
340
-
341
- // ─── spawnSupervisor ─────────────────────────────────────────────────────────
342
-
343
- /**
344
- * Spawn a detached unattended supervisor process.
345
- *
346
- * Implements the Launch Handshake from contract §7: the interactive launch
347
- * command forks a long-lived supervisor that outlives the parent, reads the
348
- * state file, and relays `claude -p` workers until the milestone terminates.
349
- *
350
- * Spawn recipe:
351
- * - `node {binPath} unattended {...args}` — the `unattended` subcommand is
352
- * prepended automatically so callers pass only user-facing args.
353
- * - `detached: true` — the child becomes a process-group leader on POSIX
354
- * (darwin/linux) so it survives the parent closing its terminal. On win32
355
- * the equivalent flag produces a separate process tree.
356
- * - `stdio: 'ignore'` — no pipes held open that would block the parent
357
- * from exiting.
358
- * - `windowsHide: true` (win32 only) — no flashed console window.
359
- * - `child.unref()` — the parent event loop will not wait on the child.
360
- *
361
- * Cross-platform notes:
362
- * - darwin / linux: runtime-tested.
363
- * - win32: implementation-complete; documented in
364
- * `docs/unattended-windows-caveats.md` (Task 3).
365
- *
366
- * @param {object} params
367
- * @param {string} params.binPath Absolute path to `bin/gsd-t.js`.
368
- * @param {string[]} params.args Extra args appended after `unattended`.
369
- * @param {string} params.cwd Project directory (supervisor's cwd).
370
- * @returns {{ pid: number }} The detached child's PID.
371
- */
372
- function spawnSupervisor({ binPath, args, cwd }) {
373
- const spawnArgs = [binPath, "unattended", ...(args || [])];
374
- const opts = {
375
- cwd,
376
- detached: true,
377
- stdio: "ignore",
378
- };
379
- if (process.platform === "win32") {
380
- opts.windowsHide = true;
381
- }
382
- const child = spawn("node", spawnArgs, opts);
383
- child.unref();
384
- return { pid: child.pid };
385
- }
386
-
387
- // ─── preventSleep ────────────────────────────────────────────────────────────
388
-
389
- /**
390
- * Prevent the OS from going to sleep while the supervisor is running.
391
- *
392
- * Returns a handle that must be passed to `releaseSleep` when the supervisor
393
- * terminates.
394
- *
395
- * Cross-platform:
396
- * - darwin: `caffeinate -i -w <supervisor-pid>` — the `-w` flag ties the
397
- * caffeinate lifetime to the supervisor's PID. Even if the supervisor
398
- * forgets to call `releaseSleep`, caffeinate will self-exit when the
399
- * supervisor dies. Returns the caffeinate child PID as the handle.
400
- * - linux: returns `null`. Reliable sleep prevention requires
401
- * `systemd-inhibit`, which only works under a user session bus and is
402
- * not universally available. v1 documents the gap; v2 may add opt-in
403
- * systemd-inhibit. Prints a one-line notice to stderr.
404
- * - win32: returns `null`. `SetThreadExecutionState` is the native API but
405
- * requires a C binding. v1 documents the gap; see
406
- * `docs/unattended-windows-caveats.md` (Task 3).
407
- *
408
- * @param {string} [reason] Informational label (reserved; not currently used
409
- * — darwin's caffeinate has no reason field, and
410
- * linux/win32 don't have sleep prevention yet).
411
- * @returns {number|null} PID handle on darwin, `null` elsewhere.
412
- */
413
- function preventSleep(reason) {
414
- void reason; // reserved for future implementations
415
- if (process.platform === "darwin") {
416
- try {
417
- const child = spawn("caffeinate", ["-i", "-w", String(process.pid)], {
418
- detached: true,
419
- stdio: "ignore",
420
- });
421
- child.unref();
422
- return typeof child.pid === "number" ? child.pid : null;
423
- } catch (err) {
424
- process.stderr.write(
425
- `[platform] caffeinate failed to spawn: ${err && err.message}\n`,
426
- );
427
- return null;
428
- }
429
- }
430
- if (process.platform === "linux") {
431
- process.stderr.write(
432
- "[platform] sleep prevention not implemented on linux\n",
433
- );
434
- return null;
435
- }
436
- process.stderr.write(
437
- "[platform] sleep prevention not implemented on win32 (see docs/unattended-windows-caveats.md)\n",
438
- );
439
- return null;
440
- }
441
-
442
- // ─── releaseSleep ────────────────────────────────────────────────────────────
443
-
444
- /**
445
- * Release a sleep-prevention handle obtained from `preventSleep`.
446
- *
447
- * Idempotent and tolerant:
448
- * - `null` / non-number handle → no-op.
449
- * - handle is a dead PID → no-op (ESRCH is swallowed).
450
- * - handle is a live PID → `SIGTERM` is delivered (EPERM and other unusual
451
- * errors are swallowed — caller cannot reasonably act on them).
452
- *
453
- * @param {number|null} handle
454
- * @returns {void}
455
- */
456
- function releaseSleep(handle) {
457
- if (handle == null) return;
458
- if (typeof handle !== "number" || !Number.isInteger(handle) || handle <= 0) {
459
- return;
460
- }
461
- if (!isAlive(handle)) return;
462
- try {
463
- process.kill(handle, "SIGTERM");
464
- } catch (_err) {
465
- // Swallow — releaseSleep must never throw. A dead/gone process is fine;
466
- // an EPERM on an adopted PID is also fine (not ours to reap).
467
- }
468
- }
469
-
470
- // ─── notify ──────────────────────────────────────────────────────────────────
471
-
472
- /**
473
- * Emit an OS-level desktop notification. Fire-and-forget — never throws.
474
- *
475
- * Cross-platform:
476
- * - darwin: `osascript -e 'display notification "msg" with title "title"'`.
477
- * - linux: `notify-send "title" "message"` (requires libnotify).
478
- * - win32: `msg.exe * "title: message"` (console msg; ships with Windows).
479
- *
480
- * All platform helpers are fire-and-forget `spawn` calls. Errors are caught
481
- * and logged to stderr so a missing binary (e.g., no libnotify installed on a
482
- * headless Linux box) does NOT break the supervisor.
483
- *
484
- * @param {string} title
485
- * @param {string} message
486
- * @param {string} [level] `info` | `warn` | `done` | `failed` — accepted but
487
- * currently unused. Reserved for future formatting.
488
- * @returns {void}
489
- */
490
- function notify(title, message, level) {
491
- void level; // reserved for future formatting
492
- const safeTitle = String(title || "");
493
- const safeMessage = String(message || "");
494
- try {
495
- if (process.platform === "darwin") {
496
- // Escape double-quotes and backslashes for the AppleScript string
497
- // literal. osascript uses double-quoted string syntax.
498
- const esc = (s) => s.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
499
- const script =
500
- `display notification "${esc(safeMessage)}" ` +
501
- `with title "${esc(safeTitle)}"`;
502
- const child = spawn("osascript", ["-e", script], { stdio: "ignore" });
503
- child.on("error", (err) => {
504
- process.stderr.write(
505
- `[platform] notify(osascript) failed: ${err && err.message}\n`,
506
- );
507
- });
508
- child.unref && child.unref();
509
- return;
510
- }
511
- if (process.platform === "linux") {
512
- const child = spawn("notify-send", [safeTitle, safeMessage], {
513
- stdio: "ignore",
514
- });
515
- child.on("error", (err) => {
516
- process.stderr.write(
517
- `[platform] notify(notify-send) failed: ${err && err.message}\n`,
518
- );
519
- });
520
- child.unref && child.unref();
521
- return;
522
- }
523
- // win32
524
- const child = spawn("msg.exe", ["*", `${safeTitle}: ${safeMessage}`], {
525
- stdio: "ignore",
526
- windowsHide: true,
527
- });
528
- child.on("error", (err) => {
529
- process.stderr.write(
530
- `[platform] notify(msg.exe) failed: ${err && err.message}\n`,
531
- );
532
- });
533
- child.unref && child.unref();
534
- } catch (err) {
535
- // Defense in depth — spawn() itself can throw synchronously on certain
536
- // argument errors. Never propagate.
537
- process.stderr.write(
538
- `[platform] notify synchronous error: ${err && err.message}\n`,
539
- );
540
- }
541
- }
542
-
543
- module.exports = {
544
- resolveClaudePath,
545
- isAlive,
546
- spawnWorker,
547
- spawnSupervisor,
548
- preventSleep,
549
- releaseSleep,
550
- notify,
551
- };