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.
- package/LICENSE +21 -0
- package/README.en.md +208 -0
- package/README.md +206 -2
- package/package.json +76 -4
- package/skills/agent-supervisor/SKILL.md +139 -0
- package/src/app/acceptance.js +263 -0
- package/src/app/auto-cleanup.js +91 -0
- package/src/app/cancel.js +57 -0
- package/src/app/cleanup-facts.js +101 -0
- package/src/app/cleanup-plan.js +166 -0
- package/src/app/compose.js +17 -0
- package/src/app/context-compiler.js +83 -0
- package/src/app/dispatch.js +398 -0
- package/src/app/followup.js +104 -0
- package/src/app/land-chain.js +134 -0
- package/src/app/landing.js +357 -0
- package/src/app/ownership.js +57 -0
- package/src/app/rebase.js +216 -0
- package/src/app/restore-worktree.js +51 -0
- package/src/app/resume.js +179 -0
- package/src/app/run-state.js +26 -0
- package/src/app/settled.js +28 -0
- package/src/app/side-chat.js +370 -0
- package/src/app/sse.js +20 -0
- package/src/app/start-run.js +77 -0
- package/src/app/verify-push.js +114 -0
- package/src/app/worktree-setup.js +218 -0
- package/src/domain/acceptance-baseline.js +65 -0
- package/src/domain/acceptance-spec.js +30 -0
- package/src/domain/cleanup-policy.js +44 -0
- package/src/domain/command-outcome.js +6 -0
- package/src/domain/failure-class.js +63 -0
- package/src/domain/owned-changes.js +27 -0
- package/src/domain/prompt.js +161 -0
- package/src/domain/side-turn-view.js +73 -0
- package/src/domain/status.js +50 -0
- package/src/domain/thread-health.js +33 -0
- package/src/domain/truncate.js +148 -0
- package/src/domain/worker-branch.js +6 -0
- package/src/domain/worker-changes.js +58 -0
- package/src/domain/worker-env.js +14 -0
- package/src/domain/worker-preflight.js +167 -0
- package/src/domain/worker-report.js +85 -0
- package/src/domain/worker-report.schema.json +10 -0
- package/src/infra/bin-resolver.js +287 -0
- package/src/infra/cleanup-hint.js +29 -0
- package/src/infra/crash-guard.js +44 -0
- package/src/infra/external-output.js +29 -0
- package/src/infra/git.js +61 -0
- package/src/infra/handoff.js +38 -0
- package/src/infra/paths.js +34 -0
- package/src/infra/process.js +59 -0
- package/src/infra/sandbox-roots.js +106 -0
- package/src/infra/skill-sync.js +109 -0
- package/src/infra/stage-store.js +39 -0
- package/src/infra/store/db.js +265 -0
- package/src/infra/store/event-body.js +82 -0
- package/src/infra/store/events.js +149 -0
- package/src/infra/store/facts.js +338 -0
- package/src/infra/store/reconcile.js +173 -0
- package/src/infra/store/records.js +171 -0
- package/src/infra/store/runner-readers.js +16 -0
- package/src/infra/store/schema.js +306 -0
- package/src/infra/store/sessions.js +138 -0
- package/src/infra/store/tasks.js +351 -0
- package/src/infra/update/auto-update-worker.js +186 -0
- package/src/infra/update/auto-update.js +143 -0
- package/src/infra/update/update-check.js +246 -0
- package/src/infra/workspace-kind.js +165 -0
- package/src/infra/worktree.js +361 -0
- package/src/interface/bin/acceptance-cli.js +62 -0
- package/src/interface/bin/cleanup.js +81 -0
- package/src/interface/bin/monitor.jsx +301 -0
- package/src/interface/bin/setup.js +342 -0
- package/src/interface/bin/stage.js +17 -0
- package/src/interface/bin/web-server.js +53 -0
- package/src/interface/mcp/handlers/delivery.js +165 -0
- package/src/interface/mcp/handlers/dispatch.js +236 -0
- package/src/interface/mcp/handlers/facts.js +204 -0
- package/src/interface/mcp/handlers/overview.js +106 -0
- package/src/interface/mcp/handlers/results.js +262 -0
- package/src/interface/mcp/handlers/review.js +115 -0
- package/src/interface/mcp/handlers/wait.js +141 -0
- package/src/interface/mcp/meta.js +7 -0
- package/src/interface/mcp/result.js +34 -0
- package/src/interface/mcp/schemas.js +24 -0
- package/src/interface/mcp/server.js +64 -0
- package/src/interface/mcp/tools/deliver.js +48 -0
- package/src/interface/mcp/tools/dispatch.js +90 -0
- package/src/interface/mcp/tools/optional.js +57 -0
- package/src/interface/mcp/tools/read.js +115 -0
- package/src/interface/mcp/tools/run.js +57 -0
- package/src/interface/mcp/tools/shapes.js +67 -0
- package/src/interface/mcp/tools/track.js +84 -0
- package/src/interface/mcp/update-state.js +34 -0
- package/src/interface/mcp/views/overview.js +183 -0
- package/src/interface/mcp/views/task.js +224 -0
- package/src/interface/web/app.js +226 -0
- package/src/interface/web/views.js +227 -0
- package/src/mcp-server.js +4 -0
- package/src/run-host/entry.js +26 -0
- package/src/run-host/finalize.js +243 -0
- package/src/run-host/launch.js +49 -0
- package/src/run-host/live-run.js +76 -0
- package/src/run-host/outcome-facts.js +61 -0
- package/src/run-host/streams.js +102 -0
- package/src/run-host/track.js +132 -0
- package/src/runners/claude/adapter.js +118 -0
- package/src/runners/claude/events.js +100 -0
- package/src/runners/claude/tool-guard.js +48 -0
- package/src/runners/codex/adapter.js +157 -0
- package/src/runners/codex/chat-chunks.js +97 -0
- package/src/runners/codex/event-parser.js +266 -0
- package/src/runners/codex/goal-store.js +54 -0
- package/src/runners/codex/mcp-config.js +39 -0
- package/src/runners/codex/tool-guard.js +184 -0
- package/src/runners/contract-check.js +82 -0
- package/src/runners/contract.js +53 -0
- package/src/runners/registry.js +45 -0
- package/web/dist/assets/index-D-A2xlpx.js +154 -0
- package/web/dist/assets/index-f8esISCp.css +2 -0
- package/web/dist/index.html +15 -0
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { newWorkerBranch } from "../domain/worker-branch.js";
|
|
2
|
+
import { gitBin, runGit } from "../infra/git.js";
|
|
3
|
+
import { worktreesDir } from "../infra/paths.js";
|
|
4
|
+
import { runToExit } from "../infra/process.js";
|
|
5
|
+
import { resolveWritableRoot } from "../infra/sandbox-roots.js";
|
|
6
|
+
import { isPidAlive } from "../infra/store/tasks.js";
|
|
7
|
+
import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, runAcceptance } from "./acceptance.js";
|
|
8
|
+
import { WORKTREE_LOCK_TIMEOUT_MS } from "./run-state.js";
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import { existsSync } from "node:fs";
|
|
11
|
+
import { lstat, mkdir, readFile, realpath, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
|
|
12
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
13
|
+
|
|
14
|
+
export function splitLines(buffer, chunk) {
|
|
15
|
+
const next = buffer + chunk;
|
|
16
|
+
const lines = next.split(/\r?\n/);
|
|
17
|
+
return { lines: lines.slice(0, -1), rest: lines.at(-1) ?? "" };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function exists(path) {
|
|
21
|
+
if (!path) return false;
|
|
22
|
+
try {
|
|
23
|
+
await stat(path);
|
|
24
|
+
return true;
|
|
25
|
+
} catch {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function resolveCommit(cwd, ref) {
|
|
31
|
+
return runGit(cwd, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], { timeout: 15000, stderr: "ignore" });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function invalidBaseRefError(cwd, baseRef) {
|
|
35
|
+
const error = new Error(`workspace.base_ref "${baseRef}" does not resolve to a commit in ${cwd}`);
|
|
36
|
+
error.code = "invalid_base_ref";
|
|
37
|
+
return error;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// The worktree is cut from workspace.base_ref when given, else from the repository's
|
|
41
|
+
// HEAD. The resolved commit is recorded on the task: it is what
|
|
42
|
+
// readWorktreeChanges diffs against, so committed work stays visible. An
|
|
43
|
+
// explicit workspace.base_ref that does not resolve is an error, not a silent fallback
|
|
44
|
+
// to HEAD - the caller asked for a specific baseline for a reason.
|
|
45
|
+
export async function ensureWorktree(cwd, taskId, baseRef = null) {
|
|
46
|
+
const taskWorktreeDir = join(worktreesDir, taskId);
|
|
47
|
+
await mkdir(worktreesDir, { recursive: true });
|
|
48
|
+
const gitDir = join(cwd, ".git");
|
|
49
|
+
if (!(await exists(cwd)) || !(await exists(gitDir))) {
|
|
50
|
+
if (baseRef) throw invalidBaseRefError(cwd, baseRef);
|
|
51
|
+
return { path: null, baseCommit: null };
|
|
52
|
+
}
|
|
53
|
+
let baseCommit;
|
|
54
|
+
try {
|
|
55
|
+
baseCommit = resolveCommit(cwd, baseRef ?? "HEAD");
|
|
56
|
+
} catch {
|
|
57
|
+
if (baseRef) throw invalidBaseRefError(cwd, baseRef);
|
|
58
|
+
return { path: null, baseCommit: null };
|
|
59
|
+
}
|
|
60
|
+
if (!baseCommit) {
|
|
61
|
+
if (baseRef) throw invalidBaseRefError(cwd, baseRef);
|
|
62
|
+
return { path: null, baseCommit: null };
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
await rm(taskWorktreeDir, { recursive: true, force: true });
|
|
66
|
+
const branch = newWorkerBranch(taskId);
|
|
67
|
+
await runToExit(gitBin(), ["-C", cwd, "worktree", "add", "--detach", taskWorktreeDir, baseCommit]);
|
|
68
|
+
await runToExit(gitBin(), ["-C", taskWorktreeDir, "switch", "-c", branch]);
|
|
69
|
+
return { path: taskWorktreeDir, baseCommit };
|
|
70
|
+
} catch (error) {
|
|
71
|
+
const failure = new Error(`could not create isolated worker checkout: ${error.message}`);
|
|
72
|
+
failure.code = "worktree_creation_failed";
|
|
73
|
+
throw failure;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function insidePath(parent, child) {
|
|
78
|
+
const rel = relative(parent, child);
|
|
79
|
+
return rel === "" || (!rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel));
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function normalizeWorkspaceSetup(value, projectRoot) {
|
|
83
|
+
if (value == null) return null;
|
|
84
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("workspace.setup must be an object");
|
|
85
|
+
const links = (value.links ?? []).map((entry) => {
|
|
86
|
+
if (!entry || typeof entry.path !== "string" || !entry.path.trim()
|
|
87
|
+
|| typeof entry.source !== "string" || !entry.source.trim()) throw new Error("workspace.setup.links requires path and source");
|
|
88
|
+
const path = entry.path.trim();
|
|
89
|
+
if (isAbsolute(path) || path.split(/[\\/]/).includes("..")) throw new Error(`workspace.setup link path must stay inside the worktree: ${path}`);
|
|
90
|
+
return { path, source: resolve(projectRoot, entry.source.trim()) };
|
|
91
|
+
});
|
|
92
|
+
const commands = (value.commands ?? []).map((command) => String(command).trim()).filter(Boolean);
|
|
93
|
+
if (links.length > 20 || commands.length > 20) throw new Error("workspace.setup accepts at most 20 links and 20 commands");
|
|
94
|
+
const submodules = value.submodules === true;
|
|
95
|
+
return links.length || submodules || commands.length ? { links, submodules, commands } : null;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const JS_DEPENDENCY_COMMAND = /(?:^|[\s"'/])(?:npm|pnpm|yarn|npx|vitest|jest|vue-tsc|tsc|eslint|oxlint|nuxi)(?:\s|$)/;
|
|
99
|
+
|
|
100
|
+
export function requireDependencySetup({ kind, projectRoot, setup, commands }) {
|
|
101
|
+
if (kind !== "git_worktree" || setup || !existsSync(join(projectRoot, "package.json"))) return;
|
|
102
|
+
const commandText = (commands ?? []).map((check) => typeof check === "string" ? check : check?.command).filter(Boolean).join("\n");
|
|
103
|
+
if (!JS_DEPENDENCY_COMMAND.test(commandText)) return;
|
|
104
|
+
const error = new Error("workspace_setup_required: this JavaScript acceptance uses local project tooling, but the new worktree has no node_modules or generated prepare files; pass workspace.setup with dependency links and prepare commands (the same setup must be used by preflight)");
|
|
105
|
+
error.code = "workspace_setup_required";
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export async function prepareWorktreeWorkspace(setup, projectRoot, worktreePath, taskId) {
|
|
110
|
+
if (!setup) return;
|
|
111
|
+
for (const link of setup.links) {
|
|
112
|
+
if (!existsSync(link.source)) throw new Error(`workspace.setup link source does not exist: ${link.source}`);
|
|
113
|
+
const destination = resolve(worktreePath, link.path);
|
|
114
|
+
if (!insidePath(worktreePath, destination)) throw new Error(`workspace.setup link escapes the worktree: ${link.path}`);
|
|
115
|
+
await mkdir(dirname(destination), { recursive: true });
|
|
116
|
+
if (existsSync(destination)) {
|
|
117
|
+
const existing = await lstat(destination);
|
|
118
|
+
if (!existing.isSymbolicLink()) throw new Error(`workspace.setup link destination already exists: ${link.path}`);
|
|
119
|
+
const [actual, expected] = await Promise.all([realpath(destination), realpath(link.source)]);
|
|
120
|
+
if (actual !== expected) throw new Error(`workspace.setup link destination points elsewhere: ${link.path}`);
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
const sourceInfo = await stat(link.source);
|
|
124
|
+
await symlink(link.source, destination, process.platform === "win32" ? "junction" : sourceInfo.isDirectory() ? "dir" : "file");
|
|
125
|
+
if (basename(link.path) === "node_modules" && sourceInfo.isDirectory()) {
|
|
126
|
+
for (const name of [".vite", ".vite-temp", ".cache"]) await mkdir(join(link.source, name), { recursive: true });
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (setup.submodules) {
|
|
130
|
+
await runToExit(gitBin(), ["-c", "protocol.file.allow=always", "-C", worktreePath, "submodule", "update", "--init", "--recursive"]);
|
|
131
|
+
}
|
|
132
|
+
if (setup.commands.length) {
|
|
133
|
+
const result = await runAcceptance(setup.commands, { cwd: worktreePath, taskId, timeoutMs: DEFAULT_ACCEPTANCE_TIMEOUT_MS });
|
|
134
|
+
if (!result.passed) {
|
|
135
|
+
const failing = result.checks.find((check) => !check.passed);
|
|
136
|
+
throw new Error(`workspace.setup command failed: ${failing?.command ?? "unknown"}${failing?.output_tail ? `\n${failing.output_tail}` : ""}`);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function workspaceSetupWriteRoots(record) {
|
|
142
|
+
const roots = [];
|
|
143
|
+
for (const link of record.workspace_metadata?.setup?.links ?? []) {
|
|
144
|
+
const source = resolveWritableRoot(link.source);
|
|
145
|
+
if (!source.error) roots.push(source.path);
|
|
146
|
+
if (basename(link.path) !== "node_modules") continue;
|
|
147
|
+
for (const name of [".vite", ".vite-temp", ".cache"]) {
|
|
148
|
+
const candidate = resolveWritableRoot(join(link.source, name));
|
|
149
|
+
if (!candidate.error) roots.push(candidate.path);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return roots;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function sleep(ms) {
|
|
156
|
+
return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// A lock whose holder died would otherwise stay for good: nothing else
|
|
160
|
+
// removes it, and every later dispatch into that repository would time out.
|
|
161
|
+
// The holder writes its pid into the lock; a waiter that finds the pid dead
|
|
162
|
+
// takes the lock away by renaming it, which only one waiter can win.
|
|
163
|
+
const LOCK_UNCLAIMED_MS = 10000;
|
|
164
|
+
|
|
165
|
+
async function lockIsAbandoned(lockPath) {
|
|
166
|
+
let owner;
|
|
167
|
+
try {
|
|
168
|
+
owner = Number(await readFile(join(lockPath, "owner"), "utf8"));
|
|
169
|
+
} catch (error) {
|
|
170
|
+
// Only a missing file means "not written yet"; anything else is a lock we cannot judge.
|
|
171
|
+
if (error.code !== "ENOENT") return false;
|
|
172
|
+
owner = 0;
|
|
173
|
+
}
|
|
174
|
+
if (owner) return !isPidAlive(owner);
|
|
175
|
+
// No owner yet: either the holder is between mkdir and its write, or it
|
|
176
|
+
// died there. Age tells them apart.
|
|
177
|
+
const info = await stat(lockPath).catch(() => null);
|
|
178
|
+
return Boolean(info) && Date.now() - info.mtimeMs > LOCK_UNCLAIMED_MS;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async function breakAbandonedLock(lockPath) {
|
|
182
|
+
const aside = `${lockPath}.${process.pid}.${Date.now()}.stale`;
|
|
183
|
+
try {
|
|
184
|
+
await rename(lockPath, aside);
|
|
185
|
+
} catch {
|
|
186
|
+
return; // someone else broke it, or the holder released it
|
|
187
|
+
}
|
|
188
|
+
// Between the check and the rename another waiter may have broken the lock
|
|
189
|
+
// and taken a fresh one, which is then what was moved. It goes back.
|
|
190
|
+
if (!await lockIsAbandoned(aside)) {
|
|
191
|
+
await rename(aside, lockPath).catch(() => {});
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
await rm(aside, { recursive: true, force: true }).catch(() => {});
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export async function withWorktreeCreationLock(cwd, work) {
|
|
198
|
+
const lockName = `create-${createHash("sha256").update(resolve(cwd)).digest("hex").slice(0, 24)}.lock`;
|
|
199
|
+
const lockPath = join(worktreesDir, lockName);
|
|
200
|
+
await mkdir(worktreesDir, { recursive: true });
|
|
201
|
+
const deadline = Date.now() + WORKTREE_LOCK_TIMEOUT_MS;
|
|
202
|
+
while (true) {
|
|
203
|
+
try {
|
|
204
|
+
await mkdir(lockPath);
|
|
205
|
+
break;
|
|
206
|
+
} catch (error) {
|
|
207
|
+
if (error.code !== "EEXIST" || Date.now() >= deadline) throw new Error(`worktree creation lock timed out for ${cwd}`, { cause: error });
|
|
208
|
+
if (await lockIsAbandoned(lockPath)) await breakAbandonedLock(lockPath);
|
|
209
|
+
else await sleep(100);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
try {
|
|
213
|
+
await writeFile(join(lockPath, "owner"), String(process.pid));
|
|
214
|
+
return await work();
|
|
215
|
+
} finally {
|
|
216
|
+
await rm(lockPath, { recursive: true, force: true }).catch(() => {});
|
|
217
|
+
}
|
|
218
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// Compare complete test identities, never a grep of the total failure count.
|
|
2
|
+
// The caller supplies an approved baseline and the current runner's evidence.
|
|
3
|
+
export function compareFailureBaseline(expected, actual) {
|
|
4
|
+
const errors = [];
|
|
5
|
+
const result = { passed: false, added: [], removed: [], changed: [], missing_required: [], errors };
|
|
6
|
+
const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
7
|
+
const text = (value) => typeof value === "string" && value.trim().length > 0;
|
|
8
|
+
if (!object(expected) || !object(actual)) {
|
|
9
|
+
errors.push("baseline and report must be objects");
|
|
10
|
+
return result;
|
|
11
|
+
}
|
|
12
|
+
if (!object(expected.identity) || !text(expected.identity.base_commit)) errors.push("baseline identity.base_commit is required");
|
|
13
|
+
if (!object(actual.identity) || !text(actual.identity.base_commit)) errors.push("report identity.base_commit is required");
|
|
14
|
+
if (expected.identity?.base_commit !== actual.identity?.base_commit) errors.push("base_commit mismatch");
|
|
15
|
+
if (actual.complete !== true) errors.push("report is not complete");
|
|
16
|
+
// Any explicitly approved identity component must match, including suite
|
|
17
|
+
// version, dataset hash or measured commit. Extra actual fields are allowed.
|
|
18
|
+
for (const [key, value] of Object.entries(expected.identity ?? {})) {
|
|
19
|
+
if (!text(value)) errors.push(`baseline identity.${key} must be a nonempty string`);
|
|
20
|
+
else if (actual.identity?.[key] !== value && key !== "base_commit") errors.push(`identity.${key} mismatch`);
|
|
21
|
+
}
|
|
22
|
+
const ids = (value, label) => {
|
|
23
|
+
if (!Array.isArray(value) || value.some((entry) => !text(entry))) {
|
|
24
|
+
errors.push(`${label} must be an array of nonempty test IDs`);
|
|
25
|
+
return new Set();
|
|
26
|
+
}
|
|
27
|
+
const unique = new Set(value);
|
|
28
|
+
if (unique.size !== value.length) errors.push(`${label} has duplicate test IDs`);
|
|
29
|
+
return unique;
|
|
30
|
+
};
|
|
31
|
+
const required = ids(expected.required, "required");
|
|
32
|
+
const executed = ids(actual.executed, "executed");
|
|
33
|
+
const skipped = ids(actual.skipped, "skipped");
|
|
34
|
+
for (const id of skipped) if (executed.has(id)) errors.push(`test ${id} is both executed and skipped`);
|
|
35
|
+
result.missing_required = [...required].filter((id) => !executed.has(id) || skipped.has(id)).sort();
|
|
36
|
+
const failures = (value, label) => {
|
|
37
|
+
const map = new Map();
|
|
38
|
+
if (!Array.isArray(value)) {
|
|
39
|
+
errors.push(`${label} failures must be an array`);
|
|
40
|
+
return map;
|
|
41
|
+
}
|
|
42
|
+
for (const item of value) {
|
|
43
|
+
if (!object(item) || !text(item.test_id) || !["failure", "error"].includes(item.kind) || !text(item.signature)) {
|
|
44
|
+
errors.push(`${label} has a malformed failure record`);
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (map.has(item.test_id)) errors.push(`${label} has duplicate failure ${item.test_id}`);
|
|
48
|
+
map.set(item.test_id, { test_id: item.test_id, kind: item.kind, signature: item.signature });
|
|
49
|
+
}
|
|
50
|
+
return map;
|
|
51
|
+
};
|
|
52
|
+
const baseline = failures(expected.failures, "baseline");
|
|
53
|
+
const observed = failures(actual.failures, "report");
|
|
54
|
+
for (const [id, item] of observed) {
|
|
55
|
+
if (!executed.has(id)) errors.push(`failure ${id} was not executed`);
|
|
56
|
+
const before = baseline.get(id);
|
|
57
|
+
if (!before) result.added.push(item);
|
|
58
|
+
else if (before.kind !== item.kind || before.signature !== item.signature) result.changed.push({ test_id: id, expected: before, actual: item });
|
|
59
|
+
}
|
|
60
|
+
for (const [id, item] of baseline) if (!observed.has(id)) result.removed.push(item);
|
|
61
|
+
for (const key of ["added", "removed", "changed"]) result[key].sort((a, b) => a.test_id.localeCompare(b.test_id));
|
|
62
|
+
const unchanged = result.added.length === 0 && result.removed.length === 0 && result.changed.length === 0;
|
|
63
|
+
result.passed = errors.length === 0 && unchanged && result.missing_required.length === 0;
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { isAbsolute } from "node:path";
|
|
2
|
+
import { compareFailureBaseline } from "./acceptance-baseline.js";
|
|
3
|
+
|
|
4
|
+
export const MAX_ACCEPTANCE_COMMANDS = 10;
|
|
5
|
+
|
|
6
|
+
// One string or a list; blanks dropped; an empty list is "not configured".
|
|
7
|
+
export function normalizeAcceptance(value) {
|
|
8
|
+
const list = Array.isArray(value) ? value : typeof value === "string" ? [value] : [];
|
|
9
|
+
const commands = list.filter((entry) => entry != null && entry !== "").map((entry) => {
|
|
10
|
+
if (typeof entry === "string") return entry.trim();
|
|
11
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry) || typeof entry.command !== "string" || !entry.command.trim()) throw new Error("acceptance requires a command string or structured check");
|
|
12
|
+
if (typeof entry.reportPath !== "string" || !entry.reportPath || isAbsolute(entry.reportPath) || /^[A-Za-z]:|^\\\\/.test(entry.reportPath) || entry.reportPath.split(/[\\/]/).includes("..")) throw new Error("report_path must stay inside the worktree");
|
|
13
|
+
const validation = compareFailureBaseline(entry.baseline, {
|
|
14
|
+
complete: true, identity: entry.baseline?.identity,
|
|
15
|
+
executed: [...new Set([...(entry.baseline?.required ?? []), ...(entry.baseline?.failures ?? []).map((item) => item?.test_id)])],
|
|
16
|
+
skipped: [], failures: entry.baseline?.failures
|
|
17
|
+
});
|
|
18
|
+
// Validation errors concern the contract; diff results concern actual
|
|
19
|
+
// failures, which do not exist at normalization time.
|
|
20
|
+
if (validation.errors.length) throw new Error(`invalid acceptance baseline: ${validation.errors.join("; ")}`);
|
|
21
|
+
return { command: entry.command.trim(), reportPath: entry.reportPath, baseline: structuredClone(entry.baseline) };
|
|
22
|
+
}).filter(Boolean);
|
|
23
|
+
if (commands.length === 0) return null;
|
|
24
|
+
if (commands.length > MAX_ACCEPTANCE_COMMANDS) {
|
|
25
|
+
const error = new Error(`acceptance lists ${commands.length} commands; at most ${MAX_ACCEPTANCE_COMMANDS} are run`);
|
|
26
|
+
error.code = "too_many_acceptance_commands";
|
|
27
|
+
throw error;
|
|
28
|
+
}
|
|
29
|
+
return commands;
|
|
30
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// When a worker's worktree may be removed.
|
|
2
|
+
//
|
|
3
|
+
// The worker's branch is never deleted, so commits are never at risk. The only
|
|
4
|
+
// thing a removal can lose is uncommitted edits, and those are saved as a
|
|
5
|
+
// checkpoint commit on the branch first. What the policy protects is therefore
|
|
6
|
+
// convenience, not data: work that has not landed keeps its worktree for a
|
|
7
|
+
// while so it can still be inspected, resumed and landed in place.
|
|
8
|
+
|
|
9
|
+
export const DEFAULT_HOLD_DAYS = 7;
|
|
10
|
+
|
|
11
|
+
export function holdMsFrom(raw) {
|
|
12
|
+
if (raw === undefined || raw === null || raw === "") return DEFAULT_HOLD_DAYS * 86400000;
|
|
13
|
+
const days = Number(raw);
|
|
14
|
+
return Number.isFinite(days) && days >= 0 ? days * 86400000 : DEFAULT_HOLD_DAYS * 86400000;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const verdict = (value, reasons, extra = {}) => ({ verdict: value, reasons, checkpoint: false, eligible_after: null, ...extra });
|
|
18
|
+
|
|
19
|
+
// facts: { active, dependent, terminal, identity, landed, uncommitted, unlandedCommits, finishedAt }
|
|
20
|
+
// active / identity are a reason string or null; finishedAt is epoch ms or null.
|
|
21
|
+
export function cleanupVerdict(facts, { now, holdMs }) {
|
|
22
|
+
if (facts.active) return verdict("blocked", [facts.active]);
|
|
23
|
+
if (facts.dependent) return verdict("blocked", ["an active dependent still needs this work"]);
|
|
24
|
+
if (!facts.terminal) return verdict("blocked", ["worker has not finished"]);
|
|
25
|
+
if (facts.identity) return verdict("review", [facts.identity]);
|
|
26
|
+
|
|
27
|
+
const unlanded = !facts.landed && facts.unlandedCommits > 0;
|
|
28
|
+
if (facts.uncommitted === 0 && !unlanded) {
|
|
29
|
+
return verdict("safe", facts.landed ? ["landed on the target branch", "worktree clean"] : ["no changes to keep"]);
|
|
30
|
+
}
|
|
31
|
+
const what = [
|
|
32
|
+
unlanded ? `${facts.unlandedCommits} commit(s) not landed` : null,
|
|
33
|
+
facts.uncommitted > 0 ? `${facts.uncommitted} uncommitted path(s)` : null
|
|
34
|
+
].filter(Boolean).join(", ");
|
|
35
|
+
const eligibleAt = (facts.finishedAt ?? now) + holdMs;
|
|
36
|
+
const eligibleAfter = new Date(eligibleAt).toISOString();
|
|
37
|
+
if (now < eligibleAt) {
|
|
38
|
+
return verdict("review", [`${what}; kept until ${eligibleAfter}, then saved on the worker branch and removed`], { eligible_after: eligibleAfter });
|
|
39
|
+
}
|
|
40
|
+
return verdict("safe", [`${what}; the hold period is over`, "everything is kept on the worker branch"], {
|
|
41
|
+
checkpoint: facts.uncommitted > 0,
|
|
42
|
+
eligible_after: eligibleAfter
|
|
43
|
+
});
|
|
44
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// A command counts as failed when the CLI said so or it exited non-zero.
|
|
2
|
+
export function commandFailed(entry) {
|
|
3
|
+
if (!entry) return false;
|
|
4
|
+
if (entry.status === "failed") return true;
|
|
5
|
+
return entry.exit_code !== null && entry.exit_code !== undefined && entry.exit_code !== 0;
|
|
6
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { isGoalNeedingAttention } from "./status.js";
|
|
2
|
+
|
|
3
|
+
function providerFailure(text) {
|
|
4
|
+
if (!/provider|upstream_status|upstream status|cc switch|responses endpoint/i.test(text)) return null;
|
|
5
|
+
const status = Number(text.match(/(?:upstream_status|upstream status|unexpected status|HTTP)\D{0,8}(\d{3})/i)?.[1] ?? 0);
|
|
6
|
+
const retryable = status === 429 || status >= 500 || /timeout|temporar|rate.?limit/i.test(text);
|
|
7
|
+
return { source: "provider", code: status ? `provider_http_${status}` : "provider_error", retryable };
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// "codex exited with code 1" says only that the process ended badly. The
|
|
11
|
+
// reason is whatever it last wrote to stderr, so that is read for the causes a
|
|
12
|
+
// caller acts on differently: fix the login, wait for the provider, fix the
|
|
13
|
+
// configuration. The last line is passed on either way.
|
|
14
|
+
const lastLine = (text) => text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).at(-1)?.slice(0, 300) ?? null;
|
|
15
|
+
|
|
16
|
+
function processExitFailure(stderr) {
|
|
17
|
+
const detail = lastLine(stderr);
|
|
18
|
+
const withDetail = (failure) => (detail ? { ...failure, detail } : failure);
|
|
19
|
+
// A bare 401 is also a line number or a millisecond; it counts only next to a word that makes it a status.
|
|
20
|
+
if (/(?:http|status|code|error)\D{0,8}(?:401|403)\b|unauthori[sz]ed|not logged in|login required|invalid api key|missing api key|forbidden/i.test(stderr)) {
|
|
21
|
+
return withDetail({ source: "auth", code: "auth_failed", retryable: false });
|
|
22
|
+
}
|
|
23
|
+
// A process of an earlier run still holds the session; it clears when that process ends.
|
|
24
|
+
if (/already has an active writer|thread-store conflict/i.test(stderr)) return withDetail({ source: "runner_session", code: "session_busy", retryable: true });
|
|
25
|
+
// The specific causes first: the general provider match answers to the word "provider" alone.
|
|
26
|
+
if (/(?:http|status|code|error)\D{0,8}429\b|rate.?limit|too many requests/i.test(stderr)) {
|
|
27
|
+
return withDetail({ source: "provider", code: "provider_rate_limited", retryable: true });
|
|
28
|
+
}
|
|
29
|
+
if (/ECONNREFUSED|ECONNRESET|ENOTFOUND|ETIMEDOUT|error sending request|connection (refused|reset|closed)|stream disconnected|dns error/i.test(stderr)) {
|
|
30
|
+
return withDetail({ source: "provider", code: "provider_unreachable", retryable: true });
|
|
31
|
+
}
|
|
32
|
+
const provider = providerFailure(stderr);
|
|
33
|
+
if (provider) return withDetail(provider);
|
|
34
|
+
if (/config\.toml|unknown model|model .{0,80}(not found|does not exist|not supported)|unexpected argument|invalid value/i.test(stderr)) {
|
|
35
|
+
return withDetail({ source: "runner_config", code: "config_invalid", retryable: false });
|
|
36
|
+
}
|
|
37
|
+
return withDetail({ source: "worker_process", code: "process_exit_nonzero", retryable: true });
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function classifyFailure(task) {
|
|
41
|
+
if (!task) return null;
|
|
42
|
+
const error = String(task.error ?? "");
|
|
43
|
+
const attention = String(task.attention_reason ?? "");
|
|
44
|
+
|
|
45
|
+
const provider = providerFailure(error);
|
|
46
|
+
if (provider) return provider;
|
|
47
|
+
if (/did not record the process exit/i.test(error)) return { source: "supervisor_process", code: "exit_unrecorded", retryable: true };
|
|
48
|
+
if (attention === "start_failed") return { source: "supervisor_process", code: "start_failed", retryable: true };
|
|
49
|
+
if (/^workspace\.setup command failed:/i.test(error)) return { source: "workspace_setup", code: "setup_command_failed", retryable: true };
|
|
50
|
+
if (/^workspace\.setup link /i.test(error)) return { source: "workspace_setup", code: "setup_link_failed", retryable: true };
|
|
51
|
+
if (attention === "invalid_report" || /Invalid final worker report/i.test(error)) return { source: "model_output", code: "invalid_report", retryable: true };
|
|
52
|
+
if (task.acceptance_results?.passed === false) return { source: "acceptance", code: "acceptance_failed", retryable: true };
|
|
53
|
+
if (attention === "no_work" || attention === "two_stall") return { source: "worker_progress", code: attention, retryable: false };
|
|
54
|
+
if (task.status === "timed_out" || attention === "run_time_limit" || attention === "total_time_limit") {
|
|
55
|
+
return { source: "time_limit", code: attention || "time_limit", retryable: false };
|
|
56
|
+
}
|
|
57
|
+
if (task.status === "lost") return { source: "supervisor_process", code: "worker_lost", retryable: true };
|
|
58
|
+
if (task.status === "cancelled") return { source: "caller", code: "cancelled", retryable: true };
|
|
59
|
+
if (/codex exited with code/i.test(error)) return processExitFailure(String(task.stderr_tail ?? ""));
|
|
60
|
+
if (isGoalNeedingAttention(task.goal_status)) return { source: "goal", code: `goal_${task.goal_status}`, retryable: false };
|
|
61
|
+
if (task.status === "failed") return { source: "unknown", code: "failed", retryable: null };
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
|
|
3
|
+
// Ownership is declared relative to the project but edits live in the worker
|
|
4
|
+
// checkout. Segment comparisons reject sibling prefixes and parent traversal.
|
|
5
|
+
export function findOutsideOwnedChanges(task, changes, { platform = process.platform } = {}) {
|
|
6
|
+
const p = platform === "win32" ? path.win32 : path.posix;
|
|
7
|
+
const fold = (value) => platform === "win32" ? value.toLowerCase() : value;
|
|
8
|
+
const root = p.resolve(task.project_root);
|
|
9
|
+
const worktree = p.resolve(task.worktree_path ?? task.cwd ?? task.project_root);
|
|
10
|
+
const within = (base, file) => {
|
|
11
|
+
const rel = p.relative(fold(base), fold(file));
|
|
12
|
+
return rel !== ".." && !rel.startsWith(`..${p.sep}`) && !p.isAbsolute(rel);
|
|
13
|
+
};
|
|
14
|
+
const mapping = (task.owned_paths ?? []).flatMap((entry) => {
|
|
15
|
+
const absolute = p.resolve(root, entry);
|
|
16
|
+
if (!within(root, absolute)) return [];
|
|
17
|
+
return [{ declared: entry, worker: p.resolve(worktree, p.relative(root, absolute)) }];
|
|
18
|
+
});
|
|
19
|
+
const owned = [];
|
|
20
|
+
const outside = [];
|
|
21
|
+
for (const change of changes) {
|
|
22
|
+
const absolute = p.resolve(worktree, change);
|
|
23
|
+
const allowed = within(worktree, absolute) && mapping.some((entry) => within(entry.worker, absolute));
|
|
24
|
+
(allowed ? owned : outside).push(change);
|
|
25
|
+
}
|
|
26
|
+
return { owned, outside, mapping };
|
|
27
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// Worker prompt framing: what goes around the task text.
|
|
2
|
+
//
|
|
3
|
+
// Goal preamble, in front. Codex exposes goal tools (create_goal / get_goal /
|
|
4
|
+
// update_goal) to every thread, but the model does not create a goal on its
|
|
5
|
+
// own. A worker therefore starts with no native goal unless we ask for one,
|
|
6
|
+
// which is why the supervisor prepends this block instead of only recording
|
|
7
|
+
// the goal on its own side. create_goal fails when an unfinished goal already
|
|
8
|
+
// exists, so the resume path must not ask for one: that thread already has
|
|
9
|
+
// its goal.
|
|
10
|
+
//
|
|
11
|
+
// Report format, at the end. A worker's last message is what the supervisor
|
|
12
|
+
// reads back through get_worker (include result). Left to itself a worker narrates
|
|
13
|
+
// the whole run and lists every file it touched, and one real report ran to
|
|
14
|
+
// four thousand tokens with the conclusion buried in the middle. The format
|
|
15
|
+
// asks for the three things a reviewer checks and nothing else: the result,
|
|
16
|
+
// the commands that prove it, and what was left out. Files are not listed
|
|
17
|
+
// because the supervisor reads the diff. It goes after the task text because
|
|
18
|
+
// a format instruction at the end of a long prompt is the one that is
|
|
19
|
+
// followed, and because "the task's own format wins" has to come after the
|
|
20
|
+
// task.
|
|
21
|
+
|
|
22
|
+
function oneLine(value) {
|
|
23
|
+
return String(value ?? "").replace(/\s+/g, " ").trim();
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function buildGoalPreamble({ objective, tokenBudget = null, resume = false }) {
|
|
27
|
+
const goal = oneLine(objective);
|
|
28
|
+
if (!goal) return "";
|
|
29
|
+
if (resume) {
|
|
30
|
+
return [
|
|
31
|
+
`This thread already has a goal: ${goal}`,
|
|
32
|
+
"Do not call create_goal; it fails while an unfinished goal exists.",
|
|
33
|
+
'Call update_goal with status "complete" when the objective is achieved and no required work remains.',
|
|
34
|
+
'If the same blocker repeats for three consecutive turns and you cannot make progress, call update_goal with status "blocked" instead.'
|
|
35
|
+
].join("\n");
|
|
36
|
+
}
|
|
37
|
+
const budget = tokenBudget ? ` and token_budget ${tokenBudget}` : "";
|
|
38
|
+
return [
|
|
39
|
+
"Do this first, before any other work:",
|
|
40
|
+
`Call the create_goal tool with objective exactly "${goal}"${budget}.`,
|
|
41
|
+
tokenBudget
|
|
42
|
+
? "Include that token_budget exactly; a missing or different value is denied."
|
|
43
|
+
: "Omit the token_budget field entirely; any value, including 0, 1, or null, is denied.",
|
|
44
|
+
"That goal is how your supervisor tracks this work; do not skip it.",
|
|
45
|
+
'When the objective is achieved and no required work remains, call update_goal with status "complete".',
|
|
46
|
+
'If the same blocker repeats for three consecutive turns and you cannot make progress, call update_goal with status "blocked" instead.'
|
|
47
|
+
].join("\n");
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export const REPORT_SECTIONS = ["Result", "Verification", "Not done / risks"];
|
|
51
|
+
|
|
52
|
+
// The first thing a worker reads, and the only place the run's write boundary
|
|
53
|
+
// is stated. A worker is not always an editor: a read-only one can only read,
|
|
54
|
+
// and one with no owned_paths lands nothing, so both are told what their shell
|
|
55
|
+
// may do instead of being told to use apply_patch they cannot use.
|
|
56
|
+
export function buildGuardPreamble({ sandbox, ownedPaths = [], allowedCommands = [], forbid = [], networkAccess = false, workspaceKind = null } = {}) {
|
|
57
|
+
const forbidden = JSON.stringify(forbid);
|
|
58
|
+
const stage = 'For a long gate, checkpoint phases with node "$AGENT_SUPERVISOR_STAGE_CLI" "gate:s3" --detail "current check"; stage text is visible to status/overview/wait and must not contain secrets.';
|
|
59
|
+
if (sandbox === "read-only") {
|
|
60
|
+
return [
|
|
61
|
+
"Runtime supervisor guard: this is a read-only task.",
|
|
62
|
+
"The sandbox denies every file write, the temp directory included, and it has no network, so do not try to write files, fetch URLs or install anything: they fail and waste the turn.",
|
|
63
|
+
"Run the read commands you need (rg, cat, git, jq, the project's own read-only tools) and put the findings in the final report.",
|
|
64
|
+
`Forbidden: ${forbidden}.`,
|
|
65
|
+
stage
|
|
66
|
+
].join(" ");
|
|
67
|
+
}
|
|
68
|
+
if (Array.isArray(ownedPaths) && ownedPaths.length === 0) {
|
|
69
|
+
const location = workspaceKind === "scratch"
|
|
70
|
+
? "Its execution directory is a supervisor-managed scratch directory, not the user's source directory"
|
|
71
|
+
: "Its worktree is a scratch copy";
|
|
72
|
+
return [
|
|
73
|
+
"Runtime supervisor guard: this worker lands nothing: no owned_paths means nothing it writes is ever merged into the project.",
|
|
74
|
+
`${location}, so the shell is unrestricted apart from the red lines; keep notes and downloads inside it.`,
|
|
75
|
+
networkAccess ? "Network is available." : "There is no network in this sandbox; ask for it instead of retrying a failing fetch.",
|
|
76
|
+
`Forbidden: ${forbidden}.`,
|
|
77
|
+
stage,
|
|
78
|
+
"Report what you found and name the files a writer would have to change."
|
|
79
|
+
].join(" ");
|
|
80
|
+
}
|
|
81
|
+
// A model whose toolset has no apply_patch tool sends the patch through the
|
|
82
|
+
// shell as a heredoc; the guard accepts that shape too, so the worker is told
|
|
83
|
+
// about it instead of stalling on a tool it does not have.
|
|
84
|
+
const shellEdit = "If your toolset has no apply_patch tool, run it through the shell as apply_patch <<'EOF' ... EOF; the guard checks the file paths the same way. A declared command ending in * is a prefix, so go test ./internal/* covers go test ./internal/service -run TestX.";
|
|
85
|
+
const delivery = sandbox === "workspace-write" && (!workspaceKind || workspaceKind === "git_worktree")
|
|
86
|
+
? "Do not run git add, git commit or git commit --amend: the dispatcher commits reviewed edits with land_worker({commit_message}). Leave your edits uncommitted; clean status and commit-count checks belong after landing. If the task or acceptance requires a self-commit or a clean edited worktree, report the contract conflict instead of bypassing the guard."
|
|
87
|
+
: "";
|
|
88
|
+
return `Runtime supervisor guard: edits must use apply_patch within ${JSON.stringify(ownedPaths)}. ${shellEdit} ${delivery} Safe read-only inspection commands (rg, cat, sed without -i, git status/diff/log, jq without -i, find without -exec/-delete) are allowed and never reserve another worker's paths. Commands that validate, write, execute code or have side effects must exactly match declared commands ${JSON.stringify(allowedCommands)}. Forbidden: ${forbidden}. Undeclared shell programs are denied; report a needed validation command instead of bypassing the guard. ${stage}`;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// The acceptance commands are shown to the worker. Hiding them would not
|
|
92
|
+
// stop a worker from gaming a check (it can see the tests in the tree
|
|
93
|
+
// anyway) and would stop it from running them before it reports, which is
|
|
94
|
+
// the cheapest fix loop there is. The supervisor runs them again after the
|
|
95
|
+
// worker exits regardless of what the worker says.
|
|
96
|
+
export function buildAcceptanceBlock(acceptance, { resume = false } = {}) {
|
|
97
|
+
const commands = Array.isArray(acceptance) ? acceptance.filter(Boolean) : [];
|
|
98
|
+
if (commands.length === 0) return "";
|
|
99
|
+
const runner = 'Run node "$AGENT_SUPERVISOR_ACCEPTANCE_CLI" to execute this exact contract through the supervisor\'s non-interactive Bash with errexit and pipefail. Do not retype the commands in zsh; the interactive shell is not the acceptance shell.';
|
|
100
|
+
if (resume) {
|
|
101
|
+
return ["Acceptance is unchanged.", runner, `Commands: ${commands.map((check) => typeof check === "string" ? check : JSON.stringify(check)).join(" ; ")}`].join("\n");
|
|
102
|
+
}
|
|
103
|
+
return [
|
|
104
|
+
"Acceptance: when you exit, the supervisor runs these commands in this directory and each must exit 0:",
|
|
105
|
+
...commands.map((command) => `- ${typeof command === "string" ? command : JSON.stringify(command)}`),
|
|
106
|
+
runner,
|
|
107
|
+
"Run that contract before you report and put its exit code and key evidence under Verification. Do not edit what it tests to make it pass; if a check is wrong, say why under Not done / risks."
|
|
108
|
+
].join("\n");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function buildReportPreamble({ resume = false, acceptance = null, outputSchema = true } = {}) {
|
|
112
|
+
const acceptanceBlock = buildAcceptanceBlock(acceptance, { resume });
|
|
113
|
+
const withAcceptance = (text) => (acceptanceBlock ? `${text}\n\n${acceptanceBlock}` : text);
|
|
114
|
+
if (resume) {
|
|
115
|
+
return withAcceptance(`Report as before using JSON with result string, verification string[] (every command you ran to check, with exit codes), not_done string[] (remaining work and risks). ${outputSchema ? "The output schema enforces these fields. " : "No output schema is active on this resume, so follow the shape yourself. "}Under 2000 characters, no list of changed files, quote raw errors verbatim.`);
|
|
116
|
+
}
|
|
117
|
+
return withAcceptance([
|
|
118
|
+
"Final report (your last message), under 2000 characters, in the language of the task. Quoted command output does not count toward the limit.",
|
|
119
|
+
`Return JSON with exactly result:string, verification:string[], not_done:string[]; ${outputSchema ? "an output schema enforces these fields" : "no output schema is active, so follow this shape exactly"}. Cover the following content in those fields.`,
|
|
120
|
+
"Write that JSON value on its own: no markdown code fences and nothing before or after it.",
|
|
121
|
+
"Keep each verification entry concise: command name, exit code and key evidence; avoid embedding long quoted shell source. Ensure arrays and the object are fully closed and all strings use valid JSON escaping.",
|
|
122
|
+
"1. Result: what is done, in two or three sentences. Say plainly what is not done.",
|
|
123
|
+
"2. Verification: every command you ran to check the work, its exit code, and the output lines that prove the result. Write \"not verified\" if you ran none.",
|
|
124
|
+
"3. Not done / risks: what you skipped, what you are unsure of, what the reviewer should look at first.",
|
|
125
|
+
"Do not list the files you changed; the supervisor reads the diff.",
|
|
126
|
+
"Never call a failure an environment problem without quoting the raw error verbatim.",
|
|
127
|
+
"If the task specifies content or language, preserve it inside these JSON fields."
|
|
128
|
+
].join("\n"));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function withGoalPreamble(prompt, goalOptions) {
|
|
132
|
+
const preamble = buildGoalPreamble(goalOptions);
|
|
133
|
+
return preamble ? `${preamble}\n\n${prompt}` : prompt;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// The whole frame: goal in front, task text, report format at the end.
|
|
137
|
+
// nativeGoal false is a CLI with no goal of its own: it is told the objective
|
|
138
|
+
// in a line, not to call goal tools it does not have.
|
|
139
|
+
export function frameWorkerPrompt(prompt, goalOptions, { acceptance = null, outputSchema = true, nativeGoal = true } = {}) {
|
|
140
|
+
const plainObjective = !goalOptions?.resume && goalOptions?.objective ? `Objective: ${goalOptions.objective}\n\n${prompt}` : prompt;
|
|
141
|
+
const framed = nativeGoal ? withGoalPreamble(prompt, goalOptions) : plainObjective;
|
|
142
|
+
return `${framed}\n\n${buildReportPreamble({ resume: Boolean(goalOptions?.resume), acceptance, outputSchema })}`;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// Claude's native /goal owns its Stop condition. MCP cannot silently replace
|
|
146
|
+
// it, so return a concrete current-policy condition for the host's goal UI.
|
|
147
|
+
// The condition references the current revision instead of copying long or
|
|
148
|
+
// soon-stale commands into the host's independently stored Stop hook.
|
|
149
|
+
export function buildHostGoalSync(session) {
|
|
150
|
+
const id = JSON.stringify(String(session.id));
|
|
151
|
+
const condition = [
|
|
152
|
+
`For supervisor session ${id}, read find_works and use its current objective, default_acceptance, approval_state and policy_revision (at least ${session.policy_revision ?? 0}).`,
|
|
153
|
+
"Use the latest explicit human instruction and approved failure baseline; superseded goals and checks must not be revived.",
|
|
154
|
+
"Stop when the current approved objective is verified and all required worker results are collected, checked and integrated as requested.",
|
|
155
|
+
"If approval_state is waiting_user, stop after clearly reporting the blocker, attempted checks, options and recommendation and asking for the required decision; do not auto-resume or repeat unchanged waiting reports.",
|
|
156
|
+
"Report the policy revision and actual evidence. A worker exit, acceptance green, push or publish alone is not proof that the whole objective is done."
|
|
157
|
+
].join(" ");
|
|
158
|
+
return { revision: session.policy_revision ?? 0, approval_state: session.approval_state ?? "approved", condition,
|
|
159
|
+
claude_command: `/goal ${condition}`, requires_host_action: true,
|
|
160
|
+
instruction: "If a native Claude goal is active, replace its condition through /goal with this current-policy condition; ProposeGoal may propose it for host approval where available. MCP has not modified or disabled the host Stop hook." };
|
|
161
|
+
}
|