agent-supervisor-mcp 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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,106 @@
1
+ import { lstatSync, realpathSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, isAbsolute, posix, resolve, win32 } from "node:path";
4
+
5
+ function pathJoin(platform, ...parts) {
6
+ return (platform === "win32" ? win32 : posix).join(...parts);
7
+ }
8
+
9
+ // Codex refuses a writable root that contains a symlink component: the worker
10
+ // does not merely lose that directory, every command in it fails with
11
+ // UnsupportedOperation("writable root ... contains symlink component ...").
12
+ // ~/.cache is a symlink on the machine this was found on, so every candidate is
13
+ // resolved to a symlink-free absolute path before the sandbox sees it, and a
14
+ // candidate that cannot be resolved that way is dropped instead of poisoning
15
+ // the whole run. allow_symlinked_codex_home does not help here: it only covers
16
+ // writable roots under CODEX_HOME.
17
+ export function symlinkComponents(target) {
18
+ const links = [];
19
+ let current = resolve(target);
20
+ for (;;) {
21
+ try { if (lstatSync(current).isSymbolicLink()) links.push(current); }
22
+ catch { /* a missing component is reported by the caller */ }
23
+ const parent = dirname(current);
24
+ if (parent === current) break;
25
+ current = parent;
26
+ }
27
+ return links;
28
+ }
29
+
30
+ export function resolveWritableRoot(candidate) {
31
+ if (typeof candidate !== "string" || !candidate.trim()) return { error: "empty path" };
32
+ if (!isAbsolute(candidate)) return { error: "not an absolute path" };
33
+ let resolved;
34
+ try { resolved = realpathSync(candidate.trim()); } catch { return { error: "does not exist" }; }
35
+ try { if (!lstatSync(resolved).isDirectory()) return { error: "not a directory" }; } catch { return { error: "not a directory" }; }
36
+ const links = symlinkComponents(resolved);
37
+ if (links.length) return { error: "resolved path still contains a symlink component: " + links.join(", ") };
38
+ return { path: resolved };
39
+ }
40
+
41
+ // Cache locations a build writes to outside the worktree. The OS cache
42
+ // directory covers everything that follows XDG or the platform convention
43
+ // (Go build cache, pip, uv, huggingface, gh, ...). Toolchains that keep their
44
+ // own store under the home directory are listed by directory instead, because
45
+ // naming one environment variable per language stops working the moment a new
46
+ // language shows up: a directory that exists is granted, one that does not is
47
+ // not, and a new toolchain only adds a line here at most.
48
+ export const TOOLCHAIN_CACHE_DIRS = [
49
+ ".cargo", // Rust: registry, git checkouts, .package-cache
50
+ ".npm", // Node: _cacache, _logs
51
+ ".yarn",
52
+ ".pnpm-store",
53
+ ".bun",
54
+ ".m2", // Maven local repository
55
+ ".gradle", // Gradle user home
56
+ ".nuget", // NuGet global packages
57
+ ".ivy2", // sbt / Ivy
58
+ ".bundle", // Ruby Bundler
59
+ ".composer", // PHP Composer
60
+ ".pub-cache", // Dart / Flutter
61
+ ".mix", // Elixir
62
+ ".hex",
63
+ ".stack", // Haskell
64
+ ".cpanm", // Perl
65
+ ".deno",
66
+ ".conda", // conda package cache
67
+ "go/pkg" // Go module cache
68
+ ];
69
+
70
+ // Credentials are never granted automatically. A dispatcher that needs them
71
+ // names the directory in sandbox.writable_roots for that one dispatch: an ssh test wants
72
+ // ~/.ssh (known_hosts, ControlMaster sockets), a kubectl test ~/.kube, a registry
73
+ // push ~/.docker, an aws test ~/.aws, a signed commit ~/.gnupg. Everything here is
74
+ // granted automatically only when it holds build state, not secrets, so a worker
75
+ // steered by injected text cannot persist a key or swap a trust anchor.
76
+ export const EXPLICIT_ONLY_DIRS = [".ssh", ".gnupg", ".config", ".aws", ".docker", ".kube", ".netrc", ".git-credentials", "Library/Keychains"];
77
+ function osCacheCandidates({ env, platform, home }) {
78
+ if (platform === "win32") return [env.LOCALAPPDATA];
79
+ return [env.XDG_CACHE_HOME, platform === "darwin" ? pathJoin(platform, home, "Library", "Caches") : null, pathJoin(platform, home, ".cache")];
80
+ }
81
+
82
+ function goBuildCacheCandidate({ env, platform, home }) {
83
+ const configured = env.GOCACHE?.trim();
84
+ if (configured && configured !== "off") return configured;
85
+ if (platform === "win32") return env.LOCALAPPDATA ? win32.join(env.LOCALAPPDATA, "go-build") : null;
86
+ if (platform === "darwin") return pathJoin(platform, home, "Library", "Caches", "go-build");
87
+ return pathJoin(platform, env.XDG_CACHE_HOME?.trim() || pathJoin(platform, home, ".cache"), "go-build");
88
+ }
89
+
90
+ export function cacheRoots(options = {}) {
91
+ const { env = process.env, platform = process.platform, home = homedir(), resolveRoot = resolveWritableRoot, includeToolchain = true } = options;
92
+ if (/^(1|true|yes)$/i.test((env.SUPERVISOR_NO_AUTO_CACHE_ROOTS ?? "").trim())) return [];
93
+ const candidates = [
94
+ ...osCacheCandidates({ env, platform, home }),
95
+ goBuildCacheCandidate({ env, platform, home }),
96
+ ...(includeToolchain ? TOOLCHAIN_CACHE_DIRS.map((dir) => pathJoin(platform, home, dir)) : [])
97
+ ];
98
+ const roots = [];
99
+ for (const candidate of candidates) {
100
+ if (!candidate?.trim()) continue;
101
+ const resolved = resolveRoot(candidate.trim());
102
+ if (resolved?.path) roots.push(resolved.path);
103
+ }
104
+ return [...new Set(roots)];
105
+ }
106
+
@@ -0,0 +1,109 @@
1
+ // Copies the bundled skill into the skill directories of the agent clients on
2
+ // this machine. setup.js runs it after a global install; mcp-server.js runs it
3
+ // every time the server starts, because a server launched through
4
+ // `npx -y agent-supervisor-mcp@latest` never runs postinstall, and the skill
5
+ // text has to move together with the tool surface it describes.
6
+ import { existsSync } from "node:fs";
7
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
+ import { homedir } from "node:os";
9
+ import { dirname, join } from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+
12
+ const packageRoot = dirname(dirname(dirname(fileURLToPath(import.meta.url))));
13
+
14
+ export const SKILL_NAME = "agent-supervisor";
15
+ export const skillSource = join(packageRoot, "skills", SKILL_NAME, "SKILL.md");
16
+
17
+ // Resolved on each call so a test can point HOME somewhere else first.
18
+ export function skillRoots() {
19
+ const home = homedir();
20
+ return {
21
+ claude: { id: "claude", label: "Claude Code", skillRoot: join(process.env.CLAUDE_CONFIG_DIR?.trim() || join(home, ".claude"), "skills") },
22
+ agents: { id: "agents", label: "~/.agents", skillRoot: join(home, ".agents", "skills") },
23
+ codex: { id: "codex", label: "Codex", skillRoot: join(process.env.CODEX_HOME?.trim() || join(home, ".codex"), "skills") }
24
+ };
25
+ }
26
+
27
+ // The skill is read by other processes at any moment, and the server that
28
+ // writes it may be killed at any moment: write beside it, then rename, so
29
+ // the file is always either the old text or the new one, never a torso.
30
+ async function writeAtomically(destination, text) {
31
+ const staging = `${destination}.tmp-${process.pid}-${Date.now()}`;
32
+ await writeFile(staging, text);
33
+ await rename(staging, destination);
34
+ }
35
+
36
+ // The skill this package installed when it was codex-supervisor-mcp describes
37
+ // tools that no longer exist. Left in place a session would load both. The
38
+ // file is renamed, not deleted: a directory without SKILL.md is no skill, and
39
+ // whatever the user wrote in it is still there.
40
+ export const LEGACY_SKILL_NAME = "codex-supervisor";
41
+
42
+ async function retireLegacySkill(client, log) {
43
+ const legacy = join(client.skillRoot, LEGACY_SKILL_NAME, "SKILL.md");
44
+ if (!existsSync(legacy)) return;
45
+ await rename(legacy, `${legacy}.retired`);
46
+ log(`skill ${client.label}: retired the former ${LEGACY_SKILL_NAME} skill`);
47
+ }
48
+
49
+ // Writes the bundled skill under client.skillRoot. A file that differs is
50
+ // backed up as SKILL.md.bak-<timestamp> first unless options.force is set.
51
+ // Returns one of: unchanged, updated, installed, would-update, would-install.
52
+ export async function installSkill(client, options = {}, log = () => {}) {
53
+ const destination = join(client.skillRoot, SKILL_NAME, "SKILL.md");
54
+ const source = await readFile(skillSource, "utf8");
55
+
56
+ if (existsSync(destination)) {
57
+ const current = await readFile(destination, "utf8");
58
+ if (current === source) {
59
+ if (!options.dryRun) await retireLegacySkill(client, log);
60
+ log(`skill ${client.label}: up to date`);
61
+ return "unchanged";
62
+ }
63
+ if (!options.force) {
64
+ const backup = `${destination}.bak-${Date.now()}`;
65
+ if (options.dryRun) {
66
+ log(`skill ${client.label}: would back up to ${backup} and overwrite`);
67
+ return "would-update";
68
+ }
69
+ await writeAtomically(backup, current);
70
+ }
71
+ if (options.dryRun) {
72
+ log(`skill ${client.label}: would overwrite`);
73
+ return "would-update";
74
+ }
75
+ await writeAtomically(destination, source);
76
+ await retireLegacySkill(client, log);
77
+ log(`skill ${client.label}: updated`);
78
+ return "updated";
79
+ }
80
+
81
+ if (options.dryRun) {
82
+ log(`skill ${client.label}: would install to ${destination}`);
83
+ return "would-install";
84
+ }
85
+ await mkdir(dirname(destination), { recursive: true });
86
+ await writeAtomically(destination, source);
87
+ await retireLegacySkill(client, log);
88
+ log(`skill ${client.label}: installed`);
89
+ return "installed";
90
+ }
91
+
92
+ // Brings every client whose skill directory already exists up to date. It
93
+ // never creates a client's skill directory: a missing ~/.codex/skills means
94
+ // Codex is not used here. One client failing does not stop the others.
95
+ // Returns { installed, updated, unchanged, failed } as lists of client labels
96
+ // (failed entries carry the error message).
97
+ export async function syncSkills({ force = false } = {}) {
98
+ const result = { installed: [], updated: [], unchanged: [], failed: [] };
99
+ for (const client of Object.values(skillRoots())) {
100
+ if (!existsSync(client.skillRoot)) continue;
101
+ try {
102
+ const outcome = await installSkill(client, { force });
103
+ result[outcome].push(client.label);
104
+ } catch (error) {
105
+ result.failed.push(`${client.label}: ${error.message}`);
106
+ }
107
+ }
108
+ return result;
109
+ }
@@ -0,0 +1,39 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { stagesDir } from "./paths.js";
4
+
5
+ function validate(taskId, stage, detail) {
6
+ if (!/^[a-z][a-z0-9-]*-[A-Za-z0-9-]+$/.test(String(taskId ?? ""))) throw new Error("invalid task id for stage checkpoint");
7
+ const name = String(stage ?? "").trim();
8
+ if (!name || name.length > 200) throw new Error("stage must be 1-200 characters");
9
+ const note = detail == null ? null : String(detail).trim();
10
+ if (note && note.length > 1000) throw new Error("stage detail must be at most 1000 characters");
11
+ return { name, note };
12
+ }
13
+
14
+ export function stagePath(taskId) {
15
+ validate(taskId, "stage", null);
16
+ return join(stagesDir, `${taskId}.json`);
17
+ }
18
+
19
+ export function writeStage(taskId, stage, detail = null) {
20
+ const value = validate(taskId, stage, detail);
21
+ mkdirSync(stagesDir, { recursive: true });
22
+ const destination = stagePath(taskId);
23
+ const staging = `${destination}.tmp-${process.pid}-${Date.now()}`;
24
+ const payload = { task_id: taskId, stage: value.name, detail: value.note, updated_at: new Date().toISOString() };
25
+ writeFileSync(staging, JSON.stringify(payload, null, 2));
26
+ renameSync(staging, destination);
27
+ return payload;
28
+ }
29
+
30
+ export function readStage(taskId) {
31
+ let path;
32
+ try { path = stagePath(taskId); } catch { return null; }
33
+ if (!existsSync(path)) return null;
34
+ try { return JSON.parse(readFileSync(path, "utf8")); } catch { return null; }
35
+ }
36
+
37
+ export function clearStage(taskId) {
38
+ try { rmSync(stagePath(taskId), { force: true }); } catch { /* invalid legacy task id */ }
39
+ }
@@ -0,0 +1,265 @@
1
+ import { PHASES } from "../../domain/status.js";
2
+ import { artifactsDir, dataDir, dbPath, runsDir } from "../paths.js";
3
+ import { git } from "./facts.js";
4
+ import { CONTROL_DDL, POST_V1_COLUMNS, SESSIONS_DDL, SIDE_DDL, TASK_COLUMNS, TASK_EVENTS_DDL, TASK_EVENTS_INDEX_DDL, TASK_EXTRA_COLUMNS, TASKS_DDL, TASKS_SESSION_INDEX_DDL } from "./schema.js";
5
+ import { createHash } from "node:crypto";
6
+ import { mkdir } from "node:fs/promises";
7
+ import { isAbsolute, resolve } from "node:path";
8
+ import { DatabaseSync } from "node:sqlite";
9
+
10
+ let db;
11
+
12
+ function tableColumns(dbInstance, tableName) {
13
+ return dbInstance.prepare(`PRAGMA table_info(${tableName})`).all();
14
+ }
15
+
16
+ // v1 stored progress phases ("editing", "command", "reporting") in the status
17
+ // column and required phase to be non-null. Both have to change, and SQLite
18
+ // cannot relax NOT NULL in place, so the table is rebuilt once.
19
+ function migrateTasksTable(dbInstance, columns) {
20
+ const phaseColumn = columns.find((column) => column.name === "phase");
21
+ const isCurrentSchema = POST_V1_COLUMNS.every(([name]) => columns.some((column) => column.name === name))
22
+ && phaseColumn
23
+ && !phaseColumn.notnull;
24
+ if (isCurrentSchema) return { migrated: false, rows: 0 };
25
+
26
+ const legacyNames = new Set(columns.map((column) => column.name));
27
+ const rows = dbInstance.prepare("SELECT COUNT(*) AS count FROM tasks").get().count;
28
+
29
+ const selectExpression = (name) => {
30
+ if (legacyNames.has(name)) return name;
31
+ const definition = [...POST_V1_COLUMNS, ...TASK_EXTRA_COLUMNS].find(([columnName]) => columnName === name);
32
+ if (definition && definition[1].includes("DEFAULT '[]'")) return "'[]'";
33
+ if (definition && definition[1].includes("DEFAULT 'legacy'")) return "'legacy'";
34
+ if (definition && definition[1].includes("DEFAULT 0")) return "0";
35
+ return "NULL";
36
+ };
37
+
38
+ const statusExpression = legacyNames.has("status")
39
+ ? `CASE WHEN status IN ('editing','command','command_completed','reporting') THEN 'running' ELSE status END`
40
+ : "'failed'";
41
+
42
+ const phaseExpression = legacyNames.has("phase")
43
+ ? `CASE
44
+ WHEN status IN ('editing','command','reporting') THEN status
45
+ WHEN status = 'command_completed' THEN 'command'
46
+ WHEN status = 'running' THEN CASE WHEN phase IN (${PHASES.map((p) => `'${p}'`).join(",")}) THEN phase ELSE 'starting' END
47
+ ELSE NULL
48
+ END`
49
+ : "NULL";
50
+
51
+ {
52
+ dbInstance.exec("ALTER TABLE tasks RENAME TO tasks_legacy_v1;");
53
+ dbInstance.exec(TASKS_DDL);
54
+ const selectList = TASK_COLUMNS.map((name) => {
55
+ if (name === "status") return `${statusExpression} AS status`;
56
+ if (name === "phase") return `${phaseExpression} AS phase`;
57
+ return `${selectExpression(name)} AS ${name}`;
58
+ }).join(", ");
59
+ dbInstance.exec(`INSERT INTO tasks (${TASK_COLUMNS.join(", ")}) SELECT ${selectList} FROM tasks_legacy_v1;`);
60
+ dbInstance.exec("DROP TABLE tasks_legacy_v1;");
61
+ }
62
+ return { migrated: true, rows };
63
+ }
64
+
65
+ function sleepSync(ms) {
66
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
67
+ }
68
+
69
+ function isBusyError(error) {
70
+ return /SQLITE_BUSY|database is locked|database table is locked/i.test(String(error?.message ?? ""));
71
+ }
72
+
73
+ // Several MCP processes may open a brand-new database at the same moment, so
74
+ // schema setup runs inside one immediate transaction (which the busy timeout
75
+ // makes wait instead of failing) and is retried if the file is still locked.
76
+ export function runWithRetry(dbInstance, work, attempts = 10) {
77
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
78
+ try {
79
+ return work();
80
+ } catch (error) {
81
+ if (attempt === attempts - 1 || !isBusyError(error)) throw error;
82
+ sleepSync(50 * (attempt + 1));
83
+ }
84
+ }
85
+ return undefined;
86
+ }
87
+
88
+ function initializeSchema(dbInstance) {
89
+ runWithRetry(dbInstance, () => {
90
+ dbInstance.exec("BEGIN IMMEDIATE;");
91
+ try {
92
+ const columns = tableColumns(dbInstance, "tasks");
93
+ if (columns.length === 0) dbInstance.exec(TASKS_DDL);
94
+ else migrateTasksTable(dbInstance, columns);
95
+ dbInstance.exec(TASK_EVENTS_DDL);
96
+ for (const [name, definition] of [
97
+ ["run_id", "TEXT"],
98
+ ["actor", "TEXT NOT NULL DEFAULT 'legacy'"],
99
+ ["payload_sha256", "TEXT"]
100
+ ]) {
101
+ if (!tableColumns(dbInstance, "task_events").some((column) => column.name === name)) dbInstance.exec(`ALTER TABLE task_events ADD COLUMN ${name} ${definition}`);
102
+ }
103
+ dbInstance.exec("UPDATE task_events SET actor = 'legacy' WHERE actor IS NULL");
104
+ dbInstance.exec(TASK_EVENTS_INDEX_DDL);
105
+ dbInstance.exec(TASKS_SESSION_INDEX_DDL);
106
+ for (const [name, definition] of TASK_EXTRA_COLUMNS) {
107
+ if (!tableColumns(dbInstance, "tasks").some((column) => column.name === name)) dbInstance.exec(`ALTER TABLE tasks ADD COLUMN ${name} ${definition}`);
108
+ }
109
+ dbInstance.exec(CONTROL_DDL);
110
+ for (const [name, definition] of [
111
+ ["watched_paths", "TEXT NOT NULL DEFAULT '[]'"],
112
+ ["source_artifact_id", "TEXT"],
113
+ ["valid_for_content_hash", "TEXT"],
114
+ ["valid_for_manifest_hash", "TEXT"],
115
+ ["verified_by", "TEXT"]
116
+ ]) {
117
+ if (!tableColumns(dbInstance, "facts").some((column) => column.name === name)) dbInstance.exec(`ALTER TABLE facts ADD COLUMN ${name} ${definition}`);
118
+ }
119
+ dbInstance.exec(SESSIONS_DDL);
120
+ for (const [name, definition] of [
121
+ ["objective", "TEXT"], ["default_acceptance", "TEXT"],
122
+ ["approval_state", "TEXT NOT NULL DEFAULT 'approved'"], ["policy_revision", "INTEGER NOT NULL DEFAULT 0"]
123
+ ]) {
124
+ if (!tableColumns(dbInstance, "sessions").some((column) => column.name === name)) dbInstance.exec(`ALTER TABLE sessions ADD COLUMN ${name} ${definition}`);
125
+ }
126
+ dbInstance.exec("CREATE TABLE IF NOT EXISTS observer_cursors (id TEXT PRIMARY KEY, cursor TEXT NOT NULL, updated_at TEXT NOT NULL)");
127
+ dbInstance.exec("CREATE TABLE IF NOT EXISTS run_claims (task_id TEXT PRIMARY KEY, token TEXT NOT NULL, owner_pid INTEGER NOT NULL)");
128
+ dbInstance.exec(SIDE_DDL);
129
+ // Rows written before 0.7.1 have no worker_run_count: the fork is then
130
+
131
+ // never judged stale, which is what those rows did before.
132
+
133
+ if (!dbInstance.prepare("PRAGMA table_info(side_sessions)").all().some((column) => column.name === "worker_run_count")) {
134
+
135
+ dbInstance.exec("ALTER TABLE side_sessions ADD COLUMN worker_run_count INTEGER;");
136
+
137
+ }
138
+ backfillControlRecords(dbInstance);
139
+ dbInstance.exec("COMMIT;");
140
+ } catch (error) {
141
+ try {
142
+ dbInstance.exec("ROLLBACK;");
143
+ } catch {
144
+ /* transaction already unwound */
145
+ }
146
+ throw error;
147
+ }
148
+ });
149
+ }
150
+
151
+ function stableId(prefix, value) {
152
+ return `${prefix}-${createHash("sha256").update(String(value)).digest("hex").slice(0, 24)}`;
153
+ }
154
+
155
+ function repoIdForRoot(root) {
156
+ return stableId("repo", resolve(root));
157
+ }
158
+
159
+ function canonicalizeRemote(value) {
160
+ let raw = String(value ?? "").trim();
161
+ if (!raw) return null;
162
+ const scp = raw.match(/^((?:[^@/:\s]+@)?)([^:/\s]+):(.+)$/);
163
+ if (scp && !raw.includes("://")) raw = `ssh://${scp[1]}${scp[2]}/${scp[3]}`;
164
+ try {
165
+ const parsed = new URL(raw);
166
+ if (parsed.protocol === "file:") {
167
+ const path = resolve(decodeURIComponent(parsed.pathname)).replace(/\.git$/i, "");
168
+ return `file://${path}`;
169
+ }
170
+ if (!parsed.hostname || !["ssh:", "https:", "http:"].includes(parsed.protocol)) return null;
171
+ const path = decodeURIComponent(parsed.pathname).replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
172
+ if (!path) return null;
173
+ return `${parsed.protocol}//${parsed.hostname.toLowerCase()}${parsed.port ? `:${parsed.port}` : ""}/${path}`;
174
+ } catch {
175
+ return isAbsolute(raw) ? `file://${resolve(raw).replace(/\.git$/i, "")}` : null;
176
+ }
177
+ }
178
+
179
+ export function canonicalRemoteForRoot(root) {
180
+ try {
181
+ return canonicalizeRemote(git(root, ["remote", "get-url", "origin"]));
182
+ } catch {
183
+ return null;
184
+ }
185
+ }
186
+
187
+ export function workItemIdForTask(taskId) {
188
+ return `work-${taskId}`;
189
+ }
190
+
191
+ export function runIdFor(taskId, attempt) {
192
+ return `run-${taskId}-${attempt}`;
193
+ }
194
+
195
+ export function ensureControlRecords(dbInstance, task, { refreshRepo = false, canonicalRemote = undefined } = {}) {
196
+ if (!task?.id || !task.project_root) return;
197
+ const now = new Date().toISOString();
198
+ const root = resolve(task.project_root);
199
+ const repoId = repoIdForRoot(root);
200
+ const workItemId = workItemIdForTask(task.id);
201
+ const repo = dbInstance.prepare("SELECT id FROM repos WHERE root = ?").get(root);
202
+ if (!repo || refreshRepo) {
203
+ const resolvedRemote = canonicalRemote === undefined ? canonicalRemoteForRoot(root) : canonicalRemote;
204
+ dbInstance.prepare(`
205
+ INSERT INTO repos (id, canonical_remote, root, default_branch, created_at, updated_at)
206
+ VALUES (@id, @canonical_remote, @root, NULL, @now, @now)
207
+ ON CONFLICT(root) DO UPDATE SET canonical_remote = excluded.canonical_remote, updated_at = excluded.updated_at
208
+ `).run({ id: repoId, canonical_remote: resolvedRemote, root, now });
209
+ }
210
+ const workItem = dbInstance.prepare("SELECT id FROM work_items WHERE task_id = ?").get(task.id);
211
+ if (workItem) return;
212
+ dbInstance.prepare(`
213
+ INSERT INTO work_items (id, repo_id, task_id, parent_work_item_id, objective, owner, delivery_state, created_at, updated_at)
214
+ VALUES (@id, @repo_id, @task_id, NULL, @objective, NULL, @delivery_state, @now, @now)
215
+ `).run({
216
+ id: workItemId,
217
+ repo_id: repoId,
218
+ task_id: task.id,
219
+ objective: task.goal_objective ?? task.title ?? null,
220
+ delivery_state: task.landed_at ? "landed" : "draft",
221
+ now
222
+ });
223
+ }
224
+
225
+ function backfillControlRecords(dbInstance) {
226
+ const rows = dbInstance.prepare(`
227
+ SELECT t.id,t.title,t.project_root,t.goal_objective,t.landed_at
228
+ FROM tasks AS t
229
+ LEFT JOIN work_items AS w ON w.task_id = t.id
230
+ WHERE w.task_id IS NULL
231
+ `).all();
232
+ for (const row of rows) ensureControlRecords(dbInstance, row);
233
+ }
234
+
235
+ export function openDb() {
236
+ if (db) return db;
237
+ db = new DatabaseSync(dbPath);
238
+ // Several MCP processes share one database file. The busy timeout has to be
239
+ // set before anything that can touch the write lock, otherwise a concurrent
240
+ // writer turns into an immediate SQLITE_BUSY.
241
+ db.exec("PRAGMA busy_timeout=15000;");
242
+ runWithRetry(db, () => db.exec("PRAGMA journal_mode=WAL;"));
243
+ db.exec("PRAGMA synchronous=NORMAL;");
244
+ initializeSchema(db);
245
+ return db;
246
+ }
247
+
248
+ export async function ensureFilesystem() {
249
+ await mkdir(dataDir, { recursive: true });
250
+ await mkdir(runsDir, { recursive: true });
251
+ await mkdir(artifactsDir, { recursive: true });
252
+ }
253
+
254
+ export function encodeJson(value) {
255
+ return JSON.stringify(value ?? []);
256
+ }
257
+
258
+ export function decodeJson(value, fallback) {
259
+ if (!value) return fallback;
260
+ try {
261
+ return JSON.parse(value);
262
+ } catch {
263
+ return fallback;
264
+ }
265
+ }
@@ -0,0 +1,82 @@
1
+ // A worker's output is written twice: the raw line to its JSONL log and the
2
+ // event to the store. Nearly all of the store's size was the second copy of
3
+ // command output. A large event from the worker now keeps only a clipped copy
4
+ // in the store, marked with the hash of the full line; the JSONL is the one
5
+ // place the full body lives, and it is read back from there on request.
6
+ //
7
+ // Kept whole whatever their size: the worker's messages and turn events, which
8
+ // the state machine and the result readers query, and everything the
9
+ // supervisor writes itself, which is in no log.
10
+ import { truncateEventStrings } from "../../domain/truncate.js";
11
+ import { extractAgentMessage } from "./runner-readers.js";
12
+ import { createHash } from "node:crypto";
13
+ import { createReadStream } from "node:fs";
14
+ import { createInterface } from "node:readline";
15
+
16
+ export const EVENT_INLINE_BYTES = 2048;
17
+ const CLIPPED_STRING_BYTES = 1024;
18
+ // The marker is the supervisor's, named so it cannot be taken for a field of the worker's event.
19
+ export const CLIP_KEY = "supervisor_clipped";
20
+
21
+ const sha256 = (text) => createHash("sha256").update(text).digest("hex");
22
+
23
+ function keptWhole(event) {
24
+ if (String(event.type ?? "").startsWith("turn.") || event.type === "thread.started") return true;
25
+ try {
26
+ return extractAgentMessage(event) != null;
27
+ } catch {
28
+ return true; // an event the runner cannot read is not ours to cut
29
+ }
30
+ }
31
+
32
+ // Returns what goes in the store for one event: { payload, sha256 }, where
33
+ // sha256 is always the hash of the full line as the log has it.
34
+ export function storedForm(event, { bodyInLog = false, offset = null } = {}) {
35
+ const full = JSON.stringify(event);
36
+ const hash = sha256(full);
37
+ const bytes = Buffer.byteLength(full, "utf8");
38
+ if (!bodyInLog || bytes <= EVENT_INLINE_BYTES || keptWhole(event)) return { payload: full, sha256: hash };
39
+ const clipped = JSON.stringify({ ...truncateEventStrings(event, CLIPPED_STRING_BYTES), [CLIP_KEY]: { stored: "jsonl", bytes, sha256: hash, offset } });
40
+ // An event made of many small strings does not shrink; marking it would only cost a log read later.
41
+ if (Buffer.byteLength(clipped, "utf8") > bytes / 2) return { payload: full, sha256: hash };
42
+ return { payload: clipped, sha256: hash };
43
+ }
44
+
45
+ const isClipped = (event) => event?.[CLIP_KEY]?.stored === "jsonl" && typeof event[CLIP_KEY].sha256 === "string";
46
+
47
+ // Collects the wanted lines from the log, reading from `start`.
48
+ async function scanLog(logPath, start, wanted, found) {
49
+ const lines = createInterface({ input: createReadStream(logPath, { encoding: "utf8", start }), crlfDelay: Infinity });
50
+ for await (const line of lines) {
51
+ if (Buffer.byteLength(line, "utf8") <= EVENT_INLINE_BYTES) continue;
52
+ const hash = sha256(line);
53
+ if (wanted.has(hash)) found.set(hash, line);
54
+ if (found.size === wanted.size) break;
55
+ }
56
+ }
57
+
58
+ // Puts the full bodies back from the log. The recorded offset says where to
59
+ // start, so reading the newest events does not mean reading the whole log; a
60
+ // line that is not where it was recorded is looked for once from the top. An
61
+ // event whose line cannot be found stays clipped and says so.
62
+ export async function restoreEventBodies(events, logPath) {
63
+ const clipped = events.filter(isClipped);
64
+ if (clipped.length === 0) return events;
65
+ const wanted = new Set(clipped.map((event) => event[CLIP_KEY].sha256));
66
+ const found = new Map();
67
+ if (logPath) {
68
+ try {
69
+ const offsets = clipped.map((event) => event[CLIP_KEY].offset);
70
+ const start = offsets.every((offset) => Number.isInteger(offset) && offset >= 0) ? Math.min(...offsets) : 0;
71
+ await scanLog(logPath, start, wanted, found);
72
+ if (found.size < wanted.size && start > 0) await scanLog(logPath, 0, wanted, found);
73
+ } catch {
74
+ // a log that is gone leaves the events clipped, marked below
75
+ }
76
+ }
77
+ return events.map((event) => {
78
+ if (!isClipped(event)) return event;
79
+ const line = found.get(event[CLIP_KEY].sha256);
80
+ return line ? JSON.parse(line) : { ...event, [CLIP_KEY]: { ...event[CLIP_KEY], missing: true } };
81
+ });
82
+ }