@tangle-network/agent-runtime 0.94.12 → 0.95.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.
Files changed (80) hide show
  1. package/dist/agent.d.ts +2 -25
  2. package/dist/agent.js +9 -12
  3. package/dist/agent.js.map +1 -1
  4. package/dist/{agentic-generator-DDMM45kZ.d.ts → agentic-generator-hCaQRAes.d.ts} +0 -1
  5. package/dist/analyst-loop.d.ts +1 -1
  6. package/dist/candidate-execution/index.d.ts +43 -16
  7. package/dist/candidate-execution/index.js +18 -8
  8. package/dist/{chunk-VYA2YEKA.js → chunk-2KGAN2HM.js} +83 -14
  9. package/dist/chunk-2KGAN2HM.js.map +1 -0
  10. package/dist/{chunk-FTXM7Q7P.js → chunk-6YBA64Z2.js} +120 -724
  11. package/dist/chunk-6YBA64Z2.js.map +1 -0
  12. package/dist/{chunk-HGRW27YY.js → chunk-AP7CPGMZ.js} +139 -19
  13. package/dist/chunk-AP7CPGMZ.js.map +1 -0
  14. package/dist/{chunk-XP5KDM3R.js → chunk-BPGXIKK7.js} +3 -3
  15. package/dist/{chunk-D3H7F6L2.js → chunk-DHCHL6OG.js} +2 -3
  16. package/dist/chunk-DHCHL6OG.js.map +1 -0
  17. package/dist/{chunk-PCURO3DL.js → chunk-G55QE4IQ.js} +512 -36
  18. package/dist/chunk-G55QE4IQ.js.map +1 -0
  19. package/dist/{chunk-C3UKLQ54.js → chunk-IADLKE7I.js} +14 -4
  20. package/dist/chunk-IADLKE7I.js.map +1 -0
  21. package/dist/{chunk-WIPGQ4GT.js → chunk-IMSNJSXH.js} +1 -1
  22. package/dist/{chunk-WIPGQ4GT.js.map → chunk-IMSNJSXH.js.map} +1 -1
  23. package/dist/{chunk-VSWBYWFK.js → chunk-M6MD6JBS.js} +20 -27
  24. package/dist/chunk-M6MD6JBS.js.map +1 -0
  25. package/dist/chunk-MKGRLDWB.js +684 -0
  26. package/dist/chunk-MKGRLDWB.js.map +1 -0
  27. package/dist/{chunk-AEG3NGJ2.js → chunk-Q2JSAVQ3.js} +34 -2
  28. package/dist/chunk-Q2JSAVQ3.js.map +1 -0
  29. package/dist/{chunk-37V4KQDC.js → chunk-WTZ37EQY.js} +1021 -514
  30. package/dist/chunk-WTZ37EQY.js.map +1 -0
  31. package/dist/{chunk-U33YZ7B2.js → chunk-YLUOTX6U.js} +4 -4
  32. package/dist/{chunk-33OG2NN3.js → chunk-Z5I642SY.js} +2 -2
  33. package/dist/{completion-gate-D1gX1-hg.d.ts → completion-gate-C80jiRfN.d.ts} +1 -1
  34. package/dist/conversation.d.ts +12 -1
  35. package/dist/conversation.js +2 -2
  36. package/dist/{coordination-Dr_axlAf.d.ts → coordination-BFE3Den7.d.ts} +10 -11
  37. package/dist/environment-provider.d.ts +2 -2
  38. package/dist/environment-provider.js +1 -1
  39. package/dist/{improve-BN3HyXIO.d.ts → improve-B-UYaEH5.d.ts} +3 -3
  40. package/dist/index.d.ts +22 -25
  41. package/dist/index.js +45 -50
  42. package/dist/index.js.map +1 -1
  43. package/dist/intelligence.d.ts +177 -119
  44. package/dist/intelligence.js +501 -342
  45. package/dist/intelligence.js.map +1 -1
  46. package/dist/knowledge.d.ts +22 -11
  47. package/dist/knowledge.js +9 -4
  48. package/dist/lifecycle.d.ts +2 -2
  49. package/dist/lifecycle.js +1 -1
  50. package/dist/{loop-runner-bin-BRQSQdHa.d.ts → loop-runner-bin-BIQldFS8.d.ts} +2 -2
  51. package/dist/loop-runner-bin.d.ts +5 -5
  52. package/dist/loop-runner-bin.js +6 -6
  53. package/dist/loops.d.ts +12 -12
  54. package/dist/loops.js +5 -5
  55. package/dist/mcp/bin.js +3 -3
  56. package/dist/mcp/index.d.ts +6 -6
  57. package/dist/mcp/index.js +6 -6
  58. package/dist/{mcp-serve-verifier-DQQDbuyz.d.ts → mcp-serve-verifier-Bs_n0xPc.d.ts} +1 -1
  59. package/dist/primeintellect/index.js +1 -1
  60. package/dist/profile-DbfaMTdk.d.ts +233 -0
  61. package/dist/profiles.d.ts +1 -1
  62. package/dist/{supervise-DmYOug5f.d.ts → supervise-BLPI50-w.d.ts} +3 -3
  63. package/dist/{types-ByAYqlVb.d.ts → types-B3vAW0Oq.d.ts} +1 -1
  64. package/dist/types-CWqfCO8s.d.ts +491 -0
  65. package/dist/{types-1d5QGK3t.d.ts → types-CmnA2iL3.d.ts} +3 -3
  66. package/dist/{worktree-fanout-CPprU-qI.d.ts → worktree-fanout-DCA3G4bO.d.ts} +3 -3
  67. package/package.json +13 -10
  68. package/dist/chunk-37V4KQDC.js.map +0 -1
  69. package/dist/chunk-AEG3NGJ2.js.map +0 -1
  70. package/dist/chunk-C3UKLQ54.js.map +0 -1
  71. package/dist/chunk-D3H7F6L2.js.map +0 -1
  72. package/dist/chunk-FTXM7Q7P.js.map +0 -1
  73. package/dist/chunk-HGRW27YY.js.map +0 -1
  74. package/dist/chunk-PCURO3DL.js.map +0 -1
  75. package/dist/chunk-VSWBYWFK.js.map +0 -1
  76. package/dist/chunk-VYA2YEKA.js.map +0 -1
  77. package/dist/prepare-DIeVgQG3.d.ts +0 -718
  78. /package/dist/{chunk-XP5KDM3R.js.map → chunk-BPGXIKK7.js.map} +0 -0
  79. /package/dist/{chunk-U33YZ7B2.js.map → chunk-YLUOTX6U.js.map} +0 -0
  80. /package/dist/{chunk-33OG2NN3.js.map → chunk-Z5I642SY.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/improvement/agentic-generator.ts"],"sourcesContent":["/**\n *\n * `agenticGenerator` — the full-agentic `CandidateGenerator`: the\n * `shots=N, sandbox=on` setting of the one `improvementDriver`. It runs a real\n * coding harness (claude / codex / opencode) inside the candidate worktree the\n * driver already created, letting the agent read the codebase + the research\n * report and make the change in place. The driver then commits the worktree\n * into a `CodeSurface`.\n *\n * Mechanism: identical to the proven Phase-2.8 in-process executor — spawn the\n * harness as a subprocess with `cwd` = the worktree, on the same filesystem,\n * so edits land in place (no sandbox-mount round-trip). `runLocalHarness` is\n * the verified primitive. The OUTER sandbox is the improvement loop's own\n * execution context; the generator does not nest a second sandbox per\n * candidate (which would reintroduce a host↔sandbox worktree-transport\n * problem that does not need solving here).\n *\n * `maxShots` is the DEPTH dial — a multi-shot verify-in-session loop, NOT the\n * kernel `runLoop`. Each shot runs one full harness session in the (persistent)\n * worktree; between shots the loop refines based on what the last shot produced:\n * - empty tree → \"you changed nothing, make the edits\" → retry\n * - dirty + `verify` fails → feed the verifier's failure into the next shot\n * (the worktree persists, so the harness RESUMES atop its own failing\n * edits with the error in hand — no `--resume` session plumbing needed,\n * and harness-agnostic across claude/codex/opencode)\n * - dirty + `verify` ok (or no verifier configured) → return the candidate\n * A candidate that never verifies within `maxShots` is discarded (`applied:\n * false`), never shipped — if you configured a verifier, a non-passing tree is\n * not a candidate. With no verifier the legacy behavior holds: first dirty shot\n * is the candidate.\n *\n * @experimental\n */\n\nimport { spawnSync } from 'node:child_process'\nimport { createHash } from 'node:crypto'\nimport { existsSync, readFileSync, rmSync } from 'node:fs'\nimport { join, resolve, sep } from 'node:path'\nimport type {\n AnalystFinding,\n CostLedgerHandle,\n CostReceipt,\n CostReceiptInput,\n MaximumCharge,\n} from '@tangle-network/agent-eval'\nimport type { AgentProfile, ReasoningEffort } from '@tangle-network/agent-interface'\nimport {\n applyWorkspacePlan,\n materializeProfile,\n type WorkspacePlan,\n type WorkspacePlanReceipt,\n} from '@tangle-network/agent-profile-materialize'\nimport {\n type CodexExecutionEvidence,\n type CodexTokenUsage,\n harnessInvocation,\n type LocalHarness,\n type LocalHarnessResult,\n runLocalHarness,\n} from '../mcp/local-harness'\nimport type { CandidateGenerator } from './improvement-driver'\n\nconst RAW_TRACE_ANALYST_ID = 'raw-trace-distiller'\nconst RAW_TRACE_AREA = 'raw-trace-context'\nconst RAW_TRACE_DIAGNOSIS_PATH = '.improve/raw-trace-diagnosis.md'\n\n/** Dedicated ephemeral root for generic author-profile files. Every declared\n * file must live below this root so cleanup cannot alter candidate-owned files. */\nexport const AGENTIC_PROFILE_RESOURCE_ROOT = '.agent-runtime-profile-resources'\n\n/** Outcome of verifying a candidate worktree. `feedback` (compiler errors,\n * failing test output) is fed into the next shot when `ok` is false. */\nexport interface VerifyResult {\n ok: boolean\n feedback?: string\n}\n\n/** Verifies the edited worktree. Sync or async; throws only on a setup fault\n * (a candidate that fails verification returns `{ok:false}`, it does not\n * throw). */\nexport type Verifier = (worktreePath: string) => Promise<VerifyResult> | VerifyResult\n\nexport interface AgenticGeneratorShotReceipt {\n readonly schemaVersion: 1\n readonly generation: number | null\n readonly candidateIndex: number | null\n /** One-based shot number within this candidate. */\n readonly shot: number\n readonly maxShots: number\n readonly harness: LocalHarness\n readonly model: string | null\n readonly reasoningEffort: ReasoningEffort | null\n readonly promptSha256: `sha256:${string}`\n readonly startedAt: string\n readonly completedAt: string\n readonly durationMs: number\n readonly exitCode: number | null\n readonly timedOut: boolean\n readonly killedBySignal: NodeJS.Signals | null\n readonly stdoutBytes: number | null\n readonly stdoutSha256: `sha256:${string}` | null\n readonly stderrBytes: number | null\n readonly stderrSha256: `sha256:${string}` | null\n readonly usage: CodexTokenUsage | null\n /** Digest of the exact profile-file workspace plan applied for this shot. */\n readonly profileWorkspacePlanDigest: string | null\n readonly profileWorkspaceFileCount: number\n /** Shared run-ledger call id for this exact shot. */\n readonly costCallId: string | null\n /** Whether dollars came from the provider, the pricing table, or are unknown. */\n readonly costBasis: 'provider-reported' | 'estimated-pricing' | 'unknown'\n readonly costUsd: number | null\n /** True only for a provider-reported amount, never for a pricing estimate. */\n readonly costUsdKnown: boolean\n readonly evidence: CodexExecutionEvidence | null\n readonly error: { readonly name: string; readonly message: string } | null\n}\n\n/** Frozen exact harness result for an author shot: full streams, process state,\n * token usage, and execution-policy evidence.\n * The `onShotCompleted` callback receives `null` when execution failed before\n * the harness returned. */\nexport type AgenticGeneratorShotExecution = Readonly<\n Omit<LocalHarnessResult, 'usage' | 'evidence'> & {\n readonly usage?: Readonly<CodexTokenUsage>\n readonly evidence?: Readonly<Omit<CodexExecutionEvidence, 'readDeniedPaths' | 'policy'>> & {\n readonly readDeniedPaths: ReadonlyArray<string>\n readonly policy: Readonly<CodexExecutionEvidence['policy']>\n }\n }\n>\n\n/** Worktree decision emitted before a completed shot is retried, accepted, or\n * discarded. The callback runs while `worktreePath` is still available, so\n * callers can persist the exact diff. */\nexport type AgenticGeneratorShotDisposition =\n | {\n readonly kind: 'clean'\n readonly worktreePath: string\n }\n | {\n readonly kind: 'rejected'\n readonly worktreePath: string\n readonly stage: 'raw-trace-evidence' | 'verification'\n readonly feedback: string | null\n }\n | {\n readonly kind: 'accepted'\n readonly worktreePath: string\n readonly verified: boolean\n }\n | {\n readonly kind: 'setup-error'\n readonly worktreePath: string\n readonly stage: 'worktree-inspection' | 'raw-trace-evidence' | 'verification'\n readonly error: { readonly name: string; readonly message: string }\n }\n\nexport interface AgenticGeneratorOptions {\n /** Local coding harness to run in the worktree. Default `claude`. */\n harness?: LocalHarness\n /** Author profile rendered through the canonical harness mapper. Required\n * for reproducible Codex so model and reasoning settings are explicit. */\n profile?: AgentProfile\n /** Run Codex with isolated configuration, exact prompt evidence, and required\n * terminal token usage. Requires `harness: 'codex'` and `profile`. */\n codexReproducible?: boolean\n /** Absolute paths reproducible Codex must not read. A function can derive\n * candidate-specific paths after the driver creates its worktree. */\n codexReadDeniedPaths?: ReadonlyArray<string> | ((worktreePath: string) => ReadonlyArray<string>)\n /** Awaited once for every attempted author shot, including process failures.\n * The second argument preserves the exact harness result, including stdout\n * and stderr, before worktree inspection or verification can reject the\n * shot. Throwing aborts the candidate so evidence persistence fails closed. */\n onShotCompleted?: (\n receipt: AgenticGeneratorShotReceipt,\n execution: AgenticGeneratorShotExecution | null,\n ) => void | Promise<void>\n /** Awaited after worktree inspection and before the shot is accepted,\n * retried, or discarded. Throwing aborts the candidate. */\n onShotDisposition?: (\n receipt: AgenticGeneratorShotReceipt,\n disposition: AgenticGeneratorShotDisposition,\n ) => void | Promise<void>\n /** Optional hard upper bound passed to the run-wide CostLedger before each\n * author shot. This MUST be enforced by the provider or executor; a planning\n * estimate is not an admissible bound. Omit for an uncapped ledger. A capped\n * ledger rejects before model dispatch when this is absent. */\n maximumCharge?: MaximumCharge\n /** Per-shot wall-clock timeout (ms). Default = `runLocalHarness` default (5m). */\n timeoutMs?: number\n /** Build the harness task prompt from the report + findings. Override for\n * domain phrasing; the default turns findings into a concrete coder task. */\n buildPrompt?: (args: { report: unknown; findings: AnalystFinding[] }) => string\n /** Verify the worktree after each dirtying shot. When set, a candidate that\n * fails verification is NOT returned — the failure feeds the next shot\n * (verify-in-session), up to `maxShots`; a candidate that never verifies is\n * discarded (`applied:false`), never shipped. Omitted ⇒ legacy behavior:\n * the first dirty shot is the candidate. See `commandVerifier`. */\n verify?: Verifier\n /** Test seam — inject the harness runner (defaults to `runLocalHarness`). */\n runHarness?: typeof runLocalHarness\n /** Test seam — inject the worktree-dirty check (defaults to `git status`). */\n isDirty?: (worktreePath: string) => boolean\n}\n\n/** Full-agentic `CandidateGenerator` (the `shots=N, sandbox=on` setting): run a real coding harness inside the candidate worktree so the agent makes the change in place. */\nexport function agenticGenerator(opts: AgenticGeneratorOptions = {}): CandidateGenerator {\n const harness = opts.harness ?? 'claude'\n if (opts.codexReproducible && harness !== 'codex') {\n throw new Error(\"agenticGenerator: codexReproducible requires harness 'codex'\")\n }\n if (opts.codexReproducible && !opts.profile) {\n throw new Error('agenticGenerator: codexReproducible requires an explicit author profile')\n }\n if (opts.codexReadDeniedPaths && !opts.codexReproducible) {\n throw new Error('agenticGenerator: codexReadDeniedPaths requires codexReproducible')\n }\n if (opts.maximumCharge && !opts.codexReproducible) {\n throw new Error('agenticGenerator: maximumCharge requires codexReproducible')\n }\n const profileResourcePlan = opts.codexReproducible\n ? authorProfileResourcePlan(opts.profile as AgentProfile)\n : null\n const buildPrompt = opts.buildPrompt ?? defaultBuildPrompt\n const run = opts.runHarness ?? runLocalHarness\n const dirty = opts.isDirty ?? worktreeDirty\n const verify = opts.verify\n\n return {\n kind: `agentic:${harness}`,\n // The seed repo + (in rawTraceContext mode) the raw-trace filesystem context\n // are the change signal — an agentic coder proposes from them even when the\n // distiller yielded zero findings. Without this, the improvementDriver's\n // empty-findings guard short-circuits and generates ZERO candidates on the\n // first (and, for a single-generation run, only) proposal round.\n proposesWithoutFindings: true,\n async generate({\n worktreePath,\n report,\n findings,\n maxShots,\n signal,\n generation,\n candidateIndex,\n costLedger,\n costPhase,\n }) {\n let reproducibleCostLedger: CostLedgerHandle | undefined\n if (opts.codexReproducible) {\n if (!costLedger) {\n throw new Error(\n 'agenticGenerator: reproducible Codex requires the run-wide CostLedger supplied by agent-eval 0.117+',\n )\n }\n reproducibleCostLedger = costLedger\n }\n const basePrompt = appendProfileResourcePaths(\n buildPrompt({ report, findings }),\n profileResourcePlan,\n )\n const needsRawTraceEvidence = requiresRawTraceEvidence(findings)\n const shots = Math.max(1, maxShots)\n // Feedback appended to the base prompt for the NEXT shot — empty on shot 0.\n let attemptNote = ''\n\n for (let shot = 0; shot < shots; shot++) {\n if (signal.aborted) break\n const taskPrompt = attemptNote ? `${basePrompt}\\n\\n${attemptNote}` : basePrompt\n const invocation = opts.profile\n ? harnessInvocation(harness, opts.profile, taskPrompt, {\n dangerouslySkipPermissions: harness === 'claude',\n ...(opts.codexReproducible ? { codexReproducible: true } : {}),\n })\n : undefined\n const exactPrompt = invocation?.prompt ?? taskPrompt\n const readDeniedPaths =\n typeof opts.codexReadDeniedPaths === 'function'\n ? opts.codexReadDeniedPaths(worktreePath)\n : opts.codexReadDeniedPaths\n const startedAt = new Date()\n let harnessResult: LocalHarnessResult | null = null\n let profileWorkspaceReceipt: WorkspacePlanReceipt | null = null\n let costReceipt: CostReceipt | null = null\n let costCallId: string | null = null\n let shotError: Error | null = null\n try {\n const execute = async (executionSignal: AbortSignal): Promise<LocalHarnessResult> => {\n harnessResult = await withAuthorProfileResources(\n profileResourcePlan,\n worktreePath,\n async (receipt) => {\n profileWorkspaceReceipt = receipt\n const result = await run({\n harness,\n cwd: worktreePath,\n taskPrompt,\n ...(invocation\n ? { invocation: { command: invocation.command, args: invocation.args } }\n : {}),\n // The candidate worktree is isolated and must be editable without an\n // interactive permission prompt. Other runLocalHarness callers remain\n // permission-safe by default.\n dangerouslySkipPermissions: harness === 'claude',\n ...(opts.codexReproducible ? { codexReproducible: true } : {}),\n ...(readDeniedPaths ? { codexReadDeniedPaths: readDeniedPaths } : {}),\n timeoutMs: opts.timeoutMs,\n signal: executionSignal,\n })\n // Assign before profile cleanup so a cleanup failure still\n // settles the model usage already returned by the harness.\n harnessResult = result\n return result\n },\n )\n const failure = shotFailure(harnessResult, exactPrompt, opts.codexReproducible === true)\n if (failure) throw failure\n return harnessResult\n }\n\n if (reproducibleCostLedger) {\n const model = opts.profile?.model?.default\n if (!model) {\n throw new Error('agenticGenerator: reproducible Codex requires profile.model.default')\n }\n const paid = await reproducibleCostLedger.runPaidCall({\n channel: 'driver',\n phase: costPhase ?? 'search.proposal',\n actor: `agentic-generator:${harness}`,\n model,\n tags: {\n generation: String(generation ?? -1),\n candidateIndex: String(candidateIndex ?? -1),\n shot: String(shot + 1),\n },\n signal,\n ...(opts.maximumCharge ? { maximumCharge: opts.maximumCharge } : {}),\n execute,\n receipt: (result) => costReceiptFromHarness(result, model),\n receiptFromError: () =>\n harnessResult?.usage ? costReceiptFromHarness(harnessResult, model) : undefined,\n })\n costCallId = paid.callId ?? null\n costReceipt = paid.receipt ?? null\n if (!paid.succeeded) throw paid.error\n harnessResult = paid.value\n } else {\n harnessResult = await execute(signal)\n }\n } catch (cause) {\n shotError = cause instanceof Error ? cause : new Error(String(cause))\n }\n const execution = shotExecutionSnapshot(harnessResult)\n const receipt = shotReceipt({\n generation,\n candidateIndex,\n shot,\n maxShots: shots,\n harness,\n profile: opts.profile,\n prompt: exactPrompt,\n startedAt,\n completedAt: new Date(),\n result: execution,\n profileWorkspaceReceipt,\n costCallId,\n costReceipt,\n error: shotError,\n })\n await emitShotReceipt(opts.onShotCompleted, receipt, execution, shotError)\n\n if (!execution) {\n throw new Error('agenticGenerator: author shot completed without a harness result')\n }\n\n let worktreeChanged: boolean\n try {\n worktreeChanged = dirty(worktreePath)\n } catch (cause) {\n return rethrowShotSetupError(\n opts.onShotDisposition,\n receipt,\n worktreePath,\n 'worktree-inspection',\n cause,\n )\n }\n\n // The worktree IS the signal: no edits ⇒ tell the next shot to act.\n if (!worktreeChanged) {\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'clean',\n worktreePath,\n })\n attemptNote = EMPTY_TREE_NOTE\n continue\n }\n\n if (needsRawTraceEvidence) {\n let problem: string | null\n try {\n problem = rawTraceEvidenceProblem(worktreePath, findings)\n } catch (cause) {\n return rethrowShotSetupError(\n opts.onShotDisposition,\n receipt,\n worktreePath,\n 'raw-trace-evidence',\n cause,\n )\n }\n if (problem) {\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'rejected',\n worktreePath,\n stage: 'raw-trace-evidence',\n feedback: problem,\n })\n attemptNote = problem\n continue\n }\n }\n\n // Dirty: with no verifier the diff IS the candidate (we trust the diff,\n // not the harness's stdout). With a verifier the candidate must pass it.\n if (!verify) {\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'accepted',\n worktreePath,\n verified: false,\n })\n return { applied: true, summary: summarize(findings) }\n }\n let result: VerifyResult\n try {\n result = await verify(worktreePath)\n } catch (cause) {\n return rethrowShotSetupError(\n opts.onShotDisposition,\n receipt,\n worktreePath,\n 'verification',\n cause,\n )\n }\n if (result.ok) {\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'accepted',\n worktreePath,\n verified: true,\n })\n return { applied: true, summary: summarize(findings) }\n }\n await emitShotDisposition(opts.onShotDisposition, receipt, {\n kind: 'rejected',\n worktreePath,\n stage: 'verification',\n feedback: result.feedback ?? null,\n })\n // Dirty but failing — resume next shot atop these edits with the error.\n attemptNote = failureNote(result.feedback)\n }\n\n // Shots exhausted: no verified candidate (or, sans verifier, no edits).\n return { applied: false, summary: '' }\n },\n }\n}\n\nfunction authorProfileResourcePlan(profile: AgentProfile): WorkspacePlan | null {\n const resources = profile.resources\n if (!resources) return null\n const unsupportedKinds = [\n resources.tools?.length ? 'tools' : null,\n resources.skills?.length ? 'skills' : null,\n resources.agents?.length ? 'agents' : null,\n ].filter((kind): kind is string => kind !== null)\n if (unsupportedKinds.length > 0) {\n throw new Error(\n `agenticGenerator: reproducible Codex author resources support files only; unsupported: ${unsupportedKinds.join(', ')}`,\n )\n }\n if (!resources.files || resources.files.length === 0) return null\n\n const plan = materializeProfile(\n {\n name: profile.name,\n resources: { files: resources.files },\n },\n 'codex',\n )\n if (plan.unsupported.length > 0) {\n throw new Error(\n `agenticGenerator: author profile files could not be materialized: ${plan.unsupported.map((item) => item.reason).join('; ')}`,\n )\n }\n if (Object.keys(plan.env).length > 0 || plan.flags.length > 0) {\n throw new Error(\n 'agenticGenerator: generic author profile files unexpectedly changed spawn values',\n )\n }\n\n const virtualRoot = resolve('/', AGENTIC_PROFILE_RESOURCE_ROOT)\n const seen = new Set<string>()\n for (const file of plan.files) {\n const target = resolve('/', file.relPath)\n if (!target.startsWith(`${virtualRoot}${sep}`)) {\n throw new Error(\n `agenticGenerator: author profile file must be below ${AGENTIC_PROFILE_RESOURCE_ROOT}: ${file.relPath}`,\n )\n }\n if (seen.has(target)) {\n throw new Error(`agenticGenerator: duplicate author profile file path: ${file.relPath}`)\n }\n seen.add(target)\n }\n return plan\n}\n\nfunction appendProfileResourcePaths(prompt: string, plan: WorkspacePlan | null): string {\n if (!plan) return prompt\n return [\n prompt,\n '',\n 'Profile resource files available for this shot:',\n ...plan.files.map((file) => `- ${file.relPath}`),\n ].join('\\n')\n}\n\nasync function withAuthorProfileResources<T>(\n plan: WorkspacePlan | null,\n worktreePath: string,\n run: (receipt: WorkspacePlanReceipt | null) => Promise<T>,\n): Promise<T> {\n if (!plan) return run(null)\n\n const rootPath = resolve(worktreePath, AGENTIC_PROFILE_RESOURCE_ROOT)\n if (existsSync(rootPath)) {\n throw new Error(\n `agenticGenerator: ephemeral author profile root already exists: ${AGENTIC_PROFILE_RESOURCE_ROOT}`,\n )\n }\n\n let value: T | undefined\n let primaryError: unknown\n try {\n const receipt = applyWorkspacePlan(plan, worktreePath)\n value = await run(receipt)\n } catch (cause) {\n primaryError = cause\n }\n\n let cleanupError: unknown\n try {\n rmSync(rootPath, { recursive: true, force: true })\n if (existsSync(rootPath)) {\n throw new Error(\n `agenticGenerator: ephemeral author profile root survived cleanup: ${AGENTIC_PROFILE_RESOURCE_ROOT}`,\n )\n }\n } catch (cause) {\n cleanupError = cause\n }\n\n if (primaryError !== undefined && cleanupError !== undefined) {\n throw new AggregateError(\n [primaryError, cleanupError],\n 'agenticGenerator: author shot and profile resource cleanup both failed',\n )\n }\n if (primaryError !== undefined) throw primaryError\n if (cleanupError !== undefined) throw cleanupError\n return value as T\n}\n\nasync function emitShotReceipt(\n callback: AgenticGeneratorOptions['onShotCompleted'],\n receipt: AgenticGeneratorShotReceipt,\n execution: AgenticGeneratorShotExecution | null,\n primaryError: Error | null,\n): Promise<void> {\n try {\n await callback?.(receipt, execution)\n } catch (callbackError) {\n if (primaryError !== null) {\n throw new AggregateError(\n [primaryError, callbackError],\n 'agenticGenerator: author shot failed and its receipt could not be persisted',\n )\n }\n throw callbackError\n }\n if (primaryError !== null) throw primaryError\n}\n\nasync function emitShotDisposition(\n callback: AgenticGeneratorOptions['onShotDisposition'],\n receipt: AgenticGeneratorShotReceipt,\n disposition: AgenticGeneratorShotDisposition,\n): Promise<void> {\n await callback?.(receipt, disposition)\n}\n\nasync function rethrowShotSetupError(\n callback: AgenticGeneratorOptions['onShotDisposition'],\n receipt: AgenticGeneratorShotReceipt,\n worktreePath: string,\n stage: Extract<AgenticGeneratorShotDisposition, { kind: 'setup-error' }>['stage'],\n cause: unknown,\n): Promise<never> {\n const error = cause instanceof Error ? cause : new Error(String(cause))\n try {\n await emitShotDisposition(callback, receipt, {\n kind: 'setup-error',\n worktreePath,\n stage,\n error: { name: error.name, message: error.message },\n })\n } catch (callbackError) {\n throw new AggregateError(\n [cause, callbackError],\n 'agenticGenerator: shot processing failed and its worktree disposition could not be persisted',\n )\n }\n throw cause\n}\n\nfunction shotExecutionSnapshot(\n result: LocalHarnessResult | null,\n): AgenticGeneratorShotExecution | null {\n if (result === null) return null\n const usage = result.usage ? Object.freeze({ ...result.usage }) : undefined\n const evidence = result.evidence\n ? Object.freeze({\n ...result.evidence,\n readDeniedPaths: Object.freeze([...result.evidence.readDeniedPaths]),\n policy: Object.freeze({ ...result.evidence.policy }),\n })\n : undefined\n return Object.freeze({\n exitCode: result.exitCode,\n stdout: result.stdout,\n stderr: result.stderr,\n killedBySignal: result.killedBySignal,\n durationMs: result.durationMs,\n timedOut: result.timedOut,\n ...(usage ? { usage } : {}),\n ...(evidence ? { evidence } : {}),\n })\n}\n\nfunction shotReceipt(input: {\n readonly generation: number | undefined\n readonly candidateIndex: number | undefined\n readonly shot: number\n readonly maxShots: number\n readonly harness: LocalHarness\n readonly profile: AgentProfile | undefined\n readonly prompt: string\n readonly startedAt: Date\n readonly completedAt: Date\n readonly result: AgenticGeneratorShotExecution | null\n readonly profileWorkspaceReceipt: WorkspacePlanReceipt | null\n readonly costCallId: string | null\n readonly costReceipt: CostReceipt | null\n readonly error: unknown\n}): AgenticGeneratorShotReceipt {\n const error = input.error\n ? {\n name: input.error instanceof Error ? input.error.name : 'Error',\n message: input.error instanceof Error ? input.error.message : String(input.error),\n }\n : null\n const result = input.result\n const costBasis = costBasisFor(input.costReceipt)\n return {\n schemaVersion: 1,\n generation: input.generation ?? null,\n candidateIndex: input.candidateIndex ?? null,\n shot: input.shot + 1,\n maxShots: input.maxShots,\n harness: input.harness,\n model: input.profile?.model?.default ?? null,\n reasoningEffort: input.profile?.model?.reasoningEffort ?? null,\n promptSha256: sha256(input.prompt),\n startedAt: input.startedAt.toISOString(),\n completedAt: input.completedAt.toISOString(),\n durationMs: result?.durationMs ?? input.completedAt.getTime() - input.startedAt.getTime(),\n exitCode: result?.exitCode ?? null,\n timedOut: result?.timedOut ?? false,\n killedBySignal: result?.killedBySignal ?? null,\n stdoutBytes: result ? Buffer.byteLength(result.stdout) : null,\n stdoutSha256: result ? sha256(result.stdout) : null,\n stderrBytes: result ? Buffer.byteLength(result.stderr) : null,\n stderrSha256: result ? sha256(result.stderr) : null,\n usage: result?.usage ? { ...result.usage } : null,\n profileWorkspacePlanDigest: input.profileWorkspaceReceipt?.workspacePlanDigest ?? null,\n profileWorkspaceFileCount: input.profileWorkspaceReceipt?.written.length ?? 0,\n costCallId: input.costCallId,\n costBasis,\n costUsd: costBasis === 'unknown' ? null : (input.costReceipt?.costUsd ?? null),\n costUsdKnown: costBasis === 'provider-reported',\n evidence: result?.evidence\n ? {\n ...result.evidence,\n readDeniedPaths: [...result.evidence.readDeniedPaths],\n policy: { ...result.evidence.policy },\n }\n : null,\n error,\n }\n}\n\nfunction costBasisFor(receipt: CostReceipt | null): AgenticGeneratorShotReceipt['costBasis'] {\n if (receipt === null || receipt.costUnknown) return 'unknown'\n return receipt.actualCostUsd === undefined ? 'estimated-pricing' : 'provider-reported'\n}\n\nfunction shotFailure(\n result: LocalHarnessResult,\n exactPrompt: string,\n codexReproducible: boolean,\n): Error | null {\n if (result.timedOut) {\n return new Error('agenticGenerator: author shot timed out')\n }\n if (result.killedBySignal) {\n return new Error(`agenticGenerator: author shot was killed by ${result.killedBySignal}`)\n }\n if (result.exitCode !== 0) {\n return new Error(`agenticGenerator: author shot exited with code ${String(result.exitCode)}`)\n }\n if (!codexReproducible) return null\n if (!result.usage || !result.evidence) {\n return new Error(\n 'agenticGenerator: reproducible Codex shot completed without usage or execution evidence',\n )\n }\n const expectedPromptSha256 = sha256(exactPrompt).slice('sha256:'.length)\n if (result.evidence.requestedPromptSha256 !== expectedPromptSha256) {\n return new Error(\n 'agenticGenerator: reproducible Codex prompt evidence does not match the exact authored prompt',\n )\n }\n return null\n}\n\nfunction costReceiptFromHarness(result: LocalHarnessResult, model: string): CostReceiptInput {\n if (!result.usage) {\n throw new Error('agenticGenerator: author shot did not report terminal token usage')\n }\n return {\n model,\n inputTokens: result.usage.inputTokens - result.usage.cachedInputTokens,\n outputTokens: result.usage.outputTokens,\n ...(result.usage.cachedInputTokens > 0 ? { cachedTokens: result.usage.cachedInputTokens } : {}),\n }\n}\n\nfunction sha256(value: string): `sha256:${string}` {\n return `sha256:${createHash('sha256').update(value).digest('hex')}`\n}\n\n/** Turn the analyst's findings (+ optional report) into a concrete coder task. */\nfunction defaultBuildPrompt(args: { report: unknown; findings: AnalystFinding[] }): string {\n const lines: string[] = [\n 'You are improving this codebase based on an evaluation analysis.',\n 'Make the smallest set of edits that addresses the findings below, then stop.',\n 'Do not change unrelated code. Do not commit — leave changes in the working tree.',\n '',\n 'Findings:',\n ]\n for (const f of args.findings) {\n const where = f.subject ? ` [${f.subject}]` : ''\n lines.push(`- (${f.severity})${where} ${f.claim}`)\n if (f.recommended_action) lines.push(` → ${f.recommended_action}`)\n }\n if (requiresRawTraceEvidence(args.findings)) {\n lines.push(\n '',\n 'Raw trace evidence requirement:',\n `- Inspect at least one raw trace path named above before editing.`,\n `- Write ${RAW_TRACE_DIAGNOSIS_PATH} in this worktree.`,\n '- Include the exact trace path(s) inspected, the failure mechanism, and the code change made.',\n '- A candidate without this file, or with only this file changed, is discarded.',\n )\n }\n return lines.join('\\n')\n}\n\nconst EMPTY_TREE_NOTE =\n 'NOTE: your previous attempt left the working tree unchanged. Make the concrete file edits now.'\n\n/** Next-shot feedback when the worktree is dirty but failed verification. The\n * edits persist on disk, so the harness resumes atop them — tell it to fix in\n * place, not start over. Verifier detail is truncated to keep the prompt bounded. */\nfunction failureNote(feedback?: string): string {\n const detail = feedback?.trim()\n return [\n 'NOTE: your edits are in the working tree but verification FAILED.',\n 'Fix the problem in place — build on your existing edits, do not revert them.',\n detail ? `Verifier output:\\n${truncate(detail, 4000)}` : 'No verifier detail was captured.',\n ].join('\\n')\n}\n\nfunction rawTraceEvidenceProblem(worktreePath: string, findings: AnalystFinding[]): string | null {\n const changedPaths = worktreeChangedPaths(worktreePath)\n const substantive = changedPaths.filter((path) => path !== RAW_TRACE_DIAGNOSIS_PATH)\n if (substantive.length === 0) {\n return [\n `NOTE: raw-trace mode requires a real code/config edit in addition to ${RAW_TRACE_DIAGNOSIS_PATH}.`,\n 'Your previous attempt only changed the diagnosis artifact. Inspect the cited traces and make the causal code change.',\n ].join('\\n')\n }\n\n const diagnosisPath = join(worktreePath, RAW_TRACE_DIAGNOSIS_PATH)\n if (!existsSync(diagnosisPath)) {\n return [\n `NOTE: raw-trace mode requires ${RAW_TRACE_DIAGNOSIS_PATH}.`,\n 'Before retrying, inspect at least one cited spans.jsonl/cached-result.json/artifact path, then write the diagnosis file with the exact path, failure mechanism, and code change.',\n ].join('\\n')\n }\n\n const body = readFileSync(diagnosisPath, 'utf8')\n const evidencePaths = traceEvidencePaths(findings)\n if (evidencePaths.length > 0 && !evidencePaths.some((path) => body.includes(path))) {\n return [\n `${RAW_TRACE_DIAGNOSIS_PATH} exists, but it does not cite any exact raw trace path from the findings.`,\n `Cite at least one of these inspected paths exactly: ${evidencePaths.slice(0, 5).join(', ')}`,\n ].join('\\n')\n }\n\n return null\n}\n\nfunction requiresRawTraceEvidence(findings: AnalystFinding[]): boolean {\n return findings.some((finding) => {\n const f = finding as unknown as Record<string, unknown>\n return f.analyst_id === RAW_TRACE_ANALYST_ID || f.area === RAW_TRACE_AREA\n })\n}\n\nfunction traceEvidencePaths(findings: AnalystFinding[]): string[] {\n const out: string[] = []\n for (const finding of findings) {\n const refs = (finding as unknown as { evidence_refs?: unknown }).evidence_refs\n if (!Array.isArray(refs)) continue\n for (const ref of refs) {\n if (!ref || typeof ref !== 'object') continue\n const uri = (ref as { uri?: unknown }).uri\n if (typeof uri === 'string' && uri.length > 0) out.push(uri)\n }\n }\n return [...new Set(out)]\n}\n\n/** A `Verifier` that runs a command in the worktree: exit 0 ⇒ ok, any other\n * exit ⇒ failed with stdout+stderr as feedback. The common case — verify by\n * `tsc --noEmit`, `pnpm build`, or a test command. A timeout is treated as a\n * FAILED candidate (a change that hangs the build is a bad change); a missing\n * binary or spawn fault throws (a setup bug, not a failed candidate — no\n * silent fallback). */\nexport function commandVerifier(\n command: string,\n args: string[] = [],\n timeoutMs = 300_000,\n): Verifier {\n return (worktreePath: string): VerifyResult => {\n const result = spawnSync(command, args, {\n cwd: worktreePath,\n encoding: 'utf-8',\n timeout: timeoutMs,\n })\n if (result.signal) {\n return {\n ok: false,\n feedback: `verifier '${command}' killed by ${result.signal} (likely timeout after ${timeoutMs}ms)`,\n }\n }\n if (result.error) {\n const code = (result.error as NodeJS.ErrnoException).code\n if (code === 'ENOENT') {\n throw new Error(\n `commandVerifier: '${command}' not found in PATH (setup bug, not a failed candidate)`,\n )\n }\n throw new Error(`commandVerifier: '${command}' failed to spawn: ${result.error.message}`)\n }\n if (result.status === 0) return { ok: true }\n const out = `${result.stdout ?? ''}${result.stderr ?? ''}`.trim()\n return { ok: false, feedback: out.length > 0 ? out : `exit ${result.status}` }\n }\n}\n\n/** A one-line summary for the commit message, derived from the findings. */\nfunction summarize(findings: AnalystFinding[]): string {\n if (findings.length === 0) return 'agentic improvement'\n if (findings.length === 1) return `agentic: ${truncate(findings[0]!.claim, 64)}`\n return `agentic: ${findings.length} findings addressed`\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`\n}\n\n/** Non-empty `git status --porcelain` ⇒ the harness changed the worktree.\n * Fails loud: the worktree is a fresh checkout, so a git error here means\n * something is genuinely broken (git missing, corrupt index, killed mid-run).\n * Folding that into `false` would silently discard a candidate and mask the\n * real failure — forbidden by the no-silent-fallbacks doctrine. */\nfunction worktreeDirty(worktreePath: string): boolean {\n return worktreeChangedPaths(worktreePath).length > 0\n}\n\nfunction worktreeChangedPaths(worktreePath: string): string[] {\n const result = spawnSync('git', ['status', '--porcelain', '--untracked-files=all'], {\n cwd: worktreePath,\n encoding: 'utf-8',\n })\n if (result.error) {\n throw new Error(\n `agenticGenerator: git status failed to spawn in ${worktreePath}: ${result.error.message}`,\n )\n }\n if (result.status !== 0) {\n throw new Error(\n `agenticGenerator: git status exited ${result.status} in ${worktreePath}: ${result.stderr.trim()}`,\n )\n }\n return result.stdout\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => line.slice(3).trim())\n}\n"],"mappings":";;;;;;AAkCA,SAAS,iBAAiB;AAC1B,SAAS,kBAAkB;AAC3B,SAAS,YAAY,cAAc,cAAc;AACjD,SAAS,MAAM,SAAS,WAAW;AASnC;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAWP,IAAM,uBAAuB;AAC7B,IAAM,iBAAiB;AACvB,IAAM,2BAA2B;AAI1B,IAAM,gCAAgC;AA2ItC,SAAS,iBAAiB,OAAgC,CAAC,GAAuB;AACvF,QAAM,UAAU,KAAK,WAAW;AAChC,MAAI,KAAK,qBAAqB,YAAY,SAAS;AACjD,UAAM,IAAI,MAAM,8DAA8D;AAAA,EAChF;AACA,MAAI,KAAK,qBAAqB,CAAC,KAAK,SAAS;AAC3C,UAAM,IAAI,MAAM,yEAAyE;AAAA,EAC3F;AACA,MAAI,KAAK,wBAAwB,CAAC,KAAK,mBAAmB;AACxD,UAAM,IAAI,MAAM,mEAAmE;AAAA,EACrF;AACA,MAAI,KAAK,iBAAiB,CAAC,KAAK,mBAAmB;AACjD,UAAM,IAAI,MAAM,4DAA4D;AAAA,EAC9E;AACA,QAAM,sBAAsB,KAAK,oBAC7B,0BAA0B,KAAK,OAAuB,IACtD;AACJ,QAAM,cAAc,KAAK,eAAe;AACxC,QAAM,MAAM,KAAK,cAAc;AAC/B,QAAM,QAAQ,KAAK,WAAW;AAC9B,QAAM,SAAS,KAAK;AAEpB,SAAO;AAAA,IACL,MAAM,WAAW,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAMxB,yBAAyB;AAAA,IACzB,MAAM,SAAS;A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EAAE,IAAI,OAAO,UAAU,IAAI,SAAS,IAAI,MAAM,QAAQ,OAAO,MAAM,GAAG;AAAA,EAC/E;AACF;AAGA,SAAS,UAAU,UAAoC;AACrD,MAAI,SAAS,WAAW,EAAG,QAAO;AAClC,MAAI,SAAS,WAAW,EAAG,QAAO,YAAY,SAAS,SAAS,CAAC,EAAG,OAAO,EAAE,CAAC;AAC9E,SAAO,YAAY,SAAS,MAAM;AACpC;AAEA,SAAS,SAAS,GAAW,GAAmB;AAC9C,SAAO,EAAE,UAAU,IAAI,IAAI,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC,CAAC;AACjD;AAOA,SAAS,cAAc,cAA+B;AACpD,SAAO,qBAAqB,YAAY,EAAE,SAAS;AACrD;AAEA,SAAS,qBAAqB,cAAgC;AAC5D,QAAM,SAAS,UAAU,OAAO,CAAC,UAAU,eAAe,uBAAuB,GAAG;AAAA,IAClF,KAAK;AAAA,IACL,UAAU;AAAA,EACZ,CAAC;AACD,MAAI,OAAO,OAAO;AAChB,UAAM,IAAI;AAAA,MACR,mDAAmD,YAAY,KAAK,OAAO,MAAM,OAAO;AAAA,IAC1F;AAAA,EACF;AACA,MAAI,OAAO,WAAW,GAAG;AACvB,UAAM,IAAI;AAAA,MACR,uCAAuC,OAAO,MAAM,OAAO,YAAY,KAAK,OAAO,OAAO,KAAK,CAAC;AAAA,IAClG;AAAA,EACF;AACA,SAAO,OAAO,OACX,MAAM,IAAI,EACV,IAAI,CAAC,SAAS,KAAK,KAAK,CAAC,EACzB,OAAO,CAAC,SAAS,KAAK,SAAS,CAAC,EAChC,IAAI,CAAC,SAAS,KAAK,MAAM,CAAC,EAAE,KAAK,CAAC;AACvC;","names":["receipt","result"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/candidate-execution/builder.ts","../src/candidate-execution/claim-file-store.ts","../src/candidate-execution/dispose.ts","../src/candidate-execution/protected-model-port.ts","../src/candidate-execution/recover.ts","../src/candidate-execution/workspace-archive.ts"],"sourcesContent":["import type { CodeSurface } from '@tangle-network/agent-eval/campaign'\nimport { verifyCodeSurface } from '@tangle-network/agent-eval/campaign'\nimport type {\n AgentCandidateCodeDisabled,\n AgentCandidateCodeNoOp,\n AgentCandidateExecution,\n AgentCandidateGitHubRepository,\n AgentCandidateKnowledge,\n AgentCandidateLineage,\n AgentCandidateMemoryPolicy,\n AgentCandidateProfile,\n AgentProfile,\n AgentProfileDiff,\n} from '@tangle-network/agent-interface'\nimport { type AgentCandidateBundleInput, sealAgentCandidateBundle } from './bundle'\nimport { canonicalCandidateDigest, embeddedCandidateArtifact } from './digest'\nimport {\n applyExactAgentProfileDiff,\n freezeGenericAgentCandidateProfile,\n parseExactAgentProfile,\n parseExactAgentProfileDiff,\n parseExactCandidateProfile,\n} from './profile'\n\n/** A complete profile that can be frozen without losing behavior. */\nexport type AgentCandidateProfileSource =\n | {\n kind: 'profile'\n profile: AgentProfile\n }\n | {\n kind: 'profile-diffs'\n base: AgentProfile\n /** Applied in order. Each exact diff is content-addressed into lineage. */\n diffs: readonly AgentProfileDiff[]\n }\n | {\n kind: 'candidate-profile'\n /** Already converted to the closed, secret-free candidate profile contract. */\n profile: AgentCandidateProfile\n }\n\n/** The only accepted path from an agent-eval code candidate to executable bytes. */\nexport interface AgentCandidateCodeSurfaceSource {\n kind: 'code-surface'\n surface: CodeSurface\n repository: AgentCandidateGitHubRepository\n /** Optional parent directory used to resolve a relative `surface.worktreeRef`. */\n worktreeDir?: string\n}\n\n/** Explicit control/no-op code or one finalized CodeSurface whose bytes must still verify. */\nexport type AgentCandidateCodeSource =\n | AgentCandidateCodeDisabled\n | AgentCandidateCodeNoOp\n | AgentCandidateCodeSurfaceSource\n\n/** Complete measured surfaces and execution policy compiled into one candidate bundle. */\nexport interface BuildAgentCandidateBundleInput {\n profile: AgentCandidateProfileSource\n code: AgentCandidateCodeSource\n execution: AgentCandidateExecution\n knowledge?: AgentCandidateKnowledge\n memory: AgentCandidateMemoryPolicy\n /** `profileDiffIds` is derived from `profile`; callers cannot contradict it. */\n lineage: Omit<AgentCandidateLineage, 'profileDiffIds'>\n}\n\n/**\n * Compile one measured profile/code candidate into the immutable execution\n * contract. Code bytes are re-read and verified by agent-eval before they are\n * embedded. The returned bundle is schema-validated, canonically digested, and\n * deeply immutable; call `verifyAgentCandidateBundle` at the execution boundary\n * to re-read external knowledge, memory, repository, and workspace artifacts.\n */\nexport function buildAgentCandidateBundle(\n input: BuildAgentCandidateBundleInput,\n): ReturnType<typeof sealAgentCandidateBundle> {\n if (Object.hasOwn(input.lineage, 'profileDiffIds')) {\n throw new Error('profileDiffIds is derived from the profile source and cannot be supplied')\n }\n const compiledProfile = compileCandidateProfile(input.profile)\n const profileDiffIds = compiledProfile.profileDiffIds\n const bundle: AgentCandidateBundleInput = {\n schemaVersion: 1,\n kind: 'agent-candidate-bundle',\n digestAlgorithm: 'rfc8785-sha256',\n profile: compiledProfile.profile,\n code: compileCandidateCode(input.code),\n execution: input.execution,\n ...(input.knowledge ? { knowledge: input.knowledge } : {}),\n memory: input.memory,\n lineage: {\n ...input.lineage,\n ...(profileDiffIds.length > 0 ? { profileDiffIds } : {}),\n },\n }\n return sealAgentCandidateBundle(bundle)\n}\n\nfunction compileCandidateProfile(source: AgentCandidateProfileSource): {\n profile: AgentCandidateProfile\n profileDiffIds: string[]\n} {\n if (source.kind === 'candidate-profile') {\n return {\n profile: parseExactCandidateProfile(source.profile),\n profileDiffIds: [],\n }\n }\n\n if (source.kind === 'profile') {\n return { profile: freezeGenericAgentCandidateProfile(source.profile), profileDiffIds: [] }\n }\n\n if (source.kind !== 'profile-diffs') {\n throw new Error(\n `unsupported candidate profile source: ${String((source as { kind?: unknown }).kind)}`,\n )\n }\n if (source.diffs.length === 0) {\n throw new Error('profile-diffs source requires at least one AgentProfileDiff')\n }\n let profile = parseExactAgentProfile(source.base, 'base profile')\n const profileDiffIds: string[] = []\n for (const [index, inputDiff] of source.diffs.entries()) {\n const diff = parseExactAgentProfileDiff(inputDiff, `profile diff ${index}`)\n profile = applyExactAgentProfileDiff(profile, diff, `profile diff ${index}`)\n profileDiffIds.push(canonicalCandidateDigest(diff))\n }\n return { profile: freezeGenericAgentCandidateProfile(profile), profileDiffIds }\n}\n\nfunction compileCandidateCode(source: AgentCandidateCodeSource): AgentCandidateBundleInput['code'] {\n if (source.kind === 'disabled' || source.kind === 'no-op') return source\n if (source.kind !== 'code-surface') {\n throw new Error(\n `unsupported candidate code source: ${String((source as { kind?: unknown }).kind)}`,\n )\n }\n\n const verified = verifyCodeSurface(source.surface, source.worktreeDir)\n const patch = embeddedCandidateArtifact(verified.patchBytes)\n if (\n patch.sha256 !== source.surface.patch.sha256 ||\n patch.byteLength !== source.surface.patch.byteLength\n ) {\n throw new Error('verified CodeSurface patch bytes do not match its content identity')\n }\n return {\n kind: 'git-patch',\n repository: source.repository,\n baseCommit: source.surface.baseCommit,\n baseTree: source.surface.baseTree,\n candidateTree: source.surface.candidateTree,\n patch: { format: 'git-diff-binary', artifact: patch },\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { linkSync } from 'node:fs'\nimport { mkdir, open, unlink } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type { Sha256Digest } from '@tangle-network/agent-interface'\n\nimport {\n type AgentCandidateExecutionAttemptRecord,\n type AgentCandidateExecutionAttemptRef,\n type AgentCandidateExecutionClaim,\n type AgentCandidateExecutionClaimResult,\n type AgentCandidateExecutionClaimStore,\n type AgentCandidateExecutionFinishResult,\n type AgentCandidateExecutionLease,\n type AgentCandidateExecutionPhase,\n type AgentCandidateExecutionPhaseResult,\n type AgentCandidateExecutionRecoveryEvidence,\n type AgentCandidateExecutionStageResult,\n type AgentCandidateExecutionTerminalRecord,\n type AgentCandidateExecutionTerminalResult,\n type AgentCandidateRetryRejection,\n candidateClaimFileInternals,\n} from './claim'\nimport {\n CLAIM_FORMAT_VERSION,\n PENDING_FORMAT_VERSION,\n PHASE_FORMAT_VERSION,\n TERMINAL_FORMAT_VERSION,\n} from './claim-file-formats'\nimport {\n assertRecoveryMatchesStaged,\n assertTerminalAllowedInPhase,\n assertTerminalMatchesClaim,\n assertTerminalMatchesStaged,\n recoveredTerminalRecord,\n rejectedFinish,\n rejectedStage,\n requireStagedTerminal,\n sealTerminalDigest,\n terminalRecord,\n} from './claim-terminal'\nimport { canonicalCandidateBytes } from './digest'\n\nconst {\n assertExpiredLease,\n assertLease,\n assertSameSlot,\n assertUnexpiredLease,\n attemptRecord,\n claimSlot,\n leaseDigest,\n newLease,\n readClaim,\n readClaimIfPresent,\n readTerminal,\n readTerminalIfPresent,\n readTransitionIfPresent,\n rejectedExistingClaim,\n rejectedRetry,\n retryRejection,\n sealAttemptRef,\n sealClaim,\n sealLease,\n} = candidateClaimFileInternals\n\nexport interface FileAgentCandidateExecutionClaimStoreOptions {\n /** Evaluator-owned directory shared by every process allowed to execute candidates. */\n directory: string\n /** Testable evaluator clock; defaults to `Date.now`. */\n now?: () => number\n}\n\n/** Cross-process lifecycle implemented as fsynced, create-if-absent records. */\nexport class FileAgentCandidateExecutionClaimStore implements AgentCandidateExecutionClaimStore {\n private readonly directory: string\n private readonly now: () => number\n\n constructor(options: FileAgentCandidateExecutionClaimStoreOptions) {\n if (options.directory.length === 0) {\n throw new Error('candidate execution claim directory must not be empty')\n }\n this.directory = options.directory\n this.now = options.now ?? Date.now\n }\n\n async tryClaim(\n requested: AgentCandidateExecutionClaim,\n ): Promise<AgentCandidateExecutionClaimResult> {\n const claim = sealClaim(requested)\n await mkdir(this.directory, { recursive: true })\n const claimPath = this.claimPath(claim)\n const existing = await readClaimIfPresent(claimPath)\n if (existing) {\n assertSameSlot(existing.claim, claim, claimPath)\n return rejectedExistingClaim(existing.claim, claim)\n }\n assertUnexpiredLease(claim.leaseExpiresAtMs, this.now())\n const retryFailure = await this.retryFailure(claim)\n if (retryFailure) return rejectedRetry(claim, retryFailure)\n\n const lease = newLease(claim)\n const acquired = await writeRecordIfAbsent(this.directory, claimPath, {\n version: CLAIM_FORMAT_VERSION,\n ...claim,\n phase: 'claimed',\n leaseDigest: leaseDigest(lease),\n })\n if (acquired) return Object.freeze({ acquired: true, claim, lease })\n\n const winner = await readClaim(claimPath)\n assertSameSlot(winner.claim, claim, claimPath)\n return rejectedExistingClaim(winner.claim, claim)\n }\n\n async getAttempt(\n requestedAttempt: AgentCandidateExecutionAttemptRef,\n ): Promise<AgentCandidateExecutionAttemptRecord | undefined> {\n return await this.storedAttempt(sealAttemptRef(requestedAttempt))\n }\n\n async markCandidateMayRun(\n requestedLease: AgentCandidateExecutionLease,\n ): Promise<AgentCandidateExecutionPhaseResult> {\n const lease = sealLease(requestedLease)\n const claimPath = this.claimPath(lease)\n const stored = await readClaim(claimPath)\n assertSameSlot(stored.claim, lease, claimPath)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const state = await this.transitionState(stored.claim)\n if (state.phase === 'candidate-may-run') {\n return Object.freeze({ marked: false, phase: 'candidate-may-run' })\n }\n if (state.staged) {\n throw new Error('candidate execution terminal was staged before candidate-may-run phase')\n }\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const marked = await writeRecordIfAbsent(\n this.directory,\n this.transitionPath(stored.claim, 1),\n {\n version: PHASE_FORMAT_VERSION,\n kind: 'candidate-execution-phase',\n executionId: stored.claim.executionId,\n attempt: stored.claim.attempt,\n executionPlanDigest: stored.claim.executionPlanDigest,\n phase: 'candidate-may-run',\n },\n this.ownerPublication(stored.claim),\n )\n if (marked) return Object.freeze({ marked: true, phase: 'candidate-may-run' })\n const winner = await this.transitionState(stored.claim)\n if (winner.phase === 'candidate-may-run') {\n return Object.freeze({ marked: false, phase: 'candidate-may-run' })\n }\n throw new Error('candidate execution terminal was staged before candidate-may-run phase')\n }\n\n async stageTerminal(\n requestedLease: AgentCandidateExecutionLease,\n result: AgentCandidateExecutionTerminalResult,\n ): Promise<AgentCandidateExecutionStageResult> {\n const lease = sealLease(requestedLease)\n const claimPath = this.claimPath(lease)\n const stored = await readClaim(claimPath)\n assertSameSlot(stored.claim, lease, claimPath)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const terminal = terminalRecord(stored.claim, result)\n const state = await this.transitionState(stored.claim)\n if (state.staged) return rejectedStage(state.staged, terminal)\n assertTerminalAllowedInPhase(state.phase, terminal)\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const transition = state.phase === 'claimed' ? 1 : 2\n const staged = await writeRecordIfAbsent(\n this.directory,\n this.transitionPath(stored.claim, transition),\n {\n version: PENDING_FORMAT_VERSION,\n kind: 'candidate-execution-pending-terminal',\n terminal,\n },\n this.ownerPublication(stored.claim),\n )\n if (staged) return Object.freeze({ staged: true, terminal })\n const winner = await this.transitionState(stored.claim)\n if (!winner.staged) {\n throw new Error('candidate execution phase transition won while staging terminal')\n }\n return rejectedStage(winner.staged, terminal)\n }\n\n async finish(\n requestedLease: AgentCandidateExecutionLease,\n requestedTerminalDigest: Sha256Digest,\n ): Promise<AgentCandidateExecutionFinishResult> {\n const lease = sealLease(requestedLease)\n const terminalDigest = sealTerminalDigest(requestedTerminalDigest)\n const claimPath = this.claimPath(lease)\n const stored = await readClaim(claimPath)\n assertSameSlot(stored.claim, lease, claimPath)\n assertLease(stored.leaseDigest, stored.claim.leaseExpiresAtMs, lease)\n const state = await this.transitionState(stored.claim)\n const staged = requireStagedTerminal(state.staged, terminalDigest)\n const terminalPath = this.terminalPath(lease)\n const existing = await readTerminalIfPresent(terminalPath)\n if (existing) {\n assertTerminalMatchesClaim(existing, stored.claim, terminalPath)\n assertTerminalMatchesStaged(existing, staged, terminalPath)\n return rejectedFinish(existing, terminalDigest)\n }\n assertUnexpiredLease(stored.claim.leaseExpiresAtMs, this.now())\n const finished = await writeRecordIfAbsent(\n this.directory,\n terminalPath,\n {\n version: TERMINAL_FORMAT_VERSION,\n terminal: staged,\n },\n this.ownerPublication(stored.claim),\n )\n if (finished) return Object.freeze({ finished: true, terminal: staged })\n const winner = await readTerminal(terminalPath)\n assertSameSlot(winner, lease, terminalPath)\n assertTerminalMatchesClaim(winner, stored.claim, terminalPath)\n assertTerminalMatchesStaged(winner, staged, terminalPath)\n return rejectedFinish(winner, terminalDigest)\n }\n\n async recoverExpired(\n requestedAttempt: AgentCandidateExecutionAttemptRef,\n evidence: AgentCandidateExecutionRecoveryEvidence,\n ): Promise<AgentCandidateExecutionFinishResult> {\n const attempt = sealAttemptRef(requestedAttempt)\n const record = await this.storedAttempt(attempt)\n if (!record) throw new Error('candidate execution recovery does not name an acquired attempt')\n const recovered = recoveredTerminalRecord(record.claim, record.phase, evidence)\n if (record.staged) assertRecoveryMatchesStaged(record.staged, recovered)\n const requestedDigest = record.staged?.terminalDigest ?? recovered.terminalDigest\n if (record.terminal) return rejectedFinish(record.terminal, requestedDigest)\n assertExpiredLease(record.claim.leaseExpiresAtMs, this.now())\n\n let staged = record.staged\n if (!staged) {\n const transition = record.phase === 'claimed' ? 1 : 2\n const didStage = await writeRecordIfAbsent(\n this.directory,\n this.transitionPath(record.claim, transition),\n {\n version: PENDING_FORMAT_VERSION,\n kind: 'candidate-execution-pending-terminal',\n terminal: recovered,\n },\n )\n if (didStage) {\n staged = recovered\n } else {\n const winner = await this.transitionState(record.claim)\n if (!winner.staged) {\n throw new Error(\n 'candidate execution recovery lost terminal staging to a phase transition',\n )\n }\n assertRecoveryMatchesStaged(winner.staged, recovered)\n staged = winner.staged\n }\n }\n\n const terminalPath = this.terminalPath(attempt)\n const didFinish = await writeRecordIfAbsent(this.directory, terminalPath, {\n version: TERMINAL_FORMAT_VERSION,\n terminal: staged,\n })\n if (didFinish) return Object.freeze({ finished: true, terminal: staged })\n const winner = await readTerminal(terminalPath)\n assertSameSlot(winner, attempt, terminalPath)\n assertTerminalMatchesClaim(winner, record.claim, terminalPath)\n assertTerminalMatchesStaged(winner, staged, terminalPath)\n return rejectedFinish(winner, staged.terminalDigest)\n }\n\n private async storedAttempt(\n claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n ): Promise<AgentCandidateExecutionAttemptRecord | undefined> {\n const claimPath = this.claimPath(claim)\n const stored = await readClaimIfPresent(claimPath)\n if (!stored) return undefined\n assertSameSlot(stored.claim, claim, claimPath)\n const state = await this.transitionState(stored.claim)\n const terminalPath = this.terminalPath(claim)\n const terminal = await readTerminalIfPresent(terminalPath)\n if (terminal) {\n assertTerminalMatchesClaim(terminal, stored.claim, terminalPath)\n if (!state.staged) {\n throw new Error(\n `candidate execution terminal record at ${terminalPath} has no staged outbox`,\n )\n }\n assertTerminalMatchesStaged(terminal, state.staged, terminalPath)\n }\n return attemptRecord(stored.claim, state.phase, state.staged, terminal)\n }\n\n private async transitionState(claim: AgentCandidateExecutionClaim): Promise<{\n phase: AgentCandidateExecutionPhase\n staged?: AgentCandidateExecutionTerminalRecord\n }> {\n const firstPath = this.transitionPath(claim, 1)\n const first = await readTransitionIfPresent(firstPath, claim)\n if (!first) return { phase: 'claimed' }\n if (first.kind === 'pending') return { phase: 'claimed', staged: first.terminal }\n const secondPath = this.transitionPath(claim, 2)\n const second = await readTransitionIfPresent(secondPath, claim)\n if (!second) return { phase: 'candidate-may-run' }\n if (second.kind !== 'pending') {\n throw new Error(`candidate execution transition at ${secondPath} repeats the phase marker`)\n }\n return { phase: 'candidate-may-run', staged: second.terminal }\n }\n\n private async retryFailure(\n claim: AgentCandidateExecutionClaim,\n ): Promise<AgentCandidateRetryRejection | undefined> {\n if (claim.attempt === 1) return undefined\n return retryRejection(\n claim,\n await this.storedAttempt({\n executionId: claim.executionId,\n attempt: claim.attempt - 1,\n }),\n )\n }\n\n private ownerPublication(claim: AgentCandidateExecutionClaim): {\n authorizePublish: () => true\n } {\n return {\n authorizePublish: () => {\n assertUnexpiredLease(claim.leaseExpiresAtMs, this.now())\n return true\n },\n }\n }\n\n private claimPath(claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>): string {\n return join(this.directory, `${claimSlot(claim)}.claim.json`)\n }\n\n private terminalPath(\n claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n ): string {\n return join(this.directory, `${claimSlot(claim)}.terminal.json`)\n }\n\n private transitionPath(\n claim: Pick<AgentCandidateExecutionClaim, 'executionId' | 'attempt'>,\n ordinal: 1 | 2,\n ): string {\n return join(this.directory, `${claimSlot(claim)}.transition-${ordinal}.json`)\n }\n}\n\nasync function writeRecordIfAbsent(\n directory: string,\n destination: string,\n record: object,\n options: {\n /** Synchronous authorization checked after temp fsync, immediately before atomic publication. */\n authorizePublish?: () => true\n } = {},\n): Promise<boolean> {\n const temporaryPath = join(directory, `.candidate-execution-${process.pid}-${randomUUID()}.tmp`)\n const handle = await open(temporaryPath, 'wx', 0o600)\n try {\n await handle.writeFile(\n Buffer.concat([Buffer.from(canonicalCandidateBytes(record)), Buffer.from('\\n')]),\n )\n await handle.sync()\n } finally {\n await handle.close()\n }\n\n let written = false\n try {\n if (options.authorizePublish && options.authorizePublish() !== true) {\n throw new Error('candidate execution record publication was not authorized')\n }\n // Authorization and the atomic filesystem call are one synchronous critical\n // section so the event loop cannot advance an injected lease clock between them.\n linkSync(temporaryPath, destination)\n written = true\n await syncDirectory(directory)\n } catch (error) {\n if (!isNodeError(error, 'EEXIST')) throw error\n } finally {\n await unlink(temporaryPath).catch((error: unknown) => {\n if (!isNodeError(error, 'ENOENT')) throw error\n })\n }\n return written\n}\n\nasync function syncDirectory(directory: string): Promise<void> {\n const handle = await open(directory, 'r')\n try {\n await handle.sync()\n } finally {\n await handle.close()\n }\n}\n\nfunction isNodeError(error: unknown, code: string): boolean {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as { code?: unknown }).code === code\n )\n}\n","import { candidateCleanupDeadline, withinCandidateCleanupDeadline } from './cleanup'\nimport { sealAgentCandidateModelSettlement } from './model-settlement'\nimport {\n assertPreparedCandidateIntegrity,\n beginPreparedCandidateDisposal,\n consumePreparedCandidateExecution,\n} from './prepared-state'\nimport type { PreparedAgentCandidateExecution } from './types'\n\nexport interface DisposePreparedAgentCandidateOptions {\n cleanupTimeoutMs?: number\n}\n\n/** Revoke reservations held by a prepared candidate that will not be executed. */\nexport async function disposePreparedAgentCandidateExecution(\n prepared: PreparedAgentCandidateExecution,\n options: DisposePreparedAgentCandidateOptions = {},\n): Promise<{ disposed: true }> {\n const initialState = assertPreparedCandidateIntegrity(prepared)\n const cleanupTimeoutMs = options.cleanupTimeoutMs ?? initialState.cleanupTimeoutMs\n if (cleanupTimeoutMs > initialState.cleanupTimeoutMs) {\n throw new Error('disposal cleanup timeout exceeds the frozen preparation bound')\n }\n const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs)\n const state = beginPreparedCandidateDisposal(prepared)\n const cleanup: Array<Promise<unknown>> = []\n\n if (state.memory.mode === 'isolated') {\n const reservation = state.memoryReservation\n if (!reservation) throw new Error('isolated memory reservation is missing')\n cleanup.push(\n withinCandidateCleanupDeadline(\n async () => {\n const closed = await state.ports.memory.close({\n executionId: state.executionId,\n preparationId: reservation.preparationId,\n accessDigest: reservation.accessDigest,\n effectiveNamespace: reservation.effectiveNamespace,\n reason: 'abandoned',\n })\n if (closed.closed !== true || Object.keys(closed).some((key) => key !== 'closed')) {\n throw new Error('abandoned isolated memory access did not acknowledge closure')\n }\n },\n cleanupDeadlineAtMs,\n 'isolated memory disposal',\n ),\n )\n }\n\n cleanup.push(\n withinCandidateCleanupDeadline(\n async () => {\n const settlement = sealAgentCandidateModelSettlement(\n await state.ports.models.settleGrant({\n executionId: state.executionId,\n preparationId: state.preparationId,\n grantDigest: state.modelReservation.digest,\n resolved: state.resolvedModel,\n reason: 'abandoned',\n }),\n {\n preparationId: state.preparationId,\n grantDigest: state.modelReservation.digest,\n model: state.resolvedModel.model,\n },\n )\n if (settlement.usage.modelCalls !== 0) {\n throw new Error('unexecuted model reservation unexpectedly contains calls')\n }\n },\n cleanupDeadlineAtMs,\n 'model reservation disposal',\n ),\n )\n\n const results = await Promise.allSettled(cleanup)\n const failures = results\n .filter((result): result is PromiseRejectedResult => result.status === 'rejected')\n .map((result) => result.reason)\n if (failures.length > 0) {\n consumePreparedCandidateExecution(prepared, 'disposal-failed')\n throw new AggregateError(failures, 'candidate preparation disposal failed')\n }\n\n consumePreparedCandidateExecution(prepared, 'disposed')\n return Object.freeze({ disposed: true as const })\n}\n","import type {\n AgentCandidateModelAccessNetwork,\n AgentCandidateResolvedModel,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue } from './digest'\nimport { assertExactObjectKeys } from './exact-object'\nimport { sealAgentCandidateModelSettlement, usdToNanos } from './model-settlement'\nimport type {\n AgentCandidateModelLimits,\n AgentCandidateModelPort,\n AgentCandidateProtectedModelActivation,\n AgentCandidateProtectedModelReservation,\n AgentCandidateProtectedModelSettlement,\n} from './types'\n\nexport type AgentCandidateModelGrantReserveInput = Parameters<\n AgentCandidateModelPort['reserveGrant']\n>[0]\nexport type AgentCandidateModelGrantActivateInput = Parameters<\n AgentCandidateModelPort['activateGrant']\n>[0]\nexport type AgentCandidateModelGrantSettleInput = Parameters<\n AgentCandidateModelPort['settleGrant']\n>[0]\n\n/** Secret-free response from the service's reservation endpoint. */\nexport type AgentCandidateModelGrantReservation = AgentCandidateProtectedModelReservation\n\n/**\n * Narrow transport contract for a service that owns scoped model credentials\n * and the authoritative per-call usage ledger.\n *\n * An HTTP client can bind these methods to control-plane endpoints. Keeping\n * transport out of the runtime prevents parent credentials, endpoint paths,\n * and retry policy from becoming part of the portable candidate contract.\n */\nexport interface AgentCandidateModelGrantClient {\n reserve(input: AgentCandidateModelGrantReserveInput): Promise<AgentCandidateModelGrantReservation>\n activate(\n input: AgentCandidateModelGrantActivateInput,\n ): Promise<AgentCandidateProtectedModelActivation>\n settle(\n input: AgentCandidateModelGrantSettleInput,\n ): Promise<AgentCandidateProtectedModelSettlement>\n}\n\nexport interface CreateProtectedAgentCandidateModelPortOptions {\n client: AgentCandidateModelGrantClient\n /** Catalog/snapshot resolution stays separate from credential issuance. */\n resolveModel: AgentCandidateModelPort['resolve']\n /** The only public DNS name candidate processes may reach for inference. */\n gatewayDomain: string\n /** Exact environment names the activation endpoint must return, no more or fewer. */\n activationEnvNames: readonly string[]\n}\n\ninterface RememberedReservation {\n requestDigest: Sha256Digest\n responseDigest: Sha256Digest\n executionId: string\n preparationId: string\n grantDigest: Sha256Digest\n expiresAtMs: number\n resolved: AgentCandidateResolvedModel\n limits: AgentCandidateModelLimits\n maxCostUsdNanos: number\n activation: 'reserved' | 'activating' | 'activated'\n settlementDigest?: Sha256Digest\n settlementReason?: AgentCandidateModelGrantSettleInput['reason']\n}\n\ninterface RememberedSettlement {\n settlementDigest: Sha256Digest\n settlementReason: AgentCandidateModelGrantSettleInput['reason']\n expiresAtMs: number\n}\n\nconst MAX_RECENT_SETTLEMENTS = 4_096\nconst RECOVERED_SETTLEMENT_RETENTION_MS = 15 * 60 * 1_000\n\n/**\n * Bind a protected model-grant service to the immutable candidate runtime.\n *\n * The service remains the authority for expiry, admission, revocation, and\n * metering. This adapter independently checks every response before allowing\n * it to cross into candidate execution or durable receipt finalization.\n */\nexport function createProtectedAgentCandidateModelPort(\n options: CreateProtectedAgentCandidateModelPortOptions,\n): AgentCandidateModelPort {\n const gatewayDomain = assertGatewayDomain(options.gatewayDomain)\n const activationEnvNames = exactEnvironmentNames(options.activationEnvNames)\n const reservations = new Map<string, RememberedReservation>()\n const recentSettlements = new Map<string, RememberedSettlement>()\n\n return {\n resolve: async (input) => {\n const request = immutableCandidateValue(input)\n const resolved = validateResolvedModel(await options.resolveModel(request), request)\n return immutableCandidateValue(resolved)\n },\n\n reserveGrant: async (input) => {\n pruneExpiredState(reservations, recentSettlements, Date.now())\n const request = immutableCandidateValue(input)\n validateReserveInput(request)\n const requestDigest = canonicalCandidateDigest(request)\n const key = reservationKey(request.executionId, request.preparationId)\n if (recentSettlements.has(key)) {\n throw new Error('protected model reservation is already settled')\n }\n const previous = reservations.get(key)\n if (previous && previous.requestDigest !== requestDigest) {\n throw new Error('protected model reservation retry changed immutable input')\n }\n\n const reservation = validateReservation(\n await options.client.reserve(request),\n request,\n gatewayDomain,\n )\n const responseDigest = canonicalCandidateDigest(reservation)\n if (recentSettlements.has(key)) {\n throw new Error('protected model reservation completed after the grant was settled')\n }\n const recorded = previous ?? reservations.get(key)\n if (recorded && recorded.requestDigest !== requestDigest) {\n throw new Error('protected model reservation retry changed immutable input')\n }\n if (recorded && recorded.responseDigest !== responseDigest) {\n throw new Error('protected model reservation retry returned different evidence')\n }\n if (!recorded) {\n reservations.set(key, {\n requestDigest,\n responseDigest,\n executionId: request.executionId,\n preparationId: request.preparationId,\n grantDigest: reservation.digest,\n expiresAtMs: request.expiresAtMs,\n resolved: immutableCandidateValue(request.resolved),\n limits: immutableCandidateValue(request.limits),\n maxCostUsdNanos: usdToNanos(request.limits.maxCostUsd, 'reserved maxCostUsd'),\n activation: 'reserved',\n })\n }\n return reservation\n },\n\n activateGrant: async (input) => {\n pruneExpiredState(reservations, recentSettlements, Date.now())\n const request = immutableCandidateValue(input)\n const key = reservationKey(request.executionId, request.preparationId)\n if (recentSettlements.has(key)) throw new Error('protected model grant is already settled')\n const state = reservations.get(key)\n if (!state) throw new Error('protected model grant was not reserved by this port')\n assertGrantIdentity(state, request)\n if (state.settlementDigest) throw new Error('protected model grant is already settled')\n if (state.activation !== 'reserved') {\n throw new Error('protected model grant activation is single-use')\n }\n if (!Number.isSafeInteger(request.deadlineAtMs) || request.deadlineAtMs <= 0) {\n throw new Error('protected model activation deadline must be a positive safe integer')\n }\n if (request.deadlineAtMs <= Date.now()) {\n throw new Error('protected model activation deadline must be in the future')\n }\n if (request.deadlineAtMs > state.expiresAtMs) {\n throw new Error('protected model activation deadline exceeds the reserved expiry')\n }\n state.activation = 'activating'\n try {\n const activation = validateActivation(\n await options.client.activate(request),\n state.limits.maxModelCalls === 0 ? [] : activationEnvNames,\n )\n if (recentSettlements.has(key) || reservations.get(key) !== state) {\n throw new Error('protected model grant settled while activation was in flight')\n }\n state.activation = 'activated'\n return activation\n } catch (error) {\n state.activation = 'reserved'\n throw error\n }\n },\n\n settleGrant: async (input) => {\n const now = Date.now()\n pruneExpiredState(reservations, recentSettlements, now)\n const request = immutableCandidateValue(input)\n const key = reservationKey(request.executionId, request.preparationId)\n const state = reservations.get(key)\n if (state) assertGrantIdentity(state, request)\n const remembered = state ?? recentSettlements.get(key)\n if (remembered?.settlementReason && remembered.settlementReason !== request.reason) {\n throw new Error('protected model settlement retry changed the termination reason')\n }\n\n const sealed = sealAgentCandidateModelSettlement(await options.client.settle(request), {\n preparationId: request.preparationId,\n grantDigest: request.grantDigest,\n model: request.resolved.model,\n })\n if (state) assertWithinReservedLimits(sealed.fixedUsage, state)\n\n const settlementDigest = canonicalCandidateDigest(sealed.value)\n if (remembered?.settlementDigest && remembered.settlementDigest !== settlementDigest) {\n throw new Error('protected model settlement retry returned a different final ledger')\n }\n if (remembered?.settlementReason && remembered.settlementReason !== request.reason) {\n throw new Error('protected model settlement retry changed the termination reason')\n }\n const expiresAtMs = state?.expiresAtMs ?? now + RECOVERED_SETTLEMENT_RETENTION_MS\n if (state) {\n state.settlementDigest = settlementDigest\n state.settlementReason = request.reason\n }\n reservations.delete(key)\n rememberSettlement(recentSettlements, key, {\n settlementDigest,\n settlementReason: request.reason,\n expiresAtMs,\n })\n return sealed.value\n },\n }\n}\n\nfunction validateReserveInput(input: AgentCandidateModelGrantReserveInput): void {\n if (!Number.isSafeInteger(input.expiresAtMs) || input.expiresAtMs <= 0) {\n throw new Error('protected model reservation expiry must be a positive safe integer')\n }\n if (input.expiresAtMs <= Date.now()) {\n throw new Error('protected model reservation expiry must be in the future')\n }\n for (const [name, value] of [\n ['maxModelCalls', input.limits.maxModelCalls],\n ['maxInputTokens', input.limits.maxInputTokens],\n ['maxOutputTokens', input.limits.maxOutputTokens],\n ] as const) {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`protected model reservation ${name} must be a nonnegative safe integer`)\n }\n }\n usdToNanos(input.limits.maxCostUsd, 'reserved maxCostUsd')\n}\n\nfunction validateReservation(\n value: unknown,\n expected: AgentCandidateModelGrantReserveInput,\n gatewayDomain: string,\n): AgentCandidateModelGrantReservation {\n const source = exactRecord(\n value,\n ['preparationId', 'digest', 'expiresAtMs', 'enforcedLimits', 'network'],\n 'protected model reservation response',\n )\n if (source.preparationId !== expected.preparationId) {\n throw new Error('protected model reservation response changed preparation identity')\n }\n if (!isSha256Digest(source.digest)) {\n throw new Error('protected model reservation response has an invalid digest')\n }\n if (source.expiresAtMs !== expected.expiresAtMs) {\n throw new Error('protected model reservation response changed expiry')\n }\n exactRecord(\n source.enforcedLimits,\n ['maxModelCalls', 'maxInputTokens', 'maxOutputTokens', 'maxCostUsd'],\n 'protected model reservation enforced limits',\n )\n if (\n canonicalCandidateDigest(source.enforcedLimits) !== canonicalCandidateDigest(expected.limits)\n ) {\n throw new Error('protected model reservation response changed enforced limits')\n }\n\n const network = validateReservationNetwork(\n source.network,\n expected.limits.maxModelCalls,\n gatewayDomain,\n )\n return immutableCandidateValue({\n preparationId: source.preparationId,\n digest: source.digest,\n expiresAtMs: source.expiresAtMs,\n enforcedLimits: source.enforcedLimits,\n network,\n }) as AgentCandidateModelGrantReservation\n}\n\nfunction validateReservationNetwork(\n value: unknown,\n maxModelCalls: number,\n gatewayDomain: string,\n): AgentCandidateModelAccessNetwork {\n if (maxModelCalls === 0) {\n const source = exactRecord(value, ['mode'], 'protected model reservation network')\n if (source.mode !== 'disabled') {\n throw new Error('zero-call protected model reservation must disable gateway access')\n }\n return { mode: 'disabled' }\n }\n\n const source = exactRecord(value, ['mode', 'domains'], 'protected model reservation network')\n if (source.mode !== 'gateway-only') {\n throw new Error('protected model reservation must allow only its model gateway')\n }\n if (\n !Array.isArray(source.domains) ||\n source.domains.length !== 1 ||\n source.domains[0] !== gatewayDomain\n ) {\n throw new Error('protected model reservation returned an unexpected gateway domain')\n }\n return { mode: 'gateway-only', domains: [gatewayDomain] }\n}\n\nfunction validateActivation(\n value: unknown,\n expectedNames: readonly string[],\n): AgentCandidateProtectedModelActivation {\n const source = exactRecord(value, ['env'], 'protected model activation response')\n const env = record(source.env, 'protected model activation environment')\n const actualNames = Object.keys(env).sort()\n if (\n actualNames.length !== expectedNames.length ||\n actualNames.some((name, index) => name !== expectedNames[index])\n ) {\n throw new Error('protected model activation returned unexpected environment names')\n }\n const detached: Record<string, string> = Object.create(null) as Record<string, string>\n for (const name of expectedNames) {\n const value = env[name]\n if (typeof value !== 'string' || value.length < 8 || value.length > 65_536) {\n throw new Error(`protected model activation ${name} must be a non-empty protected value`)\n }\n detached[name] = value\n }\n return Object.freeze({ env: Object.freeze(detached) })\n}\n\nfunction validateResolvedModel(\n value: unknown,\n expected: Parameters<AgentCandidateModelPort['resolve']>[0],\n): AgentCandidateResolvedModel {\n const source = exactRecord(\n value,\n ['requested', 'provider', 'model', 'snapshot', 'reasoningEffort'],\n 'resolved candidate model',\n )\n if (source.requested !== expected.requested) {\n throw new Error('model resolver changed the evaluator-owned request')\n }\n if (source.reasoningEffort !== expected.reasoningEffort) {\n throw new Error('model resolver changed the evaluator-owned reasoning effort')\n }\n for (const name of ['requested', 'provider', 'model', 'snapshot'] as const) {\n if (typeof source[name] !== 'string' || source[name].length === 0) {\n throw new Error(`resolved candidate model ${name} must be non-empty`)\n }\n }\n return source as unknown as AgentCandidateResolvedModel\n}\n\nfunction assertGrantIdentity(\n expected: RememberedReservation,\n actual: AgentCandidateModelGrantActivateInput | AgentCandidateModelGrantSettleInput,\n): void {\n if (\n actual.executionId !== expected.executionId ||\n actual.preparationId !== expected.preparationId ||\n actual.grantDigest !== expected.grantDigest ||\n canonicalCandidateDigest(actual.resolved) !== canonicalCandidateDigest(expected.resolved)\n ) {\n throw new Error('protected model grant input does not match its immutable reservation')\n }\n}\n\nfunction assertWithinReservedLimits(\n usage: {\n modelCalls: number\n inputTokens: number\n outputTokens: number\n costUsdNanos: number\n },\n reservation: RememberedReservation,\n): void {\n for (const [name, actual, limit] of [\n ['model calls', usage.modelCalls, reservation.limits.maxModelCalls],\n ['input tokens', usage.inputTokens, reservation.limits.maxInputTokens],\n ['output tokens', usage.outputTokens, reservation.limits.maxOutputTokens],\n ['cost USD nanos', usage.costUsdNanos, reservation.maxCostUsdNanos],\n ] as const) {\n if (actual > limit) {\n throw new Error(`protected model settlement ${name} ${actual} exceeds reserved ${limit}`)\n }\n }\n}\n\nfunction exactEnvironmentNames(values: readonly string[]): readonly string[] {\n if (values.length === 0) {\n throw new Error('protected model activation environment names must not be empty')\n }\n const names = [...values].sort()\n if (new Set(names).size !== names.length) {\n throw new Error('protected model activation environment names must be unique')\n }\n for (const name of names) {\n if (\n !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ||\n ['__proto__', 'constructor', 'prototype'].includes(name)\n ) {\n throw new Error(`protected model activation environment name is invalid: ${name}`)\n }\n }\n return Object.freeze(names)\n}\n\nfunction assertGatewayDomain(value: string): string {\n if (\n value.length > 253 ||\n value !== value.toLowerCase() ||\n value.endsWith('.') ||\n value.includes(':') ||\n value === 'localhost' ||\n value.endsWith('.localhost') ||\n value === 'metadata.google' ||\n value === 'metadata.google.internal'\n ) {\n throw new Error('protected model gateway must be an exact lowercase public DNS name')\n }\n const labels = value.split('.')\n if (\n labels.length < 2 ||\n !labels.every(\n (label) =>\n label.length >= 1 && label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label),\n ) ||\n !/[a-z]/.test(labels.at(-1) ?? '')\n ) {\n throw new Error('protected model gateway must be an exact lowercase public DNS name')\n }\n return value\n}\n\nfunction reservationKey(executionId: string, preparationId: string): string {\n return canonicalCandidateDigest({ executionId, preparationId })\n}\n\nfunction pruneExpiredState(\n reservations: Map<string, RememberedReservation>,\n settlements: Map<string, RememberedSettlement>,\n now: number,\n): void {\n for (const [key, value] of reservations) {\n if (value.expiresAtMs <= now) reservations.delete(key)\n }\n for (const [key, value] of settlements) {\n if (value.expiresAtMs <= now) settlements.delete(key)\n }\n}\n\nfunction rememberSettlement(\n settlements: Map<string, RememberedSettlement>,\n key: string,\n value: RememberedSettlement,\n): void {\n settlements.delete(key)\n settlements.set(key, value)\n while (settlements.size > MAX_RECENT_SETTLEMENTS) {\n const oldest = settlements.keys().next().value\n if (oldest === undefined) return\n settlements.delete(oldest)\n }\n}\n\nfunction isSha256Digest(value: unknown): value is Sha256Digest {\n return typeof value === 'string' && /^sha256:[a-f0-9]{64}$/.test(value)\n}\n\nfunction exactRecord(\n value: unknown,\n keys: readonly string[],\n label: string,\n): Record<string, unknown> {\n const source = record(value, label)\n assertExactObjectKeys(source, keys, label)\n return source\n}\n\nfunction record(value: unknown, label: string): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`)\n }\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(`${label} must be a plain object`)\n }\n return value as Record<string, unknown>\n}\n","import type { TraceStore } from '@tangle-network/agent-eval'\n\nimport type {\n AgentCandidateExecutionAttemptRef,\n AgentCandidateExecutionClaimStore,\n AgentCandidateExecutionFinishResult,\n} from './claim'\nimport {\n candidateCleanupDeadline,\n candidateCleanupTimeout,\n withinCandidateCleanupDeadline,\n} from './cleanup'\nimport { sealAgentCandidateExecutorFinalCapture } from './executor-capture'\nimport { sealAgentCandidateModelSettlement } from './model-settlement'\nimport { persistCandidateModelSettlementEvidence } from './outcome-evidence'\nimport { RecoveryAgentCandidateTraceStore } from './protected-trace-store'\nimport type {\n AgentCandidateExecutionPorts,\n AgentCandidateExecutorPort,\n AgentCandidateOutputArtifactPort,\n} from './types'\n\nexport interface RecoverExpiredAgentCandidateOptions {\n attempt: AgentCandidateExecutionAttemptRef\n claimStore: AgentCandidateExecutionClaimStore\n executor: AgentCandidateExecutorPort\n traceStore: TraceStore\n ports: Pick<AgentCandidateExecutionPorts, 'models' | 'memory'>\n outputArtifacts: AgentCandidateOutputArtifactPort\n cleanupTimeoutMs?: number\n /** Evaluator clock; must be the same clock used by the claim store. */\n now?: () => number\n}\n\n/** Close an expired crashed attempt from persisted non-secret handles, then record failure. */\nexport async function recoverExpiredAgentCandidateExecution(\n options: RecoverExpiredAgentCandidateOptions,\n): Promise<AgentCandidateExecutionFinishResult> {\n const record = await options.claimStore.getAttempt(options.attempt)\n if (!record) throw new Error('candidate execution recovery attempt is missing')\n if (record.terminal) {\n return Object.freeze({ finished: false, terminal: record.terminal, exactReplay: true })\n }\n const cleanupTimeoutMs = candidateCleanupTimeout(\n options.cleanupTimeoutMs ?? record.claim.cleanup.cleanupTimeoutMs,\n )\n if (cleanupTimeoutMs > record.claim.cleanup.cleanupTimeoutMs) {\n throw new Error('recovery cleanup timeout exceeds the frozen preparation bound')\n }\n\n const now = options.now ?? Date.now\n if (now() < record.claim.leaseExpiresAtMs) {\n throw new Error('candidate execution lease has not expired')\n }\n\n const cleanupDeadlineAtMs = candidateCleanupDeadline(cleanupTimeoutMs)\n const controller = new AbortController()\n controller.abort(new Error('recovering an expired candidate execution'))\n const recoveryTraceStore = new RecoveryAgentCandidateTraceStore(options.traceStore)\n const processClosure = withinCandidateCleanupDeadline(\n async () => {\n const stopped = await options.executor.stopAndCapture(\n {\n executionId: record.claim.executionId,\n executionPlanDigest: record.claim.executionPlanDigest,\n },\n {\n traceStore: recoveryTraceStore,\n reason: 'failed',\n signal: controller.signal,\n deadlineAtMs: record.claim.leaseExpiresAtMs,\n },\n )\n sealAgentCandidateExecutorFinalCapture(stopped)\n return { stopped: true as const }\n },\n cleanupDeadlineAtMs,\n 'expired candidate process termination',\n )\n\n const modelClosure = withinCandidateCleanupDeadline(\n async () =>\n sealAgentCandidateModelSettlement(\n await options.ports.models.settleGrant({\n executionId: record.claim.executionId,\n preparationId: record.claim.cleanup.preparationId,\n grantDigest: record.claim.cleanup.modelGrantDigest,\n resolved: record.claim.cleanup.resolvedModel,\n reason: 'failed',\n }),\n {\n preparationId: record.claim.cleanup.preparationId,\n grantDigest: record.claim.cleanup.modelGrantDigest,\n model: record.claim.cleanup.resolvedModel.model,\n },\n ),\n cleanupDeadlineAtMs,\n 'expired candidate model settlement',\n )\n\n const memoryClosure = record.claim.cleanup.memory\n ? withinCandidateCleanupDeadline(\n async () => {\n const memory = record.claim.cleanup.memory\n if (!memory) throw new Error('expired candidate memory handle is missing')\n const closed = await options.ports.memory.close({\n executionId: record.claim.executionId,\n preparationId: record.claim.cleanup.preparationId,\n accessDigest: memory.accessDigest,\n effectiveNamespace: memory.effectiveNamespace,\n reason: 'failed',\n })\n if (closed.closed !== true || Object.keys(closed).some((key) => key !== 'closed')) {\n throw new Error('expired candidate memory did not acknowledge closure')\n }\n return { closed: true as const }\n },\n cleanupDeadlineAtMs,\n 'expired candidate memory closure',\n )\n : undefined\n\n const operations = [processClosure, modelClosure, ...(memoryClosure ? [memoryClosure] : [])]\n const outcomes = await Promise.allSettled(operations)\n const failures = outcomes\n .filter((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')\n .map((outcome) => outcome.reason)\n if (failures.length > 0) {\n throw new AggregateError(failures, 'expired candidate cleanup could not be proven')\n }\n\n const model = await modelClosure\n const modelSettlement = await withinCandidateCleanupDeadline(\n () =>\n persistCandidateModelSettlementEvidence(\n {\n executionId: record.claim.executionId,\n executionPlanDigest: record.claim.executionPlanDigest,\n resolvedModel: record.claim.cleanup.resolvedModel,\n },\n model,\n options.outputArtifacts,\n ),\n cleanupDeadlineAtMs,\n 'expired candidate model-settlement persistence',\n )\n const memory = record.claim.cleanup.memory\n return await options.claimStore.recoverExpired(options.attempt, {\n failureClass:\n record.phase === 'claimed' && model.fixedUsage.modelCalls === 0\n ? 'pre-model-infrastructure'\n : 'unknown',\n usage: model.fixedUsage,\n modelSettlement: modelSettlement.artifact,\n process: {\n stopped: true,\n executionPlanDigest: record.claim.executionPlanDigest,\n },\n model: {\n closed: true,\n preparationId: record.claim.cleanup.preparationId,\n grantDigest: record.claim.cleanup.modelGrantDigest,\n },\n ...(memory\n ? {\n memory: {\n closed: true,\n preparationId: record.claim.cleanup.preparationId,\n accessDigest: memory.accessDigest,\n effectiveNamespace: memory.effectiveNamespace,\n },\n }\n : {}),\n })\n}\n","import { randomUUID } from 'node:crypto'\nimport { constants as fsConstants } from 'node:fs'\nimport {\n lstat,\n mkdir,\n mkdtemp,\n open,\n readdir,\n readFile,\n realpath,\n rename,\n rm,\n writeFile,\n} from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { dirname, isAbsolute, join, resolve, sep, win32 } from 'node:path'\nimport { isAnyArrayBuffer, isSharedArrayBuffer } from 'node:util/types'\n\nimport type {\n AgentCandidateCapturedArtifact,\n AgentCandidateWorkspaceManifestMaterialV1,\n AgentCandidateWorkspaceSnapshotEvidence,\n} from '@tangle-network/agent-interface'\nimport { type Entry, extract, type Pack, pack } from 'tar-stream'\n\nimport { captureMaterializedWorkspace, verifyBytes, verifyMaterializedWorkspace } from './artifacts'\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDigest,\n deepFreezeCandidate,\n embeddedCandidateArtifact,\n sha256Bytes,\n} from './digest'\nimport {\n assertNoGitIndirection,\n readCandidateGitTreeFiles,\n runCandidateGit,\n} from './git-materialize'\nimport { persistCandidateOutputArtifact } from './output-artifacts'\nimport type {\n AgentCandidateExecutorWorkspaceFile,\n AgentCandidateOutputArtifactPort,\n AgentCandidateWorkspacePort,\n} from './types'\n\nconst archiveKind = 'agent-candidate-workspace-archive' as const\nconst workspaceEntryPrefix = 'workspace/'\nconst repositoryMetadataEntry = 'metadata/repository.json'\nconst repositoryBundleEntry = 'metadata/repository.bundle'\nconst fixedTarTime = new Date(0)\n\nexport interface AgentCandidateWorkspaceArchiveLimits {\n maxArchiveBytes: number\n maxEmbeddedArtifactBytes: number\n maxFiles: number\n maxFileBytes: number\n maxTotalFileBytes: number\n maxPathBytes: number\n maxRepositoryBundleBytes: number\n}\n\nconst defaultLimits: AgentCandidateWorkspaceArchiveLimits = Object.freeze({\n maxArchiveBytes: 512 * 1024 * 1024,\n maxEmbeddedArtifactBytes: 1024 * 1024,\n maxFiles: 50_000,\n maxFileBytes: 128 * 1024 * 1024,\n maxTotalFileBytes: 256 * 1024 * 1024,\n maxPathBytes: 4_096,\n maxRepositoryBundleBytes: 128 * 1024 * 1024,\n})\n\ninterface WorkspaceArchiveRepositoryV1 {\n headCommit: string\n headTree: string\n bundle: {\n sha256: `sha256:${string}`\n byteLength: number\n bytes: Uint8Array\n }\n}\n\ninterface WorkspaceArchiveRepositoryMetadataV1 {\n schemaVersion: 1\n kind: typeof archiveKind\n headCommit: string\n headTree: string\n bundle: {\n sha256: `sha256:${string}`\n byteLength: number\n }\n}\n\ninterface DecodedWorkspaceArchive {\n files: Array<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }>\n repository?: WorkspaceArchiveRepositoryV1\n}\n\nexport interface CaptureAgentCandidateWorkspaceOptions {\n /** Include Git HEAD so task preparation can prove its exact commit and tree. */\n includeRepository?: boolean\n limits?: Partial<AgentCandidateWorkspaceArchiveLimits>\n /** Use the evaluator-owned artifact store when manifest or archive bytes should not be embedded. */\n artifactPersistence?: {\n executionId: string\n outputArtifacts: AgentCandidateOutputArtifactPort\n signal?: AbortSignal\n }\n}\n\nexport interface CreateAgentCandidateWorkspacePortOptions {\n limits?: Partial<AgentCandidateWorkspaceArchiveLimits>\n}\n\nexport interface CapturedAgentCandidateWorkspace {\n readonly snapshot: AgentCandidateWorkspaceSnapshotEvidence\n /** Caller-owned bytes accepted by createAgentCandidateWorkspacePort. */\n readonly archive: Uint8Array\n}\n\n/** Capture one exact regular-file workspace for immutable candidate execution. */\nexport async function captureAgentCandidateWorkspace(\n rootInput: string,\n options: CaptureAgentCandidateWorkspaceOptions = {},\n): Promise<CapturedAgentCandidateWorkspace> {\n const root = resolve(rootInput)\n const limits = workspaceLimits(options.limits)\n const captured = options.includeRepository\n ? await captureRepository(root, limits)\n : await captureMaterializedWorkspace(root, {\n limits: {\n maxFiles: limits.maxFiles,\n maxFileBytes: limits.maxFileBytes,\n maxTotalFileBytes: limits.maxTotalFileBytes,\n },\n })\n assertWorkspaceFilesWithinLimits(captured.files, limits)\n const repository = 'repository' in captured ? captured.repository : undefined\n return captureWorkspaceFiles(captured.files, repository, limits, options.artifactPersistence)\n}\n\n/** Capture detached files returned by a remote executor into the standard archive. */\nexport async function captureAgentCandidateWorkspaceFiles(\n input: readonly AgentCandidateExecutorWorkspaceFile[],\n options: Omit<CaptureAgentCandidateWorkspaceOptions, 'includeRepository'> = {},\n): Promise<CapturedAgentCandidateWorkspace> {\n const limits = workspaceLimits(options.limits)\n return captureWorkspaceFiles(\n normalizeWorkspaceFiles(input, limits),\n undefined,\n limits,\n options.artifactPersistence,\n )\n}\n\nasync function captureWorkspaceFiles(\n files: readonly AgentCandidateExecutorWorkspaceFile[],\n repository: WorkspaceArchiveRepositoryV1 | undefined,\n limits: AgentCandidateWorkspaceArchiveLimits,\n artifactPersistence: CaptureAgentCandidateWorkspaceOptions['artifactPersistence'],\n): Promise<CapturedAgentCandidateWorkspace> {\n const material = workspaceManifest(files)\n const manifest = canonicalCandidateBytes(material)\n const archive = await encodeWorkspaceArchive(files, repository, limits.maxArchiveBytes)\n if (\n !artifactPersistence &&\n (manifest.byteLength > limits.maxEmbeddedArtifactBytes ||\n archive.byteLength > limits.maxEmbeddedArtifactBytes)\n ) {\n throw new Error(\n 'candidate workspace artifacts exceed maxEmbeddedArtifactBytes; artifactPersistence is required',\n )\n }\n const manifestArtifact = await captureWorkspaceArtifact('manifest', manifest, artifactPersistence)\n const archiveArtifact = await captureWorkspaceArtifact('archive', archive, artifactPersistence)\n const snapshot = deepFreezeCandidate({\n schemaVersion: 1,\n kind: 'agent-candidate-workspace-snapshot',\n digest: canonicalCandidateDigest(material),\n material,\n manifest: manifestArtifact,\n archive: archiveArtifact,\n } satisfies AgentCandidateWorkspaceSnapshotEvidence)\n return Object.freeze({ snapshot, archive })\n}\n\nasync function captureWorkspaceArtifact(\n kind: 'manifest' | 'archive',\n bytes: Uint8Array,\n persistence: CaptureAgentCandidateWorkspaceOptions['artifactPersistence'],\n): Promise<AgentCandidateCapturedArtifact> {\n if (!persistence) return embeddedCandidateArtifact(bytes)\n if (!persistence.executionId.trim()) {\n throw new Error('candidate workspace artifact persistence requires an executionId')\n }\n return persistCandidateOutputArtifact(persistence.outputArtifacts, {\n executionId: persistence.executionId,\n purpose: kind === 'manifest' ? 'candidate-workspace-manifest' : 'candidate-workspace-archive',\n bytes,\n ...(persistence.signal ? { signal: persistence.signal } : {}),\n })\n}\n\n/** Create the standard bounded materializer for candidate execution ports. */\nexport function createAgentCandidateWorkspacePort(\n options: CreateAgentCandidateWorkspacePortOptions = {},\n): AgentCandidateWorkspacePort {\n const limits = workspaceLimits(options.limits)\n const port: AgentCandidateWorkspacePort = {\n materialize: async ({ role, snapshot, archive, destination }) => {\n await materializeAgentCandidateWorkspace({\n role,\n snapshot,\n archive,\n destination,\n limits,\n })\n },\n }\n return Object.freeze(port)\n}\n\nasync function materializeAgentCandidateWorkspace(input: {\n role: 'task' | 'candidate' | 'memory'\n snapshot: AgentCandidateWorkspaceSnapshotEvidence\n archive: Uint8Array\n destination: string\n limits: AgentCandidateWorkspaceArchiveLimits\n}): Promise<void> {\n verifyBytes(\n input.archive,\n input.snapshot.archive.sha256,\n input.snapshot.archive.byteLength,\n 'candidate workspace archive',\n )\n const decoded = await parseWorkspaceArchive(input.archive, input.limits)\n if (decoded.repository && input.role !== 'task') {\n throw new Error('only task workspaces may carry a Git repository')\n }\n assertArchiveMatchesSnapshot(decoded.files, input.snapshot)\n const destination = resolve(input.destination)\n await prepareEmptyDestination(destination)\n const staging = await mkdtemp(`${destination}.materializing-`)\n try {\n await writeWorkspaceFiles(staging, decoded.files)\n if (decoded.repository) {\n await materializeRepository(decoded.repository, staging)\n }\n await verifyMaterializedWorkspace(staging, input.snapshot.material, {\n ignoredProtectedRootEntries: decoded.repository ? ['.git'] : [],\n })\n await rename(staging, destination)\n } catch (error) {\n await rm(staging, { recursive: true, force: true })\n await rm(destination, { recursive: true, force: true })\n throw error\n }\n}\n\nasync function captureRepository(\n root: string,\n limits: AgentCandidateWorkspaceArchiveLimits,\n): Promise<{\n files: Array<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }>\n repository: WorkspaceArchiveRepositoryV1\n}> {\n const stats = await lstat(root)\n if (!stats.isDirectory() || stats.isSymbolicLink() || (await realpath(root)) !== root) {\n throw new Error('candidate repository root must be a real directory')\n }\n const topLevel = (await runCandidateGit(root, ['rev-parse', '--show-toplevel'])).stdout\n .toString('utf8')\n .trim()\n if (resolve(topLevel) !== root) {\n throw new Error('candidate repository capture must start at the Git worktree root')\n }\n const gitDir = resolve(\n (await runCandidateGit(root, ['rev-parse', '--absolute-git-dir'])).stdout\n .toString('utf8')\n .trim(),\n )\n if ((await realpath(gitDir)) !== gitDir || gitDir.includes(':')) {\n throw new Error('candidate repository Git object store has an unsupported path')\n }\n await assertNoGitIndirection(root, gitDir, 'candidate repository')\n const headCommit = (await runCandidateGit(root, ['rev-parse', 'HEAD'])).stdout\n .toString('utf8')\n .trim()\n const headTree = (await runCandidateGit(root, ['rev-parse', 'HEAD^{tree}'])).stdout\n .toString('utf8')\n .trim()\n assertGitObjectId(headCommit, 'HEAD')\n assertGitObjectId(headTree, 'HEAD tree')\n if (headCommit.length !== headTree.length) {\n throw new Error('candidate repository HEAD and tree use different object formats')\n }\n const files = await readCandidateGitTreeFiles(root, headTree, {}, limits)\n assertWorkspaceFilesWithinLimits(files, limits)\n const reachableBytesText = (\n await runCandidateGit(root, ['rev-list', '--disk-usage', '--objects', 'HEAD'])\n ).stdout\n .toString('utf8')\n .trim()\n const reachableBytes = Number(reachableBytesText)\n if (!Number.isSafeInteger(reachableBytes) || reachableBytes < 0) {\n throw new Error('candidate repository reachable size is invalid')\n }\n if (reachableBytes > limits.maxRepositoryBundleBytes) {\n throw new Error('candidate repository exceeds maxRepositoryBundleBytes')\n }\n const temporary = await mkdtemp(join(tmpdir(), 'agent-candidate-workspace-bundle-'))\n const bundlePath = join(temporary, `${randomUUID()}.bundle`)\n try {\n await runCandidateGit(root, ['bundle', 'create', bundlePath, 'HEAD'])\n const bundle = Uint8Array.from(await readFile(bundlePath))\n if (bundle.byteLength > limits.maxRepositoryBundleBytes) {\n throw new Error('candidate repository bundle exceeds maxRepositoryBundleBytes')\n }\n return {\n files,\n repository: {\n headCommit,\n headTree,\n bundle: {\n sha256: sha256Bytes(bundle),\n byteLength: bundle.byteLength,\n bytes: bundle,\n },\n },\n }\n } finally {\n await rm(temporary, { recursive: true, force: true })\n }\n}\n\nasync function encodeWorkspaceArchive(\n files: ReadonlyArray<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }>,\n repository: WorkspaceArchiveRepositoryV1 | undefined,\n maxArchiveBytes: number,\n): Promise<Uint8Array> {\n const archive = pack()\n const output = collectStream(archive, maxArchiveBytes, 'candidate workspace archive')\n try {\n await writeWorkspaceArchiveEntries(archive, files, repository)\n archive.finalize()\n return await output\n } catch (error) {\n archive.destroy(error instanceof Error ? error : new Error(String(error)))\n await output.catch(() => undefined)\n throw error\n }\n}\n\nasync function verifyCanonicalWorkspaceArchive(\n files: ReadonlyArray<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }>,\n repository: WorkspaceArchiveRepositoryV1 | undefined,\n expected: Uint8Array,\n maxArchiveBytes: number,\n): Promise<void> {\n const archive = pack()\n const comparison = streamEqualsBytes(\n archive,\n expected,\n maxArchiveBytes,\n 'candidate workspace archive',\n )\n try {\n await writeWorkspaceArchiveEntries(archive, files, repository)\n archive.finalize()\n if (!(await comparison)) throw new Error('candidate workspace tar is not canonical')\n } catch (error) {\n archive.destroy(error instanceof Error ? error : new Error(String(error)))\n await comparison.catch(() => undefined)\n throw error\n }\n}\n\nasync function writeWorkspaceArchiveEntries(\n archive: Pack,\n files: ReadonlyArray<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }>,\n repository: WorkspaceArchiveRepositoryV1 | undefined,\n): Promise<void> {\n for (const file of files) {\n await writeTarEntry(archive, `${workspaceEntryPrefix}${file.path}`, file.mode, file.bytes)\n }\n if (!repository) return\n const metadata = canonicalCandidateBytes({\n schemaVersion: 1,\n kind: archiveKind,\n headCommit: repository.headCommit,\n headTree: repository.headTree,\n bundle: {\n sha256: repository.bundle.sha256,\n byteLength: repository.bundle.byteLength,\n },\n } satisfies WorkspaceArchiveRepositoryMetadataV1)\n await writeTarEntry(archive, repositoryMetadataEntry, 0o600, metadata)\n await writeTarEntry(archive, repositoryBundleEntry, 0o600, repository.bundle.bytes)\n}\n\nasync function parseWorkspaceArchive(\n bytes: Uint8Array,\n limits: AgentCandidateWorkspaceArchiveLimits,\n): Promise<DecodedWorkspaceArchive> {\n if (bytes.byteLength > limits.maxArchiveBytes) {\n throw new Error('candidate workspace archive exceeds maxArchiveBytes')\n }\n const parser = extract()\n const files: DecodedWorkspaceArchive['files'] = []\n const observedEntryNames = new Set<string>()\n const observedPaths = new Set<string>()\n let totalBytes = 0\n let retainedEntryBytes = 0\n let previousPath: string | undefined\n let repositoryMetadata: WorkspaceArchiveRepositoryMetadataV1 | undefined\n let repositoryBundle: Uint8Array | undefined\n const decoded = (async () => {\n for await (const entry of parser) {\n const name = entry.header.name\n if (\n entry.header.type !== 'file' ||\n typeof name !== 'string' ||\n observedEntryNames.has(name)\n ) {\n throw new Error('candidate workspace tar contains an invalid entry')\n }\n observedEntryNames.add(name)\n if (name.startsWith(workspaceEntryPrefix)) {\n if (files.length >= limits.maxFiles) {\n throw new Error('candidate workspace archive has an invalid file count')\n }\n const path = safeArchivePath(name.slice(workspaceEntryPrefix.length), limits.maxPathBytes)\n if (entry.header.mode !== 0o644 && entry.header.mode !== 0o755) {\n throw new Error(`candidate workspace archive has an unsupported mode: ${path}`)\n }\n assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits)\n const fileBytes = await readTarEntry(entry, limits.maxFileBytes, `workspace file ${path}`)\n retainedEntryBytes += fileBytes.byteLength\n assertWorkspacePathOrder(\n path,\n previousPath,\n observedPaths,\n 'candidate workspace archive paths must be unique and sorted',\n )\n previousPath = path\n if (fileBytes.byteLength > limits.maxTotalFileBytes - totalBytes) {\n throw new Error('candidate workspace archive exceeds maxTotalFileBytes')\n }\n totalBytes += fileBytes.byteLength\n files.push({ path, mode: entry.header.mode, bytes: fileBytes })\n } else if (name === repositoryMetadataEntry) {\n if (entry.header.mode !== 0o600 || repositoryMetadata) {\n throw new Error('candidate workspace archive repository metadata is invalid')\n }\n assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits)\n const metadataBytes = await readTarEntry(\n entry,\n limits.maxPathBytes,\n 'candidate repository metadata',\n )\n retainedEntryBytes += metadataBytes.byteLength\n repositoryMetadata = parseRepositoryMetadata(metadataBytes, limits.maxRepositoryBundleBytes)\n } else if (name === repositoryBundleEntry) {\n if (entry.header.mode !== 0o600 || repositoryBundle) {\n throw new Error('candidate workspace archive repository bundle is invalid')\n }\n assertRetainedArchiveSize(bytes.byteLength, retainedEntryBytes, entry.header.size, limits)\n repositoryBundle = await readTarEntry(\n entry,\n limits.maxRepositoryBundleBytes,\n 'candidate Git bundle',\n )\n retainedEntryBytes += repositoryBundle.byteLength\n } else {\n throw new Error(`candidate workspace tar contains an unsupported entry: ${name}`)\n }\n }\n if (Boolean(repositoryMetadata) !== Boolean(repositoryBundle)) {\n throw new Error('candidate workspace archive repository evidence is incomplete')\n }\n const repository =\n repositoryMetadata && repositoryBundle\n ? repositoryFromTar(repositoryMetadata, repositoryBundle)\n : undefined\n return { files, ...(repository ? { repository } : {}) }\n })()\n parser.end(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength))\n const result = await decoded\n await verifyCanonicalWorkspaceArchive(\n result.files,\n result.repository,\n bytes,\n limits.maxArchiveBytes,\n )\n return result\n}\n\nfunction assertRetainedArchiveSize(\n archiveBytes: number,\n retainedEntryBytes: number,\n entryBytes: number | undefined,\n limits: AgentCandidateWorkspaceArchiveLimits,\n): void {\n if (\n !Number.isSafeInteger(entryBytes) ||\n entryBytes === undefined ||\n entryBytes < 0 ||\n entryBytes > limits.maxArchiveBytes - archiveBytes - retainedEntryBytes\n ) {\n throw new Error('candidate workspace archive exceeds maxArchiveBytes while decoding')\n }\n}\n\nfunction parseRepositoryMetadata(\n bytes: Uint8Array,\n maxBundleBytes: number,\n): WorkspaceArchiveRepositoryMetadataV1 {\n let value: unknown\n try {\n value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes))\n } catch (error) {\n throw new Error('candidate workspace archive repository metadata is invalid', { cause: error })\n }\n if (\n !isRecord(value) ||\n Object.keys(value).sort().join(',') !== 'bundle,headCommit,headTree,kind,schemaVersion' ||\n value.schemaVersion !== 1 ||\n value.kind !== archiveKind ||\n typeof value.headCommit !== 'string' ||\n typeof value.headTree !== 'string' ||\n !isRecord(value.bundle) ||\n Object.keys(value.bundle).sort().join(',') !== 'byteLength,sha256' ||\n typeof value.bundle.sha256 !== 'string' ||\n !/^sha256:[a-f0-9]{64}$/.test(value.bundle.sha256) ||\n !Number.isSafeInteger(value.bundle.byteLength) ||\n (value.bundle.byteLength as number) <= 0 ||\n (value.bundle.byteLength as number) > maxBundleBytes\n ) {\n throw new Error('candidate workspace archive repository is invalid')\n }\n if (!Buffer.from(canonicalCandidateBytes(value)).equals(Buffer.from(bytes))) {\n throw new Error('candidate workspace archive repository metadata is not canonical')\n }\n assertGitObjectId(value.headCommit, 'repository HEAD')\n assertGitObjectId(value.headTree, 'repository HEAD tree')\n if (value.headCommit.length !== value.headTree.length) {\n throw new Error('candidate repository HEAD and tree use different object formats')\n }\n return {\n schemaVersion: 1,\n kind: archiveKind,\n headCommit: value.headCommit,\n headTree: value.headTree,\n bundle: {\n sha256: value.bundle.sha256 as `sha256:${string}`,\n byteLength: value.bundle.byteLength as number,\n },\n }\n}\n\nfunction repositoryFromTar(\n metadata: WorkspaceArchiveRepositoryMetadataV1,\n bundle: Uint8Array,\n): WorkspaceArchiveRepositoryV1 {\n verifyBytes(bundle, metadata.bundle.sha256, metadata.bundle.byteLength, 'candidate Git bundle')\n return {\n headCommit: metadata.headCommit,\n headTree: metadata.headTree,\n bundle: { ...metadata.bundle, bytes: bundle },\n }\n}\n\nasync function writeTarEntry(\n archive: Pack,\n name: string,\n mode: 0o600 | 0o644 | 0o755,\n bytes: Uint8Array,\n): Promise<void> {\n await new Promise<void>((resolveEntry, rejectEntry) => {\n archive.entry(\n {\n name,\n mode,\n uid: 0,\n gid: 0,\n size: bytes.byteLength,\n mtime: fixedTarTime,\n type: 'file',\n uname: '',\n gname: '',\n },\n Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength),\n (error) => (error ? rejectEntry(error) : resolveEntry()),\n )\n })\n}\n\nasync function readTarEntry(entry: Entry, maxBytes: number, label: string): Promise<Uint8Array> {\n const size = entry.header.size\n if (!Number.isSafeInteger(size) || size === undefined || size < 0 || size > maxBytes) {\n throw new Error(`${label} has an invalid tar size`)\n }\n const bytes = await collectStream(entry, maxBytes, label)\n if (bytes.byteLength !== size) throw new Error(`${label} differs from its tar size`)\n return bytes\n}\n\nasync function collectStream(\n stream: AsyncIterable<Uint8Array>,\n maxBytes: number,\n label: string,\n): Promise<Uint8Array> {\n const chunks: Buffer[] = []\n let totalBytes = 0\n for await (const chunk of stream) {\n if (chunk.byteLength > maxBytes - totalBytes) {\n const error = new Error(`${label} exceeds its size limit`)\n if ('destroy' in stream && typeof stream.destroy === 'function') stream.destroy(error)\n throw error\n }\n const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)\n chunks.push(bytes)\n totalBytes += bytes.byteLength\n }\n return Buffer.concat(chunks, totalBytes)\n}\n\nasync function streamEqualsBytes(\n stream: AsyncIterable<Uint8Array>,\n expected: Uint8Array,\n maxBytes: number,\n label: string,\n): Promise<boolean> {\n const expectedBuffer = Buffer.from(expected.buffer, expected.byteOffset, expected.byteLength)\n let equal = true\n let offset = 0\n for await (const chunk of stream) {\n if (chunk.byteLength > maxBytes - offset) {\n const error = new Error(`${label} exceeds its size limit`)\n if ('destroy' in stream && typeof stream.destroy === 'function') stream.destroy(error)\n throw error\n }\n const observed = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)\n if (\n offset + observed.byteLength > expectedBuffer.byteLength ||\n !observed.equals(expectedBuffer.subarray(offset, offset + observed.byteLength))\n ) {\n equal = false\n }\n offset += observed.byteLength\n }\n return equal && offset === expectedBuffer.byteLength\n}\n\nasync function prepareEmptyDestination(destination: string): Promise<void> {\n await mkdir(destination, { recursive: true, mode: 0o700 })\n const stats = await lstat(destination)\n if (\n !stats.isDirectory() ||\n stats.isSymbolicLink() ||\n (await realpath(destination)) !== destination\n ) {\n throw new Error('candidate workspace destination must be a real directory')\n }\n if ((await readdir(destination)).length > 0) {\n throw new Error('candidate workspace destination must be empty')\n }\n}\n\nasync function writeWorkspaceFiles(\n destination: string,\n files: ReadonlyArray<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }>,\n): Promise<void> {\n for (const file of files) {\n const path = workspacePath(destination, file.path)\n await mkdir(dirname(path), { recursive: true, mode: 0o700 })\n const descriptor = await open(\n path,\n fsConstants.O_WRONLY |\n fsConstants.O_CREAT |\n fsConstants.O_EXCL |\n (typeof fsConstants.O_NOFOLLOW === 'number' ? fsConstants.O_NOFOLLOW : 0),\n 0o600,\n )\n try {\n await descriptor.writeFile(file.bytes)\n const stats = await descriptor.stat()\n if (!stats.isFile() || stats.nlink !== 1) {\n throw new Error(`candidate workspace file identity changed while writing: ${file.path}`)\n }\n await descriptor.chmod(file.mode)\n } finally {\n await descriptor.close()\n }\n }\n}\n\nasync function materializeRepository(\n repository: WorkspaceArchiveRepositoryV1,\n destination: string,\n): Promise<void> {\n const temporary = await mkdtemp(join(tmpdir(), 'agent-candidate-workspace-bundle-'))\n const bundlePath = join(temporary, `${randomUUID()}.bundle`)\n try {\n await writeFile(bundlePath, repository.bundle.bytes, { flag: 'wx', mode: 0o600 })\n await runCandidateGit(destination, [\n 'init',\n '--quiet',\n '--initial-branch=candidate',\n `--object-format=${repository.headCommit.length === 64 ? 'sha256' : 'sha1'}`,\n ])\n await runCandidateGit(destination, ['bundle', 'verify', bundlePath])\n await runCandidateGit(destination, ['bundle', 'unbundle', bundlePath])\n const objectType = (\n await runCandidateGit(destination, ['cat-file', '-t', repository.headCommit])\n ).stdout\n .toString('utf8')\n .trim()\n if (objectType !== 'commit') throw new Error('candidate repository HEAD is not a commit')\n const observedTree = (\n await runCandidateGit(destination, ['rev-parse', `${repository.headCommit}^{tree}`])\n ).stdout\n .toString('utf8')\n .trim()\n if (observedTree !== repository.headTree) {\n throw new Error('candidate repository bundle HEAD tree changed')\n }\n await runCandidateGit(destination, ['update-ref', '--no-deref', 'HEAD', repository.headCommit])\n await runCandidateGit(destination, ['read-tree', repository.headTree])\n const status = (\n await runCandidateGit(destination, ['status', '--porcelain=v1', '--untracked-files=all'])\n ).stdout\n .toString('utf8')\n .trim()\n if (status) throw new Error('candidate repository files do not exactly match HEAD')\n } finally {\n await rm(temporary, { recursive: true, force: true })\n }\n}\n\nfunction workspaceManifest(\n files: ReadonlyArray<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }>,\n): AgentCandidateWorkspaceManifestMaterialV1 {\n return {\n schemaVersion: 1,\n kind: 'agent-candidate-workspace-manifest',\n files: files.map((file) => ({\n path: file.path,\n mode: file.mode,\n sha256: sha256Bytes(file.bytes),\n byteLength: file.bytes.byteLength,\n })),\n }\n}\n\nfunction assertArchiveMatchesSnapshot(\n files: ReadonlyArray<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }>,\n snapshot: AgentCandidateWorkspaceSnapshotEvidence,\n): void {\n const material = workspaceManifest(files)\n const materialBytes = canonicalCandidateBytes(material)\n verifyBytes(\n materialBytes,\n snapshot.manifest.sha256,\n snapshot.manifest.byteLength,\n 'candidate workspace manifest',\n )\n if (\n canonicalCandidateDigest(material) !== snapshot.digest ||\n !Buffer.from(materialBytes).equals(Buffer.from(canonicalCandidateBytes(snapshot.material)))\n ) {\n throw new Error('candidate workspace archive does not match its snapshot manifest')\n }\n}\n\nfunction assertWorkspaceFilesWithinLimits(\n files: ReadonlyArray<{ path: string; mode: 0o644 | 0o755; bytes: Uint8Array }>,\n limits: AgentCandidateWorkspaceArchiveLimits,\n): void {\n if (files.length > limits.maxFiles) {\n throw new Error('candidate workspace exceeds maxFiles')\n }\n let totalBytes = 0\n let previousPath: string | undefined\n const observedPaths = new Set<string>()\n for (const file of files) {\n const path = safeArchivePath(file.path, limits.maxPathBytes)\n assertWorkspacePathOrder(\n path,\n previousPath,\n observedPaths,\n 'candidate workspace paths must be unique and sorted',\n )\n previousPath = path\n if (file.mode !== 0o644 && file.mode !== 0o755) {\n throw new Error(`candidate workspace file has unsupported mode: ${path}`)\n }\n if (file.bytes.byteLength > limits.maxFileBytes) {\n throw new Error(`candidate workspace file exceeds maxFileBytes: ${path}`)\n }\n totalBytes += file.bytes.byteLength\n if (totalBytes > limits.maxTotalFileBytes) {\n throw new Error('candidate workspace exceeds maxTotalFileBytes')\n }\n }\n}\n\nfunction normalizeWorkspaceFiles(\n input: readonly AgentCandidateExecutorWorkspaceFile[],\n limits: AgentCandidateWorkspaceArchiveLimits,\n): AgentCandidateExecutorWorkspaceFile[] {\n if (!Array.isArray(input)) {\n throw new Error('candidate workspace files must be an array')\n }\n const fileCount = input.length\n if (fileCount > limits.maxFiles) {\n throw new Error('candidate workspace exceeds maxFiles')\n }\n let totalBytes = 0\n const files: AgentCandidateExecutorWorkspaceFile[] = []\n for (let index = 0; index < fileCount; index++) {\n const inputFile = input[index]\n if (!isRecord(inputFile) || Object.keys(inputFile).sort().join(',') !== 'bytes,mode,path') {\n throw new Error(`candidate workspace file ${index} is invalid`)\n }\n const descriptors = Object.getOwnPropertyDescriptors(inputFile)\n if (\n !('value' in (descriptors.path ?? {})) ||\n !('value' in (descriptors.mode ?? {})) ||\n !('value' in (descriptors.bytes ?? {}))\n ) {\n throw new Error(`candidate workspace file ${index} must use fixed values`)\n }\n const path = safeArchivePath(descriptors.path?.value, limits.maxPathBytes)\n const mode = descriptors.mode?.value\n const inputBytes = descriptors.bytes?.value\n if (mode !== 0o644 && mode !== 0o755) {\n throw new Error(`candidate workspace file has unsupported mode: ${path}`)\n }\n const view = inspectWorkspaceBytes(inputBytes, path)\n if (view.byteLength > limits.maxFileBytes) {\n throw new Error(`candidate workspace file exceeds maxFileBytes: ${path}`)\n }\n if (view.byteLength > limits.maxTotalFileBytes - totalBytes) {\n throw new Error('candidate workspace exceeds maxTotalFileBytes')\n }\n if (view.byteLength > Math.max(0, limits.maxArchiveBytes - 1024)) {\n throw new Error('candidate workspace archive exceeds maxArchiveBytes')\n }\n totalBytes += view.byteLength\n files.push({ path, mode, bytes: detachWorkspaceBytes(view) })\n }\n files.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0))\n assertWorkspaceFilesWithinLimits(files, limits)\n return files\n}\n\nfunction workspaceLimits(\n overrides: Partial<AgentCandidateWorkspaceArchiveLimits> | undefined,\n): AgentCandidateWorkspaceArchiveLimits {\n const limits = { ...defaultLimits, ...overrides }\n for (const [name, value] of Object.entries(limits)) {\n if (!Number.isSafeInteger(value) || value <= 0) {\n throw new Error(`candidate workspace ${name} must be a positive safe integer`)\n }\n }\n return Object.freeze(limits)\n}\n\nfunction safeArchivePath(value: unknown, maxPathBytes: number): string {\n if (\n typeof value !== 'string' ||\n !value ||\n !isWellFormedUnicode(value) ||\n Buffer.byteLength(value, 'utf8') > maxPathBytes ||\n isAbsolute(value) ||\n win32.isAbsolute(value) ||\n value.includes('\\\\') ||\n value.includes('\\0') ||\n hasControlCharacter(value) ||\n value.split('/').some((part) => !part || part === '.' || part === '..') ||\n ['.git', '.sidecar'].includes(value.split('/')[0]?.toLowerCase() ?? '')\n ) {\n throw new Error(`candidate workspace archive contains an unsafe path: ${String(value)}`)\n }\n return value\n}\n\nfunction assertWorkspacePathOrder(\n path: string,\n previousPath: string | undefined,\n observedPaths: Set<string>,\n errorMessage: string,\n): void {\n if (previousPath !== undefined && previousPath >= path) throw new Error(errorMessage)\n for (let slash = path.indexOf('/'); slash !== -1; slash = path.indexOf('/', slash + 1)) {\n if (observedPaths.has(path.slice(0, slash))) throw new Error(errorMessage)\n }\n observedPaths.add(path)\n}\n\nfunction inspectWorkspaceBytes(\n input: unknown,\n path: string,\n): { buffer: ArrayBuffer; byteOffset: number; byteLength: number } {\n let buffer: ArrayBufferLike\n let byteOffset: number\n let byteLength: number\n try {\n buffer = typedArrayBufferGetter.call(input as Uint8Array) as ArrayBufferLike\n byteOffset = typedArrayByteOffsetGetter.call(input as Uint8Array) as number\n byteLength = typedArrayByteLengthGetter.call(input as Uint8Array) as number\n } catch {\n throw new Error(`candidate workspace file bytes are invalid: ${path}`)\n }\n if (isSharedArrayBuffer(buffer)) {\n throw new Error(`candidate workspace file uses shared bytes: ${path}`)\n }\n if (!isAnyArrayBuffer(buffer)) {\n throw new Error(`candidate workspace file bytes are invalid: ${path}`)\n }\n return { buffer, byteOffset, byteLength }\n}\n\nfunction detachWorkspaceBytes(input: {\n buffer: ArrayBuffer\n byteOffset: number\n byteLength: number\n}): Uint8Array {\n const { buffer, byteOffset, byteLength } = input\n const copy = new Uint8Array(byteLength)\n Uint8Array.prototype.set.call(copy, new Uint8Array(buffer, byteOffset, byteLength))\n return copy\n}\n\nfunction isWellFormedUnicode(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index)\n if (code >= 0xd800 && code <= 0xdbff) {\n const next = value.charCodeAt(index + 1)\n if (!(next >= 0xdc00 && next <= 0xdfff)) return false\n index++\n } else if (code >= 0xdc00 && code <= 0xdfff) {\n return false\n }\n }\n return true\n}\n\nfunction workspacePath(root: string, relativePath: string): string {\n const path = resolve(root, relativePath)\n if (!path.startsWith(`${root}${sep}`)) {\n throw new Error(`candidate workspace archive path escapes its destination: ${relativePath}`)\n }\n return path\n}\n\nfunction assertGitObjectId(value: string, label: string): void {\n if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value)) {\n throw new Error(`candidate repository ${label} is not a Git object id`)\n }\n}\n\nfunction hasControlCharacter(value: string): boolean {\n for (let index = 0; index < value.length; index++) {\n const code = value.charCodeAt(index)\n if (code < 0x20 || code === 0x7f) return true\n }\n return false\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\ntype TypedArrayGetter = (this: Uint8Array) => unknown\n\nfunction requireTypedArrayGetter(name: 'buffer' | 'byteOffset' | 'byteLength'): TypedArrayGetter {\n const typedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype) as object\n const getter = Object.getOwnPropertyDescriptor(typedArrayPrototype, name)?.get\n if (!getter) throw new Error(`typed array intrinsic ${name} accessor is unavailable`)\n return getter\n}\n\nconst typedArrayBufferGetter = requireTypedArrayGetter('buffer')\nconst typedArrayByteOffsetGetter = requireTypedArrayGetter('byteOffset')\nconst typedArrayByteLengthGetter = requireTypedArrayGetter('byteLength')\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,yBAAyB;AA0E3B,SAAS,0BACd,OAC6C;AAC7C,MAAI,OAAO,OAAO,MAAM,SAAS,gBAAgB,GAAG;AAClD,UAAM,IAAI,MAAM,0EAA0E;AAAA,EAC5F;AACA,QAAM,kBAAkB,wBAAwB,MAAM,OAAO;AAC7D,QAAM,iBAAiB,gBAAgB;AACvC,QAAM,SAAoC;AAAA,IACxC,eAAe;AAAA,IACf,MAAM;AAAA,IACN,iBAAiB;AAAA,IACjB,SAAS,gBAAgB;AAAA,IACzB,MAAM,qBAAqB,MAAM,IAAI;AAAA,IACrC,WAAW,MAAM;AAAA,IACjB,GAAI,MAAM,YAAY,EAAE,WAAW,MAAM,UAAU,IAAI,CAAC;AAAA,IACxD,QAAQ,MAAM;AAAA,IACd,SAAS;AAAA,MACP,GAAG,MAAM;AAAA,MACT,GAAI,eAAe,SAAS,IAAI,EAAE,eAAe,I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AAO,eAAe,WAAW,SAAS;AACtE,QAAM,SAAS,OAAO,yBAAyB,qBAAqB,IAAI,GAAG;AAC3E,MAAI,CAAC,OAAQ,OAAM,IAAI,MAAM,yBAAyB,IAAI,0BAA0B;AACpF,SAAO;AACT;AAEA,IAAM,yBAAyB,wBAAwB,QAAQ;AAC/D,IAAM,6BAA6B,wBAAwB,YAAY;AACvE,IAAM,6BAA6B,wBAAwB,YAAY;","names":["record","winner","source","value","record","memory","randomUUID","mkdir","open","join","join","randomUUID","mkdir","open"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/knowledge/improvement-job.ts","../src/knowledge/supervised-update.ts"],"sourcesContent":["import {\n type BuildEvalKnowledgeBundleOptions,\n evaluateKnowledgeBaseReadiness,\n improveKnowledgeBase,\n type KnowledgeBaseQualityOptions,\n type KnowledgeImprovementOptions,\n type KnowledgeImprovementResult,\n type KnowledgeReadinessSpec,\n} from '@tangle-network/agent-knowledge'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport type { SuperviseOptions } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { Budget, SupervisedResult } from '../runtime/supervise/types'\nimport {\n createSupervisedKnowledgeUpdater,\n type KnowledgeReadinessCheck,\n type KnowledgeReadinessCheckResult,\n type SupervisedKnowledgeUpdateOptions,\n} from './supervised-update'\n\nexport interface RunKnowledgeImprovementJobOptions\n extends Omit<KnowledgeImprovementOptions, 'updateKnowledge'> {\n budget: Budget\n readinessCheck?: KnowledgeReadinessCheck\n backend?: ExecutorConfig\n makeWorkerAgent?: SuperviseOptions['makeWorkerAgent']\n harness?: string\n supervisorModel?: string\n supervisorSystemPrompt?: string\n superviseOptions?: Partial<\n Omit<\n SuperviseOptions,\n 'budget' | 'backend' | 'deliverable' | 'makeWorkerAgent' | 'allowedModels'\n >\n >\n allowedModels?: readonly string[]\n runSupervised?: (\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n ) => Promise<SupervisedResult<unknown>>\n onMeasurement?: (measurement: KnowledgeImprovementJobMeasurement) => Promise<void> | void\n}\n\nexport interface KnowledgeImprovementJobMeasurement {\n startedAt: string\n finishedAt: string\n durationMs: number\n updateCalls: number\n updateDurationMs: number\n supervisedSpent: {\n iterations: number\n inputTokens: number\n outputTokens: number\n usd: number\n ms: number\n }\n}\n\nexport interface KnowledgeImprovementJobResult {\n improvement: KnowledgeImprovementResult\n measurement: KnowledgeImprovementJobMeasurement\n promoted: boolean\n blocked: boolean\n}\n\nexport interface AgentKnowledgeReadinessCheckOptions {\n goal: string\n readinessSpecs?: readonly KnowledgeReadinessSpec[]\n readinessTaskId?: string\n readiness?: Omit<BuildEvalKnowledgeBundleOptions, 'taskId' | 'index' | 'specs'>\n strict?: boolean\n kbQuality?: KnowledgeBaseQualityOptions\n}\n\n/** Build the default readiness check backed by `@tangle-network/agent-knowledge` validation and scoring. */\nexport function createAgentKnowledgeReadinessCheck(\n options: AgentKnowledgeReadinessCheckOptions,\n): KnowledgeReadinessCheck {\n return async (input): Promise<KnowledgeReadinessCheckResult> => {\n const readiness = await evaluateKnowledgeBaseReadiness({\n root: input.root,\n goal: input.goal ?? options.goal,\n readinessSpecs:\n (input.readinessSpecs as readonly KnowledgeReadinessSpec[] | undefined) ??\n options.readinessSpecs,\n readinessTaskId: input.readinessTaskId ?? options.readinessTaskId,\n readiness:\n (input.readiness as AgentKnowledgeReadinessCheckOptions['readiness'] | undefined) ??\n options.readiness,\n strict: options.strict,\n kbQuality: options.kbQuality,\n })\n return {\n ready: readiness.ready,\n summary: readiness.summary,\n metadata: {\n dimensions: readiness.dimensions,\n validationOk: readiness.validation.ok,\n kbQualityOk: readiness.kbQuality.ok,\n blockingMissing: readiness.readiness?.report.blockingMissingRequirements.length ?? 0,\n },\n }\n }\n}\n\n/** Run the full KB improvement job: candidate workspace, runtime supervisor update, readiness check, and promotion. */\nexport async function runKnowledgeImprovementJob(\n options: RunKnowledgeImprovementJobOptions,\n): Promise<KnowledgeImprovementJobResult> {\n const {\n allowedModels,\n backend,\n budget,\n harness,\n makeWorkerAgent,\n onMeasurement,\n readinessCheck,\n runSupervised,\n supervisorModel,\n supervisorSystemPrompt,\n superviseOptions,\n ...knowledgeOptions\n } = options\n const startedAtMs = Date.now()\n const startedAt = new Date(startedAtMs).toISOString()\n const supervisedSpent = emptySpent()\n let updateCalls = 0\n let updateDurationMs = 0\n\n const readiness = readinessCheck ?? createAgentKnowledgeReadinessCheck(options)\n const updateKnowledge = createSupervisedKnowledgeUpdater({\n root: options.root,\n goal: options.goal,\n readiness,\n readinessSpecs: options.readinessSpecs,\n readinessTaskId: options.readinessTaskId,\n readinessOptions: options.readiness,\n budget,\n backend,\n makeWorkerAgent,\n harness,\n supervisorModel,\n supervisorSystemPrompt,\n superviseOptions,\n allowedModels,\n runSupervised,\n } satisfies SupervisedKnowledgeUpdateOptions)\n\n const resolvedImprovement = await improveKnowledgeBase({\n ...knowledgeOptions,\n updateKnowledge: async (input) => {\n const updateStartedAt = Date.now()\n updateCalls += 1\n const result = await updateKnowledge(input)\n updateDurationMs += Date.now() - updateStartedAt\n addSpent(supervisedSpent, result.supervised)\n return result\n },\n } as KnowledgeImprovementOptions)\n const finishedAtMs = Date.now()\n const measurement: KnowledgeImprovementJobMeasurement = {\n startedAt,\n finishedAt: new Date(finishedAtMs).toISOString(),\n durationMs: finishedAtMs - startedAtMs,\n updateCalls,\n updateDurationMs,\n supervisedSpent,\n }\n await onMeasurement?.(measurement)\n return {\n improvement: resolvedImprovement,\n measurement,\n promoted: resolvedImprovement.promoted,\n blocked: resolvedImprovement.blocked,\n }\n}\n\nfunction emptySpent(): KnowledgeImprovementJobMeasurement['supervisedSpent'] {\n return { iterations: 0, inputTokens: 0, outputTokens: 0, usd: 0, ms: 0 }\n}\n\nfunction addSpent(\n target: KnowledgeImprovementJobMeasurement['supervisedSpent'],\n result: SupervisedResult<unknown>,\n): void {\n const spent = result.spentTotal\n target.iterations += spent.iterations ?? 0\n target.inputTokens += spent.tokens?.input ?? 0\n target.outputTokens += spent.tokens?.output ?? 0\n target.usd += spent.usd ?? 0\n target.ms += spent.ms ?? 0\n}\n","import { researcherProfile } from '../profiles/researcher'\nimport type { DeliverableSpec } from '../runtime/supervise/completion-gate'\nimport type { ExecutorConfig } from '../runtime/supervise/runtime'\nimport { type SuperviseOptions, supervise } from '../runtime/supervise/supervise'\nimport type { SupervisorProfile } from '../runtime/supervise/supervisor-agent'\nimport type { Budget, SupervisedResult } from '../runtime/supervise/types'\n\n/** Standing prompt for a supervisor that grows a shared knowledge base through spawned researchers. */\nexport const RESEARCH_SUPERVISOR_SYSTEM_PROMPT = [\n 'You are a research supervisor. You do not answer the research question yourself.',\n 'You create and manage researcher workers that improve one shared knowledge base until it is ready.',\n '',\n 'Each round:',\n '1. Read the goal and the gaps the readiness check still reports.',\n '2. Decompose the open work into independent sub-topics.',\n '3. Spawn one researcher per sub-topic; split by sub-topic, never duplicate work.',\n '4. Wait for researchers to settle, steer or re-spawn thin sub-topics, then stop when the check passes.',\n '',\n 'Conserve the shared budget. Prefer a small number of well-scoped researchers over a large fanout that re-covers the same ground.',\n].join('\\n')\n\nexport interface KnowledgeReadinessCheckInput {\n root: string\n goal: string\n readinessSpecs?: readonly unknown[]\n readinessTaskId?: string\n readiness?: unknown\n}\n\nexport type KnowledgeReadinessCheckResult =\n | boolean\n | {\n ready: boolean\n summary?: string\n metadata?: Record<string, unknown>\n }\n\nexport type KnowledgeReadinessCheck = (\n input: KnowledgeReadinessCheckInput,\n) => Promise<KnowledgeReadinessCheckResult> | KnowledgeReadinessCheckResult\n\nexport interface SupervisedKnowledgeUpdateInput {\n goal?: string\n root?: string\n candidateRoot?: string\n findings?: readonly unknown[]\n metadata?: Record<string, unknown>\n}\n\nexport interface SupervisedKnowledgeUpdateResult {\n applied: boolean\n summary: string\n supervised: SupervisedResult<unknown>\n metadata: Record<string, unknown>\n}\n\nexport interface SupervisedKnowledgeUpdateOptions {\n root: string\n goal: string\n readiness: KnowledgeReadinessCheck\n readinessSpecs?: readonly unknown[]\n readinessTaskId?: string\n readinessOptions?: unknown\n findings?: readonly unknown[]\n metadata?: Record<string, unknown>\n budget: Budget\n backend?: ExecutorConfig\n makeWorkerAgent?: SuperviseOptions['makeWorkerAgent']\n harness?: string\n supervisorModel?: string\n supervisorSystemPrompt?: string\n superviseOptions?: Partial<\n Omit<\n SuperviseOptions,\n 'budget' | 'backend' | 'deliverable' | 'makeWorkerAgent' | 'allowedModels'\n >\n >\n allowedModels?: readonly string[]\n runSupervised?: (\n profile: SupervisorProfile,\n task: unknown,\n opts: SuperviseOptions,\n ) => Promise<SupervisedResult<unknown>>\n}\n\nexport type SupervisedKnowledgeUpdater = (\n input: SupervisedKnowledgeUpdateInput,\n) => Promise<SupervisedKnowledgeUpdateResult>\n\n/** Build the completion check a supervised KB update uses to stop only when the KB is ready. */\nexport function knowledgeReadinessDeliverable(\n options: Pick<\n SupervisedKnowledgeUpdateOptions,\n 'root' | 'goal' | 'readiness' | 'readinessSpecs' | 'readinessTaskId' | 'readinessOptions'\n >,\n): DeliverableSpec<unknown> {\n return {\n describe: `knowledge base at ${options.root} is ready for: ${options.goal}`,\n async check() {\n const result = await options.readiness({\n root: options.root,\n goal: options.goal,\n readinessSpecs: options.readinessSpecs,\n readinessTaskId: options.readinessTaskId,\n readiness: options.readinessOptions,\n })\n return typeof result === 'boolean' ? result : result.ready\n },\n }\n}\n\n/** Create an `improveKnowledgeBase` update callback backed by runtime supervision. */\nexport function createSupervisedKnowledgeUpdater(\n options: SupervisedKnowledgeUpdateOptions,\n): SupervisedKnowledgeUpdater {\n return (input) =>\n runSupervisedKnowledgeUpdate({\n ...options,\n root: input.candidateRoot ?? input.root ?? options.root,\n goal: input.goal ?? options.goal,\n findings: input.findings ?? options.findings,\n metadata: { ...options.metadata, ...input.metadata },\n })\n}\n\n/** Run a runtime supervisor that updates one candidate knowledge base and stops on readiness. */\nexport async function runSupervisedKnowledgeUpdate(\n options: SupervisedKnowledgeUpdateOptions,\n): Promise<SupervisedKnowledgeUpdateResult> {\n const { profile: workerProfile } = researcherProfile({ harness: options.harness })\n const baseInstructions = options.supervisorSystemPrompt ?? RESEARCH_SUPERVISOR_SYSTEM_PROMPT\n const workerContract = workerProfile.prompt?.systemPrompt\n const systemPrompt = workerContract\n ? `${baseInstructions}\\n\\nEach researcher worker you spawn follows this contract:\\n${workerContract}`\n : baseInstructions\n\n const profile: SupervisorProfile = {\n name: 'knowledge-research-supervisor',\n model: options.supervisorModel,\n systemPrompt,\n }\n const run = options.runSupervised ?? supervise\n const task = formatSupervisedKnowledgeTask(options)\n const supervised = await run(profile, task, {\n ...options.superviseOptions,\n budget: options.budget,\n backend: options.backend,\n deliverable: knowledgeReadinessDeliverable(options),\n makeWorkerAgent: options.makeWorkerAgent,\n allowedModels: options.allowedModels,\n })\n return {\n applied: supervised.kind === 'winner',\n summary:\n supervised.kind === 'winner'\n ? 'research supervisor completed and the knowledge base passed readiness'\n : `research supervisor stopped without a ready knowledge base: ${supervised.reason}`,\n supervised,\n metadata: {\n supervised: true,\n root: options.root,\n goal: options.goal,\n result: supervised.kind,\n },\n }\n}\n\n/** Format the supervisor task with the KB root, readiness requirements, current findings, and metadata. */\nexport function formatSupervisedKnowledgeTask(\n options: Pick<\n SupervisedKnowledgeUpdateOptions,\n 'root' | 'goal' | 'readinessSpecs' | 'readinessTaskId' | 'findings' | 'metadata'\n >,\n): string {\n const sections = [\n `Goal: ${options.goal}`,\n `Knowledge base root: ${options.root}`,\n options.readinessTaskId ? `Readiness task id: ${options.readinessTaskId}` : undefined,\n options.readinessSpecs?.length\n ? `Readiness specs:\\n${JSON.stringify(options.readinessSpecs, null, 2)}`\n : undefined,\n options.findings?.length\n ? `Current findings:\\n${JSON.stringify(options.findings, null, 2)}`\n : undefined,\n options.metadata && Object.keys(options.metadata).length > 0\n ? `Metadata:\\n${JSON.stringify(options.metadata, null, 2)}`\n : undefined,\n ].filter((section): section is string => Boolean(section))\n return `${sections.join('\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