agent-supervisor-mcp 0.0.0-stage → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +208 -0
  3. package/README.md +206 -2
  4. package/package.json +76 -4
  5. package/skills/agent-supervisor/SKILL.md +139 -0
  6. package/src/app/acceptance.js +263 -0
  7. package/src/app/auto-cleanup.js +91 -0
  8. package/src/app/cancel.js +57 -0
  9. package/src/app/cleanup-facts.js +101 -0
  10. package/src/app/cleanup-plan.js +166 -0
  11. package/src/app/compose.js +17 -0
  12. package/src/app/context-compiler.js +83 -0
  13. package/src/app/dispatch.js +398 -0
  14. package/src/app/followup.js +104 -0
  15. package/src/app/land-chain.js +134 -0
  16. package/src/app/landing.js +357 -0
  17. package/src/app/ownership.js +57 -0
  18. package/src/app/rebase.js +216 -0
  19. package/src/app/restore-worktree.js +51 -0
  20. package/src/app/resume.js +179 -0
  21. package/src/app/run-state.js +26 -0
  22. package/src/app/settled.js +28 -0
  23. package/src/app/side-chat.js +370 -0
  24. package/src/app/sse.js +20 -0
  25. package/src/app/start-run.js +77 -0
  26. package/src/app/verify-push.js +114 -0
  27. package/src/app/worktree-setup.js +218 -0
  28. package/src/domain/acceptance-baseline.js +65 -0
  29. package/src/domain/acceptance-spec.js +30 -0
  30. package/src/domain/cleanup-policy.js +44 -0
  31. package/src/domain/command-outcome.js +6 -0
  32. package/src/domain/failure-class.js +63 -0
  33. package/src/domain/owned-changes.js +27 -0
  34. package/src/domain/prompt.js +161 -0
  35. package/src/domain/side-turn-view.js +73 -0
  36. package/src/domain/status.js +50 -0
  37. package/src/domain/thread-health.js +33 -0
  38. package/src/domain/truncate.js +148 -0
  39. package/src/domain/worker-branch.js +6 -0
  40. package/src/domain/worker-changes.js +58 -0
  41. package/src/domain/worker-env.js +14 -0
  42. package/src/domain/worker-preflight.js +167 -0
  43. package/src/domain/worker-report.js +85 -0
  44. package/src/domain/worker-report.schema.json +10 -0
  45. package/src/infra/bin-resolver.js +287 -0
  46. package/src/infra/cleanup-hint.js +29 -0
  47. package/src/infra/crash-guard.js +44 -0
  48. package/src/infra/external-output.js +29 -0
  49. package/src/infra/git.js +61 -0
  50. package/src/infra/handoff.js +38 -0
  51. package/src/infra/paths.js +34 -0
  52. package/src/infra/process.js +59 -0
  53. package/src/infra/sandbox-roots.js +106 -0
  54. package/src/infra/skill-sync.js +109 -0
  55. package/src/infra/stage-store.js +39 -0
  56. package/src/infra/store/db.js +265 -0
  57. package/src/infra/store/event-body.js +82 -0
  58. package/src/infra/store/events.js +149 -0
  59. package/src/infra/store/facts.js +338 -0
  60. package/src/infra/store/reconcile.js +173 -0
  61. package/src/infra/store/records.js +171 -0
  62. package/src/infra/store/runner-readers.js +16 -0
  63. package/src/infra/store/schema.js +306 -0
  64. package/src/infra/store/sessions.js +138 -0
  65. package/src/infra/store/tasks.js +351 -0
  66. package/src/infra/update/auto-update-worker.js +186 -0
  67. package/src/infra/update/auto-update.js +143 -0
  68. package/src/infra/update/update-check.js +246 -0
  69. package/src/infra/workspace-kind.js +165 -0
  70. package/src/infra/worktree.js +361 -0
  71. package/src/interface/bin/acceptance-cli.js +62 -0
  72. package/src/interface/bin/cleanup.js +81 -0
  73. package/src/interface/bin/monitor.jsx +301 -0
  74. package/src/interface/bin/setup.js +342 -0
  75. package/src/interface/bin/stage.js +17 -0
  76. package/src/interface/bin/web-server.js +53 -0
  77. package/src/interface/mcp/handlers/delivery.js +165 -0
  78. package/src/interface/mcp/handlers/dispatch.js +236 -0
  79. package/src/interface/mcp/handlers/facts.js +204 -0
  80. package/src/interface/mcp/handlers/overview.js +106 -0
  81. package/src/interface/mcp/handlers/results.js +262 -0
  82. package/src/interface/mcp/handlers/review.js +115 -0
  83. package/src/interface/mcp/handlers/wait.js +141 -0
  84. package/src/interface/mcp/meta.js +7 -0
  85. package/src/interface/mcp/result.js +34 -0
  86. package/src/interface/mcp/schemas.js +24 -0
  87. package/src/interface/mcp/server.js +64 -0
  88. package/src/interface/mcp/tools/deliver.js +48 -0
  89. package/src/interface/mcp/tools/dispatch.js +90 -0
  90. package/src/interface/mcp/tools/optional.js +57 -0
  91. package/src/interface/mcp/tools/read.js +115 -0
  92. package/src/interface/mcp/tools/run.js +57 -0
  93. package/src/interface/mcp/tools/shapes.js +67 -0
  94. package/src/interface/mcp/tools/track.js +84 -0
  95. package/src/interface/mcp/update-state.js +34 -0
  96. package/src/interface/mcp/views/overview.js +183 -0
  97. package/src/interface/mcp/views/task.js +224 -0
  98. package/src/interface/web/app.js +226 -0
  99. package/src/interface/web/views.js +227 -0
  100. package/src/mcp-server.js +4 -0
  101. package/src/run-host/entry.js +26 -0
  102. package/src/run-host/finalize.js +243 -0
  103. package/src/run-host/launch.js +49 -0
  104. package/src/run-host/live-run.js +76 -0
  105. package/src/run-host/outcome-facts.js +61 -0
  106. package/src/run-host/streams.js +102 -0
  107. package/src/run-host/track.js +132 -0
  108. package/src/runners/claude/adapter.js +118 -0
  109. package/src/runners/claude/events.js +100 -0
  110. package/src/runners/claude/tool-guard.js +48 -0
  111. package/src/runners/codex/adapter.js +157 -0
  112. package/src/runners/codex/chat-chunks.js +97 -0
  113. package/src/runners/codex/event-parser.js +266 -0
  114. package/src/runners/codex/goal-store.js +54 -0
  115. package/src/runners/codex/mcp-config.js +39 -0
  116. package/src/runners/codex/tool-guard.js +184 -0
  117. package/src/runners/contract-check.js +82 -0
  118. package/src/runners/contract.js +53 -0
  119. package/src/runners/registry.js +45 -0
  120. package/web/dist/assets/index-D-A2xlpx.js +154 -0
  121. package/web/dist/assets/index-f8esISCp.css +2 -0
  122. package/web/dist/index.html +15 -0
