codex-supervisor-mcp 0.10.3 → 0.11.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.
@@ -50,8 +50,10 @@ export async function compileWorkerContext(task, { attempt }) {
50
50
  `- run_id: ${runIdFor(task.id, attempt)}`,
51
51
  `- project_root: ${task.project_root}`,
52
52
  `- base_sha: ${task.base_commit ?? "unknown"}`,
53
+ `- branch: ${task.worktree_path ? `codex/${task.id}` : "not applicable (in-place workspace)"}`,
53
54
  `- worktree: ${task.worktree_path ?? task.cwd}`,
54
55
  `- owned_paths: ${JSON.stringify(task.owned_paths ?? [])}`,
56
+ `- acceptance_source: ${Array.isArray(task.acceptance) && task.acceptance.length > 0 ? "dispatch or session policy; commands stay outside this capsule" : "no acceptance configured"}`,
55
57
  "L1 task:",
56
58
  `- objective: ${task.goal_objective ?? task.title ?? "unspecified"}`
57
59
  ];
@@ -82,5 +84,5 @@ export async function compileWorkerContext(task, { attempt }) {
82
84
  candidate_facts: "never automatic"
83
85
  }
84
86
  });
85
- return { text, snapshot, sourceRefs: handoff.source_refs, factCount: usedFacts.length };
87
+ return { text, snapshot, sourceRefs: handoff.source_refs, contentHash: handoff.content_hash, factCount: usedFacts.length };
86
88
  }
package/src/handoff.js CHANGED
@@ -2,6 +2,14 @@ import { createHash } from "node:crypto";
2
2
  import { readFile, lstat } from "node:fs/promises";
3
3
  import { isAbsolute } from "node:path";
