codex-supervisor-mcp 0.9.7 → 0.10.2
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/README.md +24 -5
- package/package.json +6 -1
- package/skills/codex-supervisor/SKILL.md +24 -11
- package/src/acceptance.js +14 -1
- package/src/cleanup-hint.js +3 -3
- package/src/cleanup-plan.js +98 -0
- package/src/cleanup.js +38 -150
- package/src/codex-runner.js +209 -16
- package/src/context-compiler.js +86 -0
- package/src/handoff.js +2 -3
- package/src/mcp-config.js +35 -0
- package/src/mcp-server.js +341 -2
- package/src/overview-delta.js +34 -0
- package/src/side-chat.js +2 -22
- package/src/task-store.js +419 -10
- package/src/worker-preflight.js +111 -0
package/src/codex-runner.js
CHANGED
|
@@ -10,11 +10,15 @@ import {
|
|
|
10
10
|
getSession,
|
|
11
11
|
readActiveTasks,
|
|
12
12
|
readTasks,
|
|
13
|
-
readTasksBySession,
|
|
14
13
|
readTaskEvents,
|
|
15
14
|
taskRunPath,
|
|
16
15
|
upsertSession,
|
|
17
16
|
upsertTask,
|
|
17
|
+
ensureRunRecord,
|
|
18
|
+
completeRunRecord,
|
|
19
|
+
getWorkItemForTask,
|
|
20
|
+
recordFact,
|
|
21
|
+
updateWorkItemDelivery,
|
|
18
22
|
claimTaskRun,
|
|
19
23
|
releaseTaskRun,
|
|
20
24
|
reserveTaskOwnership
|
|
@@ -26,13 +30,16 @@ import { buildGuardPreamble, frameWorkerPrompt } from "./prompt.js";
|
|
|
26
30
|
import { cacheRoots, resolveWritableRoot } from "./sandbox-roots.js";
|
|
27
31
|
import { readTaskChanges, snapshotTaskOutput } from "./worktree.js";
|
|
28
32
|
import { rebaseWorktree } from "./landing.js";
|
|
29
|
-
import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, normalizeAcceptance, runAcceptance } from "./acceptance.js";
|
|
33
|
+
import { DEFAULT_ACCEPTANCE_TIMEOUT_MS, isArtifactOnlyAcceptance, normalizeAcceptance, runAcceptance } from "./acceptance.js";
|
|
30
34
|
import { appendFile } from "node:fs/promises";
|
|
31
35
|
import { defaultBinDirs, findBinaryPath, resolveCommand, shimMessage } from "./bin-resolver.js";
|
|
32
36
|
import { findOutsideOwnedChanges } from "./owned-changes.js";
|
|
33
37
|
import { parseWorkerReport, workerReportSchemaPath } from "./worker-report.js";
|
|
34
38
|
import { buildHandoff } from "./handoff.js";
|
|
39
|
+
import { compileWorkerContext } from "./context-compiler.js";
|
|
35
40
|
import { captureExternalOutputs, compareExternalOutputs } from "./external-output.js";
|
|
41
|
+
import { buildRuntimeContract, createPreflightMetadata, readPreflightResult, runtimeContractHash } from "./worker-preflight.js";
|
|
42
|
+
import { supervisorMcpDisableArgs } from "./mcp-config.js";
|
|
36
43
|
|
|
37
44
|
const processes = new Map();
|
|
38
45
|
// taskId -> control object of an acceptance run in progress ({ kill, cancelled }).
|
|
@@ -41,6 +48,38 @@ const cancelledTasks = new Set();
|
|
|
41
48
|
const CODEX_NPM_ENTRY = { pkg: "@openai/codex", bin: "bin/codex.js" };
|
|
42
49
|
const defaultGitBin = process.env.GIT_BIN?.trim() || "git";
|
|
43
50
|
const allowedReasoningEfforts = new Set(["minimal", "low", "medium", "high"]);
|
|
51
|
+
const MAX_RUN_HOST_PROMPT_BYTES = 4 * 1024 * 1024;
|
|
52
|
+
|
|
53
|
+
async function recordOutcomeFacts({ task, runId, report, reportEventId = null, acceptanceEventId = null, acceptancePassed = false }) {
|
|
54
|
+
if (!report?.valid) return;
|
|
55
|
+
const workItem = await getWorkItemForTask(task.id);
|
|
56
|
+
if (!workItem) return;
|
|
57
|
+
const candidate = await recordFact({
|
|
58
|
+
workItemId: workItem.id,
|
|
59
|
+
scopeType: "run",
|
|
60
|
+
scopeId: runId,
|
|
61
|
+
key: "worker_outcome",
|
|
62
|
+
value: report.report,
|
|
63
|
+
state: "candidate",
|
|
64
|
+
sourceEventId: reportEventId,
|
|
65
|
+
validForSha: task.base_commit ?? null,
|
|
66
|
+
watchedPaths: task.owned_paths ?? []
|
|
67
|
+
});
|
|
68
|
+
if (!acceptancePassed) return;
|
|
69
|
+
await recordFact({
|
|
70
|
+
workItemId: workItem.id,
|
|
71
|
+
scopeType: "work_item",
|
|
72
|
+
scopeId: workItem.id,
|
|
73
|
+
key: "accepted_outcome",
|
|
74
|
+
value: report.report,
|
|
75
|
+
state: "verified",
|
|
76
|
+
sourceEventId: acceptanceEventId,
|
|
77
|
+
validForSha: task.base_commit ?? null,
|
|
78
|
+
watchedPaths: task.owned_paths ?? [],
|
|
79
|
+
supersedesId: candidate.id
|
|
80
|
+
});
|
|
81
|
+
await updateWorkItemDelivery(task.id, "verified");
|
|
82
|
+
}
|
|
44
83
|
|
|
45
84
|
function splitLines(buffer, chunk) {
|
|
46
85
|
const next = buffer + chunk;
|
|
@@ -248,6 +287,9 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
248
287
|
const hookCommand = `${quoteCommand(process.execPath)} ${quoteCommand(guard)}`;
|
|
249
288
|
const configArgs = ["--output-schema", workerReportSchemaPath, "--dangerously-bypass-hook-trust", "-c",
|
|
250
289
|
`hooks.PreToolUse=[{matcher="Bash|apply_patch",hooks=[{type="command",command=${JSON.stringify(hookCommand)}}]}]`];
|
|
290
|
+
// A worker may use its explicitly configured business MCP servers, but it
|
|
291
|
+
// must not inherit this supervisor and create a second orchestration tree.
|
|
292
|
+
configArgs.push(...supervisorMcpDisableArgs());
|
|
251
293
|
configArgs.push("-c", `sandbox_workspace_write.network_access=${record.guard_policy?.networkAccess === true}`);
|
|
252
294
|
const sandboxWritableRoots = [...new Set([...externalBefore.map((file) => dirname(file.path)), ...cacheRoots(), ...(record.guard_policy?.writableRoots ?? [])])];
|
|
253
295
|
if (sandboxWritableRoots.length) configArgs.push("-c", `sandbox_workspace_write.writable_roots=${JSON.stringify(sandboxWritableRoots)}`);
|
|
@@ -320,6 +362,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
320
362
|
return writeChain;
|
|
321
363
|
};
|
|
322
364
|
await persist(live);
|
|
365
|
+
const runId = await ensureRunRecord(live, live.run_count);
|
|
323
366
|
|
|
324
367
|
const logStream = createWriteStream(logPath, { flags: "a" });
|
|
325
368
|
logStream.on("error", () => {});
|
|
@@ -337,6 +380,7 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
337
380
|
let eventChain = Promise.resolve();
|
|
338
381
|
let terminalEvent = false;
|
|
339
382
|
let rawReport = null;
|
|
383
|
+
let rawReportEventId = null;
|
|
340
384
|
const handleLine = async (line) => {
|
|
341
385
|
let event;
|
|
342
386
|
try {
|
|
@@ -348,7 +392,8 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
348
392
|
logStream.write(`${JSON.stringify(event)}\n`);
|
|
349
393
|
if (event.type === "item.completed" && event.item?.type === "agent_message") rawReport = event.item.text;
|
|
350
394
|
if (["turn.completed", "turn.failed"].includes(event.type)) terminalEvent = true;
|
|
351
|
-
await appendTaskEvent(record.id, event);
|
|
395
|
+
const storedEvent = await appendTaskEvent(record.id, event, { runId, actor: "codex" });
|
|
396
|
+
if (event.type === "item.completed" && event.item?.type === "agent_message") rawReportEventId = storedEvent.id;
|
|
352
397
|
await persist(applyCodexEvent(live, event));
|
|
353
398
|
};
|
|
354
399
|
|
|
@@ -484,10 +529,10 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
484
529
|
}); } finally { clearInterval(cancellationWatch); }
|
|
485
530
|
acceptanceRuns.delete(record.id);
|
|
486
531
|
const event = { type: "supervisor.acceptance", ...results };
|
|
487
|
-
await appendTaskEvent(record.id, event).catch(() =>
|
|
532
|
+
const acceptanceEvent = await appendTaskEvent(record.id, event, { runId, actor: "supervisor" }).catch(() => null);
|
|
488
533
|
await appendFile(logPath, `${JSON.stringify(event)}\n`).catch(() => {});
|
|
489
534
|
const failing = results.checks.find((check) => check.passed === false || check.exit_code !== 0 || check.timed_out);
|
|
490
|
-
|
|
535
|
+
const finalRecord = {
|
|
491
536
|
...next,
|
|
492
537
|
acceptance_results: results,
|
|
493
538
|
current_action: results.status === "passed"
|
|
@@ -496,9 +541,27 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
496
541
|
? `Acceptance failed: ${failing ? `${failing.command.slice(0, 80)} exit ${failing.error ?? (failing.baseline?.passed === false ? "baseline/evidence mismatch" : failing.timed_out ? "timeout" : failing.exit_code ?? "?")}` : results.error ?? "see acceptance_results"}`
|
|
497
542
|
: next.current_action,
|
|
498
543
|
updated_at: new Date().toISOString()
|
|
544
|
+
};
|
|
545
|
+
await persist(finalRecord);
|
|
546
|
+
await completeRunRecord(finalRecord, live.run_count);
|
|
547
|
+
await recordOutcomeFacts({
|
|
548
|
+
task: finalRecord,
|
|
549
|
+
runId,
|
|
550
|
+
report: finalRecord.run_evidence?.structured_report,
|
|
551
|
+
reportEventId: rawReportEventId,
|
|
552
|
+
acceptanceEventId: acceptanceEvent?.id ?? null,
|
|
553
|
+
acceptancePassed: results.passed === true
|
|
499
554
|
});
|
|
500
555
|
} else {
|
|
501
|
-
|
|
556
|
+
const finalRecord = acceptance ? { ...next, acceptance_results: null } : next;
|
|
557
|
+
await persist(finalRecord);
|
|
558
|
+
await completeRunRecord(finalRecord, live.run_count);
|
|
559
|
+
await recordOutcomeFacts({
|
|
560
|
+
task: finalRecord,
|
|
561
|
+
runId,
|
|
562
|
+
report: finalRecord.run_evidence?.structured_report,
|
|
563
|
+
reportEventId: rawReportEventId
|
|
564
|
+
});
|
|
502
565
|
}
|
|
503
566
|
cancelledTasks.delete(record.id);
|
|
504
567
|
});
|
|
@@ -520,13 +583,24 @@ async function trackRunInHost({ record, args, prompt, logPath, spawnOptions = {}
|
|
|
520
583
|
// streams, exit write and acceptance until all three settle; IPC is only a
|
|
521
584
|
// startup handshake and never the channel carrying worker results.
|
|
522
585
|
async function startTrackedRun(job) {
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
job.
|
|
586
|
+
if (Buffer.byteLength(String(job.prompt ?? ""), "utf8") > MAX_RUN_HOST_PROMPT_BYTES) {
|
|
587
|
+
const result = failedStart(job.record, `worker prompt is too large for the detached run host IPC channel (maximum ${MAX_RUN_HOST_PROMPT_BYTES} bytes); reduce task text and move materials to context files`);
|
|
588
|
+
await upsertTask(result.record);
|
|
589
|
+
return result;
|
|
590
|
+
}
|
|
591
|
+
const compiled = await compileWorkerContext(job.record, { attempt: (job.record.run_count ?? 0) + 1 });
|
|
592
|
+
job.record = {
|
|
593
|
+
...job.record,
|
|
594
|
+
input_context: {
|
|
595
|
+
...job.record.input_context,
|
|
596
|
+
context: compiled.sourceRefs,
|
|
597
|
+
source_refs: compiled.sourceRefs,
|
|
598
|
+
context_snapshot_id: compiled.snapshot.id,
|
|
599
|
+
context_snapshot_tokens: compiled.snapshot.estimated_tokens,
|
|
600
|
+
context_fact_count: compiled.factCount
|
|
601
|
+
}
|
|
602
|
+
};
|
|
603
|
+
job.prompt = `${compiled.text}\n\n${job.prompt}\n\nRequired input refs (read-only): ${JSON.stringify(compiled.sourceRefs)}\nRequired contracts: ${JSON.stringify(job.record.input_context.contracts ?? [])}`;
|
|
530
604
|
const host = spawn(process.execPath, [fileURLToPath(import.meta.url), "--run-host"], {
|
|
531
605
|
detached: true, stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
532
606
|
env: process.env, windowsHide: true
|
|
@@ -575,6 +649,69 @@ function validateGoal(goal) {
|
|
|
575
649
|
return { objective: goal.objective, tokenBudget };
|
|
576
650
|
}
|
|
577
651
|
|
|
652
|
+
function dependencyError(code, message, details = {}) {
|
|
653
|
+
const error = new Error(message);
|
|
654
|
+
error.code = code;
|
|
655
|
+
error.details = details;
|
|
656
|
+
return error;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
function containsCommit(cwd, ancestor, descendant) {
|
|
660
|
+
try {
|
|
661
|
+
execFileSync(defaultGitBin, ["-C", cwd, "merge-base", "--is-ancestor", ancestor, descendant], {
|
|
662
|
+
stdio: "ignore",
|
|
663
|
+
timeout: 15000
|
|
664
|
+
});
|
|
665
|
+
return true;
|
|
666
|
+
} catch {
|
|
667
|
+
return false;
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
async function validateDependencies(dependsOn, projectRoot, baseCommit) {
|
|
672
|
+
const dependencyIds = [...new Set(dependsOn ?? [])];
|
|
673
|
+
for (const dependencyId of dependencyIds) {
|
|
674
|
+
const dependency = await getTask(dependencyId);
|
|
675
|
+
if (!dependency) {
|
|
676
|
+
throw dependencyError("dependency_not_found", `dependency ${dependencyId} does not exist`, { dependency_id: dependencyId });
|
|
677
|
+
}
|
|
678
|
+
if (resolve(dependency.project_root) !== resolve(projectRoot)) {
|
|
679
|
+
throw dependencyError("dependency_project_mismatch", `dependency ${dependencyId} belongs to a different project root`, {
|
|
680
|
+
dependency_id: dependencyId,
|
|
681
|
+
dependency_project_root: dependency.project_root,
|
|
682
|
+
project_root: projectRoot
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
if (dependency.status !== "completed" || dependency.exit_code !== 0 || dependency.attention_reason) {
|
|
686
|
+
throw dependencyError("dependency_not_ready", `dependency ${dependencyId} is not successfully settled`, {
|
|
687
|
+
dependency_id: dependencyId,
|
|
688
|
+
status: dependency.status,
|
|
689
|
+
exit_code: dependency.exit_code ?? null,
|
|
690
|
+
attention_reason: dependency.attention_reason ?? null
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
if (Array.isArray(dependency.acceptance) && dependency.acceptance.length > 0 && dependency.acceptance_results?.passed !== true) {
|
|
694
|
+
throw dependencyError("dependency_not_ready", `dependency ${dependencyId} has not passed acceptance`, {
|
|
695
|
+
dependency_id: dependencyId,
|
|
696
|
+
acceptance: dependency.acceptance_results?.status ?? null
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
if (!dependency.landed_at || !dependency.landed_head) {
|
|
700
|
+
throw dependencyError("dependency_not_landed", `dependency ${dependencyId} must be landed before a dependent worker starts`, {
|
|
701
|
+
dependency_id: dependencyId,
|
|
702
|
+
landed_at: dependency.landed_at ?? null
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
if (!baseCommit || !containsCommit(projectRoot, dependency.landed_head, baseCommit)) {
|
|
706
|
+
throw dependencyError("dependency_base_mismatch", `worker base does not contain landed dependency ${dependencyId}; use the integrated branch or a newer baseRef`, {
|
|
707
|
+
dependency_id: dependencyId,
|
|
708
|
+
dependency_head: dependency.landed_head,
|
|
709
|
+
base_commit: baseCommit ?? null
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
|
|
578
715
|
export async function createCodexWorker({
|
|
579
716
|
title,
|
|
580
717
|
task,
|
|
@@ -592,6 +729,8 @@ export async function createCodexWorker({
|
|
|
592
729
|
followupOf = null,
|
|
593
730
|
useWorktree = true,
|
|
594
731
|
baseRef = null,
|
|
732
|
+
preflightId = null,
|
|
733
|
+
preflight = null,
|
|
595
734
|
acceptance = null,
|
|
596
735
|
acceptanceTimeoutMs = null,
|
|
597
736
|
forbid = [],
|
|
@@ -613,6 +752,9 @@ export async function createCodexWorker({
|
|
|
613
752
|
if (!Array.isArray(ownedPaths)) {
|
|
614
753
|
throw new Error("ownedPaths is required; pass an empty list only for a worker that must never land a change (a read-only verifier, or a research worker that reads and reports)");
|
|
615
754
|
}
|
|
755
|
+
if (ownedPaths.length > 0 && acceptanceCommands?.length && acceptanceCommands.every(isArtifactOnlyAcceptance)) {
|
|
756
|
+
throw new Error("a write worker cannot use only file-existence acceptance; add a real test, endpoint probe or structured execution evidence");
|
|
757
|
+
}
|
|
616
758
|
const validatedGoal = validateGoal(goal);
|
|
617
759
|
await buildHandoff({ context, contracts });
|
|
618
760
|
await captureExternalOutputs(externalOutputs, { checkBaseline: true });
|
|
@@ -661,6 +803,33 @@ export async function createCodexWorker({
|
|
|
661
803
|
: { path: null, baseCommit: null };
|
|
662
804
|
const worktreePath = worktree.path;
|
|
663
805
|
const effectiveCwd = worktreePath ?? projectRoot;
|
|
806
|
+
if (preflight && (!Array.isArray(preflight.probeCommands) || preflight.probeCommands.length === 0
|
|
807
|
+
|| preflight.probeCommands.some((command) => typeof command !== "string" || !command.trim()))) {
|
|
808
|
+
throw new Error("preflight.probeCommands must be a nonempty list of shell commands");
|
|
809
|
+
}
|
|
810
|
+
const guardPolicy = {
|
|
811
|
+
forbid,
|
|
812
|
+
allowedCommands,
|
|
813
|
+
externalOutputs,
|
|
814
|
+
networkAccess,
|
|
815
|
+
writableRoots: [...new Set(resolvedWritableRoots)],
|
|
816
|
+
maxRunMs,
|
|
817
|
+
maxTotalMs
|
|
818
|
+
};
|
|
819
|
+
const runtimeContract = buildRuntimeContract({
|
|
820
|
+
projectRoot,
|
|
821
|
+
baseCommit: worktree.baseCommit,
|
|
822
|
+
sandbox,
|
|
823
|
+
ownedPaths: normalizedOwnedPaths,
|
|
824
|
+
allowedCommands,
|
|
825
|
+
networkAccess,
|
|
826
|
+
writableRoots: guardPolicy.writableRoots,
|
|
827
|
+
context,
|
|
828
|
+
contracts
|
|
829
|
+
});
|
|
830
|
+
const preflightMetadata = preflight
|
|
831
|
+
? createPreflightMetadata(runtimeContract, preflight.probeCommands)
|
|
832
|
+
: null;
|
|
664
833
|
|
|
665
834
|
const record = {
|
|
666
835
|
id,
|
|
@@ -679,7 +848,11 @@ export async function createCodexWorker({
|
|
|
679
848
|
session_id: sessionId ?? null,
|
|
680
849
|
thread_id: null,
|
|
681
850
|
owned_paths: normalizedOwnedPaths,
|
|
682
|
-
guard_policy: {
|
|
851
|
+
guard_policy: {
|
|
852
|
+
...guardPolicy,
|
|
853
|
+
...(preflightMetadata ? { preflight: preflightMetadata } : {}),
|
|
854
|
+
...(preflightId ? { preflight_source_id: preflightId } : {})
|
|
855
|
+
},
|
|
683
856
|
input_context: { context, contracts },
|
|
684
857
|
depends_on: Array.isArray(dependsOn) ? dependsOn : [],
|
|
685
858
|
goal_objective: validatedGoal.objective,
|
|
@@ -703,7 +876,27 @@ export async function createCodexWorker({
|
|
|
703
876
|
updated_at: new Date().toISOString(),
|
|
704
877
|
run_log: taskRunPath(id)
|
|
705
878
|
};
|
|
706
|
-
try {
|
|
879
|
+
try {
|
|
880
|
+
await validateDependencies(dependsOn, projectRoot, worktree.baseCommit);
|
|
881
|
+
if (preflightId) {
|
|
882
|
+
const preflightTask = await getTask(preflightId);
|
|
883
|
+
const preflightResult = readPreflightResult(preflightTask);
|
|
884
|
+
if (preflightResult.status !== "passed") {
|
|
885
|
+
const error = new Error(`preflight ${preflightId} is ${preflightResult.status}; wait for its probes to pass before dispatching this worker`);
|
|
886
|
+
error.code = "preflight_not_passed";
|
|
887
|
+
error.details = preflightResult;
|
|
888
|
+
throw error;
|
|
889
|
+
}
|
|
890
|
+
const contractHash = runtimeContractHash(runtimeContract);
|
|
891
|
+
if (preflightResult.contract_hash !== contractHash) {
|
|
892
|
+
const error = new Error(`preflight ${preflightId} does not match this worker's runtime contract; create a new preflight after changing baseRef, sandbox, ownedPaths, commands, context, contracts, network or writable roots`);
|
|
893
|
+
error.code = "preflight_mismatch";
|
|
894
|
+
error.details = { preflight_id: preflightId, expected_contract_hash: contractHash, actual_contract_hash: preflightResult.contract_hash };
|
|
895
|
+
throw error;
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
await reserveTaskOwnership(record);
|
|
899
|
+
}
|
|
707
900
|
catch (error) {
|
|
708
901
|
if (worktreePath) {
|
|
709
902
|
// This checkout belongs to this not-yet-started dispatch and contains
|
|
@@ -1085,7 +1278,7 @@ export async function createFollowupWorker({
|
|
|
1085
1278
|
maxRunMs: maxRunMs ?? parent.guard_policy?.maxRunMs ?? null,
|
|
1086
1279
|
maxTotalMs: maxTotalMs ?? parent.guard_policy?.maxTotalMs ?? null,
|
|
1087
1280
|
goal: goal ?? { objective: parent.goal_objective ?? `Follow-up for ${parent.id}`, tokenBudget: parent.goal_token_budget ?? undefined },
|
|
1088
|
-
dependsOn: [
|
|
1281
|
+
dependsOn: [],
|
|
1089
1282
|
followupOf: parent.id,
|
|
1090
1283
|
useWorktree: true,
|
|
1091
1284
|
baseRef: baseRef ?? null,
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { buildHandoff } from "./handoff.js";
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { approxTokenCount } from "./truncate.js";
|
|
4
|
+
import { createContextSnapshot, listContextFacts, runIdFor } from "./task-store.js";
|
|
5
|
+
|
|
6
|
+
const MAX_CONTEXT_TOKENS = 1500;
|
|
7
|
+
|
|
8
|
+
function factAppliesToBase(task, fact) {
|
|
9
|
+
if (!fact.valid_for_sha || fact.valid_for_sha === task.base_commit) return true;
|
|
10
|
+
try {
|
|
11
|
+
execFileSync(process.env.GIT_BIN?.trim() || "git", ["-C", task.project_root, "merge-base", "--is-ancestor", fact.valid_for_sha, task.base_commit], {
|
|
12
|
+
stdio: "ignore",
|
|
13
|
+
timeout: 15000
|
|
14
|
+
});
|
|
15
|
+
return true;
|
|
16
|
+
} catch {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function clip(value, max = 360) {
|
|
22
|
+
const text = typeof value === "string" ? value : JSON.stringify(value);
|
|
23
|
+
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function addWithinBudget(lines, line) {
|
|
27
|
+
const next = [...lines, line].join("\n");
|
|
28
|
+
return approxTokenCount(next) <= MAX_CONTEXT_TOKENS ? next.split("\n") : lines;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Produces the only shared context a regular worker receives. It deliberately
|
|
32
|
+
// has no session peer lookup: session_id groups a batch and policy, not memory.
|
|
33
|
+
export async function compileWorkerContext(task, { attempt }) {
|
|
34
|
+
const handoff = await buildHandoff({
|
|
35
|
+
goal: task.goal_objective,
|
|
36
|
+
todo: task.title,
|
|
37
|
+
contracts: task.input_context?.contracts ?? [],
|
|
38
|
+
context: task.input_context?.context ?? []
|
|
39
|
+
}, { maxLines: 12, maxChars: 1200 });
|
|
40
|
+
const facts = (await listContextFacts({
|
|
41
|
+
taskId: task.id,
|
|
42
|
+
baseSha: task.base_commit ?? null,
|
|
43
|
+
ownedPaths: task.owned_paths ?? [],
|
|
44
|
+
dependencyTaskIds: task.depends_on ?? []
|
|
45
|
+
})).filter((fact) => factAppliesToBase(task, fact));
|
|
46
|
+
let lines = [
|
|
47
|
+
"Worker context capsule. This is scoped execution context, not a transcript and not authorization to expand work.",
|
|
48
|
+
"L0 identity:",
|
|
49
|
+
`- task_id: ${task.id}`,
|
|
50
|
+
`- run_id: ${runIdFor(task.id, attempt)}`,
|
|
51
|
+
`- project_root: ${task.project_root}`,
|
|
52
|
+
`- base_sha: ${task.base_commit ?? "unknown"}`,
|
|
53
|
+
`- worktree: ${task.worktree_path ?? task.cwd}`,
|
|
54
|
+
`- owned_paths: ${JSON.stringify(task.owned_paths ?? [])}`,
|
|
55
|
+
"L1 task:",
|
|
56
|
+
`- objective: ${task.goal_objective ?? task.title ?? "unspecified"}`
|
|
57
|
+
];
|
|
58
|
+
if (handoff.text) lines = addWithinBudget(lines, handoff.text);
|
|
59
|
+
const usedFacts = [];
|
|
60
|
+
if (facts.length > 0) lines = addWithinBudget(lines, "Verified facts:");
|
|
61
|
+
for (const fact of facts) {
|
|
62
|
+
const scope = fact.scope_type === "dependency" ? "dependency" : fact.scope_type;
|
|
63
|
+
const candidate = `- [${scope}:${fact.key}] ${clip(fact.value)}`;
|
|
64
|
+
const next = addWithinBudget(lines, candidate);
|
|
65
|
+
if (next === lines) break;
|
|
66
|
+
lines = next;
|
|
67
|
+
usedFacts.push(fact.id);
|
|
68
|
+
}
|
|
69
|
+
lines = addWithinBudget(lines, "Evidence on demand only: raw events, full diff, historical reports and artifacts are excluded from this capsule.");
|
|
70
|
+
const text = lines.join("\n");
|
|
71
|
+
const snapshot = await createContextSnapshot({
|
|
72
|
+
runId: runIdFor(task.id, attempt),
|
|
73
|
+
factIds: usedFacts,
|
|
74
|
+
baseSha: task.base_commit ?? null,
|
|
75
|
+
prompt: text,
|
|
76
|
+
estimatedTokens: approxTokenCount(text),
|
|
77
|
+
excluded: {
|
|
78
|
+
session_peers: "never automatic",
|
|
79
|
+
raw_events: "on demand",
|
|
80
|
+
reports: "on demand",
|
|
81
|
+
artifacts: "on demand",
|
|
82
|
+
candidate_facts: "never automatic"
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
return { text, snapshot, sourceRefs: handoff.source_refs, factCount: usedFacts.length };
|
|
86
|
+
}
|
package/src/handoff.js
CHANGED
|
@@ -2,7 +2,7 @@ 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 async function buildHandoff({ goal, todo,
|
|
5
|
+
export async function buildHandoff({ goal, todo, contracts = [], context = [] }, { maxLines = 16, maxChars = 1800 } = {}) {
|
|
6
6
|
if (!Array.isArray(context) || context.length > 20 || !Array.isArray(contracts)
|
|
7
7
|
|| contracts.some((value) => typeof value !== "string") || JSON.stringify({ context, contracts }).length > 6000) throw new Error("context and contracts exceed the 6000 character input budget");
|
|
8
8
|
const refs = [];
|
|
@@ -17,8 +17,7 @@ export async function buildHandoff({ goal, todo, peers = [], contracts = [], con
|
|
|
17
17
|
const line = (value) => String(value ?? "").replace(/\s+/g, " ").trim();
|
|
18
18
|
const candidates = ["Handoff (source refs are inputs, not write permission):", `Goal: ${line(goal)}`, `Todo: ${line(todo)}`,
|
|
19
19
|
...refs.map((ref) => `Input: ${ref.path} sha256=${ref.sha256}`),
|
|
20
|
-
...contracts.map((value) => `Contract: ${line(value)}`)
|
|
21
|
-
...peers.map((peer) => `Peer: ${line(peer.title)} | ${line(peer.status)} | ${line(peer.last_message).slice(0, 160)}`)];
|
|
20
|
+
...contracts.map((value) => `Contract: ${line(value)}`)];
|
|
22
21
|
const marker = "[handoff truncated; required task/guard/acceptance follow separately]";
|
|
23
22
|
const lines = []; let size = 0;
|
|
24
23
|
for (const candidate of candidates) {
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { codexHome } from "./paths.js";
|
|
4
|
+
|
|
5
|
+
export function configuredMcpServers(configText) {
|
|
6
|
+
const names = new Set();
|
|
7
|
+
for (const line of String(configText ?? "").split("\n")) {
|
|
8
|
+
const match = line.match(/^\s*\[mcp_servers\.(?:"([^"]+)"|([^\].]+))\]\s*(?:#.*)?$/);
|
|
9
|
+
if (match) names.add(match[1] ?? match[2]);
|
|
10
|
+
}
|
|
11
|
+
return names;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function disableMcpServerArgs(configText, names = null) {
|
|
15
|
+
const configured = configuredMcpServers(configText);
|
|
16
|
+
const selected = names ? [...configured].filter((name) => names.has(name)) : [...configured];
|
|
17
|
+
const args = [];
|
|
18
|
+
for (const name of selected) {
|
|
19
|
+
if (!/^[A-Za-z0-9_-]+$/.test(name)) continue;
|
|
20
|
+
args.push("-c", `mcp_servers.${name}.enabled=false`);
|
|
21
|
+
}
|
|
22
|
+
return args;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function codexConfigText() {
|
|
26
|
+
try {
|
|
27
|
+
return readFileSync(join(codexHome, "config.toml"), "utf8");
|
|
28
|
+
} catch {
|
|
29
|
+
return "";
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function supervisorMcpDisableArgs() {
|
|
34
|
+
return disableMcpServerArgs(codexConfigText(), new Set(["codex-supervisor"]));
|
|
35
|
+
}
|