@hearsay-tools/squawk 0.18.0-dev.6799 → 0.18.0-dev.6810

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 (213) hide show
  1. package/dist/ci-wait/controller.d.ts +4 -4
  2. package/dist/contract/delegation.d.ts +20 -0
  3. package/dist/contract/index.js +27 -2
  4. package/dist/contract/run-predicates.d.ts +28 -1
  5. package/dist/contract/runs.d.ts +4 -0
  6. package/dist/core/agent-runner.d.ts +16 -0
  7. package/dist/core/agent-runner.js +7 -0
  8. package/dist/core/agent-runner.js.map +1 -1
  9. package/dist/core/claude-cli-runner.js +3 -2
  10. package/dist/core/claude-cli-runner.js.map +1 -1
  11. package/dist/core/codex-app-server-runner.js +3 -3
  12. package/dist/core/codex-app-server-runner.js.map +1 -1
  13. package/dist/core/codex-app-server-transport.d.ts +2 -0
  14. package/dist/core/codex-app-server-transport.js +1 -1
  15. package/dist/core/codex-app-server-transport.js.map +1 -1
  16. package/dist/core/cursor-print-process.d.ts +3 -0
  17. package/dist/core/cursor-print-process.js +1 -1
  18. package/dist/core/cursor-print-process.js.map +1 -1
  19. package/dist/core/cursor-print-runner.js +3 -2
  20. package/dist/core/cursor-print-runner.js.map +1 -1
  21. package/dist/core/omp-runner.js +3 -1
  22. package/dist/core/omp-runner.js.map +1 -1
  23. package/dist/core/opencode-server-runner.js +3 -3
  24. package/dist/core/opencode-server-runner.js.map +1 -1
  25. package/dist/core/pi-runner.js +3 -2
  26. package/dist/core/pi-runner.js.map +1 -1
  27. package/dist/core/session-process.d.ts +6 -0
  28. package/dist/core/session-process.js +53 -2
  29. package/dist/core/session-process.js.map +1 -1
  30. package/dist/delegation/conversations.d.ts +2 -0
  31. package/dist/delegation/execution-identity.d.ts +13 -5
  32. package/dist/delegation/execution-identity.js +21 -8
  33. package/dist/delegation/execution-identity.js.map +1 -1
  34. package/dist/delegation/family-end.js +2 -4
  35. package/dist/delegation/family-end.js.map +1 -1
  36. package/dist/delegation/owned-workspace-release.d.ts +1 -2
  37. package/dist/delegation/owned-workspace-release.js +2 -2
  38. package/dist/delegation/owned-workspace-release.js.map +1 -1
  39. package/dist/delegation/process-liveness.d.ts +8 -58
  40. package/dist/delegation/process-liveness.js +9 -86
  41. package/dist/delegation/process-liveness.js.map +1 -1
  42. package/dist/delegation/routes.d.ts +25 -21
  43. package/dist/delegation/scratch-cleanup.d.ts +1 -1
  44. package/dist/delegation/scratch-cleanup.js +7 -10
  45. package/dist/delegation/scratch-cleanup.js.map +1 -1
  46. package/dist/delegation/service.js +2 -1
  47. package/dist/delegation/service.js.map +1 -1
  48. package/dist/delegation/transport.d.ts +82 -78
  49. package/dist/delegation/worker-cleanup.d.ts +2 -9
  50. package/dist/delegation/worker-cleanup.js +44 -86
  51. package/dist/delegation/worker-cleanup.js.map +1 -1
  52. package/dist/delegation/workspace-removal.d.ts +4 -12
  53. package/dist/delegation/workspace-removal.js +18 -51
  54. package/dist/delegation/workspace-removal.js.map +1 -1
  55. package/dist/git-worktree.js +2 -6
  56. package/dist/git-worktree.js.map +1 -1
  57. package/dist/preview/dev-server.d.ts +3 -0
  58. package/dist/preview/dev-server.js +40 -1
  59. package/dist/preview/dev-server.js.map +1 -1
  60. package/dist/preview/host.d.ts +3 -1
  61. package/dist/preview/host.js +2 -1
  62. package/dist/preview/host.js.map +1 -1
  63. package/dist/runs/private-record-file.d.ts +7 -0
  64. package/dist/runs/private-record-file.js +55 -0
  65. package/dist/runs/private-record-file.js.map +1 -0
  66. package/dist/runs/run-exits.d.ts +4 -0
  67. package/dist/runs/store.d.ts +23 -8
  68. package/dist/runs/store.js +43 -99
  69. package/dist/runs/store.js.map +1 -1
  70. package/dist/runs/worker-execution.d.ts +1 -0
  71. package/dist/runs/worker-execution.js +4 -1
  72. package/dist/runs/worker-execution.js.map +1 -1
  73. package/dist/runs/worker-resource-holders.d.ts +10 -7
  74. package/dist/runs/worker-resource-holders.js +9 -25
  75. package/dist/runs/worker-resource-holders.js.map +1 -1
  76. package/dist/server/activity-routes.d.ts +23 -23
  77. package/dist/server/open-in-targets.js +5 -4
  78. package/dist/server/open-in-targets.js.map +1 -1
  79. package/dist/server/provider-auth-runtime.js +2 -1
  80. package/dist/server/provider-auth-runtime.js.map +1 -1
  81. package/dist/server/server.d.ts +1659 -1633
  82. package/dist/server/server.js +4 -7
  83. package/dist/server/server.js.map +1 -1
  84. package/dist/server/workspace-live-routes.d.ts +6 -6
  85. package/dist/worker-scope/cgroup.d.ts +41 -0
  86. package/dist/worker-scope/cgroup.js +173 -0
  87. package/dist/worker-scope/cgroup.js.map +1 -0
  88. package/dist/worker-scope/groups.d.ts +24 -0
  89. package/dist/worker-scope/groups.js +60 -0
  90. package/dist/worker-scope/groups.js.map +1 -0
  91. package/dist/worker-scope/scope.d.ts +32 -0
  92. package/dist/worker-scope/scope.js +18 -0
  93. package/dist/worker-scope/scope.js.map +1 -0
  94. package/dist/worker-scope/worker-scopes.d.ts +63 -0
  95. package/dist/worker-scope/worker-scopes.js +181 -0
  96. package/dist/worker-scope/worker-scopes.js.map +1 -0
  97. package/dist/workflows/continuation-admission.d.ts +8 -1
  98. package/dist/workflows/continuation-admission.js +12 -7
  99. package/dist/workflows/continuation-admission.js.map +1 -1
  100. package/dist/workflows/execution-account.js +4 -3
  101. package/dist/workflows/execution-account.js.map +1 -1
  102. package/dist/workflows/grouped-command.d.ts +3 -0
  103. package/dist/workflows/grouped-command.js +28 -2
  104. package/dist/workflows/grouped-command.js.map +1 -1
  105. package/dist/workflows/run/compose.d.ts +0 -2
  106. package/dist/workflows/run/compose.js +4 -2
  107. package/dist/workflows/run/compose.js.map +1 -1
  108. package/dist/workflows/run/continuation-acceptance.js +2 -1
  109. package/dist/workflows/run/continuation-acceptance.js.map +1 -1
  110. package/dist/workflows/run/continuation-session.js +5 -3
  111. package/dist/workflows/run/continuation-session.js.map +1 -1
  112. package/dist/workflows/run/human-waits.js +2 -0
  113. package/dist/workflows/run/human-waits.js.map +1 -1
  114. package/dist/workflows/run/input-delivery.d.ts +16 -0
  115. package/dist/workflows/run/input-delivery.js +51 -4
  116. package/dist/workflows/run/input-delivery.js.map +1 -1
  117. package/dist/workflows/run/input-receipts.d.ts +1 -0
  118. package/dist/workflows/run/input-receipts.js +1 -0
  119. package/dist/workflows/run/input-receipts.js.map +1 -1
  120. package/dist/workflows/run/launch-read-resolver.d.ts +3 -1
  121. package/dist/workflows/run/launch-read-resolver.js +11 -4
  122. package/dist/workflows/run/launch-read-resolver.js.map +1 -1
  123. package/dist/workflows/run/queued-revival.js +2 -1
  124. package/dist/workflows/run/queued-revival.js.map +1 -1
  125. package/dist/workflows/run/run-settlement.d.ts +1 -1
  126. package/dist/workflows/run/run-settlement.js +3 -3
  127. package/dist/workflows/run/run-settlement.js.map +1 -1
  128. package/dist/workflows/run/session-events.js +6 -3
  129. package/dist/workflows/run/session-events.js.map +1 -1
  130. package/dist/workflows/run/step-loop.d.ts +2 -2
  131. package/dist/workflows/run/step-loop.js +6 -4
  132. package/dist/workflows/run/step-loop.js.map +1 -1
  133. package/dist/workflows/run/step-session.js +1 -0
  134. package/dist/workflows/run/step-session.js.map +1 -1
  135. package/dist/workflows/run/turn-boundary.d.ts +16 -4
  136. package/dist/workflows/run/turn-boundary.js +6 -12
  137. package/dist/workflows/run/turn-boundary.js.map +1 -1
  138. package/dist/workflows/run/turn-nudges.d.ts +6 -0
  139. package/dist/workflows/run/turn-nudges.js +21 -2
  140. package/dist/workflows/run/turn-nudges.js.map +1 -1
  141. package/dist/workflows/run/turn-settler.js +6 -5
  142. package/dist/workflows/run/turn-settler.js.map +1 -1
  143. package/dist/workflows/run/wait-engine.d.ts +1 -0
  144. package/dist/workflows/run/wake-admission.d.ts +12 -0
  145. package/dist/workflows/run/wake-admission.js +27 -1
  146. package/dist/workflows/run/wake-admission.js.map +1 -1
  147. package/dist/workflows/run/wake-ledger.d.ts +8 -1
  148. package/dist/workflows/run/wake-ledger.js +12 -2
  149. package/dist/workflows/run/wake-ledger.js.map +1 -1
  150. package/dist/workflows/run/worker-executions.d.ts +2 -1
  151. package/dist/workflows/run/worker-executions.js +8 -4
  152. package/dist/workflows/run/worker-executions.js.map +1 -1
  153. package/dist/workflows/run/worker-orphans.d.ts +16 -31
  154. package/dist/workflows/run/worker-orphans.js +71 -123
  155. package/dist/workflows/run/worker-orphans.js.map +1 -1
  156. package/dist/workflows/run.d.ts +0 -2
  157. package/dist/workflows/run.js +1 -4
  158. package/dist/workflows/run.js.map +1 -1
  159. package/dist/worktree-setup.d.ts +3 -0
  160. package/dist/worktree-setup.js +2 -1
  161. package/dist/worktree-setup.js.map +1 -1
  162. package/package.json +4 -4
  163. package/web/dist/assets/{activity-motion-gOopdagH.js → activity-motion-AuQA350-.js} +1 -1
  164. package/web/dist/assets/{activity-route-D7bDtXpW.js → activity-route-BNZ9bOOZ.js} +1 -1
  165. package/web/dist/assets/{agent-accounts-otlDWnij.js → agent-accounts-D2uZHuiM.js} +1 -1
  166. package/web/dist/assets/attention-B7icDSLh.js +1 -0
  167. package/web/dist/assets/{cez-idle-TVRD1sce.js → cez-idle-MToU9Wv_.js} +1 -1
  168. package/web/dist/assets/{commit-diff-panel-iQf0Rlcx.js → commit-diff-panel-DBW7us79.js} +1 -1
  169. package/web/dist/assets/{diff-DQfcliZC.js → diff-C3Cms5Ep.js} +2 -2
  170. package/web/dist/assets/{diff-view-BbM-71Cs.js → diff-view-D5zTYOKV.js} +1 -1
  171. package/web/dist/assets/{file-preview-DgU8vo8k.js → file-preview-FhzIdXZ3.js} +1 -1
  172. package/web/dist/assets/git-toolbar-MFjkjDDG.js +1 -0
  173. package/web/dist/assets/{github-hXmxAXmA.js → github-CYmdc5Dh.js} +1 -1
  174. package/web/dist/assets/{global-activity-route-D_r1ImUh.js → global-activity-route-C41ofuHV.js} +1 -1
  175. package/web/dist/assets/index-e1OpsDKN.js +17 -0
  176. package/web/dist/assets/{live-protocol-aMLJJ0MQ.js → live-protocol-B8boP96Z.js} +1 -1
  177. package/web/dist/assets/{preview-pane-connected-D__9JwyU.js → preview-pane-connected-Ds209_UZ.js} +1 -1
  178. package/web/dist/assets/{project-router-WQWd3UUn.js → project-router-F1inY-EB.js} +1 -1
  179. package/web/dist/assets/{project-scope-context-bgdvGX9z.js → project-scope-context-0Z0nsheq.js} +2 -2
  180. package/web/dist/assets/{prompt-template-menu-BJfUg1uF.js → prompt-template-menu-uUjg9v98.js} +1 -1
  181. package/web/dist/assets/{queries-BJM44umy.js → queries-7W9tOZsg.js} +1 -1
  182. package/web/dist/assets/{reference-chip-vraIzoEF.js → reference-chip-BqRpnpaI.js} +1 -1
  183. package/web/dist/assets/{repo-git-B4qZq37d.js → repo-git-BZcRanYE.js} +1 -1
  184. package/web/dist/assets/{report-reader-Djix-ICM.js → report-reader-BLlV3dPF.js} +1 -1
  185. package/web/dist/assets/{reports-Do-dkavq.js → reports-C--EXqf1.js} +1 -1
  186. package/web/dist/assets/{run-header-Di9LaKQs.js → run-header-CJg8dyfz.js} +1 -1
  187. package/web/dist/assets/{skills-CPnIvFnR.js → skills-CHWVejdV.js} +1 -1
  188. package/web/dist/assets/{tab-link-DiNYVlpl.js → tab-link-XI9xWLwR.js} +1 -1
  189. package/web/dist/assets/{task-changes-CW7NzgL5.js → task-changes-DFm_EHnj.js} +1 -1
  190. package/web/dist/assets/{task-commits-Bkwi7o1B.js → task-commits-BX-GVdXG.js} +1 -1
  191. package/web/dist/assets/{task-files-geRzIszC.js → task-files-Dsn11PYu.js} +1 -1
  192. package/web/dist/assets/task-github-item-3N6jEijR.js +1 -0
  193. package/web/dist/assets/task-thread-VNPhkI8i.js +9 -0
  194. package/web/dist/assets/{thread-state-CajkV5Ft.js → thread-state-D1XLo7ab.js} +1 -1
  195. package/web/dist/assets/use-desktop-DdcA0Atl.js +1 -0
  196. package/web/dist/assets/use-hand-to-agent-state-2tzEmCDo.js +1 -0
  197. package/web/dist/assets/{useInfiniteQuery-s3lTx_YX.js → useInfiniteQuery-BmmIZbVY.js} +1 -1
  198. package/web/dist/assets/useQuery-CBKC2lBX.js +1 -0
  199. package/web/dist/assets/{workflows-Csr2hbks.js → workflows-CqqdPBFr.js} +1 -1
  200. package/web/dist/assets/{ws-WW6DrfbT.js → ws-BvDSfSVH.js} +1 -1
  201. package/web/dist/index.html +14 -14
  202. package/web/dist/live-worker.js +1 -1
  203. package/dist/delegation/destroy-observation.d.ts +0 -44
  204. package/dist/delegation/destroy-observation.js +0 -116
  205. package/dist/delegation/destroy-observation.js.map +0 -1
  206. package/web/dist/assets/attention-CVI366xV.js +0 -1
  207. package/web/dist/assets/git-toolbar-C8agvpYS.js +0 -1
  208. package/web/dist/assets/index-tN02NX7A.js +0 -17
  209. package/web/dist/assets/task-github-item-UbCCP2Ud.js +0 -1
  210. package/web/dist/assets/task-thread-CkiEiypn.js +0 -9
  211. package/web/dist/assets/use-desktop-Ct4lvA3b.js +0 -1
  212. package/web/dist/assets/use-hand-to-agent-state-Cnxq_2F6.js +0 -1
  213. package/web/dist/assets/useQuery-C0ee1rw5.js +0 -1
