export const meta = {
name: 'drive-slice',
description: 'Unjail slice driver: alternating orchestrator/worker two-job loop that disposes each phase and preps the next, with bounded revive and a closing divergence advisory.',
phases: [
{ title: 'bootstrap', detail: 'Read slice readiness and prep the first worker (read-only probe on the claude arm; unjailed O on the pi arm).' },
{ title: 'drive-loop', detail: 'Per ready phase: spawn the jailed worker, then one orchestrator disposes it (bounded revive on a fixable defect) and preps the next.' },
{ title: 'divergence', detail: 'After the loop, a read-only probe reports .doctrine/** divergence from trunk — advisory, never gated, never merged.' },
],
};
const SEED_PHASE_COST = 45_000; const SOFT_CEILING = 120_000; const MAX_FIXUP = 2;
const slice = Number((typeof args === 'string' ? JSON.parse(args) : (args || {})).slice);
if (!Number.isInteger(slice) || slice < 1) {
throw new Error(`drive-slice: bad slice ${JSON.stringify(args)}`);
}
const HALT = {
NULL_RECEIPT: 'NULL_RECEIPT', CONCLUDE_INCOMPLETE: 'CONCLUDE_INCOMPLETE', PHASE_BLOCKED: 'PHASE_BLOCKED', ANOMALY: 'ANOMALY', VERIFY_RED: 'VERIFY_RED', BUDGET_EXHAUSTED: 'BUDGET_EXHAUSTED', FIXUP_EXHAUSTED: 'FIXUP_EXHAUSTED', PREP_INCOMPLETE: 'PREP_INCOMPLETE', RECEIPT_AMBIGUOUS: 'RECEIPT_AMBIGUOUS', };
const WorkReceipt = {
type: 'object',
properties: {
fork_tip: { type: ['string', 'null'], description: 'committed fork tip (B), or null for pi/(A) worktree-diff import' },
summary: { type: 'string' },
},
required: ['fork_tip', 'summary'],
};
const DivergenceReceipt = {
type: 'object',
properties: {
diverged: { type: 'boolean' },
compared_ref: { type: 'string' },
drifted_paths: { type: 'array', items: { type: 'string' } },
},
required: ['diverged', 'compared_ref'],
};
const HopReceipt = {
type: 'object',
properties: {
slice: { type: 'number' },
phase: { type: 'string' }, receipt_status: { type: 'string', enum: ['NotStarted', 'InProgress', 'Blocked', 'Completed', 'ConcludeIncomplete', 'Unknown'] },
runtime_status: { type: ['string', 'null'], description: 'advisory, sheet-derived, nullable' },
dispatch_tip: { type: 'string', description: 'dispatch branch HEAD (NOT a code oid)' },
boundary: {
type: ['object', 'null'],
properties: { code_start: { type: 'string' }, code_end: { type: 'string' } },
},
verify: {
type: 'object',
properties: { green: { type: 'boolean' }, failures: { type: 'array', items: { type: 'string' } } },
required: ['green', 'failures'],
},
halt_reason: { type: 'string', description: 'set on any stop, incl. forwarded funnel:/coord: reasons' },
fixup: {
type: 'object',
properties: { reason: { type: 'string' }, instructions: { type: 'string' } },
required: ['reason', 'instructions'],
},
prep: {
type: 'object',
properties: {
phase: { type: 'string' },
arm: { type: 'string', enum: ['claude', 'pi'] },
base_B: { type: 'string' },
worker_prompt: { type: 'string' },
worker_fork: { type: ['string', 'null'] },
},
required: ['phase', 'arm', 'base_B', 'worker_prompt'],
},
next_ready: { type: 'array', items: { type: 'string' } },
},
required: ['next_ready'],
};
function driveArm(a) {
const parsed = typeof a === 'string' ? JSON.parse(a) : (a || {});
return parsed.arm === 'pi' ? 'pi' : 'claude';
}
const arm = driveArm(args);
const bootstrapType = arm === 'pi' ? 'dispatch-orchestrator' : 'dispatch-probe';
function bootstrapPrompt(sliceId) {
return [
`You are the BOOTSTRAP planner for /drive-slice on slice ${sliceId}.`,
`This is PREP-ONLY: there is no previous worker to dispose.`,
``,
`1. Call dispatch_next_ready{slice:${sliceId}} for the slice-global ready set,`,
` and dispatch_phase_receipt{slice:${sliceId}, phase:<first ready>} to confirm`,
` the first ready phase has not already landed a boundary row.`,
`2. If the coord tree cannot be resolved (unknown-slice|ambiguous|stale), return`,
` a HopReceipt with halt_reason "coord:<reason>" and next_ready — nothing else.`,
`3. Otherwise PREP the first ready worker: emit a HopReceipt whose \`prep\` carries`,
` { phase, arm:"${arm}", base_B (the fork base OID the worker must sit on),`,
` worker_prompt (a tight, self-contained phase brief that EMBEDS a base-guard`,
` reminder — clean tree, HEAD==base_B, one non-merge commit via worker_commit),`,
` worker_fork (pi arm only: the branch you git-worktree-added; else null) }.`,
` Include next_ready. Do NOT emit a dispose half and do NOT emit \`fixup\`.`,
`If no phase is ready, return prep:null with the (empty) next_ready — the driver`,
`treats an empty next_ready + null prep as a genuine drive-complete.`,
].join('\n');
}
function hopPrompt(sliceId, phase, prep, forkTip) {
const tip = forkTip == null ? 'null (import the worker WORKTREE DIFF — (A) path)' : forkTip;
return [
`You are an interior ORCHESTRATOR (nominated-unjailed) for /drive-slice on`,
`slice ${sliceId}, phase ${phase}. You have TWO jobs in THIS one agent:`,
`DISPOSE the just-run worker, then — iff its delta is accepted — PREP the next.`,
``,
`Address the coordination tree EXPLICITLY: git -C .dispatch/SL-${sliceId} ... .`,
`FIRST assert that tree exists AND is checked out on branch dispatch/${sliceId};`,
`if not, STOP and return a HopReceipt with halt_reason "coord:<reason>" (this is`,
`now a correctness precondition, not a confinement one).`,
``,
`DISPOSE ${phase}:`,
` - Worker fork_tip: ${tip}.`,
` - Import the worker delta (dispatch_import) — from fork_tip under (B), or the`,
` worktree diff under (A). On the (A) path, VERIFY the revive commit's parent`,
` chain descends from the prepped fork before import; on a mismatch return`,
` halt_reason "coord:revive-wrong-base".`,
` - RUN the phase tests and record verify:{green, failures[]}.`,
` - If the delta is FIXABLE (verify-red-but-addressable, incomplete edit), return`,
` \`fixup\`:{reason, instructions} and NO \`prep\` — the driver will revive the`,
` worker on its fork. Do this ONLY for a repairable defect.`,
` - Otherwise conclude the phase (dispatch_conclude_phase) against the CURRENT`,
` live dispatch_tip and reap the fork (dispatch_reap). Map any funnel refusal`,
` to halt_reason "funnel:<reason>" — never auto-merge, never blind-retry.`,
` - Emit the dispose half: PhaseReceiptCore { slice, phase, receipt_status,`,
` runtime_status?, dispatch_tip, boundary? } + verify + halt_reason?.`,
``,
`PREP the next worker (only iff dispose was accepted, i.e. no fixup and no halt):`,
` - Consult dispatch_next_ready{slice:${sliceId}} and emit \`prep\`:{ phase,`,
` arm:"${arm}" (the drive arm — PINNED; do NOT choose your own, or the driver`,
` spawns the wrong worker path), base_B (the CURRENT coord tip after this`,
` phase's conclude — NOT the old base), worker_prompt (EMBED the base-guard`,
` reminder; for arm "claude" the worker SELF-COMMITS its delta via worker_commit`,
` (B) — for "pi" it leaves the worktree diff for import), worker_fork } for the`,
` next ready phase. If NO phase is ready, return prep:null.`,
` - On a HARD prep failure (distill error, pi git-worktree-add failure) set`,
` halt_reason ("coord:"/"funnel:") rather than a silent null.`,
``,
`Always include next_ready. \`fixup\` and \`prep\` are MUTUALLY EXCLUSIVE — emit at`,
`most one (the driver enforces it: a hop with both halts RECEIPT_AMBIGUOUS).`,
].join('\n');
}
function fixupPrompt(prep, fixup) {
return [
`You are a REVIVE worker for phase ${prep.phase} on the /drive-slice fork.`,
`Your prior live reasoning is GONE — you resume from the committed fork tip,`,
`which is fork-durable, not context-intact.`,
``,
`BASE GUARD (enforced, not hoped): your worktree's base is re-stamped to the`,
`prior fork tip; worker_commit refuses unless HEAD==base and the new commit's`,
`single parent == base, so a wrong-base revive is MECHANICALLY rejected before`,
`any tip moves. Do NOT git reset to "fix" the base — the base check is the`,
`guarantee, not a prompt-obeyed reset. Clean tree, ONE non-merge commit.`,
``,
`The orchestrator flagged this defect:`,
` reason: ${fixup.reason}`,
` instructions: ${fixup.instructions}`,
``,
`Apply the fix within your original declared file set, re-run the fast check,`,
`then commit via worker_commit and return a WorkReceipt { fork_tip, summary }.`,
].join('\n');
}
function divergencePrompt(sliceId) {
return [
`You are the CLOSING divergence probe for /drive-slice on slice ${sliceId}.`,
`Call dispatch_authored_divergence{slice:${sliceId}} and return its`,
`DivergenceReceipt { diverged, compared_ref, drifted_paths? } VERBATIM.`,
`This is a fact to REPORT, never a conflict to resolve: do not merge, do not`,
`write, do not land anything. compared_ref names the trunk ref the diff used.`,
].join('\n');
}
async function divergenceProbe(sliceId) {
return await agent(divergencePrompt(sliceId), {
schema: DivergenceReceipt,
agentType: 'dispatch-probe',
});
}
let lastActual = null;
const report = { phases: [], halted: null, divergence: null };
let hop = await agent(bootstrapPrompt(slice), { schema: HopReceipt, agentType: bootstrapType });
if (!hop || hop.halt_reason) {
report.halted = { reason: hop?.halt_reason ?? HALT.NULL_RECEIPT };
return report;
}
if (hop.fixup) { report.halted = { reason: HALT.RECEIPT_AMBIGUOUS }; return report; }
while (hop.prep) { const prep = hop.prep, phase = prep.phase;
if (budget.total && budget.remaining() < (lastActual ?? SEED_PHASE_COST)) {
report.halted = { reason: HALT.BUDGET_EXHAUSTED, phase };
break;
}
const before = budget.spent();
let work = prep.arm === 'claude'
? await agent(prep.worker_prompt, { schema: WorkReceipt, isolation: 'worktree', agentType: 'dispatch-worker' })
: { fork_tip: null };
let fixups = 0;
for (;;) {
hop = await agent(hopPrompt(slice, phase, prep, work.fork_tip), { schema: HopReceipt, agentType: 'dispatch-orchestrator' });
if (!hop) { hop = { halt_reason: HALT.NULL_RECEIPT, prep: null }; break; }
if (hop.fixup && hop.prep) { hop = { halt_reason: HALT.RECEIPT_AMBIGUOUS, prep: null }; break; }
if (!hop.fixup) break; if (++fixups > MAX_FIXUP) { hop = { halt_reason: HALT.FIXUP_EXHAUSTED, prep: null }; break; }
work = await agent(fixupPrompt(prep, hop.fixup), { schema: WorkReceipt, isolation: 'worktree', agentType: 'dispatch-worker' });
}
lastActual = budget.spent() - before; report.phases.push({ phase, ...hop });
log(`phase ${phase}: ${lastActual / 1000 | 0}k${fixups ? ` (${fixups} fixup)` : ''}`);
if (hop.halt_reason) { report.halted = { reason: hop.halt_reason, phase }; break; }
if (hop.receipt_status === 'ConcludeIncomplete') { report.halted = { reason: HALT.CONCLUDE_INCOMPLETE, phase }; break; }
if (hop.receipt_status === 'Blocked') { report.halted = { reason: HALT.PHASE_BLOCKED, phase }; break; } if (hop.receipt_status !== 'Completed') { report.halted = { reason: `${HALT.ANOMALY}:${hop.receipt_status}`, phase }; break; } if (!hop.verify.green) { report.halted = { reason: HALT.VERIFY_RED, phase }; break; }
if (!hop.prep && hop.next_ready && hop.next_ready.length) {
report.halted = { reason: HALT.PREP_INCOMPLETE, phase };
break;
}
}
report.divergence = await divergenceProbe(slice);
return report;