4
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
+
5
13
  export async function buildHandoff({ goal, todo, contracts = [], context = [] }, { maxLines = 16, maxChars = 1800 } = {}) {
6
14
  if (!Array.isArray(context) || context.length > 20 || !Array.isArray(contracts)
7
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");
@@ -26,5 +34,5 @@ export async function buildHandoff({ goal, todo, contracts = [], context = [] },
26
34
  }
27
35
  const truncated = lines.length !== candidates.length;
28
36
  if (truncated) lines.push(marker);
29
- return { text: lines.join("\n"), truncated, source_refs: refs };
37
+ return { text: lines.join("\n"), truncated, source_refs: refs, content_hash: contextContentHash(refs) };
30
38
  }
package/src/landing.js CHANGED
@@ -70,6 +70,16 @@ function currentBranch(cwd) {
70
70
  return name || null;
71
71
  }
72
72
 
73
+ function hasStagedChanges(cwd) {
74
+ try {
75
+ git(cwd, ["diff", "--cached", "--quiet"]);
76
+ return false;
77
+ } catch (error) {
78
+ if (error.status === 1) return true;
79
+ throw error;
80
+ }
81
+ }
82
+
73
83
  // Lands task's commits onto the current branch of its dispatch directory
74
84
  // (task.project_root: the row's cwd is the worktree the worker ran in).
75
85
  // `onto`, when given, must name that branch: it is a guard, not a switch.
@@ -145,14 +155,16 @@ export function landWorker(task, { onto = null, commitMessage = null, ignoreAcce
145
155
  if (uncommitted.length > 0 && commitMessage) {
146
156
  try {
147
157
  git(task.worktree_path, ["add", "-A"]);
148
- git(task.worktree_path, ["commit", "-q", "-m", commitMessage]);
158
+ if (hasStagedChanges(task.worktree_path)) {
159
+ git(task.worktree_path, ["commit", "-q", "-m", commitMessage]);
160
+ committedForWorker = git(task.worktree_path, ["rev-parse", "HEAD"]).trim();
161
+ commits.push(committedForWorker);
162
+ }
163
+ uncommitted = porcelainPaths(git(task.worktree_path, ["--no-optional-locks", "status", "--porcelain"]));
149
164
  } catch (error) {
150
165
  const tail = `${error.stdout ?? ""}${error.stderr ?? ""}`.trim().split("\n").slice(-3).join("\n");
151
166
  return { error: "commit_failed", reason: `could not commit the worker's uncommitted edits in ${task.worktree_path}: ${tail || error.message.split("\n")[0]}`, uncommitted };
152
167
  }
153
- committedForWorker = git(task.worktree_path, ["rev-parse", "HEAD"]).trim();
154
- commits.push(committedForWorker);
155
- uncommitted = [];
156
168
  }
157
169
  // Commits whose patch is already on the target (a previous land, or the
158
170
  // main thread cherry-picked by hand) are skipped by patch id; picking
package/src/mcp-server.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFileSync } from "node:fs";
3
3
  import { execFileSync } from "node:child_process";
4
- import { randomUUID } from "node:crypto";
4
+ import { createHash, randomUUID } from "node:crypto";
5
5
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
6
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7
7
  import { z } from "zod";
@@ -14,12 +14,22 @@ import {
14
14
  } from "./codex-runner.js";
15
15
  import {
16
16
  getSession,
17
+ getArtifact,
17
18
  getFact,
19
+ getFactEffectiveState,
20
+ isFactRevoked,
21
+ getReviewByVerifierTask,
22
+ getTaskForWorkItem,
18
23
  getWorkItemForTask,
19
24
  getTask,
20
25
  getTasks,
21
26
  isPidAlive,
22
27
  listTaskEventKinds,
28
+ listArtifactsForTask,
29
+ listContextFacts,
30
+ countVerifiedFacts,
31
+ readArtifact,
32
+ readTaskEventRecords,
23
33
  readAgentMessages,
24
34
  readTaskEvents,
25
35
  readTasks,
@@ -34,11 +44,16 @@ import {
34
44
  upsertTask,
35
45
  appendTaskEvent,
36
46
  recordFact,
47
+ recordJsonArtifact,
48
+ createReviewAssignment,
49
+ recordReviewFinding,
50
+ resolveReviewFinding,
51
+ promoteCandidateFact,
52
+ revokeFact,
37
53
  runIdFor,
38
54
  updateWorkItemDelivery,
39
55
  saveCleanupPlan,
40
56
  getCleanupPlan,
41
- markCleanupPlanItemApplied,
42
57
  readCleanupHistory
43
58
  } from "./task-store.js";
44
59
  import { readNativeGoal, readNativeGoalState } from "./goal-store.js";
@@ -56,7 +71,7 @@ import { maybeAutoUpdate } from "./auto-update.js";
56
71
  import { askWorker, endSideSession, latestSideTurn } from "./side-chat.js";
57
72
  import { landWorker } from "./landing.js";
58
73
  import { cleanupHint } from "./cleanup-hint.js";
59
- import { createCleanupPlan, removePlannedWorktree } from "./cleanup-plan.js";
74
+ import { applyCleanupPlan, createCleanupPlan } from "./cleanup-plan.js";
60
75
  import { buildOverviewDelta } from "./overview-delta.js";
61
76
 
62
77
  // Report the real package version. This string had drifted to 0.4.0 while the
@@ -269,6 +284,7 @@ function summarizeTask(task) {
269
284
  phase: task.phase ?? null,
270
285
  cwd: task.cwd,
271
286
  project_root: task.project_root,
287
+ workspace_kind: task.workspace_kind ?? "legacy",
272
288
  sandbox: task.sandbox,
273
289
  model: task.model,
274
290
  reasoning_effort: task.reasoning_effort ?? "high",
@@ -342,6 +358,7 @@ function receipt(task) {
342
358
  phase: task.phase ?? null,
343
359
  cwd: task.cwd,
344
360
  project_root: task.project_root,
361
+ workspace_kind: task.workspace_kind ?? "legacy",
345
362
  worktree_path: task.worktree_path,
346
363
  branch: task.worktree_path ? `codex/${task.id}` : null,
347
364
  base_commit: task.base_commit ?? null,
@@ -505,6 +522,7 @@ function errorResult(error) {
505
522
  error: error.code ?? "error",
506
523
  message: error.message,
507
524
  ...(error.conflicts ? { conflicts: error.conflicts } : {}),
525
+ ...(error.details?.preflight ? { preflight: error.details.preflight } : {}),
508
526
  ...(error.details ? { files: error.details.files ?? [], git: error.details.git ?? null, base_commit: error.details.base_commit ?? null, head: error.details.head ?? null } : {})
509
527
  });
510
528
  }
@@ -564,7 +582,14 @@ server.registerTool(
564
582
  await reconcileDetachedActiveTasks();
565
583
  const tasks = await readTasks();
566
584
  const previous = cursor ?? await readObserverCursor(deltaObserverId);
567
- const result = buildOverviewDelta(tasks, previous);
585
+ const candidateIds = tasks.filter((task) => task.delivery_state === "cleanup_eligible").map((task) => task.id);
586
+ const cleanupReadiness = candidateIds.length > 0
587
+ ? await createCleanupPlan({ taskIds: candidateIds, revalidateRemote: false })
588
+ : null;
589
+ const readyToCleanTaskIds = cleanupReadiness
590
+ ? new Set(cleanupReadiness.items.filter((item) => item.verdict === "safe").map((item) => item.task_id))
591
+ : new Set();
592
+ const result = buildOverviewDelta(tasks, previous, { readyToCleanTaskIds });
568
593
  await writeObserverCursor(deltaObserverId, result.cursor);
569
594
  const { cursor: nextCursor, ...reply } = result;
570
595
  return textResult({ ...reply, next_cursor: nextCursor });
@@ -644,6 +669,8 @@ server.registerTool(
644
669
  maxRunMs: z.number().int().min(1000).max(86400000).optional(),
645
670
  maxTotalMs: z.number().int().min(1000).max(604800000).optional(),
646
671
  baseRef: z.string().min(1).optional(),
672
+ workspaceKind: z.enum(["git_worktree", "read_only_in_place", "scratch", "in_place_write"]).optional(),
673
+ inPlaceAuthorization: z.string().min(1).max(2000).optional(),
647
674
  probeCommands: z.array(z.string().min(1)).min(1).max(20)
648
675
  }
649
676
  },
@@ -690,7 +717,7 @@ server.registerTool(
690
717
  {
691
718
  title: "Create Codex worker",
692
719
  description:
693
- "Launch a Codex CLI worker with codex exec --json and track its events. ownedPaths and goal are required: ownedPaths reserves the files this worker may write, and an empty list is the deliberate promise that nothing lands, which is how a read-only verifier or a research worker is dispatched. The worker is not only an editor: a read-only worker gets no network and may run any read command, and a research worker runs with sandbox \"workspace-write\", networkAccess: true and ownedPaths: [] so it can fetch, keep notes in its own throwaway worktree and never merge anything. Reading is never exclusive; only writes conflict. acceptance is the list of shell commands that decide whether the work is done: the supervisor runs them in the worker's worktree after codex exits, each must exit 0, and the worker sees them in its prompt so it can run them first. Write the check for this step (a test file, a file that must exist, an endpoint that must answer), not the whole suite; a check on another machine goes through ssh. They run with the supervisor's own privileges, as if you ran them yourself. The verdict shows as acceptance on wait, the overview and get_worker_result, and land_codex_worker refuses while it is failed. The worker's sandbox may write the worktree, the temp directory and the OS cache directory; a toolchain whose cache lives elsewhere needs writableRoots, a list of existing absolute directories.",
720
+ "Launch a Codex CLI worker with codex exec --json and track its events. workspaceKind controls where it runs: Git work writes only in an isolated git_worktree; read_only_in_place cannot write or use network; scratch writes only under SUPERVISOR_HOME and never lands; in_place_write is only for an explicitly authorized non-Git directory with ownedPaths and acceptance. A non-Git worker may never write the user directory by default. ownedPaths reserves files a landable worker may write; reading is never exclusive. acceptance is the list of shell commands that decide whether the work is done: the supervisor runs them after Codex exits. The worker's sandbox may write its execution directory, the temp directory and the OS cache directory; a toolchain whose cache lives elsewhere needs writableRoots, a list of existing absolute directories.",
694
721
  inputSchema: {
695
722
  title: z.string().optional(),
696
723
  task: z.string().min(1),
@@ -729,6 +756,8 @@ server.registerTool(
729
756
  // HEAD; pass a branch, tag or sha to build on work that is not on the
730
757
  // main line yet (for example another worker's codex/<id> branch).
731
758
  baseRef: z.string().min(1).optional(),
759
+ workspaceKind: z.enum(["git_worktree", "read_only_in_place", "scratch", "in_place_write"]).optional(),
760
+ inPlaceAuthorization: z.string().min(1).max(2000).optional(),
732
761
  // A successful preflight_codex_worker task id. When present, this worker
733
762
  // is refused unless base commit and the complete runtime contract match.
734
763
  preflight_id: z.string().min(1).optional(),
@@ -781,6 +810,8 @@ server.registerTool(
781
810
  writableRoots: z.array(z.string().min(1)).max(20).optional(),
782
811
  maxRunMs: z.number().int().min(1000).max(86400000).optional(),
783
812
  maxTotalMs: z.number().int().min(1000).max(604800000).optional(),
813
+ workspaceKind: z.enum(["git_worktree", "read_only_in_place", "scratch", "in_place_write"]).optional(),
814
+ inPlaceAuthorization: z.string().min(1).max(2000).optional(),
784
815
  goal: z
785
816
  .object({
786
817
  objective: z.string().min(1),
@@ -1184,7 +1215,310 @@ server.registerTool(
1184
1215
  },
1185
1216
  async ({ fact_id }) => {
1186
1217
  const fact = await getFact(fact_id);
1187
- return textResult(fact ? { fact } : { error: "fact_not_found", fact_id });
1218
+ if (!fact) return textResult({ error: "fact_not_found", fact_id });
1219
+ return textResult({ fact, effective_state: await getFactEffectiveState(fact_id) ?? fact.state });
1220
+ }
1221
+ );
1222
+
1223
+ server.registerTool(
1224
+ "get_artifact",
1225
+ {
1226
+ title: "Get one retained evidence artifact",
1227
+ description: "Read one supervisor-managed artifact by ID for audit. This is explicit evidence retrieval and never expands a worker context capsule into the main thread.",
1228
+ inputSchema: { artifact_id: z.string().uuid(), maxChars: z.number().int().min(0).max(100000).default(12000) }
1229
+ },
1230
+ async ({ artifact_id, maxChars }) => {
1231
+ const artifact = await getArtifact(artifact_id);
1232
+ if (!artifact) return textResult({ error: "artifact_not_found", artifact_id });
1233
+ return textResult({ artifact: await readArtifact(artifact_id, maxChars) });
1234
+ }
1235
+ );
1236
+
1237
+ server.registerTool(
1238
+ "promote_worker_fact",
1239
+ {
1240
+ title: "Promote a candidate worker fact",
1241
+ description: "Explicitly promote one candidate fact after main-thread review. The worker cannot call this: promotion writes a new verified fact with an audit event; repo scope requires watched paths.",
1242
+ inputSchema: {
1243
+ fact_id: z.string().uuid(),
1244
+ scope: z.enum(["work_item", "repo_verified"]).default("work_item"),
1245
+ watchedPaths: z.array(z.string().min(1)).max(100).optional(),
1246
+ expiresAt: z.string().datetime().optional()
1247
+ }
1248
+ },
1249
+ async ({ fact_id, scope, watchedPaths, expiresAt }) => {
1250
+ try {
1251
+ const source = await getFact(fact_id);
1252
+ if (!source) return textResult({ error: "fact_not_found", fact_id });
1253
+ if (await isFactRevoked(fact_id)) return textResult({ error: "fact_already_revoked", fact_id });
1254
+ const task = await getTaskForWorkItem(source.work_item_id);
1255
+ if (!task) return textResult({ error: "fact_task_not_found", fact_id });
1256
+ const event = await appendTaskEvent(task.id, { type: "supervisor.fact_promoted", source_fact_id: fact_id, scope, watched_paths: watchedPaths ?? source.watched_paths ?? [], expires_at: expiresAt ?? null }, {
1257
+ runId: runIdFor(task.id, task.run_count ?? 1), actor: "main_thread"
1258
+ });
1259
+ const fact = await promoteCandidateFact({
1260
+ factId: fact_id,
1261
+ scopeType: scope,
1262
+ watchedPaths,
1263
+ expiresAt: expiresAt ?? null,
1264
+ sourceEventId: event.id,
1265
+ verifiedBy: "main_thread"
1266
+ });
1267
+ return textResult({ fact, source_fact_id: fact_id });
1268
+ } catch (error) {
1269
+ return errorResult(error);
1270
+ }
1271
+ }
1272
+ );
1273
+
1274
+ server.registerTool(
1275
+ "revoke_worker_fact",
1276
+ {
1277
+ title: "Revoke a candidate or verified worker fact",
1278
+ description: "Explicitly revoke one candidate or verified fact after audit. Revoked facts are excluded from search and worker capsules; the revocation is appended to the worker event log.",
1279
+ inputSchema: { fact_id: z.string().uuid(), reason: z.string().min(1).max(2000) }
1280
+ },
1281
+ async ({ fact_id, reason }) => {
1282
+ try {
1283
+ const source = await getFact(fact_id);
1284
+ if (!source) return textResult({ error: "fact_not_found", fact_id });
1285
+ const task = await getTaskForWorkItem(source.work_item_id);
1286
+ if (!task) return textResult({ error: "fact_task_not_found", fact_id });
1287
+ const revoked = await revokeFact(fact_id);
1288
+ await appendTaskEvent(task.id, { type: "supervisor.fact_revoked", fact_id, reason }, {
1289
+ runId: runIdFor(task.id, task.run_count ?? 1), actor: "main_thread"
1290
+ });
1291
+ return textResult({ fact: revoked, reason });
1292
+ } catch (error) {
1293
+ return errorResult(error);
1294
+ }
1295
+ }
1296
+ );
1297
+
1298
+ server.registerTool(
1299
+ "get_worker_evidence",
1300
+ {
1301
+ title: "Get a worker evidence index",
1302
+ description: "Return bounded event metadata and retained artifact IDs for one worker. It does not return raw history, prompts or a worker context capsule; use get_artifact or get_codex_worker_events for a selected item.",
1303
+ inputSchema: { task_id: z.string().min(1), limit: z.number().int().min(1).max(100).default(30) }
1304
+ },
1305
+ async ({ task_id, limit }) => {
1306
+ const task = await getTask(task_id);
1307
+ if (!task) return textResult({ error: "task_not_found", task_id });
1308
+ const events = await readTaskEventRecords(task_id, limit);
1309
+ const artifacts = await listArtifactsForTask(task_id, limit);
1310
+ return textResult({
1311
+ task_id,
1312
+ events: events.map((event) => ({ id: event.id, run_id: event.run_id, type: event.event_type, actor: event.actor, payload_sha256: event.payload_sha256, created_at: event.created_at })),
1313
+ artifacts: artifacts.map((artifact) => ({ id: artifact.id, run_id: artifact.run_id, type: artifact.type, sha256: artifact.sha256, security_class: artifact.security_class, retention: artifact.retention, created_at: artifact.created_at }))
1314
+ });
1315
+ }
1316
+ );
1317
+
1318
+ function decodeFactCursor(cursor, taskId, query) {
1319
+ if (!cursor) return 0;
1320
+ try {
1321
+ const payload = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
1322
+ if (payload.task_id !== taskId || payload.query !== query || !Number.isInteger(payload.offset) || payload.offset < 0) throw new Error("mismatch");
1323
+ return payload.offset;
1324
+ } catch {
1325
+ const error = new Error("fact cursor does not match this task and query");
1326
+ error.code = "invalid_fact_cursor";
1327
+ throw error;
1328
+ }
1329
+ }
1330
+
1331
+ function encodeFactCursor(taskId, query, offset) {
1332
+ return Buffer.from(JSON.stringify({ task_id: taskId, query, offset })).toString("base64url");
1333
+ }
1334
+
1335
+ function factFreshForTask(task, fact) {
1336
+ if (!fact.valid_for_sha || !task.base_commit) return true;
1337
+ try {
1338
+ git(task.project_root, ["merge-base", "--is-ancestor", fact.valid_for_sha, task.base_commit]);
1339
+ return true;
1340
+ } catch {
1341
+ return false;
1342
+ }
1343
+ }
1344
+
1345
+ server.registerTool(
1346
+ "search_worker_facts",
1347
+ {
1348
+ title: "Search verified worker facts in scope",
1349
+ description: "Search only verified facts relevant to one task: its own work, explicit dependencies and path-matched repository facts. Returns compact summaries, coverage and a cursor; never raw events, reports, prompts or worker capsules.",
1350
+ inputSchema: {
1351
+ task_id: z.string().min(1),
1352
+ query: z.string().max(500).default(""),
1353
+ limit: z.number().int().min(1).max(50).default(20),
1354
+ cursor: z.string().min(1).optional()
1355
+ }
1356
+ },
1357
+ async ({ task_id, query, limit, cursor }) => {
1358
+ const task = await getTask(task_id);
1359
+ if (!task) return textResult({ error: "task_not_found", task_id });
1360
+ try {
1361
+ const normalizedQuery = query.trim().toLocaleLowerCase();
1362
+ const offset = decodeFactCursor(cursor, task_id, normalizedQuery);
1363
+ const scoped = (await listContextFacts({
1364
+ taskId: task_id,
1365
+ baseSha: task.base_commit ?? null,
1366
+ ownedPaths: task.owned_paths ?? [],
1367
+ dependencyTaskIds: task.depends_on ?? []
1368
+ })).filter((fact) => factFreshForTask(task, fact));
1369
+ const matching = scoped.filter((fact) => !normalizedQuery || `${fact.key}\n${JSON.stringify(fact.value)}`.toLocaleLowerCase().includes(normalizedQuery));
1370
+ const page = matching.slice(offset, offset + limit);
1371
+ const nextOffset = offset + page.length;
1372
+ const totalVerified = await countVerifiedFacts();
1373
+ return textResult({
1374
+ task_id,
1375
+ facts: page.map((fact) => ({
1376
+ id: fact.id,
1377
+ key: fact.key,
1378
+ summary: clip(typeof fact.value === "string" ? fact.value : JSON.stringify(fact.value), 360),
1379
+ state: fact.state,
1380
+ scope: fact.scope_type,
1381
+ valid_for_sha: fact.valid_for_sha ?? null,
1382
+ freshness: "current",
1383
+ source_refs: [
1384
+ ...(fact.source_event_id ? [`event:${fact.source_event_id}`] : []),
1385
+ ...(fact.source_artifact_id ? [`artifact:${fact.source_artifact_id}`] : [])
1386
+ ]
1387
+ })),
1388
+ coverage: {
1389
+ scope: "current_work+explicit_dependencies+path_matched_repo_facts",
1390
+ included_count: scoped.length,
1391
+ matched_count: matching.length,
1392
+ omitted: [
1393
+ { reason: "other_verified_scopes_excluded", count: Math.max(0, totalVerified - scoped.length) },
1394
+ { reason: "candidate_and_nonverified_facts_excluded", count: null }
1395
+ ]
1396
+ },
1397
+ next_cursor: nextOffset < matching.length ? encodeFactCursor(task_id, normalizedQuery, nextOffset) : null
1398
+ });
1399
+ } catch (error) {
1400
+ return errorResult(error);
1401
+ }
1402
+ }
1403
+ );
1404
+
1405
+ server.registerTool(
1406
+ "create_independent_verifier",
1407
+ {
1408
+ title: "Create an independent read-only verifier",
1409
+ description: "Create a fresh read-only verifier for one settled worker. It receives the target objective and current worktree path, never the target report or candidate facts, has no network and cannot dispatch workers. The review relation is persisted for later finding and resolution.",
1410
+ inputSchema: { task_id: z.string().min(1), title: z.string().min(1).max(120).optional() }
1411
+ },
1412
+ async ({ task_id, title }) => {
1413
+ try {
1414
+ const subject = await getTask(task_id);
1415
+ if (!subject) return textResult({ error: "task_not_found", task_id });
1416
+ if (!isSettled(subject)) return textResult({ error: "review_subject_active", task_id, reason: "wait for the worker and any acceptance to settle before independent review" });
1417
+ const sourceRoot = subject.worktree_path ?? subject.project_root;
1418
+ const verifier = await createCodexWorker({
1419
+ title: title ?? `Independent review: ${subject.title ?? subject.id}`,
1420
+ task: [
1421
+ "Independently verify the target worker's objective from the current source tree and Git state.",
1422
+ `Target task ID: ${subject.id}`,
1423
+ `Target objective: ${subject.goal_objective ?? subject.title ?? "unspecified"}`,
1424
+ `Inspect root: ${sourceRoot}`,
1425
+ "Do not trust or request the target worker's report. Do not inspect candidate facts. Do not edit files, use network, create workers or call MCP tools.",
1426
+ "Return whether the stated objective is met, the exact evidence you inspected, and any unresolved gap."
1427
+ ].join("\n"),
1428
+ cwd: sourceRoot,
1429
+ workspaceKind: "read_only_in_place",
1430
+ sandbox: "read-only",
1431
+ ownedPaths: [],
1432
+ networkAccess: false,
1433
+ goal: { objective: `Independently verify worker ${subject.id} without relying on its self-report` }
1434
+ });
1435
+ const fingerprint = createHash("sha256").update(JSON.stringify({
1436
+ task_id: subject.id,
1437
+ run: subject.run_count ?? 0,
1438
+ base_sha: subject.base_commit ?? null,
1439
+ worktree: sourceRoot,
1440
+ updated_at: subject.updated_at ?? null,
1441
+ changed_files: subject.changed_files ?? []
1442
+ })).digest("hex");
1443
+ const review = await createReviewAssignment({
1444
+ subjectTaskId: subject.id,
1445
+ verifierTaskId: verifier.id,
1446
+ subjectRunId: runIdFor(subject.id, subject.run_count ?? 1),
1447
+ subjectBaseSha: subject.base_commit ?? null,
1448
+ subjectFingerprint: fingerprint
1449
+ });
1450
+ return textResult({ ...receipt(verifier), review });
1451
+ } catch (error) {
1452
+ return errorResult(error);
1453
+ }
1454
+ }
1455
+ );
1456
+
1457
+ server.registerTool(
1458
+ "record_independent_finding",
1459
+ {
1460
+ title: "Record an independent verifier finding",
1461
+ description: "After a verifier settles, record its passes/fails/inconclusive verdict with a concise reason. The supervisor stores a retained finding artifact and appends an event to the reviewed worker; this does not change the reviewed worker's delivery state automatically.",
1462
+ inputSchema: { verifier_task_id: z.string().min(1), verdict: z.enum(["passes", "fails", "inconclusive"]), reason: z.string().min(1).max(4000) }
1463
+ },
1464
+ async ({ verifier_task_id, verdict, reason }) => {
1465
+ try {
1466
+ const review = await getReviewByVerifierTask(verifier_task_id);
1467
+ if (!review) return textResult({ error: "review_not_found", verifier_task_id });
1468
+ if (review.status !== "pending") return textResult({ error: "review_not_pending", verifier_task_id, status: review.status });
1469
+ const verifier = await getTask(verifier_task_id);
1470
+ if (!verifier || !isSettled(verifier)) return textResult({ error: "verifier_not_settled", verifier_task_id });
1471
+ const subject = await getTask(review.subject_task_id);
1472
+ if (!subject) return textResult({ error: "review_subject_not_found", task_id: review.subject_task_id });
1473
+ const artifact = await recordJsonArtifact({
1474
+ runId: runIdFor(verifier.id, verifier.run_count ?? 1),
1475
+ type: "independent_review_finding",
1476
+ value: { review_id: review.id, subject_task_id: subject.id, verifier_task_id, verdict, reason, verifier_run: verifier.run_count ?? 1, recorded_at: new Date().toISOString() },
1477
+ securityClass: "internal"
1478
+ });
1479
+ const event = await appendTaskEvent(subject.id, { type: "supervisor.independent_finding", review_id: review.id, verifier_task_id, verdict, reason, artifact_id: artifact.id }, {
1480
+ runId: review.subject_run_id ?? runIdFor(subject.id, subject.run_count ?? 1), actor: "main_thread"
1481
+ });
1482
+ const recorded = await recordReviewFinding({ verifierTaskId: verifier_task_id, verdict, reason, evidenceArtifactId: artifact.id, findingEventId: event.id });
1483
+ return textResult({ review: recorded, artifact_id: artifact.id });
1484
+ } catch (error) {
1485
+ return errorResult(error);
1486
+ }
1487
+ }
1488
+ );
1489
+
1490
+ server.registerTool(
1491
+ "resolve_independent_finding",
1492
+ {
1493
+ title: "Resolve an independent verifier finding",
1494
+ description: "Record how a previously recorded independent finding was resolved. This is an audit transition only; it does not hide the finding or alter worker code.",
1495
+ inputSchema: { verifier_task_id: z.string().min(1), resolution: z.string().min(1).max(4000) }
1496
+ },
1497
+ async ({ verifier_task_id, resolution }) => {
1498
+ try {
1499
+ const review = await resolveReviewFinding({ verifierTaskId: verifier_task_id, resolution });
1500
+ if (!review) return textResult({ error: "review_not_recorded", verifier_task_id });
1501
+ const subject = await getTask(review.subject_task_id);
1502
+ if (subject) await appendTaskEvent(subject.id, { type: "supervisor.independent_finding_resolved", review_id: review.id, verifier_task_id, resolution }, {
1503
+ runId: review.subject_run_id ?? runIdFor(subject.id, subject.run_count ?? 1), actor: "main_thread"
1504
+ });
1505
+ return textResult({ review });
1506
+ } catch (error) {
1507
+ return errorResult(error);
1508
+ }
1509
+ }
1510
+ );
1511
+
1512
+ server.registerTool(
1513
+ "get_independent_review",
1514
+ {
1515
+ title: "Get one independent review relation",
1516
+ description: "Read the persisted subject/verifier/finding/resolution relation for a verifier task. Use get_artifact for the retained finding evidence.",
1517
+ inputSchema: { verifier_task_id: z.string().min(1) }
1518
+ },
1519
+ async ({ verifier_task_id }) => {
1520
+ const review = await getReviewByVerifierTask(verifier_task_id);
1521
+ return textResult(review ? { review } : { error: "review_not_found", verifier_task_id });
1188
1522
  }
1189
1523
  );
1190
1524
 
@@ -1279,6 +1613,7 @@ server.registerTool(
1279
1613
  exit_code: task.exit_code ?? null,
1280
1614
  thread_id: task.thread_id,
1281
1615
  session_id: task.session_id ?? null,
1616
+ workspace_kind: task.workspace_kind ?? "legacy",
1282
1617
  worktree_path: task.worktree_path,
1283
1618
  goal_status: task.goal_status,
1284
1619
  attention_reason: task.attention_reason ?? null,
@@ -1399,6 +1734,9 @@ server.registerTool(
1399
1734
  async ({ task_id, onto, commitMessage, ignoreAcceptance, allowOutsideOwned }) => {
1400
1735
  const task = await getTask(task_id);
1401
1736
  if (!task) return textResult({ error: "task_not_found", task_id });
1737
+ if (task.workspace_kind && task.workspace_kind !== "legacy" && task.workspace_kind !== "git_worktree") {
1738
+ return textResult({ error: "workspace_kind_not_landable", task_id, workspace_kind: task.workspace_kind, reason: `${task.workspace_kind} does not create a Git worktree and cannot be landed` });
1739
+ }
1402
1740
  const session = task.session_id ? await getSession(task.session_id) : null;
1403
1741
  if (task.attention_reason === "invalid_report") return textResult({ error: "invalid_report", task_id, reason: task.error });
1404
1742
  if (!isSettled(task)) return textResult({ error: "worker_active", task_id, reason: "wait for this run and acceptance to settle before landing" });
@@ -1430,7 +1768,20 @@ server.registerTool(
1430
1768
  state: "verified",
1431
1769
  sourceEventId: event.id,
1432
1770
  validForSha: outcome.head,
1433
- watchedPaths: task.owned_paths ?? []
1771
+ watchedPaths: task.owned_paths ?? [],
1772
+ verifiedBy: "supervisor.git_land"
1773
+ });
1774
+ await recordFact({
1775
+ workItemId: workItem.id,
1776
+ scopeType: "dependency",
1777
+ scopeId: workItem.id,
1778
+ key: "landed_delivery_summary",
1779
+ value: { task_id, landed_head: outcome.head, branch: outcome.onto ?? null, acceptance: task.acceptance_results?.passed === true ? "passed" : "not_configured_or_not_passed" },
1780
+ state: "verified",
1781
+ sourceEventId: event.id,
1782
+ validForSha: outcome.head,
1783
+ watchedPaths: task.owned_paths ?? [],
1784
+ verifiedBy: "supervisor.git_land"
1434
1785
  });
1435
1786
  }
1436
1787
  }
@@ -1474,7 +1825,7 @@ server.registerTool(
1474
1825
  });
1475
1826
  }
1476
1827
  const now = new Date().toISOString();
1477
- const verified = { ...task, push_verified_at: now, push_remote: remote, push_branch: targetBranch, updated_at: now };
1828
+ const verified = { ...task, push_verified_at: now, push_remote: remote, push_branch: targetBranch, push_remote_head: remoteHead, updated_at: now };
1478
1829
  await upsertTask(verified);
1479
1830
  await updateWorkItemDelivery(task_id, "push_verified");
1480
1831
  const event = await appendTaskEvent(task_id, {
@@ -1485,6 +1836,12 @@ server.registerTool(
1485
1836
  remote_head: remoteHead,
1486
1837
  verified_at: now
1487
1838
  }, { runId: runIdFor(task_id, task.run_count ?? 1), actor: "supervisor" });
1839
+ const artifact = await recordJsonArtifact({
1840
+ runId: runIdFor(task_id, task.run_count ?? 1),
1841
+ type: "push_proof",
1842
+ value: { remote, branch: targetBranch, landed_head: task.landed_head, remote_head: remoteHead, verified_at: now, event_id: event.id },
1843
+ securityClass: "internal"
1844
+ });
1488
1845
  const workItem = await getWorkItemForTask(task_id);
1489
1846
  if (workItem) {
1490
1847
  await recordFact({
@@ -1495,8 +1852,23 @@ server.registerTool(
1495
1852
  value: { remote, branch: targetBranch, landed_head: task.landed_head, remote_head: remoteHead },
1496
1853
  state: "verified",
1497
1854
  sourceEventId: event.id,
1855
+ sourceArtifactId: artifact.id,
1856
+ validForSha: task.landed_head,
1857
+ watchedPaths: task.owned_paths ?? [],
1858
+ verifiedBy: "supervisor.remote_readback"
1859
+ });
1860
+ await recordFact({
1861
+ workItemId: workItem.id,
1862
+ scopeType: "dependency",
1863
+ scopeId: workItem.id,
1864
+ key: "push_delivery_summary",
1865
+ value: { task_id, landed_head: task.landed_head, remote, branch: targetBranch, remote_head: remoteHead },
1866
+ state: "verified",
1867
+ sourceEventId: event.id,
1868
+ sourceArtifactId: artifact.id,
1498
1869
  validForSha: task.landed_head,
1499
- watchedPaths: task.owned_paths ?? []
1870
+ watchedPaths: task.owned_paths ?? [],
1871
+ verifiedBy: "supervisor.remote_readback"
1500
1872
  });
1501
1873
  }
1502
1874
  const cleanupPlan = await createCleanupPlan({ taskIds: [task_id] });
@@ -1507,6 +1879,7 @@ server.registerTool(
1507
1879
  branch: targetBranch,
1508
1880
  landed_head: task.landed_head,
1509
1881
  remote_head: remoteHead,
1882
+ artifact_id: artifact.id,
1510
1883
  push_verified_at: now,
1511
1884
  cleanup_plan: { id: cleanupPlan.id, summary: cleanupPlan.summary, expires_at: cleanupPlan.expires_at, next_step: "Review SAFE items, then call apply_cleanup with their item IDs; cleanup is never automatic." }
1512
1885
  });
@@ -1558,34 +1931,7 @@ server.registerTool(
1558
1931
  const plan = await getCleanupPlan(plan_id);
1559
1932
  if (!plan) return textResult({ error: "cleanup_plan_not_found", plan_id });
1560
1933
  if (Date.parse(plan.expires_at) <= Date.now()) return textResult({ error: "cleanup_plan_expired", plan_id, expires_at: plan.expires_at });
1561
- const selected = plan.items.filter((item) => item_ids.includes(item.id));
1562
- if (selected.length !== item_ids.length) return textResult({ error: "cleanup_plan_item_not_found", plan_id });
1563
- const applied = [];
1564
- const skipped = [];
1565
- for (const item of selected) {
1566
- if (item.verdict !== "safe") {
1567
- skipped.push({ item_id: item.id, task_id: item.task_id, reason: "only SAFE plan items may be applied" });
1568
- continue;
1569
- }
1570
- const task = await getTask(item.task_id);
1571
- if (!task) {
1572
- skipped.push({ item_id: item.id, task_id: item.task_id, reason: "task no longer exists" });
1573
- continue;
1574
- }
1575
- try {
1576
- await removePlannedWorktree(task, item.fingerprint);
1577
- const now = await markCleanupPlanItemApplied(item.id);
1578
- await updateWorkItemDelivery(task.id, "cleanup_removed");
1579
- await appendTaskEvent(task.id, { type: "supervisor.cleanup_removed", plan_id, item_id: item.id, removed_at: now, retained: ["branch", "task", "events", "jsonl", "artifacts"] }, {
1580
- runId: runIdFor(task.id, task.run_count ?? 1),
1581
- actor: "supervisor"
1582
- });
1583
- applied.push({ item_id: item.id, task_id: task.id, worktree_path: task.worktree_path, removed_at: now });
1584
- } catch (error) {
1585
- skipped.push({ item_id: item.id, task_id: item.task_id, reason: error.message.split("\n")[0] });
1586
- }
1587
- }
1588
- return textResult({ plan_id, applied, skipped, retained: ["branch", "task", "events", "jsonl", "artifacts"] });
1934
+ return textResult(await applyCleanupPlan({ plan, itemIds: item_ids, actor: "main_thread" }));
1589
1935
  }
1590
1936
  );
1591
1937