@@ -7,6 +7,12 @@ export declare function createWorkspaceLiveRoutes(live: Parameters<typeof create
7
7
  output: {
8
8
  generation: string;
9
9
  results: ({
10
+ projectId: string;
11
+ runId: string;
12
+ type: "error" | "reset";
13
+ status: 400 | 404 | 409 | 413 | 503;
14
+ error: string;
15
+ } | {
10
16
  projectId: string;
11
17
  runId: string;
12
18
  type: "batch";
@@ -20,12 +26,6 @@ export declare function createWorkspaceLiveRoutes(live: Parameters<typeof create
20
26
  cursor: string;
21
27
  afterSeq: number;
22
28
  hasMore: boolean;
23
- } | {
24
- projectId: string;
25
- runId: string;
26
- type: "error" | "reset";
27
- status: 400 | 404 | 409 | 413 | 503;
28
- error: string;
29
29
  })[];
30
30
  };
31
31
  outputFormat: "json";
@@ -0,0 +1,41 @@
1
+ /** What cgroup operations read and write; tests replace it. */
2
+ export type CgroupFs = {
3
+ readFile: (path: string) => string;
4
+ writeFile: (path: string, data: string) => void;
5
+ mkdir: (path: string) => void;
6
+ rmdir: (path: string) => void;
7
+ /** False only when nothing is there; any other lookup failure throws: it proves no absence. */
8
+ isDir: (path: string) => boolean;
9
+ /** The child cgroups directly under `path`. */
10
+ children: (path: string) => string[];
11
+ };
12
+ export declare const realCgroupFs: CgroupFs;
13
+ /** The cgroup v2 directory this process is in, from `/proc/self/cgroup`. Undefined on cgroup v1,
14
+ * a hybrid host without a unified entry, or a path that leaves the hierarchy. */
15
+ export declare function ownCgroup(fs?: CgroupFs): string | undefined;
16
+ /** The argv that runs `file args` inside the cgroup at `path`. */
17
+ export declare function cgroupCommand(path: string, file: string, args: readonly string[]): [string, string[]];
18
+ /** Whether this host lets the controller create, enter, kill and remove a child cgroup. A writable
19
+ * mount alone is no proof, so the probe does each step for real; any failure answers why. */
20
+ export declare function probeCgroups(fs?: CgroupFs, place?: (procs: string) => boolean): {
21
+ base: string;
22
+ } | {
23
+ reason: string;
24
+ };
25
+ /** Where the worker's cgroup lives under `base`. */
26
+ export declare function workerCgroupPath(base: string, workerId: string): string;
27
+ /** The worker's cgroup under `base`, created when absent. A path that exists as anything but a
28
+ * real directory throws: it is not ours. */
29
+ export declare function ensureCgroup(base: string, workerId: string, fs?: CgroupFs): string;
30
+ /** Whether `path` still holds a process; an absent group holds none. */
31
+ export declare function cgroupPopulated(path: string, fs?: CgroupFs): boolean;
32
+ /** SIGKILL every process in `path` and its descendants now. An absent group is already empty. */
33
+ export declare function killCgroup(path: string, fs?: CgroupFs): void;
34
+ /** Kill, wait until empty, remove; repeated until the group is gone or `deadline` passes. One
35
+ * `cgroup.kill` on the worker's cgroup ends every process in it and in its descendants, and its
36
+ * `populated 0` covers them all; a child cgroup the worker made (threaded ones refuse their own
37
+ * `cgroup.kill`) is then removed depth-first, since the kernel removes only a cgroup without
38
+ * children. A process that placed itself after the kill makes a removal fail with EBUSY, so the
39
+ * round repeats; once the group is removed no process can enter it. True when the group is gone;
40
+ * a lookup that fails for any reason but absence answers false, never success. */
41
+ export declare function removeCgroup(path: string, deadline: number, fs?: CgroupFs): Promise<boolean>;
@@ -0,0 +1,173 @@
1
+ /** The Linux `cgroup` backend: one private cgroup v2 child per worker, under the controller's own
2
+ * cgroup. A process places itself before its command runs, so every descendant inherits the
3
+ * group, detached ones too, and `cgroup.kill` ends them all (ADR 0032). */
4
+ import { spawnSync } from 'node:child_process';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { lstatSync, mkdirSync, readdirSync, readFileSync, rmdirSync, writeFileSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ const CGROUP_ROOT = '/sys/fs/cgroup';
9
+ const SHELL = '/bin/sh';
10
+ /** `$0` is the target `cgroup.procs`; `0` names the writer, the shell itself, which then becomes
11
+ * the command through `exec` (same pid). A failed move ends the shell before the command runs. */
12
+ const PLACE = 'echo 0 > "$0" && exec "$@"';
13
+ const POLL_MS = 10;
14
+ export const realCgroupFs = {
15
+ readFile: path => readFileSync(path, 'utf8'),
16
+ writeFile: (path, data) => writeFileSync(path, data),
17
+ mkdir: path => mkdirSync(path, { mode: 0o700 }),
18
+ rmdir: path => rmdirSync(path),
19
+ isDir: path => {
20
+ try {
21
+ const s = lstatSync(path);
22
+ return s.isDirectory() && !s.isSymbolicLink();
23
+ }
24
+ catch (error) {
25
+ if (code(error) === 'ENOENT')
26
+ return false;
27
+ throw error;
28
+ }
29
+ },
30
+ children: path => readdirSync(path, { withFileTypes: true }).filter(entry => entry.isDirectory()).map(entry => join(path, entry.name)),
31
+ };
32
+ /** The cgroup v2 directory this process is in, from `/proc/self/cgroup`. Undefined on cgroup v1,
33
+ * a hybrid host without a unified entry, or a path that leaves the hierarchy. */
34
+ export function ownCgroup(fs = realCgroupFs) {
35
+ let text;
36
+ try {
37
+ text = fs.readFile('/proc/self/cgroup');
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ const line = text.split('\n').find(entry => entry.startsWith('0::/'));
43
+ if (!line)
44
+ return undefined;
45
+ const path = line.slice(3).trim();
46
+ if (path.split('/').includes('..'))
47
+ return undefined;
48
+ return path === '/' ? CGROUP_ROOT : join(CGROUP_ROOT, path);
49
+ }
50
+ /** The argv that runs `file args` inside the cgroup at `path`. */
51
+ export function cgroupCommand(path, file, args) {
52
+ return [SHELL, ['-c', PLACE, join(path, 'cgroup.procs'), file, ...args]];
53
+ }
54
+ /** Whether this host lets the controller create, enter, kill and remove a child cgroup. A writable
55
+ * mount alone is no proof, so the probe does each step for real; any failure answers why. */
56
+ export function probeCgroups(fs = realCgroupFs, place = placeProbe) {
57
+ const base = ownCgroup(fs);
58
+ if (!base)
59
+ return { reason: 'no cgroup v2 entry in /proc/self/cgroup' };
60
+ const probe = join(base, `squawk-probe-${randomUUID()}`);
61
+ try {
62
+ fs.mkdir(probe);
63
+ }
64
+ catch (error) {
65
+ return { reason: `cannot create a child cgroup (${code(error)})` };
66
+ }
67
+ let failure;
68
+ try {
69
+ if (!place(join(probe, 'cgroup.procs')))
70
+ failure = 'cannot move a process into a child cgroup';
71
+ else
72
+ fs.writeFile(join(probe, 'cgroup.kill'), '1');
73
+ }
74
+ catch (error) {
75
+ failure = `cannot kill a child cgroup (${code(error)})`;
76
+ }
77
+ // Removal is part of the proof: a host that cannot remove a worker's cgroup cannot destroy it.
78
+ try {
79
+ fs.rmdir(probe);
80
+ }
81
+ catch (error) {
82
+ failure ??= `cannot remove a child cgroup (${code(error)})`;
83
+ }
84
+ return failure ? { reason: failure } : { base };
85
+ }
86
+ /** A shell moves itself into the probe group and exits; exit 0 means the move worked. */
87
+ function placeProbe(procs) {
88
+ const result = spawnSync(SHELL, ['-c', 'echo 0 > "$0"', procs], { stdio: 'ignore', timeout: 5_000 });
89
+ return result.status === 0;
90
+ }
91
+ const code = (error) => error.code ?? String(error);
92
+ /** Where the worker's cgroup lives under `base`. */
93
+ export function workerCgroupPath(base, workerId) {
94
+ return join(base, `squawk-worker-${workerId}`);
95
+ }
96
+ /** The worker's cgroup under `base`, created when absent. A path that exists as anything but a
97
+ * real directory throws: it is not ours. */
98
+ export function ensureCgroup(base, workerId, fs = realCgroupFs) {
99
+ const path = workerCgroupPath(base, workerId);
100
+ if (fs.isDir(path))
101
+ return path;
102
+ fs.mkdir(path);
103
+ return path;
104
+ }
105
+ /** Whether `path` still holds a process; an absent group holds none. */
106
+ export function cgroupPopulated(path, fs = realCgroupFs) {
107
+ let events;
108
+ try {
109
+ events = fs.readFile(join(path, 'cgroup.events'));
110
+ }
111
+ catch (error) {
112
+ if (code(error) === 'ENOENT')
113
+ return false;
114
+ throw error;
115
+ }
116
+ return /(?:^|\n)populated 1(?:\n|$)/.test(events);
117
+ }
118
+ /** SIGKILL every process in `path` and its descendants now. An absent group is already empty. */
119
+ export function killCgroup(path, fs = realCgroupFs) {
120
+ try {
121
+ fs.writeFile(join(path, 'cgroup.kill'), '1');
122
+ }
123
+ catch (error) {
124
+ if (code(error) !== 'ENOENT')
125
+ throw error;
126
+ }
127
+ }
128
+ /** Kill, wait until empty, remove; repeated until the group is gone or `deadline` passes. One
129
+ * `cgroup.kill` on the worker's cgroup ends every process in it and in its descendants, and its
130
+ * `populated 0` covers them all; a child cgroup the worker made (threaded ones refuse their own
131
+ * `cgroup.kill`) is then removed depth-first, since the kernel removes only a cgroup without
132
+ * children. A process that placed itself after the kill makes a removal fail with EBUSY, so the
133
+ * round repeats; once the group is removed no process can enter it. True when the group is gone;
134
+ * a lookup that fails for any reason but absence answers false, never success. */
135
+ export async function removeCgroup(path, deadline, fs = realCgroupFs) {
136
+ try {
137
+ for (;;) {
138
+ if (!fs.isDir(path))
139
+ return true;
140
+ killCgroup(path, fs);
141
+ while (cgroupPopulated(path, fs) && Date.now() < deadline)
142
+ await sleep(POLL_MS);
143
+ const removed = removeTree(path, fs);
144
+ if (removed === true)
145
+ return true;
146
+ if (removed === 'fatal' || Date.now() >= deadline)
147
+ return false;
148
+ await sleep(POLL_MS);
149
+ }
150
+ }
151
+ catch {
152
+ return false;
153
+ }
154
+ }
155
+ /** Removes `path` and its child cgroups, deepest first. `busy` when a cgroup still holds a process. */
156
+ function removeTree(path, fs) {
157
+ for (const child of fs.children(path)) {
158
+ const removed = removeTree(child, fs);
159
+ if (removed !== true)
160
+ return removed;
161
+ }
162
+ try {
163
+ fs.rmdir(path);
164
+ return true;
165
+ }
166
+ catch (error) {
167
+ if (code(error) === 'ENOENT')
168
+ return true;
169
+ return code(error) === 'EBUSY' ? 'busy' : 'fatal';
170
+ }
171
+ }
172
+ const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
173
+ //# sourceMappingURL=cgroup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cgroup.js","sourceRoot":"","sources":["../../src/worker-scope/cgroup.ts"],"names":[],"mappings":"AAAA;;2EAE2E;AAC3E,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACpG,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,MAAM,WAAW,GAAG,gBAAgB,CAAC;AACrC,MAAM,KAAK,GAAG,SAAS,CAAC;AACxB;kGACkG;AAClG,MAAM,KAAK,GAAG,4BAA4B,CAAC;AAC3C,MAAM,OAAO,GAAG,EAAE,CAAC;AAanB,MAAM,CAAC,MAAM,YAAY,GAAa;IACpC,QAAQ,EAAE,IAAI,CAAC,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC;IAC5C,SAAS,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,aAAa,CAAC,IAAI,EAAE,IAAI,CAAC;IACpD,KAAK,EAAE,IAAI,CAAC,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;IAC/C,KAAK,EAAE,IAAI,CAAC,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC;IAC9B,KA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AAO,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,QAAQ;gBAAE,OAAO,KAAK,CAAC;YAChE,MAAM,KAAK,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;IACH,CAAC;IAAC,MAAM,CAAC;QAAC,OAAO,KAAK,CAAC;IAAC,CAAC;AAC3B,CAAC;AAED,uGAAuG;AACvG,SAAS,UAAU,CAAC,IAAY,EAAE,EAAY;IAC5C,KAAK,MAAM,KAAK,IAAI,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QACtC,MAAM,OAAO,GAAG,UAAU,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACtC,IAAI,OAAO,KAAK,IAAI;YAAE,OAAO,OAAO,CAAC;IACvC,CAAC;IACD,IAAI,CAAC;QAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAAC,OAAO,IAAI,CAAC;IAAC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAClD,IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAC;QAC1C,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;IACpD,CAAC;AACH,CAAC;AAED,MAAM,KAAK,GAAG,CAAC,EAAU,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC"}
@@ -0,0 +1,24 @@
1
+ import { type RecordedProcess } from '../core/process-stat.ts';
2
+ /** A group leader at spawn: its pid is its group id. */
3
+ export declare function groupEntry(pid: number): RecordedProcess;
4
+ /** Whether the recorded group is the one Squawk started. A live leader must be the recorded
5
+ * incarnation. A group whose leader is gone keeps its number while it has members, and the kernel
6
+ * does not reuse a pid while a group of that number exists; a reused number needs the group to
7
+ * empty first. So a leaderless group counts only where the record proves this boot: on Linux the
8
+ * start token carries the boot id, and a token from another boot (or none) is refused. The
9
+ * remaining case, the pid space wrapping within one boot while the worker lives, is ADR 0032's
10
+ * stated residual. Elsewhere (macOS: no boot id, a small pid space) a leaderless group is never
11
+ * signalled. */
12
+ export declare function groupOwned(entry: RecordedProcess): boolean;
13
+ /** SIGKILL every recorded group that is still ours, and every recorded process outside a group
14
+ * that is still the recorded incarnation. */
15
+ export declare function killGroups(entries: readonly RecordedProcess[]): void;
16
+ /** After a SIGKILL to the whole group, the recorded entries that still have a running process: a
17
+ * leader that is still the recorded incarnation, or, for a group of ours whose leader is gone, a
18
+ * running member (a zombie whose other threads run counts: they still hold its sockets). A SIGKILL takes effect asynchronously, so a member can still hold a
19
+ * port for a moment; a group of zombies still answers `kill(-pgid, 0)` until its reaper reaps it,
20
+ * which an init that does not reap never does, so zombies are never waited for. */
21
+ export declare function groupsStillStopping(entries: readonly RecordedProcess[]): RecordedProcess[];
22
+ /** The recorded groups that are still ours and have a member, and the recorded processes outside
23
+ * a group that are still the recorded incarnation. */
24
+ export declare function liveGroups(entries: readonly RecordedProcess[]): RecordedProcess[];
@@ -0,0 +1,60 @@
1
+ /** The `groups` backend: the worker's recorded POSIX process groups. A process that leaves its group
2
+ * (`setsid`, Node `detached`) is outside it; ADR 0032 states that limit. */
3
+ import { processGroupAlive, processGroupRunning, signalProcessGroup } from '../core/session-process.js';
4
+ import { linuxBootId, pidExists, processStartToken } from '../core/process-stat.js';
5
+ /** A group leader at spawn: its pid is its group id. */
6
+ export function groupEntry(pid) {
7
+ const startToken = processStartToken(pid);
8
+ return { pid, pgid: pid, ...(startToken === undefined ? {} : { startToken }) };
9
+ }
10
+ /** Whether the recorded group is the one Squawk started. A live leader must be the recorded
11
+ * incarnation. A group whose leader is gone keeps its number while it has members, and the kernel
12
+ * does not reuse a pid while a group of that number exists; a reused number needs the group to
13
+ * empty first. So a leaderless group counts only where the record proves this boot: on Linux the
14
+ * start token carries the boot id, and a token from another boot (or none) is refused. The
15
+ * remaining case, the pid space wrapping within one boot while the worker lives, is ADR 0032's
16
+ * stated residual. Elsewhere (macOS: no boot id, a small pid space) a leaderless group is never
17
+ * signalled. */
18
+ export function groupOwned(entry) {
19
+ if (entry.pgid === undefined || entry.pgid !== entry.pid || entry.startToken === undefined || !processGroupAlive(entry.pgid))
20
+ return false;
21
+ if (pidExists(entry.pid))
22
+ return processStartToken(entry.pid) === entry.startToken;
23
+ const boot = process.platform === 'linux' ? linuxBootId() : undefined;
24
+ return boot !== undefined && entry.startToken.startsWith(`${boot}:`);
25
+ }
26
+ /** SIGKILL every recorded group that is still ours, and every recorded process outside a group
27
+ * that is still the recorded incarnation. */
28
+ export function killGroups(entries) {
29
+ for (const entry of entries) {
30
+ if (entry.pgid !== undefined) {
31
+ if (groupOwned(entry))
32
+ signalProcessGroup(entry.pgid, 'SIGKILL');
33
+ }
34
+ else if (entry.startToken !== undefined && processStartToken(entry.pid) === entry.startToken) {
35
+ try {
36
+ process.kill(entry.pid, 'SIGKILL');
37
+ }
38
+ catch { /* already gone */ }
39
+ }
40
+ }
41
+ }
42
+ /** After a SIGKILL to the whole group, the recorded entries that still have a running process: a
43
+ * leader that is still the recorded incarnation, or, for a group of ours whose leader is gone, a
44
+ * running member (a zombie whose other threads run counts: they still hold its sockets). A SIGKILL takes effect asynchronously, so a member can still hold a
45
+ * port for a moment; a group of zombies still answers `kill(-pgid, 0)` until its reaper reaps it,
46
+ * which an init that does not reap never does, so zombies are never waited for. */
47
+ export function groupsStillStopping(entries) {
48
+ return entries.filter(entry => {
49
+ if (entry.startToken !== undefined && pidExists(entry.pid) && processStartToken(entry.pid) === entry.startToken)
50
+ return true;
51
+ return entry.pgid !== undefined && groupOwned(entry) && processGroupRunning(entry.pgid);
52
+ });
53
+ }
54
+ /** The recorded groups that are still ours and have a member, and the recorded processes outside
55
+ * a group that are still the recorded incarnation. */
56
+ export function liveGroups(entries) {
57
+ return entries.filter(entry => entry.pgid !== undefined ? groupOwned(entry)
58
+ : entry.startToken !== undefined && pidExists(entry.pid) && processStartToken(entry.pid) === entry.startToken);
59
+ }
60
+ //# sourceMappingURL=groups.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"groups.js","sourceRoot":"","sources":["../../src/worker-scope/groups.ts"],"names":[],"mappings":"AAAA;4EAC4E;AAC5E,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AACxG,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,iBAAiB,EAAwB,MAAM,yBAAyB,CAAC;AAE1G,wDAAwD;AACxD,MAAM,UAAU,UAAU,CAAC,GAAW;IACpC,MAAM,UAAU,GAAG,iBAAiB,CAAC,GAAG,CAAC,CAAC;IAC1C,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,CAAC;AACjF,CAAC;AAED;;;;;;;gBAOgB;AAChB,MAAM,UAAU,UAAU,CAAC,KAAsB;IAC/C,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,GAAG,IAAI,KAAK,CAAC,UAAU,KAAK,SAAS,IAAI,CAAC,iBAAiB,CAAC,KAAK,CAAC,IAAI,CAAC;QAAE,OAAO,KAAK,CAAC;IAC3I,IAAI,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC;QAAE,OAAO,iBAAiB,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC,UAAU,CAAC;IACnF,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;IACtE,OAAO,IAAI,KAAK,SAAS,IAAI,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC;A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AC,KAAK,CAAC,UAAU,KAAK,SAAS,IAAI,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,iBAAiB,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,KAAK,CAAC,UAAU,CAAC,CAAC;AACnH,CAAC"}
@@ -0,0 +1,32 @@
1
+ /** What a worker scope is: the set of OS containers that hold every process Squawk starts for one
2
+ * worker, and the record that names them. ADR 0032. */
3
+ import { z } from 'zod';
4
+ /** How a host contains a worker. `cgroup`: a private Linux cgroup, which every descendant inherits.
5
+ * `groups`: the worker's own POSIX process groups, which a detached descendant can leave. */
6
+ export type ScopeBackend = 'cgroup' | 'groups';
7
+ /** `contained`: stopping the scope ends every descendant. `scoped`: it ends the recorded groups
8
+ * only; a descendant that left them survives. */
9
+ export type ScopeGuarantee = 'contained' | 'scoped';
10
+ export declare const GUARANTEE: Readonly<Record<ScopeBackend, ScopeGuarantee>>;
11
+ /** Recorded groups kept per worker. A dead group is dropped before a new one is added. */
12
+ export declare const SCOPE_GROUP_CAP = 64;
13
+ /** Recorded cgroups kept per worker: one per controller cgroup it was spawned from. */
14
+ export declare const SCOPE_CGROUP_CAP = 8;
15
+ /** Everything one worker owns. It holds both kinds, so a worker started under one backend and
16
+ * continued under another (a controller restarted elsewhere) is stopped whole. */
17
+ export declare const scopeRecordSchema: z.ZodObject<{
18
+ workerId: z.ZodString;
19
+ cgroups: z.ZodArray<z.ZodString>;
20
+ groups: z.ZodArray<z.ZodObject<{
21
+ pid: z.ZodNumber;
22
+ startToken: z.ZodOptional<z.ZodString>;
23
+ pgid: z.ZodOptional<z.ZodNumber>;
24
+ }, z.core.$strict>>;
25
+ }, z.core.$strict>;
26
+ export type ScopeRecord = z.infer<typeof scopeRecordSchema>;
27
+ /** What a spawn site needs: the argv that runs a command inside the scope, and a report of the
28
+ * process it started. `command` may throw; the caller then starts nothing. */
29
+ export interface SpawnScope {
30
+ command(file: string, args: readonly string[]): [string, string[]];
31
+ started(pid: number): void;
32
+ }
@@ -0,0 +1,18 @@
1
+ /** What a worker scope is: the set of OS containers that hold every process Squawk starts for one
2
+ * worker, and the record that names them. ADR 0032. */
3
+ import { z } from 'zod';
4
+ export const GUARANTEE = { cgroup: 'contained', groups: 'scoped' };
5
+ /** Recorded groups kept per worker. A dead group is dropped before a new one is added. */
6
+ export const SCOPE_GROUP_CAP = 64;
7
+ /** Recorded cgroups kept per worker: one per controller cgroup it was spawned from. */
8
+ export const SCOPE_CGROUP_CAP = 8;
9
+ const recordedGroupSchema = z.object({ pid: z.number().int().positive(), startToken: z.string().min(1).max(128).optional(),
10
+ pgid: z.number().int().positive().optional() }).strict();
11
+ /** Everything one worker owns. It holds both kinds, so a worker started under one backend and
12
+ * continued under another (a controller restarted elsewhere) is stopped whole. */
13
+ export const scopeRecordSchema = z.object({
14
+ workerId: z.string().uuid(),
15
+ cgroups: z.array(z.string().startsWith('/sys/fs/cgroup/').max(4096)).max(SCOPE_CGROUP_CAP),
16
+ groups: z.array(recordedGroupSchema).max(SCOPE_GROUP_CAP),
17
+ }).strict();
18
+ //# sourceMappingURL=scope.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scope.js","sourceRoot":"","sources":["../../src/worker-scope/scope.ts"],"names":[],"mappings":"AAAA;uDACuD;AACvD,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAQxB,MAAM,CAAC,MAAM,SAAS,GAAmD,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;AAEnH,0FAA0F;AAC1F,MAAM,CAAC,MAAM,eAAe,GAAG,EAAE,CAAC;AAClC,uFAAuF;AACvF,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAElC,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,EAAE,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE;IACxH,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC;AAE3D;kFACkF;AAClF,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAC,MAAM,CAAC;IACxC,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE;IAC3B,OAAO,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,UAAU,CAAC,iBAAiB,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,gBAAgB,CAAC;IAC1F,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,mBAAmB,CAAC,CAAC,GAAG,CAAC,eAAe,CAAC;CAC1D,CAAC,CAAC,MAAM,EAAE,CAAC"}
@@ -0,0 +1,63 @@
1
+ import type { RunRecord } from '../contract/index.js';
2
+ import type { WorkerProcessRecord } from '../delegation/process-liveness.ts';
3
+ import { type ScopeBackend, type ScopeGuarantee, type ScopeRecord, type SpawnScope } from './scope.ts';
4
+ export type HostScope = {
5
+ backend: 'cgroup';
6
+ base: string;
7
+ } | {
8
+ backend: 'groups';
9
+ reason: string;
10
+ };
11
+ /** This controller's backend: `cgroup` where a real probe proves delegation, else `groups`. */
12
+ export declare function hostScope(): HostScope;
13
+ /** Tests pin the backend; `undefined` re-probes on next use. */
14
+ export declare function setHostScope(value: HostScope | undefined): void;
15
+ /** The store operations a scope needs. */
16
+ export interface ScopeStore {
17
+ readWorkerScope(id: string): ScopeRecord | 'absent' | 'unknown';
18
+ writeWorkerScope(id: string, record: ScopeRecord): void;
19
+ getRun(id: string): RunRecord | undefined;
20
+ readWorkerExecution(id: string): {
21
+ generation: string;
22
+ } | undefined;
23
+ readWorkerProcesses(id: string, generation: string): WorkerProcessRecord | 'absent' | 'unknown';
24
+ }
25
+ export declare class WorkerScopeUnreadable extends Error {
26
+ constructor();
27
+ }
28
+ export type ScopeStop = {
29
+ stopped: true;
30
+ } | {
31
+ stopped: false;
32
+ error: string;
33
+ };
34
+ export declare class WorkerScopes {
35
+ private readonly store;
36
+ private readonly hostOf;
37
+ constructor(store: ScopeStore, hostOf?: () => HostScope);
38
+ describe(): {
39
+ backend: ScopeBackend;
40
+ guarantee: ScopeGuarantee;
41
+ };
42
+ /** The scope every process of `workerId` starts in. The record names a cgroup before the cgroup
43
+ * exists and before anything enters it, so a crash at any point leaves nothing unrecorded. */
44
+ spawnScope(workerId: string): SpawnScope;
45
+ /** Whether no process the worker owns still runs: its cgroups are unpopulated and none of its
46
+ * recorded groups has a member. An unreadable record is not empty. */
47
+ empty(workerId: string): boolean;
48
+ /** After `kill`: whether nothing the worker owned still runs. A cgroup drops a task when it exits,
49
+ * zombie or not; a group counts while its recorded leader runs (see `groupsStillStopping`). */
50
+ stopped(workerId: string): boolean;
51
+ /** SIGKILL everything the worker owns, now, without waiting. */
52
+ kill(workerId: string): void;
53
+ /** End everything the worker owns and remove its cgroups, within `timeoutMs`. What could not be
54
+ * stopped stays recorded, so a retry starts from it. */
55
+ stop(workerId: string, timeoutMs: number): Promise<ScopeStop>;
56
+ /** One kill-and-wait over the record as read now; `late` when the record gained entries meanwhile. */
57
+ private stopRound;
58
+ private read;
59
+ /** The record's groups and the current execution's recorded processes, without duplicates. A
60
+ * worker created before scopes has its session groups only in its execution record. */
61
+ private groups;
62
+ private update;
63
+ }
@@ -0,0 +1,181 @@
1
+ /** The one place lifecycle code reaches a worker's scope: spawn sites wrap their command through
2
+ * `spawnScope`, Continue after a crash calls `kill`, destroy calls `stop`. The host's backend is
3
+ * picked once per controller and never changes inside it; a backend error fails the operation
4
+ * that met it, never falls back to another mechanism (ADR 0032). */
5
+ import { logPrefix } from '../home/display.js';
6
+ import { cgroupCommand, cgroupPopulated, ensureCgroup, killCgroup, probeCgroups, removeCgroup, workerCgroupPath } from './cgroup.js';
7
+ import { groupEntry, groupsStillStopping, killGroups, liveGroups } from './groups.js';
8
+ import { GUARANTEE, SCOPE_CGROUP_CAP, SCOPE_GROUP_CAP } from './scope.js';
9
+ let host;
10
+ /** This controller's backend: `cgroup` where a real probe proves delegation, else `groups`. */
11
+ export function hostScope() {
12
+ if (host)
13
+ return host;
14
+ const probe = process.platform === 'linux' ? probeCgroups() : { reason: `${process.platform} has no cgroups` };
15
+ host = 'base' in probe ? { backend: 'cgroup', base: probe.base } : { backend: 'groups', reason: probe.reason };
16
+ console.info(`${logPrefix()} worker scope: ${host.backend === 'cgroup' ? `cgroup (contained) under ${host.base}`
17
+ : `process groups (scoped: a detached descendant can outlive destroy) — ${host.reason}`}`);
18
+ return host;
19
+ }
20
+ /** Tests pin the backend; `undefined` re-probes on next use. */
21
+ export function setHostScope(value) { host = value; }
22
+ export class WorkerScopeUnreadable extends Error {
23
+ constructor() { super("the worker's scope record is unreadable; its processes cannot be found"); }
24
+ }
25
+ const key = (entry) => `${entry.pid}:${entry.startToken}`;
26
+ const capacityError = (workerId) => new Error(`worker ${workerId} already owns ${SCOPE_GROUP_CAP} live process groups`);
27
+ const STOP_POLL_MS = 10;
28
+ export class WorkerScopes {
29
+ store;
30
+ hostOf;
31
+ constructor(store, hostOf = hostScope) {
32
+ this.store = store;
33
+ this.hostOf = hostOf;
34
+ }
35
+ describe() {
36
+ const { backend } = this.hostOf();
37
+ return { backend, guarantee: GUARANTEE[backend] };
38
+ }
39
+ /** The scope every process of `workerId` starts in. The record names a cgroup before the cgroup
40
+ * exists and before anything enters it, so a crash at any point leaves nothing unrecorded. */
41
+ spawnScope(workerId) {
42
+ return {
43
+ command: (file, args) => {
44
+ const run = this.store.getRun(workerId);
45
+ if (run?.delegation?.role === 'worker' && run.delegation.destroy)
46
+ throw new Error('Worker destruction has begun; nothing new starts in its scope');
47
+ const host = this.hostOf();
48
+ // Refused before anything runs: a full group record never has to end a started process.
49
+ if (host.backend === 'groups' && liveGroups(this.read(workerId).groups).length >= SCOPE_GROUP_CAP)
50
+ throw capacityError(workerId);
51
+ if (host.backend !== 'cgroup')
52
+ return [file, [...args]];
53
+ const path = workerCgroupPath(host.base, workerId);
54
+ this.update(workerId, record => {
55
+ if (record.cgroups.includes(path))
56
+ return record;
57
+ if (record.cgroups.length >= SCOPE_CGROUP_CAP)
58
+ throw new Error(`worker ${workerId} already spans ${SCOPE_CGROUP_CAP} cgroups`);
59
+ return { ...record, cgroups: [...record.cgroups, path] };
60
+ });
61
+ return cgroupCommand(ensureCgroup(host.base, workerId), file, args);
62
+ },
63
+ started: pid => {
64
+ if (this.hostOf().backend !== 'groups' || process.platform === 'win32')
65
+ return;
66
+ this.update(workerId, record => {
67
+ const live = liveGroups(record.groups);
68
+ // Never forget a live group to make room: refuse the start instead (the caller ends it).
69
+ if (live.length >= SCOPE_GROUP_CAP)
70
+ throw capacityError(workerId);
71
+ const entry = groupEntry(pid);
72
+ // Without a start token the group can never be proven ours, so it could never be stopped:
73
+ // refuse it, and the spawn site ends the group now.
74
+ if (entry.startToken === undefined)
75
+ throw new Error(`process ${pid} exited before its identity could be recorded`);
76
+ return { ...record, groups: [...live, entry] };
77
+ });
78
+ },
79
+ };
80
+ }
81
+ /** Whether no process the worker owns still runs: its cgroups are unpopulated and none of its
82
+ * recorded groups has a member. An unreadable record is not empty. */
83
+ empty(workerId) {
84
+ let record;
85
+ try {
86
+ record = this.read(workerId);
87
+ }
88
+ catch {
89
+ return false;
90
+ }
91
+ return !record.cgroups.some(path => cgroupPopulated(path)) && !liveGroups(this.groups(workerId, record)).length;
92
+ }
93
+ /** After `kill`: whether nothing the worker owned still runs. A cgroup drops a task when it exits,
94
+ * zombie or not; a group counts while its recorded leader runs (see `groupsStillStopping`). */
95
+ stopped(workerId) {
96
+ let record;
97
+ try {
98
+ record = this.read(workerId);
99
+ }
100
+ catch {
101
+ return false;
102
+ }
103
+ return !record.cgroups.some(path => cgroupPopulated(path)) && !groupsStillStopping(this.groups(workerId, record)).length;
104
+ }
105
+ /** SIGKILL everything the worker owns, now, without waiting. */
106
+ kill(workerId) {
107
+ const record = this.read(workerId);
108
+ for (const path of record.cgroups)
109
+ killCgroup(path);
110
+ killGroups(this.groups(workerId, record));
111
+ }
112
+ /** End everything the worker owns and remove its cgroups, within `timeoutMs`. What could not be
113
+ * stopped stays recorded, so a retry starts from it. */
114
+ async stop(workerId, timeoutMs) {
115
+ const deadline = Date.now() + timeoutMs;
116
+ for (;;) {
117
+ const round = await this.stopRound(workerId, deadline, timeoutMs);
118
+ // A start admitted before destroy began can register while a round waits: stop it too.
119
+ if (round !== 'late')
120
+ return round;
121
+ if (Date.now() >= deadline)
122
+ return { stopped: false, error: `worker processes started while stopping did not stop within ${Math.round(timeoutMs / 1000)}s` };
123
+ }
124
+ }
125
+ /** One kill-and-wait over the record as read now; `late` when the record gained entries meanwhile. */
126
+ async stopRound(workerId, deadline, timeoutMs) {
127
+ let record;
128
+ try {
129
+ record = this.read(workerId);
130
+ }
131
+ catch (error) {
132
+ return { stopped: false, error: error.message };
133
+ }
134
+ killGroups(this.groups(workerId, record));
135
+ const cgroups = [];
136
+ for (const path of record.cgroups)
137
+ if (!await removeCgroup(path, deadline))
138
+ cgroups.push(path);
139
+ let groups = groupsStillStopping(this.groups(workerId, record));
140
+ while (groups.length && Date.now() < deadline) {
141
+ await new Promise(resolve => setTimeout(resolve, STOP_POLL_MS));
142
+ groups = groupsStillStopping(groups);
143
+ }
144
+ // Merged into the record as it is now: an entry written while this stop waited is kept, and only
145
+ // what this stop ended leaves it. Groups only the execution record names stay there.
146
+ const removed = new Set(record.cgroups.filter(path => !cgroups.includes(path)));
147
+ const ended = new Set(record.groups.filter(group => !groups.some(left => key(left) === key(group))).map(key));
148
+ let late = false;
149
+ this.update(workerId, current => {
150
+ late = current.cgroups.some(path => !record.cgroups.includes(path)) || current.groups.some(group => !record.groups.some(known => key(known) === key(group)));
151
+ return { ...current, cgroups: current.cgroups.filter(path => !removed.has(path)), groups: current.groups.filter(group => !ended.has(key(group))) };
152
+ });
153
+ if (late)
154
+ return 'late';
155
+ if (!cgroups.length && !groups.length)
156
+ return { stopped: true };
157
+ return { stopped: false, error: `worker processes did not stop within ${Math.round(timeoutMs / 1000)}s: ${[...cgroups.map(path => `cgroup ${path}`), ...groups.map(group => `process group ${group.pgid}`)].join(', ')}` };
158
+ }
159
+ read(workerId) {
160
+ const record = this.store.readWorkerScope(workerId);
161
+ if (record === 'unknown')
162
+ throw new WorkerScopeUnreadable();
163
+ return record === 'absent' ? { workerId, cgroups: [], groups: [] } : record;
164
+ }
165
+ /** The record's groups and the current execution's recorded processes, without duplicates. A
166
+ * worker created before scopes has its session groups only in its execution record. */
167
+ groups(workerId, record) {
168
+ const generation = this.store.readWorkerExecution(workerId)?.generation;
169
+ const execution = generation ? this.store.readWorkerProcesses(workerId, generation) : 'absent';
170
+ const seen = new Set(record.groups.map(key));
171
+ const recorded = typeof execution === 'string' ? [] : execution.processes;
172
+ return [...record.groups, ...recorded.filter(entry => !seen.has(key(entry)))];
173
+ }
174
+ update(workerId, change) {
175
+ const record = this.read(workerId);
176
+ const next = change(record);
177
+ if (next !== record)
178
+ this.store.writeWorkerScope(workerId, next);
179
+ }
180
+ }
181
+ //# sourceMappingURL=worker-scopes.js.map