@@ -0,0 +1,287 @@
1
+ // Turns a CLI name into something Node can actually spawn.
2
+ //
3
+ // Why this exists: on Windows npm installs a CLI as a `codex.cmd` / `codex.ps1`
4
+ // shim rather than an executable, and since the CVE-2024-27980 hardening in
5
+ // Node 18.20 / 20.12 `spawn` with shell:false refuses to run one (EINVAL), so
6
+ // the worker never starts. `shell: true` would "fix" that at the cost of the
7
+ // kill semantics this project depends on: the shell becomes the child, so
8
+ // cancelling a task kills cmd.exe and leaves the real Codex process running,
9
+ // which wedges the state machine in `running`.
10
+ //
11
+ // So instead of shelling out, resolve a spawnable target: a real .exe, or -
12
+ // for the npm shim case - the package's own entry point, run under node.
13
+ //
14
+ // Platform, env, filesystem probe and node path are all injectable, so the
15
+ // win32 branch is unit-testable from macOS and Linux.
16
+ import { existsSync } from "node:fs";
17
+ import { homedir } from "node:os";
18
+ import path from "node:path";
19
+
20
+ /** Windows extensions Node/libuv can hand straight to CreateProcess. */
21
+ const DIRECT_EXTS = new Set([".exe", ".com"]);
22
+ /** Windows extensions that need an interpreter - the npm-shim case. */
23
+ const SHIM_EXTS = new Set([".cmd", ".bat", ".ps1"]);
24
+ /** Fallback when PATHEXT is unset, matching the Windows default. */
25
+ const DEFAULT_PATHEXT = ".COM;.EXE;.BAT;.CMD";
26
+ /** Extensions that need node in front of them on every platform. */
27
+ const JS_EXTS = new Set([".js", ".cjs", ".mjs"]);
28
+
29
+ /**
30
+ * Well-known global install directories, probed after PATH. A CLI installed with
31
+ * a custom npm prefix or a version manager is usually absent from a
32
+ * non-interactive PATH, and without this it would look "not installed" even
33
+ * though the user runs it every day. The Windows entries are env-derived, so
34
+ * they simply drop out elsewhere.
35
+ *
36
+ * @param {Object} [options]
37
+ * @param {Record<string, string|undefined>} [options.env]
38
+ * @param {string} [options.home]
39
+ * @returns {string[]}
40
+ */
41
+ export function defaultBinDirs(options = {}) {
42
+ const env = options.env ?? process.env;
43
+ const home = options.home ?? homedir();
44
+ const dirs = [
45
+ path.join(home, ".npm-global", "bin"),
46
+ path.join(home, ".local", "bin"),
47
+ path.join(home, ".bun", "bin"),
48
+ path.join(home, ".volta", "bin"),
49
+ path.join(home, "Library", "pnpm"),
50
+ "/opt/homebrew/bin",
51
+ "/usr/local/bin"
52
+ ];
53
+ for (const [variable, ...segments] of [
54
+ ["APPDATA", "npm"], // npm global prefix on Windows
55
+ ["LOCALAPPDATA", "pnpm"],
56
+ ["LOCALAPPDATA", "Volta", "bin"],
57
+ ["ProgramFiles", "nodejs"] // nvm-windows and the official installer
58
+ ]) {
59
+ const root = env[variable]?.trim();
60
+ if (root) dirs.push(path.join(root, ...segments));
61
+ }
62
+ return dirs;
63
+ }
64
+
65
+ const isWindows = (platform) => platform === "win32";
66
+ const pathImpl = (platform) => (isWindows(platform) ? path.win32 : path.posix);
67
+ const listSeparator = (platform) => (isWindows(platform) ? ";" : ":");
68
+
69
+ /**
70
+ * @typedef {Object} NpmEntryHint
71
+ * @property {string} pkg npm package name, e.g. "@openai/codex"
72
+ * @property {string} bin entry path inside the package, e.g. "bin/codex.js"
73
+ */
74
+
75
+ /**
76
+ * @typedef {Object} SpawnTarget
77
+ * @property {string} cmd first argument to pass to spawn
78
+ * @property {string[]} prefixArgs args to prepend before the caller's own argv
79
+ * @property {boolean} shim true when the only match needs a shell we refuse to
80
+ * use - the caller should fail with an actionable message instead of spawning
81
+ */
82
+
83
+ /**
84
+ * Locate a CLI on PATH (plus optional extra directories) and return its real
85
+ * path, or null. On win32 the PATHEXT ladder is applied, so a bare `codex`
86
+ * resolves to `codex.cmd`; everywhere else the bare name is joined onto each
87
+ * PATH entry. A name carrying a path separator is probed as-is.
88
+ *
89
+ * @param {string} binary
90
+ * @param {Object} [options]
91
+ * @param {string} [options.platform]
92
+ * @param {Record<string, string|undefined>} [options.env]
93
+ * @param {(p: string) => boolean} [options.exists]
94
+ * @param {string[]} [options.extraDirs] well-known dirs to probe after PATH
95
+ * @returns {string|null}
96
+ */
97
+ export function findBinaryPath(binary, options = {}) {
98
+ if (!binary) return null;
99
+ const platform = options.platform ?? process.platform;
100
+ const env = options.env ?? process.env;
101
+ const exists = options.exists ?? existsSync;
102
+ const extraDirs = options.extraDirs ?? [];
103
+ const p = pathImpl(platform);
104
+
105
+ if (binary.includes("/") || binary.includes("\\")) return exists(binary) ? binary : null;
106
+
107
+ const fromPath = String(env.PATH ?? env.Path ?? "")
108
+ .split(listSeparator(platform))
109
+ .filter(Boolean);
110
+ const dirs = [...fromPath, ...extraDirs];
111
+ const suffixes = isWindows(platform)
112
+ ? String(env.PATHEXT || DEFAULT_PATHEXT)
113
+ .split(";")
114
+ .filter(Boolean)
115
+ .map((ext) => ext.toLowerCase())
116
+ : [""];
117
+
118
+ for (const dir of dirs) {
119
+ for (const suffix of suffixes) {
120
+ const candidate = p.join(dir, binary + suffix);
121
+ if (exists(candidate)) return candidate;
122
+ }
123
+ }
124
+ return null;
125
+ }
126
+
127
+ /**
128
+ * Resolve a command name into a spawnable target.
129
+ *
130
+ * A JS entry point (`.js` / `.cjs` / `.mjs`) is run under node on every
131
+ * platform, because a script is not something either kernel can spawn on its
132
+ * own: Windows refuses outright, and POSIX only manages it while the shebang
133
+ * and the executable bit survive - which a checkout or a copy can drop. This
134
+ * matters for `CODEX_BIN`, whose natural value is the npm package's own entry
135
+ * point (`node_modules/@openai/codex/bin/codex.js`) - the same file the shim
136
+ * bypass produces.
137
+ *
138
+ * Pass-through cases (behaviour identical to a bare `spawn(name, argv)`):
139
+ * - any other name containing a path separator - an explicit path is the
140
+ * caller's business, and the tests rely on this
141
+ * - any non-win32 platform - macOS and Linux behaviour must not change
142
+ * - win32 with no PATH match - preserve the ordinary ENOENT
143
+ *
144
+ * @param {string} name
145
+ * @param {Object} [options]
146
+ * @param {string} [options.platform]
147
+ * @param {Record<string, string|undefined>} [options.env]
148
+ * @param {(p: string) => boolean} [options.exists]
149
+ * @param {string} [options.nodePath]
150
+ * @param {NpmEntryHint} [options.npmEntry] enables the shim bypass
151
+ * @returns {SpawnTarget}
152
+ */
153
+ export function resolveCommand(name, options = {}) {
154
+ const passthrough = { cmd: name, prefixArgs: [], shim: false };
155
+ if (typeof name !== "string" || !name) return passthrough;
156
+
157
+ const platform = options.platform ?? process.platform;
158
+ const nodePath = options.nodePath ?? process.execPath;
159
+
160
+ if (JS_EXTS.has(pathImpl(platform).extname(name).toLowerCase())) {
161
+ return { cmd: nodePath, prefixArgs: [name], shim: false };
162
+ }
163
+
164
+ if (!isWindows(platform)) return passthrough;
165
+
166
+ const env = options.env ?? process.env;
167
+ const exists = options.exists ?? existsSync;
168
+ const bypass = (shimPath) => npmBypass(shimPath, options.npmEntry, exists, nodePath);
169
+
170
+ const dirs = String(env.PATH ?? env.Path ?? "")
171
+ .split(";")
172
+ .filter(Boolean);
173
+ const exts = String(env.PATHEXT || DEFAULT_PATHEXT)
174
+ .split(";")
175
+ .filter(Boolean);
176
+
177
+ // An explicitly named shim - `CODEX_BIN=codex.cmd`, or a full path to one.
178
+ // Handled before the separator pass-through below, because passing it through
179
+ // spawns a shim Node cannot execute and then tells the user to set CODEX_BIN,
180
+ // which is circular advice for someone who just did.
181
+ const namedExt = path.win32.extname(name).toLowerCase();
182
+ if (SHIM_EXTS.has(namedExt)) {
183
+ // A bare shim NAME still needs locating; only a path-bearing one is already
184
+ // located, and a global install's entry point lives beside the shim.
185
+ const located =
186
+ name.includes("/") || name.includes("\\") ? name : (findOnPath(name, dirs, exists) ?? name);
187
+ return bypass(located) ?? { cmd: located, prefixArgs: [], shim: true };
188
+ }
189
+
190
+ // Any other explicit path (absolute or relative) is already a resolved target.
191
+ if (name.includes("/") || name.includes("\\")) return passthrough;
192
+
193
+ // FIRST MATCH WINS, in PATH order then PATHEXT order - the same precedence
194
+ // libuv and `where` apply. Preferring a real .exe from a LATER directory would
195
+ // silently run a different install than the one the user's own shell picks.
196
+ /** @type {string|null} */
197
+ let firstShim = null;
198
+ for (const dir of dirs) {
199
+ for (const raw of exts) {
200
+ // PATHEXT is conventionally UPPERCASE while npm writes `codex.cmd`.
201
+ // Windows is case-insensitive either way, but the lowercase form matches
202
+ // the file as it actually sits on disk, which keeps error messages honest.
203
+ const ext = raw.toLowerCase();
204
+ const candidate = path.win32.join(dir, name + ext);
205
+ if (!exists(candidate)) continue;
206
+ // A real executable is spawnable as-is.
207
+ if (DIRECT_EXTS.has(ext)) return { cmd: candidate, prefixArgs: [], shim: false };
208
+ if (!SHIM_EXTS.has(ext)) continue;
209
+ const viaNode = bypass(candidate);
210
+ if (viaNode) return viaNode;
211
+ // No entry point behind it - a broken or partial install. Keep scanning:
212
+ // anything usable further down PATH beats failing outright when a working
213
+ // install exists. The first shim is still what gets REPORTED if nothing
214
+ // usable turns up, since that is the one the user believes they run.
215
+ if (firstShim === null) firstShim = candidate;
216
+ }
217
+ }
218
+
219
+ if (firstShim === null) return passthrough;
220
+ return { cmd: firstShim, prefixArgs: [], shim: true };
221
+ }
222
+
223
+ /**
224
+ * One-line explanation for a `shim: true` resolution, so every caller says the
225
+ * same thing.
226
+ * @param {string} name the command that was looked up
227
+ * @param {string} shimPath the shim that was found
228
+ * @param {string} envVar the override the user can set, e.g. "CODEX_BIN"
229
+ * @returns {string}
230
+ */
231
+ export function shimMessage(name, shimPath, envVar) {
232
+ return (
233
+ `${name} only resolved to a shell shim (${shimPath}), which Node cannot execute directly. ` +
234
+ `Set ${envVar} to the real executable, or reinstall ${name} so a .exe is on PATH.`
235
+ );
236
+ }
237
+
238
+ /**
239
+ * Find an exact filename on PATH. No extension is appended.
240
+ * @param {string} file
241
+ * @param {string[]} dirs
242
+ * @param {(p: string) => boolean} exists
243
+ * @returns {string|null}
244
+ */
245
+ function findOnPath(file, dirs, exists) {
246
+ for (const dir of dirs) {
247
+ const candidate = path.win32.join(dir, file);
248
+ if (exists(candidate)) return candidate;
249
+ }
250
+ return null;
251
+ }
252
+
253
+ /**
254
+ * Turn an npm shim into a directly spawnable target, or null when there is no
255
+ * entry point behind it. The shim itself is never executed.
256
+ *
257
+ * Two layouts are probed, because both put a `.cmd` on a Windows machine:
258
+ * - global: <prefix>\codex.cmd -> <prefix>\node_modules\<pkg>\<bin>
259
+ * - local: <root>\node_modules\.bin\codex.cmd -> <root>\node_modules\<pkg>\<bin>
260
+ *
261
+ * A native entry (`bin/claude.exe`) is spawned directly; a JS entry gets node in
262
+ * front of it.
263
+ *
264
+ * @param {string} shimPath
265
+ * @param {NpmEntryHint|undefined} npmEntry
266
+ * @param {(p: string) => boolean} exists
267
+ * @param {string} nodePath
268
+ * @returns {SpawnTarget|null}
269
+ */
270
+ function npmBypass(shimPath, npmEntry, exists, nodePath) {
271
+ if (!npmEntry?.pkg || !npmEntry?.bin) return null;
272
+ const dir = path.win32.dirname(shimPath);
273
+ const roots = [dir];
274
+ // npm puts a locally installed CLI's shim in node_modules/.bin, one level below the package.
275
+ if (path.win32.basename(dir).toLowerCase() === ".bin") {
276
+ roots.push(path.win32.dirname(path.win32.dirname(dir)));
277
+ }
278
+ for (const root of roots) {
279
+ const entry = path.win32.join(root, "node_modules", npmEntry.pkg, npmEntry.bin);
280
+ if (!exists(entry)) continue;
281
+ if (DIRECT_EXTS.has(path.win32.extname(entry).toLowerCase())) {
282
+ return { cmd: entry, prefixArgs: [], shim: false };
283
+ }
284
+ return { cmd: nodePath, prefixArgs: [entry], shim: false };
285
+ }
286
+ return null;
287
+ }
@@ -0,0 +1,29 @@
1
+ import { readdir } from "node:fs/promises";
2
+ import { supervisorRoot, worktreesDir } from "./paths.js";
3
+
4
+ const DEFAULT_THRESHOLD = 50;
5
+
6
+ export function cleanupThreshold(raw = process.env.SUPERVISOR_CLEANUP_HINT) {
7
+ if (raw === undefined || raw === "") return DEFAULT_THRESHOLD;
8
+ const value = Number(raw);
9
+ return Number.isFinite(value) && value >= 0 ? value : DEFAULT_THRESHOLD;
10
+ }
11
+
12
+ // Safe worktrees are removed automatically, so a store that still holds this
13
+ // many has work that is being kept on purpose (unlanded and inside the hold
14
+ // period, or needing review) or has automatic cleanup switched off. The hint
15
+ // reports the count and where to look.
16
+ export async function cleanupHint({ list = readdir, root = supervisorRoot, dir = worktreesDir, threshold = cleanupThreshold() } = {}) {
17
+ if (!threshold) return null;
18
+ let entries;
19
+ try { entries = (await list(dir)).length; } catch { return null; }
20
+ if (entries < threshold) return null;
21
+ return {
22
+ worktrees: entries,
23
+ threshold,
24
+ command: `SUPERVISOR_HOME=${root} agent-supervisor-cleanup --dry-run`,
25
+ apply: null,
26
+ next_step: "Read the plan: REVIEW items say when they become removable. Land or resume the work you still want; cleanup (action apply) removes a SAFE item right away.",
27
+ note: "a worktree is SAFE once its work has landed, or has nothing to keep, or its hold period is over; uncommitted edits are saved on the worker branch first, and branches and evidence are never removed"
28
+ };
29
+ }
@@ -0,0 +1,44 @@
1
+ // Last line of defence for a long-lived process. Without it one promise that
2
+ // nobody awaited ends the MCP server, and every tool call after that answers
3
+ // "Connection closed" with no trace of why.
4
+ //
5
+ // A rejection nobody handled is written down and the process carries on: the
6
+ // state is in the store, not in memory, so the next call is as good as the
7
+ // last. A thrown exception is written down and the process exits, because
8
+ // after one the stack it interrupted cannot be trusted.
9
+ import { appendFileSync, mkdirSync, statSync, writeFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { dataDir } from "./paths.js";
12
+
13
+ export const crashLogPath = join(dataDir, "crash.log");
14
+ const MAX_BYTES = 1024 * 1024;
15
+
16
+ function record(role, kind, error) {
17
+ const text = error instanceof Error ? (error.stack ?? error.message) : String(error);
18
+ const line = `${JSON.stringify({ at: new Date().toISOString(), role, pid: process.pid, kind, error: text })}\n`;
19
+ process.stderr.write(`[agent-supervisor] ${role} ${kind}: ${text}\n`);
20
+ try {
21
+ mkdirSync(dataDir, { recursive: true });
22
+ const size = statSync(crashLogPath, { throwIfNoEntry: false })?.size ?? 0;
23
+ if (size > MAX_BYTES) writeFileSync(crashLogPath, line);
24
+ else appendFileSync(crashLogPath, line);
25
+ } catch (writeError) {
26
+ process.stderr.write(`[agent-supervisor] could not write ${crashLogPath}: ${writeError.message}\n`);
27
+ }
28
+ }
29
+
30
+ // role names the process in the log: "mcp-server", "run-host", "web".
31
+ //
32
+ // exitOnRejection is for the run host, whose state is in memory: the live run,
33
+ // the child, the write chains. Kept alive after a rejection it would hold its
34
+ // row at "running" for good, where a dead one is found and recovered by pid.
35
+ export function installCrashGuard(role, { exitOnRejection = false } = {}) {
36
+ process.on("unhandledRejection", (reason) => {
37
+ record(role, "unhandled_rejection", reason);
38
+ if (exitOnRejection) process.exit(1);
39
+ });
40
+ process.on("uncaughtException", (error) => {
41
+ record(role, "uncaught_exception", error);
42
+ process.exit(1);
43
+ });
44
+ }
@@ -0,0 +1,29 @@
1
+ import { lstat, readFile, realpath } from "node:fs/promises";
2
+ import { isAbsolute, dirname } from "node:path";
3
+ import { createHash } from "node:crypto";
4
+
5
+ export async function captureExternalOutputs(declarations, { checkBaseline = false } = {}) {
6
+ if (!Array.isArray(declarations) || declarations.length > 20) throw new Error("workspace.external_outputs must contain at most 20 files");
7
+ const captured = [];
8
+ for (const entry of declarations) {
9
+ if (!entry || !isAbsolute(entry.path)) throw new Error("workspace.external_outputs must use absolute file paths");
10
+ let info;
11
+ try { info = await lstat(entry.path); } catch (error) { if (error.code !== "ENOENT") throw error; }
12
+ let snapshot = { path: entry.path, exists: false, sha256: null, content: null, truncated: false };
13
+ if (info) {
14
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 1_000_000) throw new Error("external output must be a regular file of at most 1 MB");
15
+ const bytes = await readFile(entry.path);
16
+ snapshot = { ...snapshot, exists: true, canonical_path: await realpath(entry.path), sha256: createHash("sha256").update(bytes).digest("hex"),
17
+ content: bytes.includes(0) ? null : bytes.subarray(0, 3000).toString("utf8"), truncated: bytes.length > 3000 };
18
+ } else { snapshot.canonical_parent = await realpath(dirname(entry.path)); }
19
+ if (checkBaseline && entry.sha256 && snapshot.sha256 !== entry.sha256) throw new Error(`external output baseline changed: ${entry.path}`);
20
+ captured.push(snapshot);
21
+ }
22
+ return captured;
23
+ }
24
+
25
+ export function compareExternalOutputs(before, after) {
26
+ return before.map((old, index) => ({ path: old.path, before: old, after: after[index],
27
+ changed: old.exists !== after[index]?.exists || old.sha256 !== after[index]?.sha256,
28
+ integration: "shared_file_already_written_not_cherry_pick" }));
29
+ }
@@ -0,0 +1,61 @@
1
+ // The only place that runs git. Callers differ in real ways (optional locks,
2
+ // path quoting, what happens to stderr, whether output is trimmed), so those
3
+ // are options here instead of one private copy per caller.
4
+ import { execFile, execFileSync } from "node:child_process";
5
+
6
+ export const gitBin = () => process.env.GIT_BIN?.trim() || "git";
7
+
8
+ export function runGit(cwd, args, options = {}) {
9
+ const { timeout = 60000, noOptionalLocks = false, rawPaths = false, stderr = "pipe", input = null, maxBuffer, encoding = "utf8", env, trim = true } = options;
10
+ const argv = [...(noOptionalLocks ? ["--no-optional-locks"] : []), "-C", cwd, ...(rawPaths ? ["-c", "core.quotePath=false"] : []), ...args];
11
+ const output = execFileSync(gitBin(), argv, {
12
+ encoding,
13
+ timeout,
14
+ stdio: [input == null ? "ignore" : "pipe", "pipe", stderr],
15
+ ...(input == null ? {} : { input }),
16
+ ...(maxBuffer ? { maxBuffer } : {}),
17
+ ...(env ? { env } : {})
18
+ });
19
+ return trim && typeof output === "string" ? output.trim() : output;
20
+ }
21
+
22
+ // git that does not hold the event loop, for the paths that run many
23
+ // commands inside one request: cleanup walks every finished worktree during a
24
+ // poll. Takes the options runGit takes, apart from input and stderr.
25
+ export function runGitAsync(cwd, args, options = {}) {
26
+ const { timeout = 60000, noOptionalLocks = false, rawPaths = false, maxBuffer, env, trim = true } = options;
27
+ const argv = [...(noOptionalLocks ? ["--no-optional-locks"] : []), "-C", cwd, ...(rawPaths ? ["-c", "core.quotePath=false"] : []), ...args];
28
+ return new Promise((resolveRun, rejectRun) => {
29
+ execFile(gitBin(), argv, { encoding: "utf8", timeout, ...(maxBuffer ? { maxBuffer } : {}), ...(env ? { env } : {}) }, (error, stdout, stderr) => {
30
+ if (!error) return resolveRun(trim ? stdout.trim() : stdout);
31
+ error.message = `${error.message.split("\n")[0]}${stderr?.trim() ? `\n${stderr.trim()}` : ""}`;
32
+ rejectRun(error);
33
+ });
34
+ });
35
+ }
36
+
37
+ // A question git answers with its exit code, such as merge-base
38
+ // --is-ancestor. An exit code is an answer. A timeout, a signal or a git that
39
+ // could not be started is not "no", and reading it as one turns a slow disk
40
+ // into "this commit never landed", so those throw.
41
+ const answered = (error) => typeof (error.status ?? error.code) === "number";
42
+
43
+ export function gitSucceeds(cwd, args, { timeout = 15000 } = {}) {
44
+ try {
45
+ execFileSync(gitBin(), ["-C", cwd, ...args], { stdio: "ignore", timeout });
46
+ return true;
47
+ } catch (error) {
48
+ if (answered(error)) return false;
49
+ throw error;
50
+ }
51
+ }
52
+
53
+ export function gitSucceedsAsync(cwd, args, { timeout = 15000 } = {}) {
54
+ return new Promise((resolveRun, rejectRun) => {
55
+ execFile(gitBin(), ["-C", cwd, ...args], { timeout }, (error) => {
56
+ if (!error) resolveRun(true);
57
+ else if (answered(error)) resolveRun(false);
58
+ else rejectRun(error);
59
+ });
60
+ });
61
+ }
@@ -0,0 +1,38 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFile, lstat } from "node:fs/promises";
3
+ import { isAbsolute } from "node:path";
4
+
5
+ export function contextContentHash(refs = []) {
6
+ if (!Array.isArray(refs) || refs.length === 0) return null;
7
+ const canonical = refs
8
+ .map((ref) => ({ path: String(ref.path), sha256: String(ref.sha256) }))
9
+ .sort((left, right) => left.path.localeCompare(right.path));
10
+ return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
11
+ }
12
+
13
+ export async function buildHandoff({ goal, todo, contracts = [], context = [] }, { maxLines = 16, maxChars = 1800 } = {}) {
14
+ if (!Array.isArray(context) || context.length > 20 || !Array.isArray(contracts)
15
+ || contracts.some((value) => typeof value !== "string") || JSON.stringify({ context, contracts }).length > 6000) throw new Error("context and contracts exceed the 6000 character input budget");
16
+ const refs = [];
17
+ for (const entry of context) {
18
+ if (!entry || !isAbsolute(entry.path)) throw new Error("context paths must be absolute");
19
+ const info = await lstat(entry.path);
20
+ if (!info.isFile() || info.size > 5_000_000) throw new Error("context source must be a regular file of at most 5 MB");
21
+ const sha256 = createHash("sha256").update(await readFile(entry.path)).digest("hex");
22
+ if (entry.sha256 && entry.sha256 !== sha256) throw new Error(`context source changed: ${entry.path}`);
23
+ refs.push({ path: entry.path, sha256 });
24
+ }
25
+ const line = (value) => String(value ?? "").replace(/\s+/g, " ").trim();
26
+ const candidates = ["Handoff (source refs are inputs, not write permission):", `Goal: ${line(goal)}`, `Todo: ${line(todo)}`,
27
+ ...refs.map((ref) => `Input: ${ref.path} sha256=${ref.sha256}`),
28
+ ...contracts.map((value) => `Contract: ${line(value)}`)];
29
+ const marker = "[handoff truncated; required task/guard/acceptance follow separately]";
30
+ const lines = []; let size = 0;
31
+ for (const candidate of candidates) {
32
+ if (lines.length >= maxLines - 1 || size + candidate.length + 1 > maxChars - marker.length - 1) break;
33
+ lines.push(candidate); size += candidate.length + 1;
34
+ }
35
+ const truncated = lines.length !== candidates.length;
36
+ if (truncated) lines.push(marker);
37
+ return { text: lines.join("\n"), truncated, source_refs: refs, content_hash: contextContentHash(refs) };
38
+ }
@@ -0,0 +1,34 @@
1
+ import { existsSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+
5
+ // Runtime state root, one stable directory wherever npm put the package.
6
+ // Override with SUPERVISOR_HOME.
7
+ //
8
+ // The package used to be codex-supervisor-mcp and kept its state in
9
+ // ~/.codex-supervisor. A machine that has that directory keeps using it:
10
+ // worktrees are registered in each repository by absolute path, so moving or
11
+ // copying the directory would orphan them. Only a machine without it starts in
12
+ // ~/.agent-supervisor.
13
+ export function defaultSupervisorRoot(home = homedir(), exists = existsSync) {
14
+ const legacy = join(home, ".codex-supervisor");
15
+ return exists(legacy) ? legacy : join(home, ".agent-supervisor");
16
+ }
17
+
18
+ export const supervisorRoot = resolve(process.env.SUPERVISOR_HOME?.trim() || defaultSupervisorRoot());
19
+
20
+ // Codex's own home, used to read native thread goals. Read-only.
21
+ // Override with CODEX_HOME.
22
+ export const codexHome = resolve(
23
+ process.env.CODEX_HOME?.trim() || join(homedir(), ".codex")
24
+ );
25
+
26
+ export const goalsDbPath = join(codexHome, "goals_1.sqlite");
27
+
28
+ export const dataDir = join(supervisorRoot, "data");
29
+ export const dbPath = join(dataDir, "supervisor.sqlite");
30
+ export const runsDir = join(dataDir, "runs");
31
+ export const artifactsDir = join(dataDir, "artifacts");
32
+ export const stagesDir = join(dataDir, "stages");
33
+ export const worktreesDir = join(supervisorRoot, "worktrees");
34
+ export const scratchDir = join(supervisorRoot, "scratch");
@@ -0,0 +1,59 @@
1
+ // The only place, besides git.js, that touches node:child_process. Everything
2
+ // else asks for a process through these names, which keeps blocking calls and
3
+ // platform-specific process handling in one file.
4
+ import { execFile, execFileSync, spawn } from "node:child_process";
5
+ import { existsSync } from "node:fs";
6
+ import { join } from "node:path";
7
+
8
+ export const runSync = execFileSync;
9
+ export const runFile = execFile;
10
+ export const spawnProcess = spawn;
11
+
12
+ // Resolves when the command exits 0, rejects otherwise. Output is discarded.
13
+ export function runToExit(command, args, options = {}) {
14
+ return new Promise((resolvePromise, reject) => {
15
+ const child = spawn(command, args, { stdio: "ignore", windowsHide: true, ...options });
16
+ child.on("exit", (code) => {
17
+ if (code === 0) resolvePromise();
18
+ else reject(new Error(`${command} ${args.join(" ")} exited with ${code}`));
19
+ });
20
+ child.on("error", reject);
21
+ });
22
+ }
23
+
24
+ function powershellBin() {
25
+ const root = process.env.SystemRoot?.trim() || "C:\\Windows";
26
+ const full = join(root, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
27
+ return existsSync(full) ? full : "powershell";
28
+ }
29
+
30
+ // The command line of a pid, or "" when it cannot be read. A pid recorded on
31
+ // disk is only signalled once this confirms it still belongs to a worker, so a
32
+ // recycled pid is never killed. Windows has no `ps`: CIM is the only reliable
33
+ // source for a full command line, and the full line matters because the npm
34
+ // shim is bypassed by running `node <entry>`, which puts the CLI's name in the
35
+ // arguments, not the image name. `tasklist` is the fallback when PowerShell is
36
+ // unavailable; it only reports the image name.
37
+ //
38
+ // The timeout is generous on purpose: this runs once per cross-process cancel,
39
+ // and a cold Windows PowerShell on a fresh machine routinely takes several
40
+ // seconds to print anything. A tight timeout silently degrades to the useless
41
+ // tasklist probe, and the cancel comes back "process_not_found".
42
+ export function describeProcess(pid) {
43
+ const options = { encoding: "utf8", timeout: 15000, windowsHide: true };
44
+ try {
45
+ if (process.platform === "win32") {
46
+ try {
47
+ const command = `(Get-CimInstance Win32_Process -Filter "ProcessId=${Number(pid)}").CommandLine`;
48
+ const viaCim = execFileSync(powershellBin(), ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", command], options).trim();
49
+ if (viaCim) return viaCim;
50
+ } catch {
51
+ // fall through to the image-name probe below
52
+ }
53
+ return execFileSync("tasklist", ["/FI", `PID eq ${Number(pid)}`, "/FO", "CSV", "/NH"], options).trim();
54
+ }
55
+ return execFileSync("ps", ["-p", String(pid), "-o", "command="], options).trim();
56
+ } catch {
57
+ return "";
58
+ }
59
+ }