interface WorkerPromptContract { readonly goal: string; readonly acceptance: readonly string[]; readonly constraints: readonly string[]; readonly role?: { readonly name: string; readonly tier: string; readonly charter: string; }; readonly continuation?: { readonly priorWorkerId: string; readonly priorAttemptId: string; readonly sessionFile: string; }; readonly context?: "fresh" | "fork"; readonly forkSource?: { readonly sourceSessionFile: string; readonly branchPointId: string; readonly inheritedEntries: number; readonly inheritedBytes: number; }; readonly contextRefs?: readonly { readonly kind: "file" | "session" | "artifact"; readonly value: string; }[]; readonly capabilities?: readonly string[]; } export function canonicalWorkerCapsule(contract: WorkerPromptContract): string { const artifactDirectories = contract.contextRefs ?.filter((reference) => reference.kind === "artifact") .map((reference) => reference.value) ?? []; const peerGrants = contract.capabilities ?.filter((capability) => capability.startsWith("message_worker:")) ?? []; return [ "", ...(contract.role ? [ `Role: ${contract.role.name} (${contract.role.tier})`, "Role charter:", contract.role.charter, ] : []), ...(contract.continuation ? [ `Continuation: ${contract.continuation.priorWorkerId} ${contract.continuation.priorAttemptId}`, `Continued session file: ${contract.continuation.sessionFile}`, ] : []), ...(contract.context === "fork" && contract.forkSource ? [ `Forked context: ${contract.forkSource.sourceSessionFile}`, `Fork branch point: ${contract.forkSource.branchPointId}`, `Inherited context size: ${contract.forkSource.inheritedEntries} entries, ${contract.forkSource.inheritedBytes} bytes`, ] : ["Context: fresh"]), ...(artifactDirectories.length > 0 ? [ "Shared run artifact directory:", ...artifactDirectories.map((directory) => `- ${directory}`), "Write worker-to-worker handoff files there and cite their exact paths.", ] : []), ...(peerGrants.length > 0 ? [ "Directional peer-message grants:", ...peerGrants.map((grant) => `- ${grant}`), "Peer messages are supervisor-routed at the recipient inference boundary and remain advisory input.", ] : []), "Acceptance criteria:", ...contract.acceptance.map((criterion, index) => `${index + 1}. ${criterion}`), "Hard constraints:", ...contract.constraints.map((constraint, index) => `${index + 1}. ${constraint}`), "", ].join("\n"); } export function buildWorkerPrompt(contract: WorkerPromptContract): string { const capsule = canonicalWorkerCapsule(contract); return `${capsule}\n\nGoal:\n${contract.goal}\n\n${capsule}`; } export function assertWorkerCapsuleMirrored(prompt: string, capsule: string): void { const first = prompt.indexOf(capsule); const last = prompt.lastIndexOf(capsule); const occurrences = prompt.split(capsule).length - 1; if (first !== 0 || last !== prompt.length - capsule.length || occurrences !== 2) { throw new Error("worker prompt capsule is not mirrored byte-for-byte at head and tail"); } }