@effect-agent/testing 0.0.1-beta.6 → 0.1.0-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +113 -83
- package/dist/index.mjs +5 -0
- package/dist/index.mjs.map +1 -1
- package/package.json +18 -18
- package/src/certification.ts +5 -0
- package/src/fixtures/travel-planner/phase6.ts +4 -0
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["decodeConversationId","decodeIdempotencyKey","decodeToolCallId","usage","finalParts","toolCallPart","toolTurn","policy","plainDefinition","Itinerary","BookApproval","approvalDefinition","childDefinition","coordinatorDefinition","delegationSupport","usage","Itinerary","digestOf","scriptedUsage","digest","digest","decodeComparableJson","scriptedUsage","researcherLookupParts","researcherReportParts","digestOf","scriptedUsage","researcherLookupParts","researcherReportParts"],"sources":["../src/certification.ts","../src/chaos.ts","../src/code-executor-conformance.ts","../src/code-executor-substitute.ts","../src/fixtures/docs-researcher/definition.ts","../src/fixtures/travel-planner/definition.ts","../src/fixtures/travel-planner/deterministic-layers.ts","../src/fixtures/docs-researcher/mcp.ts","../src/fixtures/docs-researcher/harness.ts","../src/fixtures/travel-planner/phase2.ts","../src/fixtures/travel-planner/scenarios.ts","../src/fixtures/travel-planner/phase3.ts","../src/scripted-model.ts","../src/fixtures/travel-planner/phase4.ts","../src/fixtures/travel-planner/phase5.ts","../src/fixtures/travel-planner/subagents.ts","../src/fixtures/travel-planner/subagents-durable.ts","../src/fixtures/travel-planner/phase6.ts","../src/fixtures/travel-planner/phase7.ts"],"sourcesContent":["import {\n Subagent,\n SubagentPolicy,\n SubagentReservationsMemoryLive,\n SubagentRuntime,\n} from \"@effect-agent/capabilities\";\nimport {\n Agent,\n AgentPolicy,\n ConversationId,\n IdGenerator,\n RunId,\n ToolCallId,\n TurnId,\n type AgentId,\n type SubmissionId,\n} from \"@effect-agent/core\";\nimport { DurableStep, DurableStepError } from \"@effect-agent/engine\";\nimport {\n AgentBindingResolver,\n ApprovalDecisionCommand,\n CertificationCaseResult,\n CertificationReport,\n CertificationSweepResult,\n CertificationTierThreeReport,\n CertifiedAdapterIdentity,\n ConversationExportRequest,\n ConversationStore,\n DefinitionDigests,\n DeploymentId,\n Digest,\n DurableAgentRuntime,\n DurableRuntimeConfig,\n DurableRuntimeFailpoint,\n DurableRuntimeFailpointError,\n DurableRuntimeFailpointLocation,\n DurableRuntimeFailpointTestControl,\n DurableWorkerBinding,\n IdempotencyKey,\n LoadCheckpointRequest,\n Principal,\n ProducerId,\n ResolutionSafeToRetry,\n SubmissionLedger,\n SubmissionLookupById,\n ToolReconciler,\n UnknownResolutionCommand,\n WakeScheduler,\n DEFAULT_OWNERSHIP_LEASE_DURATION,\n certifyPorts,\n childConversationIdFor,\n verifyConversationInvariants,\n type BatchId,\n type CertificationScenario,\n type DurableSubmitFailure,\n type DurableSubmitOptions,\n type Receipt,\n type ResolvedBinding,\n type SubmissionSnapshot,\n} from \"@effect-agent/session\";\nimport {\n Cause,\n Clock,\n Crypto,\n DateTime,\n Duration,\n Effect,\n Exit,\n Layer,\n Option,\n Ref,\n Schema,\n Stream,\n} from \"effect\";\nimport { TestClock } from \"effect/testing\";\nimport { LanguageModel, Model, Tool, Toolkit, type Response } from \"effect/unstable/ai\";\n\n/**\n * P7 WP2 — `certifyDurableAdapters` (plan §1): the one certification entry point a durable\n * adapter pair runs to earn a Schema-encoded certificate.\n *\n * - **Tier 1 — port contract**: the two shared conformance case arrays, verbatim, through\n * `certifyPorts` (TEST-004/STORE-010).\n * - **Tier 2 — coordinator protocol + failpoint convergence**: the durable coordinator is\n * assembled over the CANDIDATE Layer pair with a scripted deterministic model; every\n * `DurableRuntimeFailpointLocation` is armed one-shot across the six scenario shapes\n * (plain / uncertain-tool / durable-steps / approval / join / delegation). After the injected\n * fault the runner asserts the state stays CLASSIFIABLE (recovery + the public unblocking\n * operations `resolveUnknown`/`resolveApproval` are the only levers used) and that the\n * re-drive CONVERGES to `verifyConversationInvariants` with `requireAllSettled` — including a\n * fully discharged digest-chain check, because the runner captures per-batch producer\n * identity at append time.\n * - **Tier 3 — real loss lever**: recorded honestly. A durable adapter either supplies a\n * `CertificationCrashLever` executed in this run, cites its committed real-loss evidence\n * (process-kill / eviction suites), or the certificate says `not-exercised`. A non-durable\n * reference adapter records `not-applicable`.\n *\n * The runner is adapter-neutral and platform-neutral: it imports nothing Node-only, so the\n * same entry point runs under `@effect/vitest` on Node and inside workerd (storage-cloudflare's\n * in-workerd runner). It must run under a TestClock (Tier 1 drives lease expiry through\n * virtual time), and requires only `Crypto.Crypto` from the environment.\n */\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * A real-loss lever supplied by an adapter that wants Tier 3 exercised IN this certification\n * run (kill/evict/reopen around a designated row subset). Rows report with\n * `suite: \"real-loss\"`. Failures must be captured per-row — the lever's error channel is\n * `never` so a certificate is always produced.\n */\nexport type CertificationCrashLever = Effect.Effect<ReadonlyArray<CertificationCaseResult>>;\n\nexport interface CertifyDurableAdaptersOptions<LedgerE = never, StoreE = never> {\n /** Adapter pair identity named by the certificate (durability is read from the ledger). */\n readonly adapter: {\n readonly name: string;\n readonly version?: string | undefined;\n };\n /**\n * The candidate Layer pair. When both ports must share one connection root (the ADR-0011\n * \"same file\" rule), pass the SAME combined Layer instance for both fields — Layer\n * memoization builds it once. A candidate may require `Crypto.Crypto` (the memory reference\n * does); the certification's own environment supplies nothing else.\n */\n readonly submissionLedger: Layer.Layer<SubmissionLedger, LedgerE, Crypto.Crypto>;\n readonly conversationStore: Layer.Layer<ConversationStore, StoreE, Crypto.Crypto>;\n /** Defaults to `WakeScheduler.layerNoop`; the runner re-drives lanes explicitly. */\n readonly wakeScheduler?: Layer.Layer<WakeScheduler> | undefined;\n /** Executes Tier 3 in this run; takes precedence over `tierThreeEvidence`. */\n readonly crashLever?: CertificationCrashLever | undefined;\n /** Repository-relative citations of committed real-loss suites (Tier 3 `recorded-evidence`). */\n readonly tierThreeEvidence?: ReadonlyArray<string> | undefined;\n /**\n * The candidate ledger's configured ownership lease (defaults to the D5 default, 30s).\n * Every Tier-2 re-drive round advances the TestClock past this lease before reclaiming:\n * a live lease may block ALL new claims (the SQL adapters do; the memory reference also\n * allows same-producer reclaim), so the adapter-NEUTRAL recovery lever after a mid-Attempt\n * fault is lease expiry — exactly the documented D5 liveness mechanism, driven through\n * virtual time.\n */\n readonly ownershipLeaseDuration?: Duration.Duration | undefined;\n}\n\n/** The six Tier-2 scenario shapes in sweep order. */\nexport const CERTIFICATION_SCENARIOS: ReadonlyArray<CertificationScenario> = [\n \"plain\",\n \"uncertain-tool\",\n \"durable-steps\",\n \"approval\",\n \"join\",\n \"delegation\",\n];\n\n/**\n * Coordinator failpoint locations that none of the six scenario shapes can reach, recorded\n * honestly instead of silently claimed: all three sit on operator/abort paths the shapes do\n * not take. They are pinned in-process by the P5/S2 suites\n * (`packages/testing/test/durable-tools.test.ts` \"resolveUnknown is idempotent across the\n * intent failpoint\", `durable-runtime.test.ts` abort rows,\n * `durable-subagents.test.ts` abort propagation) and by the process-kill/eviction crash\n * matrices. Runner tests assert the observed never-fired set equals EXACTLY this list, so a\n * protocol change that silently stops exercising a location fails the certification.\n */\nexport const TIER2_UNREACHED_LOCATIONS: ReadonlyArray<DurableRuntimeFailpointLocation> = [\n \"abort:after-intent\",\n \"resolve:after-intent\",\n \"subagent:after-child-abort-intent\",\n];\n\n/** Locations of `tier2` rows whose armed fault never fired in ANY scenario, sorted. */\nexport const tier2NeverFiredLocations = (\n tier2: ReadonlyArray<CertificationSweepResult>,\n): ReadonlyArray<DurableRuntimeFailpointLocation> => {\n const fired = new Set<DurableRuntimeFailpointLocation>();\n for (const row of tier2) {\n if (row.failpointFired) fired.add(row.location);\n }\n return DurableRuntimeFailpointLocation.literals.filter((location) => !fired.has(location)).sort();\n};\n\n// ---------------------------------------------------------------------------\n// Deterministic fixtures (scripted prompt-shape models, agents, delegation)\n// ---------------------------------------------------------------------------\n\nconst SHA_A = Schema.decodeSync(Digest)(\"a\".repeat(64));\nconst DIGESTS = DefinitionDigests.make({ agent: SHA_A, model: SHA_A, tools: SHA_A });\nconst CHILD_DIGEST_STRINGS = {\n agent: \"b\".repeat(64),\n model: \"c\".repeat(64),\n tools: \"d\".repeat(64),\n} as const;\nconst CHILD_DIGESTS = DefinitionDigests.make({\n agent: Schema.decodeSync(Digest)(CHILD_DIGEST_STRINGS.agent),\n model: Schema.decodeSync(Digest)(CHILD_DIGEST_STRINGS.model),\n tools: Schema.decodeSync(Digest)(CHILD_DIGEST_STRINGS.tools),\n});\nconst PRINCIPAL = Schema.decodeSync(Principal)(\"principal-certification\");\nconst decodeConversationId = Schema.decodeSync(ConversationId);\nconst decodeIdempotencyKey = Schema.decodeSync(IdempotencyKey);\nconst decodeToolCallId = Schema.decodeSync(ToolCallId);\n\nconst usage = { inputTokens: {}, outputTokens: {} };\n\nconst finalParts = (text: string): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"answer\" },\n { type: \"text-delta\", id: \"answer\", delta: text },\n { type: \"text-end\", id: \"answer\" },\n { type: \"finish\", reason: \"stop\", usage },\n];\n\nconst toolCallPart = (id: string, name: string, params: unknown): Response.StreamPartEncoded => ({\n type: \"tool-call\",\n id,\n name,\n params,\n providerExecuted: false,\n});\n\nconst toolTurn = (\n ...calls: ReadonlyArray<Response.StreamPartEncoded>\n): ReadonlyArray<Response.StreamPartEncoded> => [\n ...calls,\n { type: \"finish\", reason: \"tool-calls\", usage },\n];\n\n/**\n * Stateless scripted model that decides by PROMPT SHAPE instead of call count: while the\n * prompt carries no committed tool result the model declares `toolParts` (when given),\n * otherwise it answers with the final text. Deciding on the canonical prompt keeps every cell\n * deterministic regardless of where the injected fault fell — a re-invoked Turn re-declares\n * the same batch and a resumed batch flows into the final answer, so every scenario always\n * exercises its tool path and always converges.\n */\nconst promptShapeModel = (\n name: string,\n finalText: string,\n toolParts?: ReadonlyArray<Response.StreamPartEncoded>,\n) =>\n Model.make(\n \"scripted\",\n name,\n Layer.effect(\n LanguageModel.LanguageModel,\n LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (request) => {\n const hasToolResult = request.prompt.content.some((message) => message.role === \"tool\");\n const parts =\n toolParts === undefined || hasToolResult ? finalParts(finalText) : toolParts;\n return Stream.fromIterable(parts);\n },\n }),\n ),\n );\n\nconst policy = AgentPolicy.make({\n maxTurns: 4,\n maxToolCalls: 4,\n maxDuration: \"30 seconds\",\n toolConcurrency: 2,\n});\n\nconst QuestionInput = Schema.Struct({ question: Schema.String });\nconst AnswerOutput = Schema.Struct({ answer: Schema.String });\n\n/** plain / join: no tools — the pure Turn/submission/join seams. */\nconst plainDefinition = Agent.define(\"certify-plain\", {\n input: QuestionInput,\n output: AnswerOutput,\n instructions: \"Answer as JSON.\",\n toolkit: Toolkit.empty,\n policy,\n});\n\n/** uncertain-tool: unannotated → fail-closed `uncertain`, enters the prepared/settled protocol. */\nconst Book = Tool.make(\"book\", {\n parameters: Schema.Struct({ ref: Schema.String }),\n success: Schema.Struct({ confirmation: Schema.String }),\n});\nconst bookToolkit = Toolkit.make(Book);\nconst uncertainDefinition = Agent.define(\"certify-uncertain\", {\n input: QuestionInput,\n output: AnswerOutput,\n instructions: \"Book it.\",\n toolkit: bookToolkit,\n policy,\n});\n\n/** durable-steps: declaring `DurableStep` as a dependency is what makes the Tool durable. */\nconst Itinerary = Tool.make(\"itinerary\", {\n parameters: Schema.Struct({ ref: Schema.String }),\n success: Schema.Struct({ state: Schema.String }),\n failure: DurableStepError,\n dependencies: [DurableStep],\n});\nconst itineraryToolkit = Toolkit.make(Itinerary);\nconst stepsDefinition = Agent.define(\"certify-steps\", {\n input: QuestionInput,\n output: AnswerOutput,\n instructions: \"Reserve the itinerary.\",\n toolkit: itineraryToolkit,\n policy,\n});\n\n/** approval: fail-closed — no `DurableApprovalResolver` Layer, so undecided approvals suspend. */\nconst BookApproval = Tool.make(\"book\", {\n parameters: Schema.Struct({ ref: Schema.String }),\n success: Schema.Struct({ confirmation: Schema.String }),\n needsApproval: true,\n});\nconst approvalToolkit = Toolkit.make(BookApproval);\nconst approvalDefinition = Agent.define(\"certify-approval\", {\n input: QuestionInput,\n output: AnswerOutput,\n instructions: \"Book after approval.\",\n toolkit: approvalToolkit,\n policy,\n});\n\n/** delegation: durable attached child plus an ordinary uncertain sibling in ONE batch. */\nconst childDefinition = Agent.define(\"certify-child\", {\n input: QuestionInput,\n output: AnswerOutput,\n instructions: \"Answer as JSON.\",\n toolkit: Toolkit.empty,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 1,\n maxDuration: \"30 seconds\",\n toolConcurrency: 1,\n }),\n});\n\nclass CertifyDelegationFailed extends Schema.TaggedError<CertifyDelegationFailed>()(\n \"CertifyDelegationFailed\",\n { childErrorTag: Schema.String },\n) {}\n\nconst researchDelegation = Subagent.define(\"delegate_research\", {\n description: \"Research one bounded question and return findings.\",\n target: childDefinition,\n parameters: Schema.Struct({ topic: Schema.String }),\n success: Schema.Struct({ summary: Schema.String }),\n failure: CertifyDelegationFailed,\n prepareInput: ({ topic }) => Effect.succeed({ question: `research:${topic}` }),\n projectResult: (output) => Effect.succeed({ summary: `finding:${output.answer}` }),\n policy: SubagentPolicy.make({\n maxChildren: 2,\n maxConcurrency: 2,\n maxTurns: 4,\n maxToolCalls: 4,\n maxDuration: \"10 seconds\",\n }),\n});\n\nconst Lookup = Tool.make(\"lookup\", {\n parameters: Schema.Struct({ key: Schema.String }),\n success: Schema.Struct({ value: Schema.String }),\n});\n\nconst coordinatorDefinition = Agent.define(\"certify-coordinator\", {\n input: Schema.Struct({ mission: Schema.String }),\n output: Schema.Struct({ report: Schema.String }),\n instructions: \"Delegate and look up, then answer as JSON.\",\n toolkit: Toolkit.make(researchDelegation.tool, Lookup),\n policy: AgentPolicy.make({\n maxTurns: 4,\n maxToolCalls: 3,\n maxDuration: \"30 seconds\",\n toolConcurrency: 2,\n }),\n});\n\nconst mapChildFailure = (failure: { readonly _tag: string }) =>\n CertifyDelegationFailed.make({ childErrorTag: failure._tag });\n\nconst DELEGATE_CALL = decodeToolCallId(\"delegate-1\");\n\n/** Fixture-only identity source consumed by the delegation Layer's ephemeral capture. */\nconst identifiers = Layer.effect(\n IdGenerator,\n Effect.gen(function* () {\n const counter = yield* Ref.make(0);\n const next = <A>(decode: (value: string) => A, prefix: string) =>\n Ref.getAndUpdate(counter, (value) => value + 1).pipe(\n Effect.map((value) => decode(`${prefix}-${value}`)),\n );\n return {\n nextConversationId: next(decodeConversationId, \"certify-fixture-conversation\"),\n nextRunId: next(Schema.decodeSync(RunId), \"certify-fixture-run\"),\n nextTurnId: next(Schema.decodeSync(TurnId), \"certify-fixture-turn\"),\n };\n }),\n);\n\nconst delegationSupport = Layer.mergeAll(SubagentReservationsMemoryLive, identifiers);\n\n// ---------------------------------------------------------------------------\n// Tier 2 — scenario cells\n// ---------------------------------------------------------------------------\n\ninterface CertificationCell {\n readonly resolver: (typeof AgentBindingResolver)[\"Service\"];\n /** Idempotent submission batch — safe to replay verbatim after a submit-boundary fault. */\n readonly submit: Effect.Effect<ReadonlyArray<Receipt>, DurableSubmitFailure, DurableAgentRuntime>;\n /** All lanes of the cell in drive order, computed from the (possibly replayed) receipts. */\n readonly lanes: (receipts: ReadonlyArray<Receipt>) => ReadonlyArray<ConversationId>;\n}\n\nconst submitOptionsFor = (slug: string, conversationId: ConversationId): DurableSubmitOptions => ({\n conversationId,\n principal: PRINCIPAL,\n idempotencyKey: decodeIdempotencyKey(`certify-key-${slug}`),\n definitions: DIGESTS,\n});\n\n/** One single-agent cell: one lane, one Submission, one registered exact-digest binding. */\nconst makeSingleAgentCell = (\n definition: { readonly id: AgentId; readonly input: typeof QuestionInput },\n resolved: ResolvedBinding,\n slug: string,\n): CertificationCell => {\n const conversationId = decodeConversationId(`certify-${slug}`);\n const submit = Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n const receipt = yield* runtime.submit(\n { definition: { id: definition.id, input: definition.input } },\n { question: `certify ${slug}` },\n submitOptionsFor(slug, conversationId),\n );\n return [receipt];\n });\n return {\n resolver: AgentBindingResolver.fromBindings([resolved]),\n submit,\n lanes: () => [conversationId],\n };\n};\n\nconst makeCell = Effect.fn(\"Certification.makeCell\")(function* (\n scenario: CertificationScenario,\n slug: string,\n) {\n switch (scenario) {\n case \"plain\": {\n const binding = Agent.withModel(\n plainDefinition,\n promptShapeModel(\"certify-plain\", '{\"answer\":\"done\"}'),\n );\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS);\n return makeSingleAgentCell(plainDefinition, resolved, slug);\n }\n case \"uncertain-tool\": {\n const binding = Agent.withModel(\n uncertainDefinition,\n promptShapeModel(\n \"certify-uncertain\",\n '{\"answer\":\"booked\"}',\n toolTurn(toolCallPart(\"book-1\", \"book\", { ref: `r-${slug}` })),\n ),\n );\n const toolLayer = bookToolkit.toLayer({\n book: ({ ref }) => Effect.succeed({ confirmation: `confirmed-${ref}` }),\n });\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(\n Effect.provide(toolLayer),\n );\n return makeSingleAgentCell(uncertainDefinition, resolved, slug);\n }\n case \"durable-steps\": {\n const binding = Agent.withModel(\n stepsDefinition,\n promptShapeModel(\n \"certify-steps\",\n '{\"answer\":\"reserved\"}',\n toolTurn(toolCallPart(\"itinerary-1\", \"itinerary\", { ref: `trip-${slug}` })),\n ),\n );\n const toolLayer = itineraryToolkit.toLayer({\n itinerary: ({ ref }) =>\n Effect.gen(function* () {\n const step = yield* DurableStep;\n const flight = yield* step.do(\n \"reserve-flight\",\n Schema.String,\n Effect.succeed(`flight-${ref}`),\n );\n const lodging = yield* step.do(\n \"reserve-lodging\",\n Schema.String,\n Effect.succeed(`lodging-${ref}`),\n );\n return { state: `${flight}+${lodging}` };\n }),\n });\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(\n Effect.provide(toolLayer),\n );\n return makeSingleAgentCell(stepsDefinition, resolved, slug);\n }\n case \"approval\": {\n const binding = Agent.withModel(\n approvalDefinition,\n promptShapeModel(\n \"certify-approval\",\n '{\"answer\":\"approved\"}',\n toolTurn(toolCallPart(\"book-1\", \"book\", { ref: `r-${slug}` })),\n ),\n );\n const toolLayer = approvalToolkit.toLayer({\n book: ({ ref }) => Effect.succeed({ confirmation: `confirmed-${ref}` }),\n });\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(\n Effect.provide(toolLayer),\n );\n return makeSingleAgentCell(approvalDefinition, resolved, slug);\n }\n case \"join\": {\n const binding = Agent.withModel(\n plainDefinition,\n promptShapeModel(\"certify-join\", '{\"answer\":\"host answer\"}'),\n );\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS);\n const conversationId = decodeConversationId(`certify-${slug}`);\n const submitOne = (key: string, question: string) =>\n Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n return yield* runtime.submit(\n { definition: { id: plainDefinition.id, input: plainDefinition.input } },\n { question },\n {\n conversationId,\n principal: PRINCIPAL,\n idempotencyKey: decodeIdempotencyKey(key),\n definitions: DIGESTS,\n },\n );\n });\n const cell: CertificationCell = {\n resolver: AgentBindingResolver.fromBindings([resolved]),\n submit: Effect.gen(function* () {\n const host = yield* submitOne(`certify-key-${slug}-host`, \"host question\");\n const queued = yield* submitOne(`certify-key-${slug}-queued`, \"queued question\");\n return [host, queued];\n }),\n lanes: () => [conversationId],\n };\n return cell;\n }\n case \"delegation\": {\n const childBinding = Agent.withModel(\n childDefinition,\n promptShapeModel(\"certify-child\", '{\"answer\":\"child-answer\"}'),\n );\n const parentBinding = Agent.withModel(\n coordinatorDefinition,\n promptShapeModel(\n \"certify-parent\",\n '{\"report\":\"done\"}',\n toolTurn(\n toolCallPart(\"delegate-1\", \"delegate_research\", { topic: \"paris\" }),\n toolCallPart(\"lookup-1\", \"lookup\", { key: \"hotels\" }),\n ),\n ),\n );\n const delegationLayer = SubagentRuntime.layer(researchDelegation, childBinding, {\n mapChildFailure,\n durable: { targetDigests: CHILD_DIGEST_STRINGS },\n }).pipe(Layer.provide(delegationSupport));\n const lookupLayer = Toolkit.make(Lookup).toLayer({\n lookup: ({ key }) => Effect.succeed({ value: `found-${key}` }),\n });\n const parentResolved = yield* DurableWorkerBinding.make(parentBinding, DIGESTS).pipe(\n Effect.provide(Layer.mergeAll(delegationLayer, lookupLayer)),\n );\n const childResolved = yield* DurableWorkerBinding.make(childBinding, CHILD_DIGESTS);\n const conversationId = decodeConversationId(`certify-${slug}`);\n const cell: CertificationCell = {\n resolver: AgentBindingResolver.fromBindings([parentResolved, childResolved]),\n submit: Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n const receipt = yield* runtime.submit(\n { definition: { id: coordinatorDefinition.id, input: coordinatorDefinition.input } },\n { mission: \"plan\" },\n submitOptionsFor(slug, conversationId),\n );\n return [receipt];\n }),\n lanes: (receipts) => {\n const parent = receipts.at(0);\n return parent === undefined\n ? [conversationId]\n : [conversationId, childConversationIdFor(parent.submissionId, DELEGATE_CALL)];\n },\n };\n return cell;\n }\n }\n});\n\n/** Maximum recovery/drive/unblock rounds before a cell is reported non-convergent. */\nconst MAX_REDRIVE_ROUNDS = 8;\n\n/**\n * Verify one lane after convergence: canonical export + every lane Submission the ledger or\n * the log names (the same collection rule as the admin `verify` member), fed to the shared\n * invariant checker in convergence mode WITH the captured per-batch producer directory, so\n * the digest chain is fully recomputed instead of skipped.\n */\nconst verifyLane = Effect.fn(\"Certification.verifyLane\")(function* (\n lane: ConversationId,\n batchProducers: ReadonlyMap<BatchId, ProducerId>,\n) {\n const store = yield* ConversationStore;\n const ledger = yield* SubmissionLedger;\n const exported = yield* store.export(ConversationExportRequest.make({ conversationId: lane }));\n const rows = new Map<SubmissionId, SubmissionSnapshot>();\n const nonterminal = yield* Stream.runCollect(ledger.scanNonterminal);\n for (const submission of nonterminal) {\n if (submission.conversationId === lane) rows.set(submission.submissionId, submission);\n }\n const named = new Set<SubmissionId>();\n for (const envelope of exported.records) {\n const payload = envelope.record.payload;\n if (\n payload._tag === \"UserInputRecorded\" ||\n payload._tag === \"SubmissionSettled\" ||\n payload._tag === \"AbortRequested\"\n ) {\n named.add(payload.submissionId);\n }\n }\n for (const submissionId of named) {\n if (rows.has(submissionId)) continue;\n const found = yield* ledger.lookup(SubmissionLookupById.make({ submissionId }));\n if (Option.isSome(found) && found.value.conversationId === lane) {\n rows.set(submissionId, found.value);\n }\n }\n const checkpoint = yield* store.loadCheckpoint(\n LoadCheckpointRequest.make({ conversationId: lane }),\n );\n return yield* verifyConversationInvariants({\n export: exported,\n submissions: [...rows.values()],\n batchProducers,\n checkpoint: Option.getOrUndefined(checkpoint),\n requireAllSettled: true,\n });\n});\n\nconst failureTagOf = <E>(cause: Cause.Cause<E>): string => {\n const failure = Cause.findErrorOption(cause);\n if (Option.isSome(failure)) {\n const error: unknown = failure.value;\n if (typeof error === \"object\" && error !== null && \"_tag\" in error) {\n return String((error as { _tag: unknown })._tag);\n }\n return String(error).slice(0, 256);\n }\n return \"defect\";\n};\n\n/** One Tier-2 sweep cell: arm `location` one-shot, drive `scenario`, converge, verify. */\nconst runSweepCell = Effect.fn(\"Certification.runSweepCell\")(function* (\n scenario: CertificationScenario,\n location: DurableRuntimeFailpointLocation,\n batchProducers: ReadonlyMap<BatchId, ProducerId>,\n leaseAdvance: Duration.Duration,\n) {\n const runtime = yield* DurableAgentRuntime;\n const ledger = yield* SubmissionLedger;\n const control = yield* DurableRuntimeFailpointTestControl;\n const slug = `${scenario}-${location.replaceAll(\":\", \"-\")}`;\n\n const failed = (detail: string, fired: boolean): CertificationSweepResult =>\n CertificationSweepResult.make({\n scenario,\n location,\n failpointFired: fired,\n status: \"failed\",\n digestChainVerified: false,\n detail: detail.slice(0, 4_096),\n });\n\n const cell = yield* makeCell(scenario, slug);\n\n // One-shot arm: the fault fires at most once anywhere in the cell (initial drive OR a\n // re-drive round's public unblocking operation), modelling one crash at this boundary.\n const fired = yield* Ref.make(false);\n yield* control.setHandler((hit) =>\n hit !== location\n ? Effect.void\n : Ref.getAndSet(fired, true).pipe(\n Effect.flatMap((already) =>\n already\n ? Effect.void\n : Effect.fail(DurableRuntimeFailpointError.make({ location: hit })),\n ),\n ),\n );\n\n // Submissions are idempotent (DUR-001): one replay recovers a submit-boundary fault.\n let receipts: ReadonlyArray<Receipt>;\n const firstSubmit = yield* Effect.exit(cell.submit);\n if (Exit.isSuccess(firstSubmit)) {\n receipts = firstSubmit.value;\n } else {\n const secondSubmit = yield* Effect.exit(cell.submit);\n if (Exit.isFailure(secondSubmit)) {\n yield* control.clear;\n return failed(\n `submission replay did not recover: ${failureTagOf(secondSubmit.cause)}`,\n yield* Ref.get(fired),\n );\n }\n receipts = secondSubmit.value;\n }\n const lanes = cell.lanes(receipts);\n\n const driveLane = (lane: ConversationId) =>\n runtime\n .processConversationResolved(lane)\n .pipe(Effect.provideService(AgentBindingResolver, cell.resolver));\n\n const allSettled = Effect.gen(function* () {\n for (const receipt of receipts) {\n const snapshot = yield* ledger.lookup(\n SubmissionLookupById.make({ submissionId: receipt.submissionId }),\n );\n if (Option.isNone(snapshot) || snapshot.value.state !== \"settled\") return false;\n }\n return true;\n });\n\n // Re-drive to convergence using ONLY public operations: worker drives, recovery passes,\n // and the authorized DUR-017/approval unblocking paths chosen from `explainConversation`.\n let converged = false;\n for (let round = 0; round < MAX_REDRIVE_ROUNDS && !converged; round++) {\n // Expire any lease a faulted Attempt left behind (D5): virtual time is the\n // adapter-neutral reclaim lever — a live lease may block every new claim.\n yield* TestClock.adjust(leaseAdvance);\n yield* Effect.exit(runtime.runRecovery);\n for (const lane of lanes) {\n yield* Effect.exit(driveLane(lane));\n }\n for (const lane of lanes) {\n const explains = yield* Effect.exit(runtime.explainConversation(lane));\n if (Exit.isFailure(explains)) continue;\n for (const explanation of explains.value) {\n for (const unknown of explanation.evidence.unknownCalls) {\n if (unknown.resolved) continue;\n yield* Effect.exit(\n runtime.resolveUnknown(\n UnknownResolutionCommand.make({\n submissionId: explanation.submission.submissionId,\n toolCallId: unknown.toolCallId,\n author: \"certification-runner\",\n reason: `re-drive after injected fault at ${location}`,\n resolution: ResolutionSafeToRetry.make(),\n }),\n ),\n );\n }\n for (const pending of explanation.evidence.approvalsPending) {\n const decided = explanation.evidence.approvalDecisions.some(\n (decision) => decision.toolCallId === pending.toolCallId,\n );\n if (decided) continue;\n yield* Effect.exit(\n runtime.resolveApproval(\n ApprovalDecisionCommand.make({\n submissionId: explanation.submission.submissionId,\n toolCallId: pending.toolCallId,\n decision: \"approved\",\n resolver: \"certification-runner\",\n reason: `re-drive after injected fault at ${location}`,\n }),\n ),\n );\n }\n }\n }\n const settled = yield* Effect.exit(allSettled);\n converged = Exit.isSuccess(settled) && settled.value;\n }\n yield* control.clear;\n const wasFired = yield* Ref.get(fired);\n\n if (!converged) {\n return failed(`did not converge within ${MAX_REDRIVE_ROUNDS} re-drive rounds`, wasFired);\n }\n\n // Every lane of the cell must verify in convergence mode with a recomputed digest chain.\n let digestChainVerified = true;\n const failedChecks: Array<string> = [];\n for (const lane of lanes) {\n const verdict = yield* Effect.exit(verifyLane(lane, batchProducers));\n if (Exit.isFailure(verdict)) {\n return failed(`lane ${lane} could not be verified: ${failureTagOf(verdict.cause)}`, wasFired);\n }\n for (const check of verdict.value.checks) {\n if (check.status === \"failed\") {\n failedChecks.push(\n `${lane}:${check.name}${check.detail === undefined ? \"\" : ` (${check.detail})`}`,\n );\n }\n if (check.name === \"digest-chain\" && check.status !== \"passed\") {\n digestChainVerified = false;\n }\n }\n }\n if (failedChecks.length > 0 || !digestChainVerified) {\n return failed(\n failedChecks.length > 0\n ? `invariant checks failed: ${failedChecks.join(\"; \")}`\n : \"the digest chain was not fully recomputed\",\n wasFired,\n );\n }\n\n return CertificationSweepResult.make({\n scenario,\n location,\n failpointFired: wasFired,\n status: wasFired ? \"converged\" : \"not-triggered\",\n digestChainVerified,\n });\n});\n\n// ---------------------------------------------------------------------------\n// Tier 3 — real loss lever record\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the Tier-3 record honestly (plan §1): a non-durable reference adapter has no real\n * loss to exercise (`not-applicable`); a supplied lever runs NOW (`exercised`); committed\n * real-loss citations are recorded (`recorded-evidence`); otherwise the certificate says\n * `not-exercised` — a scoped statement, never a silent claim.\n */\nexport const resolveTierThree = Effect.fn(\"Certification.resolveTierThree\")(function* (\n durability: CertifiedAdapterIdentity[\"durability\"],\n options: {\n readonly crashLever?: CertificationCrashLever | undefined;\n readonly tierThreeEvidence?: ReadonlyArray<string> | undefined;\n },\n): Effect.fn.Return<CertificationTierThreeReport, never> {\n if (durability === \"non-durable\") {\n return CertificationTierThreeReport.make({\n status: \"not-applicable\",\n evidence: [],\n cases: [],\n detail:\n \"the adapter declares non-durable state (reference/conformance adapter); there is no real loss to exercise\",\n });\n }\n if (options.crashLever !== undefined) {\n const cases = yield* options.crashLever;\n return CertificationTierThreeReport.make({\n status: \"exercised\",\n evidence: options.tierThreeEvidence ?? [],\n cases,\n });\n }\n if (options.tierThreeEvidence !== undefined && options.tierThreeEvidence.length > 0) {\n return CertificationTierThreeReport.make({\n status: \"recorded-evidence\",\n evidence: options.tierThreeEvidence,\n cases: [],\n });\n }\n return CertificationTierThreeReport.make({\n status: \"not-exercised\",\n evidence: [],\n cases: [],\n detail:\n \"no crash lever was supplied and no committed real-loss evidence was cited; Tier 3 is NOT discharged for this adapter\",\n });\n});\n\n// ---------------------------------------------------------------------------\n// Entry point\n// ---------------------------------------------------------------------------\n\nconst nowUtc: Effect.Effect<DateTime.Utc> = Effect.map(Clock.currentTimeMillis, (millis) =>\n DateTime.toUtc(DateTime.makeUnsafe(millis)),\n);\n\n/**\n * Certify one durable adapter pair (plan §1, §8 WP2). Runs Tier 2 FIRST over pristine\n * storage (each cell converges to all-settled before the next starts, so the recovery scan\n * never sees foreign leftovers), then Tier 1's port contract cases (whose lanes deliberately\n * end in every nonterminal shape), then records Tier 3. Requires `Crypto.Crypto` and a\n * TestClock-backed environment; the candidate Layers are built exactly once.\n */\nexport const certifyDurableAdapters = <LedgerE = never, StoreE = never>(\n options: CertifyDurableAdaptersOptions<LedgerE, StoreE>,\n): Effect.Effect<CertificationReport, LedgerE | StoreE, Crypto.Crypto> => {\n const batchProducers = new Map<BatchId, ProducerId>();\n // Interpose the candidate store with an append-time capture of each batch's producer\n // identity — the one value the ConversationStore port deliberately does not export — so\n // Tier 2's invariant verification recomputes the FULL digest chain instead of skipping it.\n const capturingStore = Layer.effect(ConversationStore)(\n Effect.gen(function* () {\n const inner = yield* ConversationStore;\n return ConversationStore.of({\n ...inner,\n append: (request) =>\n Effect.sync(() => {\n batchProducers.set(request.batch.batchId, request.batch.producerId);\n }).pipe(Effect.andThen(inner.append(request))),\n });\n }),\n ).pipe(Layer.provide(options.conversationStore));\n\n const support = Layer.mergeAll(\n options.submissionLedger,\n capturingStore,\n options.wakeScheduler ?? WakeScheduler.layerNoop,\n DurableRuntimeFailpoint.layerTest,\n ToolReconciler.uncertain,\n DurableRuntimeConfig.layer({\n deploymentId: Schema.decodeSync(DeploymentId)(\"deployment-certification\"),\n producerId: Schema.decodeSync(ProducerId)(\"producer-certification\"),\n settlementPollInterval: Duration.millis(50),\n leaseRenewalInterval: Duration.seconds(5),\n abortPollInterval: Duration.millis(50),\n }),\n );\n const environment = DurableAgentRuntime.layer.pipe(Layer.provideMerge(support));\n\n const leaseAdvance = Duration.millis(\n Duration.toMillis(options.ownershipLeaseDuration ?? DEFAULT_OWNERSHIP_LEASE_DURATION) + 1_000,\n );\n\n const program = Effect.gen(function* () {\n const ledger = yield* SubmissionLedger;\n\n // Tier 2 — coordinator failpoint convergence sweep.\n const tier2: Array<CertificationSweepResult> = [];\n for (const scenario of CERTIFICATION_SCENARIOS) {\n for (const location of DurableRuntimeFailpointLocation.literals) {\n tier2.push(yield* runSweepCell(scenario, location, batchProducers, leaseAdvance));\n }\n }\n\n // Tier 1 — the shared port contract suites, verbatim.\n const tier1 = yield* certifyPorts();\n\n // Tier 3 — the real loss lever record.\n const capabilities = yield* ledger.capabilities;\n const tier3 = yield* resolveTierThree(capabilities.durability, options);\n\n const generatedAt = yield* nowUtc;\n const ok =\n tier1.every((result) => result.status === \"passed\") &&\n tier2.every((result) => result.status !== \"failed\") &&\n tier3.cases.every((result) => result.status === \"passed\");\n\n return CertificationReport.make({\n format: \"effect-agent/certification@1\",\n adapter: CertifiedAdapterIdentity.make({\n name: options.adapter.name,\n ...(options.adapter.version === undefined ? {} : { version: options.adapter.version }),\n durability: capabilities.durability,\n }),\n generatedAt,\n tier1,\n tier2,\n tier3,\n ok,\n });\n });\n\n return program.pipe(Effect.provide(environment));\n};\n","import {\n Subagent,\n SubagentPolicy,\n SubagentReservationsMemoryLive,\n SubagentRuntime,\n} from \"@effect-agent/capabilities\";\nimport {\n Agent,\n AgentPolicy,\n ConversationId,\n IdGenerator,\n RunId,\n SubmissionId,\n ToolCallId,\n TurnId,\n} from \"@effect-agent/core\";\nimport { DurableStep, DurableStepError, ToolExecutionClass } from \"@effect-agent/engine\";\nimport {\n AbortCommand,\n AgentBindingResolver,\n ApprovalDecisionCommand,\n ConversationExportRequest,\n ConversationStore,\n DefinitionDigests,\n Digest,\n DurableAgentRuntime,\n DurableRuntimeConfig,\n DurableRuntimeFailpointError,\n DurableRuntimeFailpointLocation,\n DurableRuntimeFailpointTestControl,\n DurableWorkerBinding,\n IdempotencyKey,\n ObligationThresholds,\n Principal,\n ResolutionAbortSubmission,\n ResolutionCompletedWithResult,\n ResolutionNeverHappened,\n SubmissionLedger,\n SubmissionLookupById,\n UnknownResolutionCommand,\n childConversationIdFor,\n verifyConversationInvariants,\n type CanonicalRecordEnvelope,\n type BatchId,\n type ProducerId,\n type Receipt,\n type ResolvedBinding,\n type Settlement,\n type SubmissionSnapshot,\n type UnknownResolution,\n} from \"@effect-agent/session\";\nimport { Cause, Effect, Exit, Layer, Option, Ref, Schema, Stream } from \"effect\";\nimport { FastCheck } from \"effect/testing\";\nimport { LanguageModel, Model, Prompt, Tool, Toolkit, type Response } from \"effect/unstable/ai\";\n\n/**\n * P7 WP4 chaos machinery (plan §5): a Schema-first `ChaosPlan`, a seeded generator over\n * `effect/testing/FastCheck` (already inside the pinned Effect — no new dependency), and a\n * deterministic runner that drives the durable coordinator over whatever adapter pair the test\n * provides. Every plan ends in the SAME claims the crash matrices make:\n *\n * 1. `verifyConversationInvariants` in convergence mode over every touched Conversation (the\n * shared WP1 checker — one set of claims for admin verify, certification, chaos, and soak);\n * 2. `scanObligations` returning ZERO entries (everything settled; nothing invisibly stuck);\n * 3. supplier non-fabrication wherever the deterministic desk was in play (durability §10: no\n * canonical Tool success exists that the external store did not actually produce).\n *\n * Replay contract: the memory/SQLite chaos tests derive every plan from one root seed\n * (`CHAOS_SEED` env override; see `chaosSeedFromEnv`) and print that seed plus the failing\n * plan's own seed in the failure output, so any red run is replayable byte-for-byte.\n */\n\n// ---------------------------------------------------------------------------\n// ChaosPlan schema\n// ---------------------------------------------------------------------------\n\n/** The six durable scenario flavors a chaos lane can exercise (plan §5). */\nexport const ChaosScenarioKind = Schema.Literals([\n \"plain\",\n \"uncertain-tool\",\n \"durable-steps\",\n \"approval\",\n \"join\",\n \"delegation\",\n]);\nexport type ChaosScenarioKind = typeof ChaosScenarioKind.Type;\n\nconst LaneIndex = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(7));\n\n/** One Submission of a plan: which lane it queues into and that lane's scenario flavor. */\nexport class ChaosSubmissionSpec extends Schema.Class<ChaosSubmissionSpec>(\n \"@effect-agent/testing/ChaosSubmissionSpec\",\n)({\n lane: LaneIndex,\n /** The lane's flavor; the FIRST spec of a lane fixes the lane's agent. */\n kind: ChaosScenarioKind,\n}) {}\n\n/** How the runner resolves a durable Unknown Outcome it encounters (DUR-017 driver). */\nexport const ChaosResolutionKind = Schema.Literals([\n /** The call provably never started: the batch resumes and executes it. */\n \"never-happened\",\n /**\n * Recovered supplier truth: resolve with the EXACT value the desk produced. Falls back to\n * `never-happened` when the desk holds no value for the call, so the runner never fabricates.\n */\n \"completed-from-supplier\",\n /** Unresolvable: route into the abort path (settles aborted, audit retained). */\n \"abort-submission\",\n]);\nexport type ChaosResolutionKind = typeof ChaosResolutionKind.Type;\n\nexport const ChaosApprovalDecision = Schema.Literals([\"approved\", \"denied\"]);\nexport type ChaosApprovalDecision = typeof ChaosApprovalDecision.Type;\n\nconst BoundedAdapterArm = Schema.String.check(Schema.isMaxLength(128));\n\n/**\n * One seeded chaos plan (plan §5): the full fault schedule is data, so a failing run replays\n * from the plan alone. `failpointArms` are coordinator locations; `adapterArms` are\n * adapter-owned location names the adapter test validates (the memory runner has none).\n */\nexport class ChaosPlan extends Schema.Class<ChaosPlan>(\"@effect-agent/testing/ChaosPlan\")({\n /** Identifies this plan in failure output; derived from the root seed plus the plan index. */\n seed: Schema.Int,\n /** Lane count; submissions address lanes `0..lanes-1`. */\n lanes: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(8)),\n submissions: Schema.NonEmptyArray(ChaosSubmissionSpec),\n /** Coordinator failpoint arms, consumed one per round (each fails every hit that round). */\n failpointArms: Schema.Array(DurableRuntimeFailpointLocation),\n /** Adapter-owned failpoint arms (e.g. SQLite `ledger:*`/`append:*` locations). */\n adapterArms: Schema.Array(BoundedAdapterArm),\n /** Flattened submission indices to abort mid-plan (modulo the submission count). */\n abortInjections: Schema.Array(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n /** Resolution choices for Unknown Outcomes, indexed deterministically per open call. */\n resolutionInjections: Schema.Array(ChaosResolutionKind),\n /** Approval decisions for suspended approval lanes, indexed deterministically per call. */\n approvalDecisions: Schema.Array(ChaosApprovalDecision),\n}) {}\n\n/** Per-lane verification result inside a plan report. */\nexport class ChaosLaneReport extends Schema.Class<ChaosLaneReport>(\n \"@effect-agent/testing/ChaosLaneReport\",\n)({\n conversationId: ConversationId,\n kind: ChaosScenarioKind,\n submissionCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Verdict of `verifyConversationInvariants` in convergence mode. */\n verified: Schema.Boolean,\n}) {}\n\n/** The Schema-first outcome of one executed chaos plan. */\nexport class ChaosPlanReport extends Schema.Class<ChaosPlanReport>(\n \"@effect-agent/testing/ChaosPlanReport\",\n)({\n seed: Schema.Int,\n rounds: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n lanes: Schema.Array(ChaosLaneReport),\n /** `scanObligations` entries after convergence — MUST be zero. */\n openObligations: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\n/** Typed convergence/verification failure of one chaos plan (never a bare defect). */\nexport class ChaosConvergenceFailure extends Schema.TaggedError<ChaosConvergenceFailure>()(\n \"ChaosConvergenceFailure\",\n {\n seed: Schema.Int,\n message: Schema.String.check(Schema.isMaxLength(16_384)),\n },\n) {}\n\n// ---------------------------------------------------------------------------\n// Seeded generation\n// ---------------------------------------------------------------------------\n\n/** Default root seed for chaos suites; override with the `CHAOS_SEED` environment variable. */\nexport const DEFAULT_CHAOS_SEED = 20260813;\n\n/** The root seed for this run: `CHAOS_SEED` when set to an integer, the default otherwise. */\nexport const chaosSeedFromEnv = (env: Record<string, string | undefined>): number => {\n const raw = env[\"CHAOS_SEED\"];\n if (raw === undefined || raw === \"\") return DEFAULT_CHAOS_SEED;\n const parsed = Number.parseInt(raw, 10);\n return Number.isSafeInteger(parsed) ? parsed : DEFAULT_CHAOS_SEED;\n};\n\nexport interface ChaosGeneratorOptions {\n /** Root seed (print this in failure output for replay). */\n readonly seed: number;\n /** How many plans to derive. */\n readonly count: number;\n /** Adapter failpoint location names available to arm (empty for memory). */\n readonly adapterArms?: ReadonlyArray<string> | undefined;\n}\n\ninterface GeneratedLane {\n readonly kind: ChaosScenarioKind;\n readonly depth: number;\n}\n\nconst laneArbitrary: FastCheck.Arbitrary<GeneratedLane> = FastCheck.constantFrom<ChaosScenarioKind>(\n \"plain\",\n \"uncertain-tool\",\n \"durable-steps\",\n \"approval\",\n \"join\",\n \"delegation\",\n).chain(\n (kind): FastCheck.Arbitrary<GeneratedLane> =>\n kind === \"join\"\n ? FastCheck.integer({ min: 2, max: 3 }).map((depth): GeneratedLane => ({ kind, depth }))\n : kind === \"plain\"\n ? FastCheck.integer({ min: 1, max: 2 }).map((depth): GeneratedLane => ({ kind, depth }))\n : FastCheck.constant<GeneratedLane>({ kind, depth: 1 }),\n);\n\ninterface ChaosPlanShape {\n readonly lanes: number;\n readonly submissions: readonly [ChaosSubmissionSpec, ...Array<ChaosSubmissionSpec>];\n readonly failpointArms: ReadonlyArray<DurableRuntimeFailpointLocation>;\n readonly adapterArms: ReadonlyArray<string>;\n readonly abortInjections: ReadonlyArray<number>;\n readonly resolutionInjections: ReadonlyArray<ChaosResolutionKind>;\n readonly approvalDecisions: ReadonlyArray<ChaosApprovalDecision>;\n}\n\nconst planShapeArbitrary = (\n adapterArms: ReadonlyArray<string>,\n): FastCheck.Arbitrary<ChaosPlanShape> =>\n FastCheck.record({\n lanes: FastCheck.array(laneArbitrary, { minLength: 1, maxLength: 3 }),\n failpointArms: FastCheck.uniqueArray(\n FastCheck.constantFrom(...DurableRuntimeFailpointLocation.literals),\n { maxLength: 3 },\n ),\n adapterArms:\n adapterArms.length === 0\n ? FastCheck.constant<Array<string>>([])\n : FastCheck.uniqueArray(FastCheck.constantFrom(...adapterArms), { maxLength: 2 }),\n abortInjections: FastCheck.uniqueArray(FastCheck.integer({ min: 0, max: 15 }), {\n maxLength: 2,\n }),\n resolutionInjections: FastCheck.array(\n FastCheck.constantFrom<ChaosResolutionKind>(\n \"never-happened\",\n \"completed-from-supplier\",\n \"abort-submission\",\n ),\n { maxLength: 4 },\n ),\n approvalDecisions: FastCheck.array(\n FastCheck.constantFrom<ChaosApprovalDecision>(\"approved\", \"denied\"),\n { maxLength: 2 },\n ),\n }).map((shape) => {\n const submissions = shape.lanes.flatMap((lane, index) =>\n Array.from({ length: lane.depth }, () =>\n ChaosSubmissionSpec.make({ lane: index, kind: lane.kind }),\n ),\n );\n const [first, ...rest] = submissions;\n // `lanes` >= 1 and every lane has depth >= 1, so `first` always exists.\n if (first === undefined) throw new Error(\"chaos generator produced an empty plan\");\n return {\n lanes: shape.lanes.length,\n submissions: [first, ...rest] as const,\n failpointArms: shape.failpointArms,\n adapterArms: shape.adapterArms,\n abortInjections: shape.abortInjections,\n resolutionInjections: shape.resolutionInjections,\n approvalDecisions: shape.approvalDecisions,\n };\n });\n\n/**\n * Derive `count` chaos plans deterministically from one root seed. The same\n * `{seed, count, adapterArms}` triple always yields byte-identical plans, so a failure line\n * `CHAOS_SEED=<seed>` replays the exact schedule.\n */\nexport const generateChaosPlans = (options: ChaosGeneratorOptions): ReadonlyArray<ChaosPlan> => {\n const sampled = FastCheck.sample(planShapeArbitrary(options.adapterArms ?? []), {\n seed: options.seed,\n numRuns: options.count,\n });\n return sampled.map((shape, index) =>\n ChaosPlan.make({ ...shape, seed: (Math.imul(options.seed, 31) + index) | 0 }),\n );\n};\n\n/** Deterministic PRNG for the runner's small ordering choices (lane drive order). */\nconst mulberry32 = (seed: number): (() => number) => {\n let state = seed | 0;\n return () => {\n state = (state + 0x6d2b79f5) | 0;\n let t = Math.imul(state ^ (state >>> 15), 1 | state);\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n};\n\n// ---------------------------------------------------------------------------\n// Lane fixtures (agents, scripted models, deterministic desk)\n// ---------------------------------------------------------------------------\n\nconst usage = { inputTokens: {}, outputTokens: {} };\n\nconst finalParts = (text: string): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"answer\" },\n { type: \"text-delta\", id: \"answer\", delta: text },\n { type: \"text-end\", id: \"answer\" },\n { type: \"finish\", reason: \"stop\", usage },\n];\n\nconst toolTurn = (\n ...calls: ReadonlyArray<Response.StreamPartEncoded>\n): ReadonlyArray<Response.StreamPartEncoded> => [\n ...calls,\n { type: \"finish\", reason: \"tool-calls\", usage },\n];\n\nconst toolCallPart = (id: string, name: string, params: unknown): Response.StreamPartEncoded => ({\n type: \"tool-call\",\n id,\n name,\n params,\n providerExecuted: false,\n});\n\n/**\n * Prompt-shaped scripted model: the response depends ONLY on the request prompt, so it stays\n * deterministic across Attempt re-invocations, batch resumes, and joined steering — no counter\n * to drift when chaos re-enters a Turn.\n */\nconst promptScriptedModel = (\n label: string,\n script: (prompt: Prompt.Prompt) => ReadonlyArray<Response.StreamPartEncoded>,\n) =>\n Model.make(\n \"scripted\",\n label,\n Layer.effect(\n LanguageModel.LanguageModel,\n LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (request) => Stream.fromIterable(script(request.prompt)),\n }),\n ),\n );\n\nconst lastRole = (prompt: Prompt.Prompt): string | undefined => prompt.content.at(-1)?.role;\n\nconst policy = AgentPolicy.make({\n maxTurns: 3,\n maxToolCalls: 4,\n maxDuration: \"30 seconds\",\n toolConcurrency: 2,\n});\n\nconst PlainInput = Schema.Struct({ question: Schema.String });\nconst PlainOutput = Schema.Struct({ answer: Schema.String });\n\nconst plainDefinition = Agent.define(\"chaos-plain\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Answer as JSON.\",\n toolkit: Toolkit.empty,\n policy,\n});\n\n/** Unannotated → fail-closed `uncertain`: enters the prepared/settled protocol (DUR-009). */\nconst BookUncertain = Tool.make(\"book\", {\n parameters: Schema.Struct({ ref: Schema.String }),\n success: Schema.Struct({ confirmation: Schema.String }),\n});\nconst bookTools = Toolkit.make(BookUncertain);\nconst bookDefinition = Agent.define(\"chaos-book\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Book it.\",\n toolkit: bookTools,\n policy,\n});\n\nconst BookApproval = Tool.make(\"book\", {\n parameters: Schema.Struct({ ref: Schema.String }),\n success: Schema.Struct({ confirmation: Schema.String }),\n needsApproval: true,\n});\nconst approvalTools = Toolkit.make(BookApproval);\nconst approvalDefinition = Agent.define(\"chaos-approval\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Book after approval.\",\n toolkit: approvalTools,\n policy,\n});\n\nconst Itinerary = Tool.make(\"itinerary\", {\n parameters: Schema.Struct({ ref: Schema.String }),\n success: Schema.Struct({ state: Schema.String }),\n failure: DurableStepError,\n dependencies: [DurableStep],\n}).annotate(ToolExecutionClass, \"uncertain\");\nconst itineraryTools = Toolkit.make(Itinerary);\nconst itineraryDefinition = Agent.define(\"chaos-itinerary\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Reserve the itinerary.\",\n toolkit: itineraryTools,\n policy,\n});\n\nconst childDefinition = Agent.define(\"chaos-child\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Answer as JSON.\",\n toolkit: Toolkit.empty,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 1,\n maxDuration: \"30 seconds\",\n toolConcurrency: 1,\n }),\n});\n\nclass ChaosDelegationFailed extends Schema.TaggedError<ChaosDelegationFailed>()(\n \"ChaosDelegationFailed\",\n { childErrorTag: Schema.String },\n) {}\n\nconst chaosDelegation = Subagent.define(\"delegate_chaos\", {\n description: \"Delegate one bounded chaos question.\",\n target: childDefinition,\n parameters: Schema.Struct({ topic: Schema.String }),\n success: Schema.Struct({ summary: Schema.String }),\n failure: ChaosDelegationFailed,\n prepareInput: ({ topic }) => Effect.succeed({ question: `chaos:${topic}` }),\n projectResult: (output) => Effect.succeed({ summary: `finding:${output.answer}` }),\n policy: SubagentPolicy.make({\n maxChildren: 2,\n maxConcurrency: 2,\n maxTurns: 4,\n maxToolCalls: 4,\n maxDuration: \"30 seconds\",\n }),\n});\n\nconst coordinatorDefinition = Agent.define(\"chaos-coordinator\", {\n input: Schema.Struct({ mission: Schema.String }),\n output: Schema.Struct({ report: Schema.String }),\n instructions: \"Delegate, then report as JSON.\",\n toolkit: Toolkit.make(chaosDelegation.tool),\n policy,\n});\n\nconst DELEGATE_CALL_ID = \"chaos-delegate-1\";\n\nconst HEX = \"0123456789abcdef\";\nconst decodeDigest = Schema.decodeSync(Digest);\nconst laneDigests = (lane: number): DefinitionDigests => {\n const digest = decodeDigest(HEX[lane % 8]!.repeat(64));\n return DefinitionDigests.make({ agent: digest, model: digest, tools: digest });\n};\nconst childDigestStrings = (lane: number) => {\n const char = HEX[8 + (lane % 8)]!;\n return { agent: char.repeat(64), model: char.repeat(64), tools: char.repeat(64) } as const;\n};\nconst childLaneDigests = (lane: number): DefinitionDigests => {\n const strings = childDigestStrings(lane);\n return DefinitionDigests.make({\n agent: decodeDigest(strings.agent),\n model: decodeDigest(strings.model),\n tools: decodeDigest(strings.tools),\n });\n};\n\nconst CHAOS_PRINCIPAL = Schema.decodeSync(Principal)(\"principal-chaos\");\nconst decodeConversationId = Schema.decodeSync(ConversationId);\nconst decodeIdempotencyKey = Schema.decodeSync(IdempotencyKey);\nconst decodeToolCallId = Schema.decodeSync(ToolCallId);\nconst decodeRunId = Schema.decodeSync(RunId);\nconst decodeTurnId = Schema.decodeSync(TurnId);\n\n/** Fixture-only identity source consumed by the delegation Layer's ephemeral capture. */\nconst chaosIdentifiers = Layer.effect(\n IdGenerator,\n Effect.gen(function* () {\n const counter = yield* Ref.make(0);\n const next = <A>(decode: (value: string) => A, prefix: string) =>\n Ref.getAndUpdate(counter, (value) => value + 1).pipe(\n Effect.map((value) => decode(`${prefix}-${value}`)),\n );\n return {\n nextConversationId: next(decodeConversationId, \"chaos-fixture-conversation\"),\n nextRunId: next(decodeRunId, \"chaos-fixture-run\"),\n nextTurnId: next(decodeTurnId, \"chaos-fixture-turn\"),\n };\n }),\n);\n\nconst delegationSupport = Layer.mergeAll(SubagentReservationsMemoryLive, chaosIdentifiers);\n\n/**\n * The deterministic external desk of one plan: every produced value is recorded so the final\n * non-fabrication sweep can prove each canonical Tool success came from here (durability §10).\n */\ninterface ChaosDesk {\n readonly produced: Effect.Effect<ReadonlySet<string>>;\n readonly record: (value: string) => Effect.Effect<void>;\n}\n\nconst makeChaosDesk: Effect.Effect<ChaosDesk> = Effect.gen(function* () {\n const produced = yield* Ref.make<ReadonlySet<string>>(new Set());\n return {\n produced: Ref.get(produced),\n record: (value: string) => Ref.update(produced, (current) => new Set(current).add(value)),\n };\n});\n\nconst bookConfirmation = (ref: string): string => `confirmed-${ref}`;\nconst flightValue = (ref: string): string => `flight-${ref}`;\nconst lodgingValue = (ref: string): string => `lodging-${ref}`;\n\n// ---------------------------------------------------------------------------\n// Runner\n// ---------------------------------------------------------------------------\n\n/** Adapter-owned failpoint control the SQLite runner supplies; memory has none. */\nexport interface ChaosAdapterFailpoints {\n readonly arm: (location: string) => Effect.Effect<void>;\n readonly clear: Effect.Effect<void>;\n}\n\nexport interface ChaosRunOptions {\n readonly adapterFailpoints?: ChaosAdapterFailpoints | undefined;\n /**\n * Executed at the end of every round. Adapters whose ownership leases block every new claim\n * until expiry (the SQLite ledger's D5 semantics — expiry only revokes the liveness\n * assumption; producer epochs stay the correctness fence) pass a deterministic\n * `TestClock.adjust` here so a dead Attempt's lane becomes reclaimable next round. The memory\n * ledger needs nothing: it allows same-producer reclaim under a live lease.\n */\n readonly betweenRounds?: Effect.Effect<void> | undefined;\n}\n\n/** Success → Some; typed failure → None (chaos tolerates it); defect → rethrown loudly. */\nconst tolerateTyped = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<Option.Option<A>, never, R> =>\n effect.pipe(\n Effect.exit,\n Effect.flatMap((exit) => {\n if (Exit.isSuccess(exit)) return Effect.succeed(Option.some(exit.value));\n if (Option.isSome(Cause.findErrorOption(exit.cause))) {\n return Effect.succeed(Option.none<A>());\n }\n return Effect.die(new Error(`chaos step died: ${Cause.pretty(exit.cause)}`));\n }),\n );\n\ninterface LaneFixture {\n readonly index: number;\n readonly kind: ChaosScenarioKind;\n readonly conversationId: ConversationId;\n readonly ref: string;\n readonly deskInPlay: boolean;\n readonly submissionIndexes: ReadonlyArray<number>;\n readonly submitOne: (flatIndex: number) => Effect.Effect<Receipt, unknown>;\n readonly drives: (\n firstReceipt: Receipt | undefined,\n ) => ReadonlyArray<Effect.Effect<ReadonlyArray<Settlement>, unknown>>;\n readonly childConversationOf: (firstReceipt: Receipt) => ConversationId | undefined;\n}\n\ninterface SubmissionState {\n readonly flatIndex: number;\n readonly lane: LaneFixture;\n receipt: Receipt | undefined;\n}\n\nconst scriptFor = (\n kind: ChaosScenarioKind,\n ref: string,\n): ((prompt: Prompt.Prompt) => ReadonlyArray<Response.StreamPartEncoded>) => {\n switch (kind) {\n case \"plain\":\n case \"join\":\n return () => finalParts('{\"answer\":\"chaos\"}');\n case \"uncertain-tool\":\n case \"approval\":\n return (prompt) =>\n lastRole(prompt) === \"tool\"\n ? finalParts('{\"answer\":\"booked\"}')\n : toolTurn(toolCallPart(`book-${ref}`, \"book\", { ref }));\n case \"durable-steps\":\n return (prompt) =>\n lastRole(prompt) === \"tool\"\n ? finalParts('{\"answer\":\"reserved\"}')\n : toolTurn(toolCallPart(`itinerary-${ref}`, \"itinerary\", { ref }));\n case \"delegation\":\n return (prompt) =>\n lastRole(prompt) === \"tool\"\n ? finalParts('{\"report\":\"done\"}')\n : toolTurn(toolCallPart(DELEGATE_CALL_ID, \"delegate_chaos\", { topic: ref }));\n }\n};\n\nconst makeLaneFixture = Effect.fn(\"Chaos.makeLaneFixture\")(function* (\n plan: ChaosPlan,\n laneIndex: number,\n kind: ChaosScenarioKind,\n submissionIndexes: ReadonlyArray<number>,\n desk: ChaosDesk,\n) {\n const runtime = yield* DurableAgentRuntime;\n const conversationId = decodeConversationId(`chaos-${plan.seed}-lane-${laneIndex}`);\n const ref = `ref-l${laneIndex}`;\n const script = scriptFor(kind, ref);\n const model = promptScriptedModel(`chaos-${kind}-${laneIndex}`, script);\n const digests = laneDigests(laneIndex);\n\n const submitOptionsFor = (flatIndex: number) => ({\n conversationId,\n principal: CHAOS_PRINCIPAL,\n idempotencyKey: decodeIdempotencyKey(`chaos-${plan.seed}-s${flatIndex}`),\n definitions: digests,\n });\n\n const bookToolLayerFor = (tools: typeof bookTools | typeof approvalTools) =>\n tools.toLayer({\n book: ({ ref: called }) =>\n desk\n .record(bookConfirmation(called))\n .pipe(Effect.as({ confirmation: bookConfirmation(called) })),\n });\n\n const plainLaneFixture = (\n deskInPlay: boolean,\n drive: Effect.Effect<ReadonlyArray<Settlement>, unknown>,\n submitOne: (flatIndex: number) => Effect.Effect<Receipt, unknown>,\n ): LaneFixture => ({\n index: laneIndex,\n kind,\n conversationId,\n ref,\n deskInPlay,\n submissionIndexes,\n submitOne,\n drives: () => [drive],\n childConversationOf: () => undefined,\n });\n\n switch (kind) {\n case \"plain\":\n case \"join\": {\n const agent = Agent.withModel(plainDefinition, model);\n return plainLaneFixture(\n false,\n runtime.processConversation(agent, conversationId),\n (flatIndex) =>\n runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)),\n );\n }\n case \"uncertain-tool\": {\n const agent = Agent.withModel(bookDefinition, model);\n return plainLaneFixture(\n true,\n runtime\n .processConversation(agent, conversationId)\n .pipe(Effect.provide(bookToolLayerFor(bookTools))),\n (flatIndex) =>\n runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)),\n );\n }\n case \"approval\": {\n const agent = Agent.withModel(approvalDefinition, model);\n return plainLaneFixture(\n true,\n runtime\n .processConversation(agent, conversationId)\n .pipe(Effect.provide(bookToolLayerFor(approvalTools))),\n (flatIndex) =>\n runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)),\n );\n }\n case \"durable-steps\": {\n const agent = Agent.withModel(itineraryDefinition, model);\n const toolLayer = itineraryTools.toLayer({\n itinerary: ({ ref: called }) =>\n Effect.gen(function* () {\n const step = yield* DurableStep;\n const flight = yield* step.do(\n \"reserve-flight\",\n Schema.String,\n desk.record(flightValue(called)).pipe(Effect.as(flightValue(called))),\n );\n const lodging = yield* step.do(\n \"reserve-lodging\",\n Schema.String,\n desk.record(lodgingValue(called)).pipe(Effect.as(lodgingValue(called))),\n );\n return { state: `${flight}+${lodging}` };\n }),\n });\n return plainLaneFixture(\n true,\n runtime.processConversation(agent, conversationId).pipe(Effect.provide(toolLayer)),\n (flatIndex) =>\n runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)),\n );\n }\n case \"delegation\": {\n const parentBinding = Agent.withModel(coordinatorDefinition, model);\n const childModel = promptScriptedModel(`chaos-child-${laneIndex}`, () =>\n finalParts('{\"answer\":\"child\"}'),\n );\n const childBinding = Agent.withModel(childDefinition, childModel);\n const delegationLayer = SubagentRuntime.layer(chaosDelegation, childBinding, {\n mapChildFailure: (failure) => ChaosDelegationFailed.make({ childErrorTag: failure._tag }),\n durable: { targetDigests: childDigestStrings(laneIndex) },\n }).pipe(Layer.provide(delegationSupport));\n const parentResolved: ResolvedBinding = yield* DurableWorkerBinding.make(\n parentBinding,\n digests,\n ).pipe(Effect.provide(delegationLayer));\n const childResolved: ResolvedBinding = yield* DurableWorkerBinding.make(\n childBinding,\n childLaneDigests(laneIndex),\n );\n const resolver = AgentBindingResolver.fromBindings([parentResolved, childResolved]);\n const driveResolved = (conversation: ConversationId) =>\n runtime\n .processConversationResolved(conversation)\n .pipe(Effect.provideService(AgentBindingResolver, resolver));\n const fixture: LaneFixture = {\n index: laneIndex,\n kind,\n conversationId,\n ref,\n deskInPlay: false,\n submissionIndexes,\n submitOne: (flatIndex) =>\n runtime.submit(\n { definition: { id: coordinatorDefinition.id, input: coordinatorDefinition.input } },\n { mission: `chaos ${flatIndex}` },\n submitOptionsFor(flatIndex),\n ),\n drives: (firstReceipt) => {\n const drives: Array<Effect.Effect<ReadonlyArray<Settlement>, unknown>> = [\n driveResolved(conversationId),\n ];\n if (firstReceipt !== undefined) {\n drives.push(\n driveResolved(\n childConversationIdFor(\n firstReceipt.submissionId,\n decodeToolCallId(DELEGATE_CALL_ID),\n ),\n ),\n );\n }\n return drives;\n },\n childConversationOf: (firstReceipt) =>\n childConversationIdFor(firstReceipt.submissionId, decodeToolCallId(DELEGATE_CALL_ID)),\n };\n return fixture;\n }\n }\n});\n\n/** Stable per-call index into an injection list (identical across resolution passes). */\nconst injectionIndex = (submissionFlatIndex: number, callId: string, length: number): number => {\n let hash = submissionFlatIndex + 1;\n for (const char of callId) hash = (Math.imul(hash, 31) + char.charCodeAt(0)) | 0;\n return ((hash % length) + length) % length;\n};\n\nconst resolutionFor = (\n kind: ChaosResolutionKind,\n toolName: string,\n ref: string,\n produced: ReadonlySet<string>,\n): UnknownResolution => {\n switch (kind) {\n case \"abort-submission\":\n return ResolutionAbortSubmission.make();\n case \"completed-from-supplier\": {\n if (toolName === \"book\" && produced.has(bookConfirmation(ref))) {\n return ResolutionCompletedWithResult.make({\n result: { confirmation: bookConfirmation(ref) },\n isFailure: false,\n });\n }\n if (\n toolName === \"itinerary\" &&\n produced.has(flightValue(ref)) &&\n produced.has(lodgingValue(ref))\n ) {\n return ResolutionCompletedWithResult.make({\n result: { state: `${flightValue(ref)}+${lodgingValue(ref)}` },\n isFailure: false,\n });\n }\n // The desk never produced a value for this call — resolving \"completed\" would fabricate.\n return ResolutionNeverHappened.make();\n }\n case \"never-happened\":\n return ResolutionNeverHappened.make();\n }\n};\n\n/** Drive one DUR-017 pass: resolve Unknown Outcomes and pending approvals from the plan. */\nconst resolutionPass = Effect.fn(\"Chaos.resolutionPass\")(function* (\n plan: ChaosPlan,\n states: ReadonlyArray<SubmissionState>,\n desk: ChaosDesk,\n) {\n const runtime = yield* DurableAgentRuntime;\n const ledger = yield* SubmissionLedger;\n const produced = yield* desk.produced;\n const nonterminal = yield* tolerateTyped(Stream.runCollect(ledger.scanNonterminal));\n if (Option.isNone(nonterminal)) return;\n const byId = new Map<SubmissionId, SubmissionState>();\n for (const state of states) {\n if (state.receipt !== undefined) byId.set(state.receipt.submissionId, state);\n }\n for (const row of nonterminal.value) {\n if (row.state !== \"unknown\" && row.state !== \"suspended\") continue;\n const state = byId.get(row.submissionId);\n const explanation = yield* tolerateTyped(runtime.explain(row.submissionId));\n if (Option.isNone(explanation)) continue;\n const flatIndex = state?.flatIndex ?? 0;\n const ref = state?.lane.ref ?? \"ref-child\";\n if (row.state === \"unknown\") {\n for (const call of explanation.value.evidence.unknownCalls) {\n if (call.resolved) continue;\n const kind =\n plan.resolutionInjections.length === 0\n ? \"never-happened\"\n : plan.resolutionInjections[\n injectionIndex(flatIndex, call.toolCallId, plan.resolutionInjections.length)\n ]!;\n yield* tolerateTyped(\n runtime.resolveUnknown(\n UnknownResolutionCommand.make({\n submissionId: row.submissionId,\n toolCallId: call.toolCallId,\n author: \"chaos-runner\",\n reason: `chaos plan ${plan.seed} resolution (${kind})`,\n resolution: resolutionFor(kind, call.toolName, ref, produced),\n }),\n ),\n );\n }\n } else {\n for (const pending of explanation.value.evidence.approvalsPending) {\n const decision =\n plan.approvalDecisions.length === 0\n ? \"approved\"\n : plan.approvalDecisions[\n injectionIndex(flatIndex, pending.toolCallId, plan.approvalDecisions.length)\n ]!;\n yield* tolerateTyped(\n runtime.resolveApproval(\n ApprovalDecisionCommand.make({\n submissionId: row.submissionId,\n toolCallId: pending.toolCallId,\n decision,\n resolver: \"chaos-runner\",\n reason: `chaos plan ${plan.seed} approval (${decision})`,\n }),\n ),\n );\n }\n }\n }\n});\n\nconst submissionIdsNamedBy = (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n): ReadonlySet<SubmissionId> => {\n const named = new Set<SubmissionId>();\n for (const envelope of records) {\n const payload = envelope.record.payload;\n if (\n payload._tag === \"UserInputRecorded\" ||\n payload._tag === \"SubmissionSettled\" ||\n payload._tag === \"AbortRequested\"\n ) {\n named.add(payload.submissionId);\n }\n }\n return named;\n};\n\n/**\n * The final non-fabrication sweep (durability §10): every canonical Tool success recorded on a\n * desk-backed lane must be a value the desk actually produced.\n */\nconst BookResult = Schema.Struct({ confirmation: Schema.String });\nconst ItineraryResult = Schema.Struct({ state: Schema.String });\nconst decodeBookResult = Schema.decodeUnknownOption(BookResult);\nconst decodeItineraryResult = Schema.decodeUnknownOption(ItineraryResult);\nconst decodeStepOutput = Schema.decodeUnknownOption(Schema.String);\n\nconst assertNoFabrication = (\n plan: ChaosPlan,\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n produced: ReadonlySet<string>,\n): Effect.Effect<void, ChaosConvergenceFailure> => {\n const fabricated: Array<string> = [];\n const requireProduced = (value: string, label: string): void => {\n if (!produced.has(value)) fabricated.push(`${label} \"${value}\"`);\n };\n for (const envelope of records) {\n const payload = envelope.record.payload;\n if (payload._tag === \"ToolCallSettled\" && !payload.isFailure) {\n if (payload.toolName === \"book\") {\n const result = decodeBookResult(payload.result);\n if (Option.isSome(result)) requireProduced(result.value.confirmation, \"book result\");\n }\n if (payload.toolName === \"itinerary\") {\n const result = decodeItineraryResult(payload.result);\n if (Option.isSome(result)) {\n for (const part of result.value.state.split(\"+\")) {\n requireProduced(part, \"itinerary step result\");\n }\n }\n }\n }\n if (payload._tag === \"ToolStepSettled\") {\n const output = decodeStepOutput(payload.output);\n if (Option.isSome(output)) requireProduced(output.value, \"step output\");\n }\n }\n return fabricated.length === 0\n ? Effect.void\n : Effect.fail(\n ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `fabricated Tool results absent from the desk: ${fabricated.join(\", \")}`,\n }),\n );\n};\n\n/**\n * Execute one chaos plan against whatever adapters the ambient Layer provides and end in the\n * shared invariant claims. Deterministic: same plan + same adapters → same schedule.\n */\nexport const runChaosPlan = Effect.fn(\"Chaos.runChaosPlan\")(function* (\n plan: ChaosPlan,\n options?: ChaosRunOptions,\n) {\n const runtime = yield* DurableAgentRuntime;\n const ledger = yield* SubmissionLedger;\n const store = yield* ConversationStore;\n const config = yield* DurableRuntimeConfig;\n const failpoints = yield* DurableRuntimeFailpointTestControl;\n const random = mulberry32(plan.seed);\n const desk = yield* makeChaosDesk;\n\n // Lane fixtures: the FIRST spec of each lane fixes the lane's agent kind.\n const laneKinds = new Map<number, ChaosScenarioKind>();\n const laneSubmissions = new Map<number, Array<number>>();\n plan.submissions.forEach((spec, flatIndex) => {\n const lane = spec.lane % plan.lanes;\n if (!laneKinds.has(lane)) laneKinds.set(lane, spec.kind);\n const list = laneSubmissions.get(lane) ?? [];\n list.push(flatIndex);\n laneSubmissions.set(lane, list);\n });\n const lanes: Array<LaneFixture> = [];\n for (const [lane, kind] of laneKinds) {\n lanes.push(yield* makeLaneFixture(plan, lane, kind, laneSubmissions.get(lane) ?? [], desk));\n }\n\n const states: Array<SubmissionState> = plan.submissions.map((spec, flatIndex) => ({\n flatIndex,\n lane: lanes.find((fixture) => fixture.index === spec.lane % plan.lanes)!,\n receipt: undefined,\n }));\n const appliedAborts = new Set<number>();\n\n type ArmEntry =\n | { readonly family: \"coordinator\"; readonly location: DurableRuntimeFailpointLocation }\n | { readonly family: \"adapter\"; readonly location: string };\n const armQueue: Array<ArmEntry> = [\n ...plan.failpointArms.map((location): ArmEntry => ({ family: \"coordinator\", location })),\n ...plan.adapterArms.map((location): ArmEntry => ({ family: \"adapter\", location })),\n ];\n\n const allSettled = Effect.gen(function* () {\n if (states.some((state) => state.receipt === undefined)) return false;\n const nonterminal = yield* tolerateTyped(Stream.runCollect(ledger.scanNonterminal));\n return Option.isSome(nonterminal) && Array.from(nonterminal.value).length === 0;\n });\n\n const maxRounds = armQueue.length + states.length * 2 + 12;\n let rounds = 0;\n let converged = false;\n for (let round = 0; round < maxRounds; round++) {\n rounds = round + 1;\n const arm = armQueue[round];\n if (arm?.family === \"coordinator\") {\n const location = arm.location;\n yield* failpoints.setHandler((hit) =>\n hit === location\n ? Effect.fail(DurableRuntimeFailpointError.make({ location: hit }))\n : Effect.void,\n );\n } else if (arm?.family === \"adapter\" && options?.adapterFailpoints !== undefined) {\n yield* options.adapterFailpoints.arm(arm.location);\n }\n\n // Admission chaos: pending submissions retry under the active arm until a Receipt lands;\n // the identical (conversation, principal, key) triple reattaches, never duplicates.\n for (const state of states) {\n if (state.receipt !== undefined) continue;\n const receipt = yield* tolerateTyped(state.lane.submitOne(state.flatIndex));\n if (Option.isSome(receipt)) state.receipt = receipt.value;\n }\n\n // Drive every lane (and discovered child lanes) in seeded order under the active arm.\n const order = [...lanes].sort(() => random() - 0.5);\n for (const lane of order) {\n const firstFlat = lane.submissionIndexes[0];\n const firstReceipt = firstFlat === undefined ? undefined : states[firstFlat]?.receipt;\n for (const drive of lane.drives(firstReceipt)) {\n yield* tolerateTyped(drive);\n }\n }\n\n // Abort injections fire once, while arms may still be active (abort:after-intent etc.).\n if (round >= 1) {\n for (const rawIndex of plan.abortInjections) {\n const index = rawIndex % states.length;\n if (appliedAborts.has(index)) continue;\n const receipt = states[index]?.receipt;\n if (receipt === undefined) continue;\n appliedAborts.add(index);\n yield* tolerateTyped(\n runtime.abort(\n AbortCommand.make({\n submissionId: receipt.submissionId,\n author: \"chaos-runner\",\n reason: `chaos plan ${plan.seed} abort injection`,\n }),\n ),\n );\n }\n }\n\n // First resolution pass runs under the arm so resolve:* locations can fire.\n yield* resolutionPass(plan, states, desk);\n\n yield* failpoints.clear;\n if (options?.adapterFailpoints !== undefined) yield* options.adapterFailpoints.clear;\n\n yield* tolerateTyped(runtime.runRecovery);\n // Second, unarmed pass guarantees forward progress for newly marked Unknown lanes.\n yield* resolutionPass(plan, states, desk);\n\n if (yield* allSettled) {\n converged = true;\n break;\n }\n if (options?.betweenRounds !== undefined) yield* options.betweenRounds;\n }\n\n if (!converged) {\n const nonterminal = yield* tolerateTyped(Stream.runCollect(ledger.scanNonterminal));\n const detail = Option.isSome(nonterminal)\n ? Array.from(nonterminal.value)\n .map((row: SubmissionSnapshot) => `${row.submissionId}(${row.state})`)\n .join(\", \")\n : \"ledger scan failed\";\n return yield* ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `plan did not converge within ${maxRounds} rounds; nonterminal: [${detail}]; pending receipts: ${states.filter((state) => state.receipt === undefined).length}`,\n });\n }\n\n // Final claims: the shared invariant checker per touched Conversation, in convergence mode,\n // with the full digest chain (single known producer), plus the desk non-fabrication sweep.\n const produced = yield* desk.produced;\n const laneReports: Array<ChaosLaneReport> = [];\n const verifyConversation = Effect.fn(\"Chaos.verifyConversation\")(function* (\n conversationId: ConversationId,\n kind: ChaosScenarioKind,\n deskInPlay: boolean,\n ) {\n const exported = yield* store.export(ConversationExportRequest.make({ conversationId })).pipe(\n Effect.mapError((error) =>\n ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `export of ${conversationId} failed: ${String(error)}`,\n }),\n ),\n );\n const rows: Array<SubmissionSnapshot> = [];\n for (const submissionId of submissionIdsNamedBy(exported.records)) {\n const found = yield* ledger.lookup(SubmissionLookupById.make({ submissionId })).pipe(\n Effect.mapError((error) =>\n ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `lookup of ${submissionId} failed: ${String(error)}`,\n }),\n ),\n );\n if (Option.isSome(found)) rows.push(found.value);\n }\n const batchProducers = new Map<BatchId, ProducerId>(\n exported.records.map((envelope) => [envelope.batchId, config.producerId]),\n );\n const report = yield* verifyConversationInvariants({\n export: exported,\n submissions: rows,\n batchProducers,\n requireAllSettled: true,\n });\n if (!report.ok) {\n const failed = report.checks\n .filter((check) => check.status === \"failed\")\n .map((check) => `${check.name}: ${check.detail ?? \"failed\"}`)\n .join(\"; \");\n return yield* ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `invariants failed for ${conversationId} (${kind}): ${failed}`,\n });\n }\n if (deskInPlay) {\n yield* assertNoFabrication(plan, exported.records, produced);\n }\n laneReports.push(\n ChaosLaneReport.make({\n conversationId,\n kind,\n submissionCount: rows.length,\n verified: report.ok,\n }),\n );\n });\n\n for (const lane of lanes) {\n yield* verifyConversation(lane.conversationId, lane.kind, lane.deskInPlay);\n // Delegation lanes: verify every materialized child Conversation too.\n for (const flatIndex of lane.submissionIndexes) {\n const receipt = states[flatIndex]?.receipt;\n if (receipt === undefined) continue;\n const child = lane.childConversationOf(receipt);\n if (child === undefined) continue;\n const childExport = yield* Effect.exit(\n store.export(ConversationExportRequest.make({ conversationId: child })),\n );\n if (Exit.isSuccess(childExport) && childExport.value.records.length > 0) {\n yield* verifyConversation(child, \"plain\", false);\n }\n }\n }\n\n const obligations = yield* runtime\n .scanObligations(ObligationThresholds.make({ agingSeconds: 0, overdueSeconds: 0 }))\n .pipe(\n Effect.mapError((error) =>\n ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `scanObligations failed: ${String(error)}`,\n }),\n ),\n );\n if (obligations.entries.length > 0) {\n return yield* ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `open obligations after convergence: ${obligations.entries\n .map((entry) => `${entry.submissionId}(${entry.blockedOn})`)\n .join(\", \")}`,\n });\n }\n\n return ChaosPlanReport.make({\n seed: plan.seed,\n rounds,\n lanes: laneReports,\n openObligations: obligations.entries.length,\n });\n});\n","import {\n CodeExecutionError,\n CodeExecutionHost,\n CodeExecutionLimits,\n CodeExecutionNamespace,\n CodeExecutionRequest,\n CodeExecutionResult,\n CodeExecutor,\n CodeHostCall,\n CodeHostCallFailure,\n CodeHostCallResult,\n CodeHostCallSuccess,\n NetworkAllowlist,\n NetworkDisabled,\n SandboxImplementation,\n} from \"@effect-agent/sandbox\";\nimport { Deferred, Duration, Effect, Fiber, Schema } from \"effect\";\n\n/**\n * Shared `CodeExecutor` conformance (TEST-015). Every adapter — the\n * deterministic `unisolated` substitute and each isolated adapter — runs\n * `codeExecutorConformanceCases` verbatim. Enforcement cases that only genuine\n * isolation can prove (ambient network denial, synchronous CPU runaway\n * termination) are NOT here; they belong to isolated adapters only\n * (testing spec §8.1).\n *\n * Cases assume the live `Clock` (the wall-clock case uses a short real\n * deadline) and take one fresh executor pass per case, so a suite may share\n * one executor Layer across cases.\n */\nexport class CodeExecutorConformanceViolation extends Schema.TaggedError<CodeExecutorConformanceViolation>()(\n \"CodeExecutorConformanceViolation\",\n {\n caseName: Schema.String,\n message: Schema.String,\n },\n) {}\n\nexport interface CodeExecutorConformanceCase {\n readonly name: string;\n readonly run: Effect.Effect<void, CodeExecutorConformanceViolation, CodeExecutor>;\n}\n\nexport interface CodeExecutorConformanceOptions {\n /** The posture the adapter under test must stamp on results and errors. */\n readonly implementation: SandboxImplementation;\n}\n\nconst baseLimits = CodeExecutionLimits.make({\n maxSourceBytes: 64 * 1024,\n maxWallTime: Duration.seconds(10),\n maxLogBytes: 16 * 1024,\n maxResultBytes: 64 * 1024,\n maxHostCalls: 8,\n maxHostCallArgumentBytes: 16 * 1024,\n maxHostCallResultBytes: 32 * 1024,\n});\n\nconst warehouseNamespace = CodeExecutionNamespace.make({\n name: \"warehouse\",\n methods: [\"query\", \"count\"],\n});\n\nconst makeRequest = (\n source: string,\n overrides?: {\n readonly limits?: CodeExecutionLimits;\n readonly namespaces?: ReadonlyArray<CodeExecutionNamespace>;\n readonly network?: CodeExecutionRequest[\"network\"];\n },\n): CodeExecutionRequest =>\n CodeExecutionRequest.make({\n language: \"javascript\",\n source,\n namespaces: overrides?.namespaces ?? [],\n network: overrides?.network ?? NetworkDisabled.make(),\n limits: overrides?.limits ?? baseLimits,\n });\n\nconst unusedHost: CodeExecutionHost[\"Service\"] = {\n call: () =>\n Effect.die(\n new Error(\"this conformance case expected no host call to reach the CodeExecutionHost\"),\n ),\n};\n\nconst respondingHost = (\n respond: (call: CodeHostCall) => CodeHostCallResult,\n): { readonly host: CodeExecutionHost[\"Service\"]; readonly calls: Array<CodeHostCall> } => {\n const calls: Array<CodeHostCall> = [];\n return {\n calls,\n host: {\n call: (call) =>\n Effect.sync(() => {\n calls.push(call);\n return respond(call);\n }),\n },\n };\n};\n\nconst runPass = (\n request: CodeExecutionRequest,\n host: CodeExecutionHost[\"Service\"],\n): Effect.Effect<CodeExecutionResult, CodeExecutionError, CodeExecutor> =>\n Effect.gen(function* () {\n const executor = yield* CodeExecutor;\n return yield* executor\n .execute(request)\n .pipe(Effect.provideService(CodeExecutionHost, CodeExecutionHost.of(host)));\n }).pipe(Effect.scoped);\n\nconst violation = (caseName: string, message: string) =>\n CodeExecutorConformanceViolation.make({ caseName, message });\n\nconst preview = (value: unknown): string => {\n try {\n return JSON.stringify(value)?.slice(0, 200) ?? String(value).slice(0, 200);\n } catch {\n return String(value).slice(0, 200);\n }\n};\n\nconst expectSuccess = (\n caseName: string,\n request: CodeExecutionRequest,\n host: CodeExecutionHost[\"Service\"],\n check: (result: CodeExecutionResult) => string | undefined,\n): Effect.Effect<void, CodeExecutorConformanceViolation, CodeExecutor> =>\n runPass(request, host).pipe(\n Effect.mapError((error) =>\n violation(caseName, `expected success, got ${error._tag}: ${preview(error)}`),\n ),\n Effect.flatMap((result) => {\n const complaint = check(result);\n return complaint === undefined ? Effect.void : Effect.fail(violation(caseName, complaint));\n }),\n );\n\nconst expectFailure = (\n caseName: string,\n request: CodeExecutionRequest,\n host: CodeExecutionHost[\"Service\"],\n tag: CodeExecutionError[\"_tag\"],\n check?: (error: CodeExecutionError) => string | undefined,\n): Effect.Effect<void, CodeExecutorConformanceViolation, CodeExecutor> =>\n runPass(request, host).pipe(\n Effect.flip,\n Effect.mapError((result) =>\n violation(caseName, `expected ${tag}, but the pass succeeded with ${preview(result.value)}`),\n ),\n Effect.flatMap((error) => {\n if (error._tag !== tag) {\n return Effect.fail(\n violation(caseName, `expected ${tag}, got ${error._tag}: ${preview(error)}`),\n );\n }\n const complaint = check?.(error);\n return complaint === undefined ? Effect.void : Effect.fail(violation(caseName, complaint));\n }),\n );\n\nexport const codeExecutorConformanceCases = (\n options: CodeExecutorConformanceOptions,\n): ReadonlyArray<CodeExecutorConformanceCase> => {\n const posture = options.implementation;\n return [\n {\n name: \"TEST-015 executes bounded JSON computation and returns the program value\",\n run: expectSuccess(\n \"TEST-015 executes bounded JSON computation and returns the program value\",\n makeRequest(\n \"async () => { const xs = [1, 2, 3].map((n) => n * 2); return { xs, sum: xs.reduce((a, b) => a + b, 0) }; }\",\n ),\n unusedHost,\n (result) =>\n JSON.stringify(result.value) === JSON.stringify({ xs: [2, 4, 6], sum: 12 })\n ? undefined\n : `unexpected program value ${preview(result.value)}`,\n ),\n },\n {\n name: \"CAP-015 reports its isolation posture honestly in results and errors\",\n run: Effect.gen(function* () {\n const caseName = \"CAP-015 reports its isolation posture honestly in results and errors\";\n const result = yield* runPass(makeRequest(\"async () => 1\"), unusedHost).pipe(\n Effect.mapError((error) => violation(caseName, `expected success, got ${error._tag}`)),\n );\n if (\n result.implementation.isolation !== posture.isolation ||\n result.implementation.identity !== posture.identity\n ) {\n return yield* violation(\n caseName,\n `result posture ${preview(result.implementation)} does not match the declared ${preview(posture)}`,\n );\n }\n const error = yield* runPass(makeRequest(\"async () => {\"), unusedHost).pipe(\n Effect.flip,\n Effect.mapError(() => violation(caseName, \"expected the invalid-source pass to fail\")),\n );\n // Every expected execution failure carries the posture; an adapter\n // omitting the field must fail this case, not slip past a probe.\n if (\n error.implementation === undefined ||\n error.implementation.isolation !== posture.isolation ||\n error.implementation.identity !== posture.identity\n ) {\n return yield* violation(\n caseName,\n `error posture ${preview(error.implementation)} does not match the declared ${preview(posture)}`,\n );\n }\n }),\n },\n {\n name: \"TEST-015 routes host calls through the CodeExecutionHost in program order\",\n run: Effect.gen(function* () {\n const caseName =\n \"TEST-015 routes host calls through the CodeExecutionHost in program order\";\n const { host, calls } = respondingHost((call) =>\n call.method === \"query\"\n ? CodeHostCallSuccess.make({ value: { rows: [1, 2, 3] } })\n : CodeHostCallSuccess.make({ value: 3 }),\n );\n const result = yield* runPass(\n makeRequest(\n \"async () => { const q = await warehouse.query({ sql: 'select' }); const c = await warehouse.count({ table: 't' }); return { rows: q.rows, count: c }; }\",\n { namespaces: [warehouseNamespace] },\n ),\n host,\n ).pipe(\n Effect.mapError((error) =>\n violation(caseName, `expected success, got ${error._tag}: ${preview(error)}`),\n ),\n );\n if (JSON.stringify(result.value) !== JSON.stringify({ rows: [1, 2, 3], count: 3 })) {\n return yield* violation(caseName, `unexpected value ${preview(result.value)}`);\n }\n const observed = calls.map((call) => `${call.namespace}.${call.method}`);\n if (JSON.stringify(observed) !== JSON.stringify([\"warehouse.query\", \"warehouse.count\"])) {\n return yield* violation(caseName, `unexpected host call order ${preview(observed)}`);\n }\n if (result.resourceUse.hostCalls !== 2) {\n return yield* violation(\n caseName,\n `expected 2 accounted host calls, got ${result.resourceUse.hostCalls}`,\n );\n }\n }),\n },\n {\n name: \"TEST-015 a caught failed host call lets the program branch on the envelope\",\n run: expectSuccess(\n \"TEST-015 a caught failed host call lets the program branch on the envelope\",\n makeRequest(\n \"async () => { try { await warehouse.query({ sql: 'x' }); return 'unreachable'; } catch (envelope) { return { caught: envelope }; } }\",\n { namespaces: [warehouseNamespace] },\n ),\n respondingHost(() =>\n CodeHostCallFailure.make({ error: { _tag: \"ToolInputError\", message: \"bad input\" } }),\n ).host,\n (result) =>\n JSON.stringify(result.value) ===\n JSON.stringify({ caught: { _tag: \"ToolInputError\", message: \"bad input\" } })\n ? undefined\n : `the envelope did not round-trip: ${preview(result.value)}`,\n ),\n },\n {\n name: \"TEST-015 an uncaught failed host call fails the program with the envelope\",\n run: expectFailure(\n \"TEST-015 an uncaught failed host call fails the program with the envelope\",\n makeRequest(\"async () => warehouse.query({ sql: 'x' })\", {\n namespaces: [warehouseNamespace],\n }),\n respondingHost(() =>\n CodeHostCallFailure.make({ error: { _tag: \"PolicyDenied\", message: \"denied\" } }),\n ).host,\n \"CodeProgramFailedError\",\n (error) =>\n error._tag === \"CodeProgramFailedError\" &&\n error.reason === \"rejected\" &&\n JSON.stringify(error.thrown) ===\n JSON.stringify({ _tag: \"PolicyDenied\", message: \"denied\" })\n ? undefined\n : `unexpected failure detail ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 fails typed on syntactically invalid source\",\n run: expectFailure(\n \"TEST-015 fails typed on syntactically invalid source\",\n makeRequest(\"async () => {\"),\n unusedHost,\n \"CodeSourceError\",\n (error) =>\n error._tag === \"CodeSourceError\" && error.reason === \"invalid\"\n ? undefined\n : `expected reason invalid, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 fails typed when the expression is not one async function\",\n run: expectFailure(\n \"TEST-015 fails typed when the expression is not one async function\",\n makeRequest(\"1 + 1\"),\n unusedHost,\n \"CodeSourceError\",\n (error) =>\n error._tag === \"CodeSourceError\" && error.reason === \"not-a-function\"\n ? undefined\n : `expected reason not-a-function, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 fails typed on source larger than the declared byte limit\",\n run: expectFailure(\n \"TEST-015 fails typed on source larger than the declared byte limit\",\n makeRequest(`async () => \"${\"x\".repeat(2_000)}\"`, {\n limits: CodeExecutionLimits.make({ ...baseLimits, maxSourceBytes: 256 }),\n }),\n unusedHost,\n \"CodeSourceError\",\n (error) =>\n error._tag === \"CodeSourceError\" && error.reason === \"oversized\"\n ? undefined\n : `expected reason oversized, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 terminates a never-settling program at the wall-clock deadline\",\n run: expectFailure(\n \"TEST-015 terminates a never-settling program at the wall-clock deadline\",\n makeRequest(\"async () => { await new Promise(() => {}); return 1; }\", {\n limits: CodeExecutionLimits.make({ ...baseLimits, maxWallTime: Duration.millis(250) }),\n }),\n unusedHost,\n \"CodeExecutionTimeoutError\",\n ),\n },\n {\n name: \"TEST-015 fails typed when console output exceeds its byte budget\",\n run: expectFailure(\n \"TEST-015 fails typed when console output exceeds its byte budget\",\n makeRequest(\n \"async () => { for (let i = 0; i < 64; i += 1) { console.log('x'.repeat(256)); } return 1; }\",\n { limits: CodeExecutionLimits.make({ ...baseLimits, maxLogBytes: 2_048 }) },\n ),\n unusedHost,\n \"CodeOutputLimitError\",\n (error) =>\n error._tag === \"CodeOutputLimitError\" && error.surface === \"logs\"\n ? undefined\n : `expected surface logs, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 fails typed when the final result exceeds its byte budget\",\n run: expectFailure(\n \"TEST-015 fails typed when the final result exceeds its byte budget\",\n makeRequest(\"async () => 'y'.repeat(4096)\", {\n limits: CodeExecutionLimits.make({ ...baseLimits, maxResultBytes: 1_024 }),\n }),\n unusedHost,\n \"CodeOutputLimitError\",\n (error) =>\n error._tag === \"CodeOutputLimitError\" && error.surface === \"result\"\n ? undefined\n : `expected surface result, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 fails typed when host calls exceed the executor cap\",\n run: Effect.gen(function* () {\n const caseName = \"TEST-015 fails typed when host calls exceed the executor cap\";\n const { host, calls } = respondingHost(() => CodeHostCallSuccess.make({ value: null }));\n yield* expectFailure(\n caseName,\n makeRequest(\n \"async () => { await warehouse.query({}); await warehouse.query({}); await warehouse.query({}); return 1; }\",\n {\n namespaces: [warehouseNamespace],\n limits: CodeExecutionLimits.make({ ...baseLimits, maxHostCalls: 2 }),\n },\n ),\n host,\n \"CodeHostCallLimitError\",\n );\n // The cap is enforced before dispatch: the over-limit call must never\n // have reached the host, or an unauthorized side effect already ran.\n if (calls.length !== 2) {\n return yield* violation(\n caseName,\n `expected exactly 2 dispatched host calls under a cap of 2, observed ${calls.length}`,\n );\n }\n }),\n },\n {\n name: \"TEST-015 fails typed on a host outcome outside the protocol schema\",\n run: expectFailure(\n \"TEST-015 fails typed on a host outcome outside the protocol schema\",\n makeRequest(\"async () => warehouse.query({})\", { namespaces: [warehouseNamespace] }),\n {\n call: () => Effect.succeed({ bogus: true } as unknown as CodeHostCallResult),\n },\n \"CodeExecutionProtocolError\",\n ),\n },\n {\n name: \"TEST-015 surfaces an uncaught program throw with its bounded log capture\",\n run: expectFailure(\n \"TEST-015 surfaces an uncaught program throw with its bounded log capture\",\n makeRequest(\n \"async () => { console.log('before the failure'); throw new Error('deliberate'); }\",\n ),\n unusedHost,\n \"CodeProgramFailedError\",\n (error) =>\n error._tag === \"CodeProgramFailedError\" &&\n error.reason === \"threw\" &&\n error.logs.some((line) => line.includes(\"before the failure\"))\n ? undefined\n : `expected a threw failure carrying the log capture, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 fails typed when the program returns a non-JSON value\",\n run: expectFailure(\n \"TEST-015 fails typed when the program returns a non-JSON value\",\n makeRequest(\"async () => (() => 1)\"),\n unusedHost,\n \"CodeProgramFailedError\",\n (error) =>\n error._tag === \"CodeProgramFailedError\" && error.reason === \"non-json-result\"\n ? undefined\n : `expected reason non-json-result, got ${preview(error)}`,\n ),\n },\n {\n name: \"CAP-015 rejects a network allowlist it cannot enforce with a typed unsupported error\",\n run: expectFailure(\n \"CAP-015 rejects a network allowlist it cannot enforce with a typed unsupported error\",\n makeRequest(\"async () => 1\", {\n network: NetworkAllowlist.make({ domains: [\"example.com\"], ports: [443] }),\n }),\n unusedHost,\n \"CodeExecutorUnsupportedError\",\n (error) =>\n error._tag === \"CodeExecutorUnsupportedError\" && error.feature === \"network\"\n ? undefined\n : `expected feature network, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 interruption reaches in-flight host calls and pass teardown\",\n run: Effect.gen(function* () {\n const caseName = \"TEST-015 interruption reaches in-flight host calls and pass teardown\";\n const started = yield* Deferred.make<void>();\n const witness = { hostCallInterrupted: false };\n const host: CodeExecutionHost[\"Service\"] = {\n call: () =>\n Deferred.succeed(started, undefined).pipe(\n Effect.andThen(Effect.never),\n Effect.ensuring(\n Effect.sync(() => {\n witness.hostCallInterrupted = true;\n }),\n ),\n ),\n };\n const fiber = yield* runPass(\n makeRequest(\"async () => warehouse.query({})\", { namespaces: [warehouseNamespace] }),\n host,\n ).pipe(Effect.forkChild);\n // Guard against a broken adapter that settles the pass without ever\n // reaching the host: the case must report a violation, not hang.\n const winner = yield* Effect.raceFirst(\n Deferred.await(started).pipe(Effect.as(\"started\" as const)),\n Fiber.join(fiber).pipe(Effect.exit, Effect.as(\"exited\" as const)),\n );\n if (winner === \"exited\") {\n return yield* violation(\n caseName,\n \"the pass settled before any host call reached the CodeExecutionHost\",\n );\n }\n yield* Fiber.interrupt(fiber);\n if (!witness.hostCallInterrupted) {\n return yield* violation(\n caseName,\n \"interrupting the pass did not interrupt the in-flight host call\",\n );\n }\n }),\n },\n ];\n};\n","import {\n CodeExecutionHost,\n CodeExecutionLimits,\n CodeExecutionNamespace,\n CodeExecutionProtocolError,\n CodeExecutionRequest,\n CodeExecutionResourceUse,\n CodeExecutionResult,\n CodeExecutionTimeoutError,\n CodeExecutor,\n type CodeExecutorExecute,\n CodeExecutorUnsupportedError,\n CodeHostCall,\n CodeHostCallLimitError,\n CodeHostCallResult,\n CodeOutputLimitError,\n CodeProgramFailedError,\n CodeSourceError,\n SandboxImplementation,\n} from \"@effect-agent/sandbox\";\nimport { Clock, Duration, Effect, Fiber, Layer, Option, Queue, Schema } from \"effect\";\n\n/**\n * The deterministic in-process executor substitute (C1 of ADR-0017). It runs\n * the generated program on the host JavaScript engine with best-effort global\n * shadowing only, so it self-identifies as `unisolated` and is never a\n * security boundary (CAP-010, CAP-015). It exists to prove the public\n * `CodeExecutor` contract and to drive deterministic capability tests.\n */\nexport const inProcessCodeExecutorImplementation = SandboxImplementation.make({\n isolation: \"unisolated\",\n identity: \"in-process-javascript\",\n});\n\n// These two caps mirror the wire schema bounds (`BoundedLogs` is at most\n// 4096 lines of at most 16 KiB each): capture must stay inside what\n// `CodeExecutionResult` can carry. A line over the per-line cap is truncated\n// with an explicit `…` marker; exceeding either the byte budget or the line\n// cap fails the pass typed.\nconst MAX_LOG_LINES = 4_096;\nconst MAX_LOG_LINE_CHARACTERS = 16_000;\nconst MAX_THROWN_CHARACTERS = 4_000;\n\nconst utf8ByteLength = (value: string): number => new TextEncoder().encode(value).byteLength;\n\n/**\n * Ambient globals shadowed inside the harness. Shadowing blocks the obvious\n * identifier paths only; a determined program can still escape, which is\n * exactly why this executor reports `unisolated` and the isolated network and\n * CPU enforcement conformance cases run only against isolated adapters.\n */\nconst shadowedGlobals = [\n \"fetch\",\n \"process\",\n \"require\",\n \"module\",\n \"exports\",\n \"global\",\n \"globalThis\",\n \"XMLHttpRequest\",\n \"WebSocket\",\n \"Deno\",\n \"Bun\",\n] as const;\n\nclass LogLimitSignal {\n constructor(readonly observed: number) {}\n}\n\nclass EvaluationThrew {\n constructor(readonly inner: unknown) {}\n}\n\nclass NotAFunction {\n constructor(readonly actual: string) {}\n}\n\ninterface LogCapture {\n readonly lines: Array<string>;\n bytes: number;\n}\n\n/**\n * Total, defect-free rendering of untrusted values: a hostile Proxy can throw\n * from property access, `toString`, and `Symbol.toPrimitive`, and an expected\n * program failure must never escape the typed channel as a defect while its\n * diagnostics are being serialized.\n */\nconst formatLogValue = (value: unknown): string => {\n try {\n if (typeof value === \"string\") {\n return value;\n }\n return JSON.stringify(value) ?? String(value);\n } catch {\n try {\n return String(value);\n } catch {\n return \"[unprintable value]\";\n }\n }\n};\n\nconst makeConsole = (capture: LogCapture, limits: CodeExecutionLimits) => {\n const write = (...values: ReadonlyArray<unknown>): void => {\n const joined = values.map(formatLogValue).join(\" \");\n const line =\n joined.length > MAX_LOG_LINE_CHARACTERS\n ? `${joined.slice(0, MAX_LOG_LINE_CHARACTERS - 1)}…`\n : joined;\n const bytes = utf8ByteLength(line);\n if (capture.lines.length >= MAX_LOG_LINES || capture.bytes + bytes > limits.maxLogBytes) {\n throw new LogLimitSignal(capture.bytes + bytes);\n }\n capture.lines.push(line);\n capture.bytes += bytes;\n };\n return { debug: write, error: write, info: write, log: write, warn: write };\n};\n\ninterface PendingHostCall {\n readonly namespace: string;\n readonly method: string;\n readonly argument: unknown;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n}\n\nconst buildNamespaceObject = (\n namespace: CodeExecutionNamespace,\n offer: (pending: PendingHostCall) => void,\n): Record<string, unknown> => {\n const methods: Record<string, unknown> = {};\n for (const method of namespace.methods) {\n methods[method] = (argument: unknown) =>\n new Promise((resolve, reject) => {\n offer({ namespace: namespace.name, method, argument, resolve, reject });\n });\n }\n return methods;\n};\n\nconst boundedText = (value: unknown): string => {\n try {\n const text = value instanceof Error ? `${value.name}: ${value.message}` : formatLogValue(value);\n return text.slice(0, MAX_THROWN_CHARACTERS);\n } catch {\n return \"[unserializable thrown value]\";\n }\n};\n\n/** Schema decoding of hostile values may itself throw through trap getters. */\nconst safeDecodeJson = (value: unknown): Option.Option<Schema.Json> => {\n try {\n return Schema.decodeUnknownOption(Schema.Json)(value);\n } catch {\n return Option.none();\n }\n};\n\nconst boundedThrown = (value: unknown): Schema.Json => {\n const decoded = safeDecodeJson(value);\n if (Option.isSome(decoded)) {\n try {\n const encoded = JSON.stringify(decoded.value);\n if (encoded !== undefined && encoded.length <= MAX_THROWN_CHARACTERS) {\n return decoded.value;\n }\n } catch {\n // fall through to the bounded string form\n }\n }\n return boundedText(value);\n};\n\nconst encodedJsonByteLength = (value: Schema.Json): number | undefined => {\n try {\n const encoded = JSON.stringify(value);\n return encoded === undefined ? undefined : utf8ByteLength(encoded);\n } catch {\n return undefined;\n }\n};\n\n/** Host outcomes are protocol input; a hostile value must not defect mid-decode. */\nconst decodeHostOutcome = (value: unknown): Option.Option<CodeHostCallResult> => {\n try {\n return Schema.decodeUnknownOption(CodeHostCallResult)(value);\n } catch {\n return Option.none();\n }\n};\n\nconst validateRequest = (\n request: CodeExecutionRequest,\n): Effect.Effect<void, CodeExecutorUnsupportedError | CodeSourceError> =>\n Effect.gen(function* () {\n if (request.network._tag !== \"NetworkDisabled\") {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: inProcessCodeExecutorImplementation,\n feature: \"network\",\n message:\n \"The unisolated in-process executor cannot enforce an egress allowlist; only NetworkDisabled is accepted, and even that is shadowed rather than enforced\",\n });\n }\n if (request.limits.cpuMillis !== undefined) {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: inProcessCodeExecutorImplementation,\n feature: \"cpu-limit\",\n message:\n \"The unisolated in-process executor shares the host engine and cannot enforce a CPU limit\",\n });\n }\n const reservedNames = new Set<string>([...shadowedGlobals, \"console\"]);\n const seen = new Set<string>();\n for (const namespace of request.namespaces) {\n if (reservedNames.has(namespace.name) || seen.has(namespace.name)) {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: inProcessCodeExecutorImplementation,\n feature: \"namespaces\",\n message: `Namespace ${namespace.name} collides with a harness binding or another namespace`,\n });\n }\n seen.add(namespace.name);\n }\n const sourceBytes = utf8ByteLength(request.source);\n if (sourceBytes > request.limits.maxSourceBytes) {\n return yield* CodeSourceError.make({\n implementation: inProcessCodeExecutorImplementation,\n reason: \"oversized\",\n message: `Source is ${sourceBytes} bytes; the request allows ${request.limits.maxSourceBytes}`,\n });\n }\n });\n\nconst serveHostCalls = (\n host: CodeExecutionHost[\"Service\"],\n queue: Queue.Queue<PendingHostCall>,\n limits: CodeExecutionLimits,\n capture: LogCapture,\n counter: { calls: number },\n): Effect.Effect<\n never,\n CodeHostCallLimitError | CodeOutputLimitError | CodeExecutionProtocolError\n> =>\n Effect.gen(function* () {\n while (true) {\n const pending = yield* Queue.take(queue);\n counter.calls += 1;\n if (counter.calls > limits.maxHostCalls) {\n return yield* CodeHostCallLimitError.make({\n implementation: inProcessCodeExecutorImplementation,\n limit: limits.maxHostCalls,\n logs: [...capture.lines],\n });\n }\n const argument = safeDecodeJson(pending.argument);\n if (Option.isNone(argument)) {\n pending.reject(new TypeError(\"host call arguments must be JSON values\"));\n continue;\n }\n const argumentBytes = encodedJsonByteLength(argument.value);\n if (argumentBytes === undefined || argumentBytes > limits.maxHostCallArgumentBytes) {\n return yield* CodeOutputLimitError.make({\n implementation: inProcessCodeExecutorImplementation,\n surface: \"host-call-argument\",\n limit: limits.maxHostCallArgumentBytes,\n observed: argumentBytes ?? 0,\n logs: [...capture.lines],\n });\n }\n const rawOutcome = yield* host.call(\n CodeHostCall.make({\n namespace: pending.namespace,\n method: pending.method,\n argument: argument.value,\n }),\n );\n const outcome = decodeHostOutcome(rawOutcome);\n if (Option.isNone(outcome)) {\n return yield* CodeExecutionProtocolError.make({\n implementation: inProcessCodeExecutorImplementation,\n message: \"The execution host returned a value outside the CodeHostCallResult schema\",\n });\n }\n if (outcome.value._tag === \"CodeHostCallFailure\") {\n pending.reject(outcome.value.error);\n continue;\n }\n const resultBytes = encodedJsonByteLength(outcome.value.value);\n if (resultBytes === undefined || resultBytes > limits.maxHostCallResultBytes) {\n return yield* CodeOutputLimitError.make({\n implementation: inProcessCodeExecutorImplementation,\n surface: \"host-call-result\",\n limit: limits.maxHostCallResultBytes,\n observed: resultBytes ?? 0,\n logs: [...capture.lines],\n });\n }\n pending.resolve(outcome.value.value);\n }\n });\n\nconst classifyProgramFailure = (\n thrown: unknown,\n limits: CodeExecutionLimits,\n capture: LogCapture,\n): CodeOutputLimitError | CodeSourceError | CodeProgramFailedError => {\n const inner = thrown instanceof EvaluationThrew ? thrown.inner : thrown;\n if (inner instanceof LogLimitSignal) {\n return CodeOutputLimitError.make({\n implementation: inProcessCodeExecutorImplementation,\n surface: \"logs\",\n limit: limits.maxLogBytes,\n observed: inner.observed,\n logs: [...capture.lines],\n });\n }\n if (inner instanceof NotAFunction) {\n return CodeSourceError.make({\n implementation: inProcessCodeExecutorImplementation,\n reason: \"not-a-function\",\n message: `The source expression evaluated to ${inner.actual}; it must evaluate to one async function`,\n });\n }\n // An async function converts a body-level `throw` into a rejection, so the\n // split is by value shape: exception-like values read as `threw`, plain\n // rejection values (an uncaught host failure envelope) read as `rejected`.\n const reason = thrown instanceof EvaluationThrew || inner instanceof Error ? \"threw\" : \"rejected\";\n return CodeProgramFailedError.make({\n implementation: inProcessCodeExecutorImplementation,\n reason,\n thrown: boundedThrown(inner),\n message: boundedText(inner),\n logs: [...capture.lines],\n });\n};\n\nconst executeInProcess: CodeExecutorExecute = Effect.fn(\"InProcessCodeExecutor.execute\")(\n function* (request) {\n yield* validateRequest(request);\n const host = yield* CodeExecutionHost;\n const capture: LogCapture = { lines: [], bytes: 0 };\n const counter = { calls: 0 };\n const queue = yield* Queue.unbounded<PendingHostCall>();\n\n const factory = yield* Effect.try({\n try: () =>\n new Function(\n ...shadowedGlobals,\n \"console\",\n ...request.namespaces.map((namespace) => namespace.name),\n `\"use strict\";\\nreturn (\\n${request.source}\\n);`,\n ),\n catch: (cause) =>\n CodeSourceError.make({\n implementation: inProcessCodeExecutorImplementation,\n reason: \"invalid\",\n message: boundedText(cause),\n }),\n });\n\n const harnessConsole = makeConsole(capture, request.limits);\n // Admission is enforced at call creation, not only at the single-consumer\n // dequeue: a burst of unawaited calls can enqueue at most one entry past\n // the cap (the entry the server fails the pass on); everything beyond is\n // rejected synchronously, so the queue stays bounded against hostile\n // programs.\n let issuedHostCalls = 0;\n const namespaceObjects = request.namespaces.map((namespace) =>\n buildNamespaceObject(namespace, (pending) => {\n issuedHostCalls += 1;\n if (issuedHostCalls > request.limits.maxHostCalls + 1) {\n pending.reject(new Error(`host-call limit of ${request.limits.maxHostCalls} exceeded`));\n return;\n }\n Queue.offerUnsafe(queue, pending);\n }),\n );\n\n const server = yield* serveHostCalls(host, queue, request.limits, capture, counter).pipe(\n Effect.forkScoped,\n );\n\n const program = Effect.tryPromise({\n try: async () => {\n let candidate: unknown;\n try {\n candidate = factory(\n ...shadowedGlobals.map(() => undefined),\n harnessConsole,\n ...namespaceObjects,\n );\n } catch (cause) {\n throw new EvaluationThrew(cause);\n }\n if (typeof candidate !== \"function\") {\n throw new EvaluationThrew(new NotAFunction(typeof candidate));\n }\n let outcome: unknown;\n try {\n outcome = (candidate as () => unknown)();\n } catch (cause) {\n throw new EvaluationThrew(cause);\n }\n return await Promise.resolve(outcome);\n },\n catch: (thrown) => classifyProgramFailure(thrown, request.limits, capture),\n });\n\n const startedAt = yield* Clock.currentTimeMillis;\n // The wall-clock deadline interrupts only at asynchronous suspension\n // points: a synchronous runaway shares the host thread and cannot be\n // stopped in-process — exactly why the platform CPU enforcement cases\n // belong to isolated adapters only (testing spec §8.1). The server fiber\n // is interrupted when the pass settles so no host call outlives the\n // program that issued it.\n const returned = yield* Effect.raceFirst(program, Fiber.join(server)).pipe(\n Effect.timeoutOrElse({\n duration: request.limits.maxWallTime,\n orElse: () =>\n CodeExecutionTimeoutError.make({\n implementation: inProcessCodeExecutorImplementation,\n kind: \"wall-clock\",\n maxWallTime: request.limits.maxWallTime,\n logs: [...capture.lines],\n }),\n }),\n Effect.ensuring(Fiber.interrupt(server)),\n );\n const finishedAt = yield* Clock.currentTimeMillis;\n\n // An unawaited burst can outrun the server: the program may return before\n // the over-limit entry is dequeued, so the admission counter is the\n // authority — a pass that ISSUED more calls than the cap fails even when\n // its promise settled first.\n if (issuedHostCalls > request.limits.maxHostCalls) {\n return yield* CodeHostCallLimitError.make({\n implementation: inProcessCodeExecutorImplementation,\n limit: request.limits.maxHostCalls,\n logs: [...capture.lines],\n });\n }\n\n const value = yield* Schema.decodeUnknownEffect(Schema.Json)(returned).pipe(\n Effect.mapError(() =>\n CodeProgramFailedError.make({\n implementation: inProcessCodeExecutorImplementation,\n reason: \"non-json-result\",\n thrown: null,\n message: \"The program must return a JSON value\",\n logs: [...capture.lines],\n }),\n ),\n );\n const resultBytes = encodedJsonByteLength(value);\n if (resultBytes === undefined || resultBytes > request.limits.maxResultBytes) {\n return yield* CodeOutputLimitError.make({\n implementation: inProcessCodeExecutorImplementation,\n surface: \"result\",\n limit: request.limits.maxResultBytes,\n observed: resultBytes ?? 0,\n logs: [...capture.lines],\n });\n }\n\n return CodeExecutionResult.make({\n implementation: inProcessCodeExecutorImplementation,\n value,\n logs: [...capture.lines],\n resourceUse: CodeExecutionResourceUse.make({\n wallTime: Duration.millis(Math.max(0, finishedAt - startedAt)),\n hostCalls: counter.calls,\n logBytes: capture.bytes,\n resultBytes,\n }),\n });\n },\n);\n\n/**\n * Layer providing the unisolated in-process `CodeExecutor` substitute. The\n * per-pass `CodeExecutionHost` stays in the caller's requirement channel, the\n * same as every real adapter.\n */\nexport const inProcessCodeExecutorLayer: Layer.Layer<CodeExecutor> = Layer.succeed(CodeExecutor)(\n CodeExecutor.of({ execute: executeInProcess }),\n);\n","import { Subagent, SubagentPolicy, SubagentRuntime } from \"@effect-agent/capabilities\";\nimport { Agent, AgentPolicy } from \"@effect-agent/core\";\nimport type { RuntimeBinding } from \"@effect-agent/engine\";\nimport { Context, Effect, Schema } from \"effect\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\n\n// ---------------------------------------------------------------------------\n// Docs Researcher (P7 internal agent #3, plan §6): a coordinator that\n// delegates per-document summarization to a doc-summarizer child through the\n// S2 durable delegation surface, with the child's content tools served —\n// and validated — through the MCP connector against a scripted MCP fixture.\n// The corpus, tools, and both Agent Definitions are deterministic fixtures in\n// the travel-planner style so DN tests (and any later DC assembly) reuse them.\n// ---------------------------------------------------------------------------\n\nexport const ResearchDocumentId = Schema.NonEmptyString.check(Schema.isMaxLength(64)).pipe(\n Schema.brand(\"@effect-agent/testing/docs-researcher/ResearchDocumentId\"),\n);\nexport type ResearchDocumentId = typeof ResearchDocumentId.Type;\n\nconst BoundedTitle = Schema.NonEmptyString.check(Schema.isMaxLength(120));\nconst BoundedBody = Schema.NonEmptyString.check(Schema.isMaxLength(16 * 1024));\n/** Bounded summary text: the ONLY child-derived text that may cross to the parent. */\nexport const BoundedSummary = Schema.NonEmptyString.check(Schema.isMaxLength(240));\n\nexport class DocumentQuery extends Schema.Class<DocumentQuery>(\"DocumentQuery\")({\n documentId: ResearchDocumentId,\n}) {}\n\n/** One bounded research document as the MCP content server exposes it. */\nexport class ResearchDocument extends Schema.Class<ResearchDocument>(\"ResearchDocument\")({\n documentId: ResearchDocumentId,\n title: BoundedTitle,\n body: BoundedBody,\n}) {}\n\nexport class DocumentUnavailable extends Schema.TaggedError<DocumentUnavailable>()(\n \"DocumentUnavailable\",\n {\n documentId: ResearchDocumentId,\n message: Schema.String,\n },\n) {}\n\n/** The content store behind the scripted MCP server. */\nexport class DocumentLibrary extends Context.Service<\n DocumentLibrary,\n {\n readonly fetch: (query: DocumentQuery) => Effect.Effect<ResearchDocument, DocumentUnavailable>;\n }\n>()(\"@effect-agent/testing/docs-researcher/DocumentLibrary\") {}\n\n/**\n * The one content tool the doc-summarizer child uses. Its authored JSON\n * schema is what MCP discovery must serve byte-for-byte: the scripted MCP\n * fixture derives its discovery entry from `Tool.getJsonSchema(FetchDocument)`\n * and `validateMcpDiscovery` re-derives and digests both sides (CAP-009).\n */\nexport const FetchDocument = Tool.make(\"fetch_document\", {\n description: \"Fetch one bounded research document by its identifier.\",\n parameters: DocumentQuery,\n success: ResearchDocument,\n failure: DocumentUnavailable,\n failureMode: \"error\",\n dependencies: [DocumentLibrary],\n});\n\nexport const DocContentToolkit = Toolkit.make(FetchDocument);\nexport const docContentToolkitLayer = DocContentToolkit.toLayer({\n fetch_document: (query) => Effect.flatMap(DocumentLibrary, (library) => library.fetch(query)),\n});\n\n// ---------------------------------------------------------------------------\n// Deterministic corpus. Every body deliberately embeds BOTH a secret marker\n// and a distinctive body phrase: the tests assert that neither ever reaches\n// the parent Conversation, the parent prompts, or a redacted preview — only\n// the bounded summary crosses the delegation boundary (SUB-015, SEC-008).\n// ---------------------------------------------------------------------------\n\n/** Never allowed outside a child Conversation or an unredacted fixture value. */\nexport const docsDocumentBodySecret = \"docs-vault-secret-771\";\n\nconst decodeDocumentId = Schema.decodeSync(ResearchDocumentId);\n\ninterface CorpusEntry {\n readonly document: ResearchDocument;\n readonly bodyPhrase: string;\n readonly summary: string;\n}\n\nconst corpusEntries = new Map<string, CorpusEntry>(\n [\n {\n documentId: \"durability-notes\",\n title: \"Durability protocol notes\",\n bodyPhrase: \"amber-ledger-passage\",\n summary:\n \"Settlement results are recorded exactly once while external side effects stay at-least-once.\",\n },\n {\n documentId: \"subagent-notes\",\n title: \"Subagent join notes\",\n bodyPhrase: \"cobalt-join-corridor\",\n summary: \"A parent joins only the verified settlement of its own established child.\",\n },\n ].map((entry) => [\n entry.documentId,\n {\n document: ResearchDocument.make({\n documentId: decodeDocumentId(entry.documentId),\n title: entry.title,\n body: `${entry.bodyPhrase}: internal working notes. ${docsDocumentBodySecret}. ${entry.summary} Raw notes stay inside the child Conversation.`,\n }),\n bodyPhrase: entry.bodyPhrase,\n summary: entry.summary,\n },\n ]),\n);\n\n/** The corpus document ids in canonical fixture order. */\nexport const researchCorpusDocumentIds: ReadonlyArray<ResearchDocumentId> = [\n decodeDocumentId(\"durability-notes\"),\n decodeDocumentId(\"subagent-notes\"),\n];\n\nconst requireCorpusEntry = (documentId: string): CorpusEntry => {\n const entry = corpusEntries.get(documentId);\n if (entry === undefined) {\n throw new Error(`No deterministic corpus entry exists for document ${documentId}`);\n }\n return entry;\n};\n\n/** Deterministic library lookup shared by the scripted MCP content handlers. */\nexport const researchDocumentLookup = (\n query: DocumentQuery,\n): Effect.Effect<ResearchDocument, DocumentUnavailable> => {\n const entry = corpusEntries.get(query.documentId);\n return entry === undefined\n ? Effect.fail(\n DocumentUnavailable.make({\n documentId: query.documentId,\n message: \"No deterministic corpus entry exists for this document.\",\n }),\n )\n : Effect.succeed(entry.document);\n};\n\n/** The full fixture document (body includes the secret marker — child-side only). */\nexport const researchDocumentFor = (documentId: string): ResearchDocument =>\n requireCorpusEntry(documentId).document;\n\n/** The distinctive body phrase used by context-isolation assertions. */\nexport const documentBodyPhrase = (documentId: string): string =>\n requireCorpusEntry(documentId).bodyPhrase;\n\n// ---------------------------------------------------------------------------\n// Doc Summarizer: the child Agent Definition. Its toolkit is the authored\n// `DocContentToolkit`; the harness registers its worker Binding only after\n// MCP discovery validates that exact toolkit (mcp.ts).\n// ---------------------------------------------------------------------------\n\nexport class SummaryBrief extends Schema.Class<SummaryBrief>(\"SummaryBrief\")({\n documentId: ResearchDocumentId,\n focus: Schema.NonEmptyString,\n}) {}\n\nexport class DocumentSummary extends Schema.Class<DocumentSummary>(\"DocumentSummary\")({\n documentId: ResearchDocumentId,\n summary: BoundedSummary,\n}) {}\n\n/** The summary the scripted child writes after fetching the document. */\nexport const documentSummaryFor = (documentId: string): DocumentSummary =>\n DocumentSummary.make({\n documentId: requireCorpusEntry(documentId).document.documentId,\n summary: requireCorpusEntry(documentId).summary,\n });\n\nexport const encodedDocumentSummary = (documentId: string): string =>\n JSON.stringify(Schema.encodeSync(DocumentSummary)(documentSummaryFor(documentId)));\n\nexport const DocSummarizer = Agent.define(\"doc-summarizer\", {\n input: SummaryBrief,\n output: DocumentSummary,\n instructions:\n \"Fetch the briefed document with fetch_document exactly once, then return only a JSON document summary. Never copy raw notes or secrets into the summary.\",\n toolkit: DocContentToolkit,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 1,\n maxDuration: \"30 seconds\",\n toolConcurrency: 1,\n }),\n description: \"Summarize one bounded research document fetched through MCP content tools.\",\n metadata: { deploymentClass: \"DN\", phase: \"P7\" },\n});\n\n// ---------------------------------------------------------------------------\n// Delegation Definition: the coordinator sees exactly one Tool with explicit\n// projections and finite bounds. `projectResult` is the declassification\n// boundary (SUB-015): only the bounded summary crosses; the fetched body —\n// secret marker included — stays in the child Conversation.\n// ---------------------------------------------------------------------------\n\nexport class SummaryRequest extends Schema.Class<SummaryRequest>(\"SummaryRequest\")({\n documentId: ResearchDocumentId,\n}) {}\n\nexport class SummaryFinding extends Schema.Class<SummaryFinding>(\"SummaryFinding\")({\n documentId: ResearchDocumentId,\n summary: BoundedSummary,\n}) {}\n\nexport class DocumentSummaryFailed extends Schema.TaggedError<DocumentSummaryFailed>()(\n \"DocumentSummaryFailed\",\n {\n childErrorTag: Schema.NonEmptyString,\n },\n) {}\n\n/** Finite per-invocation bounds (SUB-009): one fetch per child, two children per Run. */\nexport const documentSummaryPolicy = SubagentPolicy.make({\n maxChildren: 2,\n maxConcurrency: 2,\n maxTurns: 2,\n maxToolCalls: 1,\n maxDuration: \"10 seconds\",\n});\n\nexport const delegateDocumentSummary = Subagent.define(\"delegate_document_summary\", {\n description:\n \"Summarize one research document through the doc-summarizer child and return a bounded finding.\",\n target: DocSummarizer,\n parameters: SummaryRequest,\n success: SummaryFinding,\n failure: DocumentSummaryFailed,\n prepareInput: (request) =>\n Effect.succeed(\n SummaryBrief.make({\n documentId: request.documentId,\n focus: \"summarize:durability-claims\",\n }),\n ),\n projectResult: (summary) =>\n Effect.succeed(\n SummaryFinding.make({\n documentId: summary.documentId,\n summary: summary.summary,\n }),\n ),\n policy: documentSummaryPolicy,\n});\n\n/** Total mapping from every expected child Run failure to the declared Tool failure (SUB-028). */\nexport const mapSummaryChildFailure = (failure: { readonly _tag: string }): DocumentSummaryFailed =>\n DocumentSummaryFailed.make({ childErrorTag: failure._tag });\n\n/** The exact digest strings the durable declaration AND host registration must share (SUB-023). */\nexport const docsSummarizerDigestStrings = {\n agent: \"50\".repeat(32),\n model: \"51\".repeat(32),\n tools: \"52\".repeat(32),\n} as const;\n\n/** Runtime wiring: the immutable delegation plus one explicit child Binding (S2 declaration). */\nexport const docsSummaryHandlersLayer = <Provider, ModelProvides, ModelRequires>(\n childBinding: RuntimeBinding<\n typeof SummaryBrief,\n typeof DocumentSummary,\n string,\n Toolkit.Tools<typeof DocContentToolkit>,\n Provider,\n ModelProvides,\n ModelRequires\n >,\n) =>\n SubagentRuntime.layer(delegateDocumentSummary, childBinding, {\n mapChildFailure: mapSummaryChildFailure,\n durable: { targetDigests: docsSummarizerDigestStrings },\n });\n\n// ---------------------------------------------------------------------------\n// Docs Researcher: the parent Agent Definition.\n// ---------------------------------------------------------------------------\n\nexport class ResearchRequest extends Schema.Class<ResearchRequest>(\"ResearchRequest\")({\n question: Schema.NonEmptyString,\n documentIds: Schema.Array(ResearchDocumentId).check(Schema.isMinLength(1)),\n}) {}\n\nexport class ResearchDigest extends Schema.Class<ResearchDigest>(\"ResearchDigest\")({\n findings: Schema.Array(SummaryFinding),\n nextAction: Schema.Literal(\"review\"),\n}) {}\n\n/** Parent-only transcript markers proving child context isolation (SUB-006/SUB-015). */\nexport const docsCoordinatorConfidentialMarker = \"docs-coordinator-vault-19x\";\nexport const docsMissionConfidentialMarker = \"docs-mission-dossier-42f\";\n\nexport const DocsResearcherToolkit = Toolkit.make(delegateDocumentSummary.tool);\n\nexport const DocsResearcher = Agent.define(\"docs-researcher\", {\n input: ResearchRequest,\n output: ResearchDigest,\n instructions: [\n \"You are the Effect Agent P7 docs-researcher coordinator.\",\n `Coordinator-only context: ${docsCoordinatorConfidentialMarker}.`,\n \"Call delegate_document_summary once per requested document in one Tool batch.\",\n \"Return only a JSON digest built from the delegated findings. This is read-only research.\",\n ].join(\"\\n\"),\n toolkit: DocsResearcherToolkit,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 2,\n maxDuration: \"30 seconds\",\n toolConcurrency: 2,\n }),\n description: \"Coordinate per-document summarization through one declared delegation Tool.\",\n metadata: { deploymentClass: \"DN\", phase: \"P7\" },\n});\n\n/** The default two-document research mission. */\nexport const researchMissionRequest = ResearchRequest.make({\n question: `Summarize the durability and subagent notes; keep ${docsMissionConfidentialMarker} inside the coordinator conversation.`,\n documentIds: researchCorpusDocumentIds,\n});\n\n/** The coordinator's expected final digest for the given documents. */\nexport const expectedResearchDigest = (\n documentIds: ReadonlyArray<string> = researchCorpusDocumentIds,\n): ResearchDigest =>\n ResearchDigest.make({\n findings: documentIds.map((documentId) => {\n const summary = documentSummaryFor(documentId);\n return SummaryFinding.make({\n documentId: summary.documentId,\n summary: summary.summary,\n });\n }),\n nextAction: \"review\",\n });\n","import { Agent, AgentPolicy } from \"@effect-agent/core\";\nimport { Context, Effect, Schema } from \"effect\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\n\nexport const AirportCode = Schema.NonEmptyString.pipe(\n Schema.brand(\"@effect-agent/testing/travel-planner/AirportCode\"),\n);\nexport type AirportCode = typeof AirportCode.Type;\n\nexport const QuoteId = Schema.NonEmptyString.pipe(\n Schema.brand(\"@effect-agent/testing/travel-planner/QuoteId\"),\n);\nexport type QuoteId = typeof QuoteId.Type;\n\nexport class TripRequest extends Schema.Class<TripRequest>(\"TripRequest\")({\n request: Schema.NonEmptyString,\n origin: AirportCode,\n destination: AirportCode,\n departOn: Schema.String,\n nights: Schema.Int.check(Schema.isGreaterThan(0)),\n travelers: Schema.Int.check(Schema.isGreaterThan(0)),\n budgetCents: Schema.Int.check(Schema.isGreaterThan(0)),\n currency: Schema.Literal(\"USD\"),\n}) {}\n\nexport class FlightQuery extends Schema.Class<FlightQuery>(\"FlightQuery\")({\n origin: AirportCode,\n destination: AirportCode,\n departOn: Schema.String,\n travelers: Schema.Int.check(Schema.isGreaterThan(0)),\n}) {}\n\nexport class LodgingQuery extends Schema.Class<LodgingQuery>(\"LodgingQuery\")({\n destination: AirportCode,\n departOn: Schema.String,\n nights: Schema.Int.check(Schema.isGreaterThan(0)),\n travelers: Schema.Int.check(Schema.isGreaterThan(0)),\n}) {}\n\nexport class ActivityQuery extends Schema.Class<ActivityQuery>(\"ActivityQuery\")({\n destination: AirportCode,\n departOn: Schema.String,\n nights: Schema.Int.check(Schema.isGreaterThan(0)),\n travelers: Schema.Int.check(Schema.isGreaterThan(0)),\n}) {}\n\nexport class FlightOption extends Schema.Class<FlightOption>(\"FlightOption\")({\n quoteId: QuoteId,\n flight: Schema.String,\n estimatedCents: Schema.Int.check(Schema.isGreaterThan(0)),\n currency: Schema.Literal(\"USD\"),\n}) {}\n\nexport class LodgingOption extends Schema.Class<LodgingOption>(\"LodgingOption\")({\n lodging: Schema.String,\n estimatedCents: Schema.Int.check(Schema.isGreaterThan(0)),\n currency: Schema.Literal(\"USD\"),\n}) {}\n\n/** A successful empty activity search is distinct from supplier unavailability. */\nexport class ActivitySearchResult extends Schema.Class<ActivitySearchResult>(\n \"ActivitySearchResult\",\n)({\n activities: Schema.Array(Schema.String),\n}) {}\n\nexport class Itinerary extends Schema.Class<Itinerary>(\"Itinerary\")({\n title: Schema.String,\n route: Schema.String,\n dates: Schema.String,\n flight: Schema.String,\n lodging: Schema.String,\n activities: Schema.Array(Schema.String),\n estimatedTotalCents: Schema.Int.check(Schema.isGreaterThan(0)),\n currency: Schema.Literal(\"USD\"),\n quoteId: QuoteId,\n assumptions: Schema.Array(Schema.String),\n unresolvedConstraints: Schema.Array(Schema.String),\n nextAction: Schema.Literal(\"review\"),\n}) {}\n\nexport class TravelPlan extends Schema.Class<TravelPlan>(\"TravelPlan\")({\n itineraries: Schema.Array(Itinerary),\n}) {}\n\nconst unavailableFields = { query: Schema.String, message: Schema.String };\nexport class FlightUnavailable extends Schema.TaggedError<FlightUnavailable>()(\n \"FlightUnavailable\",\n unavailableFields,\n) {}\nexport class LodgingUnavailable extends Schema.TaggedError<LodgingUnavailable>()(\n \"LodgingUnavailable\",\n unavailableFields,\n) {}\nexport class ActivityUnavailable extends Schema.TaggedError<ActivityUnavailable>()(\n \"ActivityUnavailable\",\n unavailableFields,\n) {}\nexport class GuidanceFailure extends Schema.TaggedError<GuidanceFailure>()(\"GuidanceFailure\", {\n message: Schema.String,\n}) {}\n\nexport class FlightCatalog extends Context.Service<\n FlightCatalog,\n { readonly search: (query: FlightQuery) => Effect.Effect<FlightOption, FlightUnavailable> }\n>()(\"@effect-agent/testing/travel-planner/FlightCatalog\") {}\nexport class LodgingCatalog extends Context.Service<\n LodgingCatalog,\n { readonly search: (query: LodgingQuery) => Effect.Effect<LodgingOption, LodgingUnavailable> }\n>()(\"@effect-agent/testing/travel-planner/LodgingCatalog\") {}\nexport class ActivityCatalog extends Context.Service<\n ActivityCatalog,\n {\n readonly search: (\n query: ActivityQuery,\n ) => Effect.Effect<ActivitySearchResult, ActivityUnavailable>;\n }\n>()(\"@effect-agent/testing/travel-planner/ActivityCatalog\") {}\nexport class TravelGuidance extends Context.Service<\n TravelGuidance,\n { readonly instructions: (input: TripRequest) => Effect.Effect<string, GuidanceFailure> }\n>()(\"@effect-agent/testing/travel-planner/TravelGuidance\") {}\n\nexport const SearchFlights = Tool.make(\"search_flights\", {\n parameters: FlightQuery,\n success: FlightOption,\n failure: FlightUnavailable,\n failureMode: \"error\",\n dependencies: [FlightCatalog],\n});\nexport const SearchLodging = Tool.make(\"search_lodging\", {\n parameters: LodgingQuery,\n success: LodgingOption,\n failure: LodgingUnavailable,\n failureMode: \"error\",\n dependencies: [LodgingCatalog],\n});\nexport const SearchActivities = Tool.make(\"search_activities\", {\n parameters: ActivityQuery,\n success: ActivitySearchResult,\n failure: ActivityUnavailable,\n failureMode: \"error\",\n dependencies: [ActivityCatalog],\n});\n\nexport const TravelPlannerToolkit = Toolkit.make(SearchFlights, SearchLodging, SearchActivities);\nexport const TravelPlannerToolkitLayer = TravelPlannerToolkit.toLayer({\n search_flights: (query) => Effect.flatMap(FlightCatalog, (catalog) => catalog.search(query)),\n search_lodging: (query) => Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(query)),\n search_activities: (query) => Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(query)),\n});\n\nexport const TravelPlanner = Agent.define(\"travel-planner\", {\n input: TripRequest,\n output: TravelPlan,\n instructions: (input) =>\n Effect.flatMap(TravelGuidance, (guidance) => guidance.instructions(input)),\n toolkit: TravelPlannerToolkit,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 3,\n maxDuration: \"30 seconds\",\n toolConcurrency: 3,\n }),\n description: \"Build one review-only itinerary from bounded parallel deterministic searches.\",\n metadata: { deploymentClass: \"E\", phase: \"P1\" },\n});\n","import { ConversationId, IdGenerator, RunId, TurnId } from \"@effect-agent/core\";\nimport { Context, Deferred, Effect, Layer, Option, Ref, Schema } from \"effect\";\n\nimport {\n ActivityCatalog,\n ActivitySearchResult,\n ActivityUnavailable,\n FlightCatalog,\n FlightOption,\n FlightUnavailable,\n LodgingCatalog,\n LodgingOption,\n LodgingUnavailable,\n QuoteId,\n TravelGuidance,\n TravelPlannerToolkit,\n TravelPlannerToolkitLayer,\n} from \"./definition.ts\";\n\nexport class CatalogLifecycleCounts extends Schema.Class<CatalogLifecycleCounts>(\n \"CatalogLifecycleCounts\",\n)({\n acquired: Schema.Natural,\n finalized: Schema.Natural,\n}) {}\nexport class CatalogLifecycle extends Context.Service<\n CatalogLifecycle,\n {\n readonly markAcquired: Effect.Effect<void>;\n readonly markFinalized: Effect.Effect<void>;\n readonly counts: Effect.Effect<CatalogLifecycleCounts>;\n }\n>()(\"@effect-agent/testing/travel-planner/CatalogLifecycle\") {\n static readonly layerNoDeps = Layer.effect(\n this,\n Effect.gen(function* () {\n const acquired = yield* Ref.make(0);\n const finalized = yield* Ref.make(0);\n return CatalogLifecycle.of({\n markAcquired: Ref.update(acquired, (n) => n + 1),\n markFinalized: Ref.update(finalized, (n) => n + 1),\n counts: Effect.all({ acquired: Ref.get(acquired), finalized: Ref.get(finalized) }).pipe(\n Effect.map((counts) => CatalogLifecycleCounts.make(counts)),\n ),\n });\n }),\n );\n}\n\nconst flight = FlightOption.make({\n quoteId: Schema.decodeSync(QuoteId)(\"quote-sfo-lhr-001\"),\n flight: \"EA 218 · nonstop · SFO 18:40 → LHR 13:05+1\",\n estimatedCents: 180_000,\n currency: \"USD\",\n});\nconst lodging = LodgingOption.make({\n lodging: \"Bloomsbury House · refundable studio · 4 nights\",\n estimatedCents: 104_000,\n currency: \"USD\",\n});\nconst activities = ActivitySearchResult.make({\n activities: [\"British Museum timed entry\", \"Thames evening walk\"],\n});\n\n/**\n * Deterministic controls for a Tool batch whose completions are released in a\n * caller-selected order. This is intentionally a test fixture: it uses no\n * clock or sleep and lets engine scheduler tests prove parallel starts and\n * declaration-order prompt materialization.\n */\nexport interface TravelPlannerCompletionControls {\n readonly flightStarted: Effect.Effect<void>;\n readonly lodgingStarted: Effect.Effect<void>;\n readonly activityStarted: Effect.Effect<void>;\n readonly releaseFlight: Effect.Effect<void>;\n readonly releaseLodging: Effect.Effect<void>;\n readonly releaseActivity: Effect.Effect<void>;\n}\n\nexport const ReverseCompletionToolkitLayer = Effect.gen(function* () {\n const flightStarted = yield* Deferred.make<void>();\n const lodgingStarted = yield* Deferred.make<void>();\n const activityStarted = yield* Deferred.make<void>();\n const releaseFlight = yield* Deferred.make<void>();\n const releaseLodging = yield* Deferred.make<void>();\n const releaseActivity = yield* Deferred.make<void>();\n const awaitRelease = <A>(\n started: Deferred.Deferred<void>,\n release: Deferred.Deferred<void>,\n value: A,\n ) =>\n Deferred.succeed(started, undefined).pipe(\n Effect.andThen(Deferred.await(release)),\n Effect.as(value),\n );\n return {\n controls: {\n flightStarted: Deferred.await(flightStarted),\n lodgingStarted: Deferred.await(lodgingStarted),\n activityStarted: Deferred.await(activityStarted),\n releaseFlight: Deferred.succeed(releaseFlight, undefined).pipe(Effect.asVoid),\n releaseLodging: Deferred.succeed(releaseLodging, undefined).pipe(Effect.asVoid),\n releaseActivity: Deferred.succeed(releaseActivity, undefined).pipe(Effect.asVoid),\n },\n layer: TravelPlannerToolkit.toLayer({\n search_flights: () => awaitRelease(flightStarted, releaseFlight, flight),\n search_lodging: () => awaitRelease(lodgingStarted, releaseLodging, lodging),\n search_activities: () => awaitRelease(activityStarted, releaseActivity, activities),\n }),\n };\n});\n\nexport const FlightCatalogLayer = Layer.effect(\n FlightCatalog,\n Effect.gen(function* () {\n const lifecycle = yield* CatalogLifecycle;\n yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);\n return FlightCatalog.of({\n search: (query) =>\n query.origin === query.destination\n ? Effect.fail(\n FlightUnavailable.make({\n query: `${query.origin}-${query.destination}`,\n message: \"Origin and destination must differ.\",\n }),\n )\n : Effect.succeed(flight),\n });\n }),\n);\nexport const LodgingCatalogLayer = Layer.effect(\n LodgingCatalog,\n Effect.gen(function* () {\n const lifecycle = yield* CatalogLifecycle;\n yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);\n return LodgingCatalog.of({\n search: (query) =>\n query.nights < 1\n ? Effect.fail(\n LodgingUnavailable.make({\n query: query.destination,\n message: \"At least one night is required.\",\n }),\n )\n : Effect.succeed(lodging),\n });\n }),\n);\nexport const ActivityCatalogLayer = Layer.effect(\n ActivityCatalog,\n Effect.gen(function* () {\n const lifecycle = yield* CatalogLifecycle;\n yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);\n return ActivityCatalog.of({\n search: (query) =>\n query.destination === \"\"\n ? Effect.fail(\n ActivityUnavailable.make({\n query: query.destination,\n message: \"Destination is required.\",\n }),\n )\n : Effect.succeed(activities),\n });\n }),\n);\n/** Stable supplier-side booking identity, minted deterministically from the idempotency key. */\nexport const BookingRef = Schema.NonEmptyString.pipe(\n Schema.brand(\"@effect-agent/testing/travel-planner/BookingRef\"),\n);\nexport type BookingRef = typeof BookingRef.Type;\n\n/** The supplier desk operations the P5 booking Tools and Steps invoke. */\nexport const SupplierOperation = Schema.Literals([\n \"book-flight\",\n \"cancel-booking\",\n \"reserve-flight\",\n \"reserve-lodging\",\n \"issue-confirmation\",\n]);\nexport type SupplierOperation = typeof SupplierOperation.Type;\n\n/**\n * One row of external supplier truth. The desk deduplicates by `idempotencyKey` — replaying a\n * call with the same key returns this exact record without creating a second booking — which is\n * precisely the honesty model of DUR-010: the framework never makes an external call\n * exactly-once; the supplier's idempotency key does.\n */\nexport class SupplierBookingRecord extends Schema.Class<SupplierBookingRecord>(\n \"@effect-agent/testing/travel-planner/SupplierBookingRecord\",\n)({\n bookingRef: BookingRef,\n idempotencyKey: Schema.NonEmptyString,\n operation: SupplierOperation,\n detail: Schema.NonEmptyString,\n status: Schema.Literals([\"confirmed\", \"cancelled\"]),\n}) {}\n\nexport class SupplierUnavailable extends Schema.TaggedError<SupplierUnavailable>()(\n \"SupplierUnavailable\",\n { message: Schema.String },\n) {}\n\nexport interface SupplierBookRequest {\n readonly operation: SupplierOperation;\n readonly idempotencyKey: string;\n readonly detail: string;\n}\n\n/** Controls returned by an armed crash window (`holdAfterWrite`). */\nexport interface SupplierHoldControls {\n /** Resolves once the armed call has performed its supplier write and is blocked. */\n readonly held: Effect.Effect<void>;\n /** Releases the blocked call (tests that interrupt the Attempt never call this). */\n readonly release: Effect.Effect<void>;\n}\n\n/** The desk-internal idempotency key of one cancellation: cancel is idempotent by bookingRef. */\nexport const cancelBookingIdempotencyKey = (bookingRef: string): string =>\n `cancel-booking:${bookingRef}`;\n\n/** The deterministic bookingRef the desk mints for one idempotency key. */\nexport const supplierBookingRefFor = (idempotencyKey: string): BookingRef =>\n Schema.decodeSync(BookingRef)(`ref:${idempotencyKey}`);\n\ninterface SupplierHoldWindow {\n readonly held: Deferred.Deferred<void>;\n readonly release: Deferred.Deferred<void>;\n}\n\ninterface SupplierDeskState {\n readonly bookings: ReadonlyMap<string, SupplierBookingRecord>;\n readonly counts: ReadonlyMap<string, number>;\n readonly holds: ReadonlyMap<string, SupplierHoldWindow>;\n}\n\n/**\n * The deterministic in-memory supplier: an idempotency-keyed booking store with per-key call\n * counters and injectable crash windows.\n *\n * - `book`/`cancel` always count the call (at-least-once execution stays observable), then\n * dedupe the external effect by idempotency key — the supplier-side contract the P5 Tools and\n * Steps rely on.\n * - `holdAfterWrite` arms a one-shot crash window: the next call with that key performs its\n * supplier write, signals `held`, and never returns. Interrupting the Attempt at that point\n * models \"the external effect happened but no outcome was recorded\" without any wall clock.\n * - `bookings`/`lookup` expose external truth for the reconciler and for never-fabricate\n * assertions.\n */\nexport class SupplierBookingDesk extends Context.Service<\n SupplierBookingDesk,\n {\n readonly book: (\n request: SupplierBookRequest,\n ) => Effect.Effect<SupplierBookingRecord, SupplierUnavailable>;\n readonly cancel: (\n bookingRef: BookingRef,\n ) => Effect.Effect<SupplierBookingRecord, SupplierUnavailable>;\n readonly lookup: (\n idempotencyKey: string,\n ) => Effect.Effect<Option.Option<SupplierBookingRecord>>;\n readonly bookings: Effect.Effect<ReadonlyArray<SupplierBookingRecord>>;\n readonly callCount: (idempotencyKey: string) => Effect.Effect<number>;\n readonly holdAfterWrite: (idempotencyKey: string) => Effect.Effect<SupplierHoldControls>;\n }\n>()(\"@effect-agent/testing/travel-planner/SupplierBookingDesk\") {\n static readonly layer: Layer.Layer<SupplierBookingDesk> = Layer.effect(\n this,\n Effect.gen(function* () {\n const state = yield* Ref.make<SupplierDeskState>({\n bookings: new Map(),\n counts: new Map(),\n holds: new Map(),\n });\n\n const enterHold = (hold: Option.Option<SupplierHoldWindow>) =>\n Option.isSome(hold)\n ? Deferred.succeed(hold.value.held, undefined).pipe(\n Effect.andThen(Deferred.await(hold.value.release)),\n )\n : Effect.void;\n\n const book = (request: SupplierBookRequest) =>\n Ref.modify(state, (current) => {\n const counts = new Map(current.counts).set(\n request.idempotencyKey,\n (current.counts.get(request.idempotencyKey) ?? 0) + 1,\n );\n const existing = current.bookings.get(request.idempotencyKey);\n const record =\n existing ??\n SupplierBookingRecord.make({\n bookingRef: supplierBookingRefFor(request.idempotencyKey),\n idempotencyKey: request.idempotencyKey,\n operation: request.operation,\n detail: request.detail,\n status: \"confirmed\",\n });\n const bookings =\n existing === undefined\n ? new Map(current.bookings).set(request.idempotencyKey, record)\n : current.bookings;\n const hold = Option.fromNullishOr(current.holds.get(request.idempotencyKey));\n const holds = Option.isSome(hold)\n ? (() => {\n const next = new Map(current.holds);\n next.delete(request.idempotencyKey);\n return next;\n })()\n : current.holds;\n return [\n { record, hold },\n { bookings, counts, holds },\n ] as const;\n }).pipe(Effect.flatMap(({ hold, record }) => enterHold(hold).pipe(Effect.as(record))));\n\n const cancel = (bookingRef: BookingRef) =>\n Ref.modify(state, (current) => {\n const key = cancelBookingIdempotencyKey(bookingRef);\n const counts = new Map(current.counts).set(key, (current.counts.get(key) ?? 0) + 1);\n const existingEntry = [...current.bookings.entries()].find(\n ([, record]) => record.bookingRef === bookingRef,\n );\n if (existingEntry === undefined) {\n return [\n { record: Option.none<SupplierBookingRecord>(), hold: Option.none() },\n { ...current, counts },\n ] as const;\n }\n const [storeKey, existing] = existingEntry;\n const cancelled =\n existing.status === \"cancelled\"\n ? existing\n : SupplierBookingRecord.make({ ...existing, status: \"cancelled\" });\n const bookings = new Map(current.bookings).set(storeKey, cancelled);\n const hold = Option.fromNullishOr(current.holds.get(key));\n const holds = Option.isSome(hold)\n ? (() => {\n const next = new Map(current.holds);\n next.delete(key);\n return next;\n })()\n : current.holds;\n return [\n { record: Option.some(cancelled), hold },\n { bookings, counts, holds },\n ] as const;\n }).pipe(\n Effect.flatMap(({ hold, record }) =>\n Option.isNone(record)\n ? Effect.fail(\n SupplierUnavailable.make({\n message: `The supplier desk has no booking under ${bookingRef}.`,\n }),\n )\n : enterHold(hold).pipe(Effect.as(record.value)),\n ),\n );\n\n return SupplierBookingDesk.of({\n book,\n cancel,\n lookup: (idempotencyKey) =>\n Ref.get(state).pipe(\n Effect.map((current) => Option.fromNullishOr(current.bookings.get(idempotencyKey))),\n ),\n bookings: Ref.get(state).pipe(Effect.map((current) => [...current.bookings.values()])),\n callCount: (idempotencyKey) =>\n Ref.get(state).pipe(Effect.map((current) => current.counts.get(idempotencyKey) ?? 0)),\n holdAfterWrite: (idempotencyKey) =>\n Effect.gen(function* () {\n const held = yield* Deferred.make<void>();\n const release = yield* Deferred.make<void>();\n yield* Ref.update(state, (current) => ({\n ...current,\n holds: new Map(current.holds).set(idempotencyKey, { held, release }),\n }));\n return {\n held: Deferred.await(held),\n release: Deferred.succeed(release, undefined).pipe(Effect.asVoid),\n };\n }),\n });\n }),\n );\n}\n\nexport const TravelGuidanceLayer = Layer.succeed(\n TravelGuidance,\n TravelGuidance.of({\n instructions: (input) =>\n Effect.succeed(\n [\n \"You are the Effect Agent Travel Planner P1 interpreter fixture.\",\n `The user asked: ${input.request}`,\n \"Call search_flights, search_lodging, and search_activities exactly once in one Tool batch.\",\n \"Then return only a JSON object of exactly this shape, no prose:\",\n '{\"itineraries\": [{\"title\": \"<short itinerary name>\", \"route\": \"<origin-destination>\", \"dates\": \"<date range>\", \"flight\": \"<flight description from the Tool result>\", \"lodging\": \"<lodging description from the Tool result>\", \"activities\": [\"<activity>\", \"...\"], \"estimatedTotalCents\": <positive integer total in cents>, \"currency\": \"USD\", \"quoteId\": \"<quoteId from the flight Tool result>\", \"assumptions\": [\"<assumption>\", \"...\"], \"unresolvedConstraints\": [], \"nextAction\": \"review\"}]}',\n \"Use the Tool results verbatim; activity results may legitimately be an empty array.\",\n \"This is read-only planning. Require review before any mutation.\",\n ].join(\"\\n\"),\n ),\n }),\n);\nexport const DeterministicIdGeneratorLayer = Layer.effect(\n IdGenerator,\n Effect.gen(function* () {\n const conversation = yield* Ref.make(0);\n const run = yield* Ref.make(0);\n const turn = yield* Ref.make(0);\n return IdGenerator.of({\n nextConversationId: Ref.updateAndGet(conversation, (n) => n + 1).pipe(\n Effect.map((n) => Schema.decodeSync(ConversationId)(`conversation-${n}`)),\n ),\n nextRunId: Ref.updateAndGet(run, (n) => n + 1).pipe(\n Effect.map((n) => Schema.decodeSync(RunId)(`run-${n}`)),\n ),\n nextTurnId: Ref.updateAndGet(turn, (n) => n + 1).pipe(\n Effect.map((n) => Schema.decodeSync(TurnId)(`turn-${n}`)),\n ),\n });\n }),\n);\nexport const TravelPlannerRuntimeLayer = Layer.mergeAll(\n TravelPlannerToolkitLayer,\n FlightCatalogLayer,\n LodgingCatalogLayer,\n ActivityCatalogLayer,\n TravelGuidanceLayer,\n DeterministicIdGeneratorLayer,\n).pipe(Layer.provide(CatalogLifecycle.layerNoDeps));\n","import {\n McpConnectionRequest,\n McpConnector,\n McpServerIdentity,\n McpToolkitMismatch,\n type McpConnection,\n} from \"@effect-agent/capabilities\";\nimport { Effect, Layer, Schema } from \"effect\";\nimport { Tool } from \"effect/unstable/ai\";\nimport * as McpSchema from \"effect/unstable/ai/McpSchema\";\n\nimport { DocContentToolkit, FetchDocument } from \"./definition.ts\";\n\n// ---------------------------------------------------------------------------\n// Scripted MCP fixture: a deterministic `McpConnector` adapter that serves the\n// doc-summarizer's content tool. Discovery entries are DERIVED from the\n// authored Tool (`Tool.getJsonSchema`), so `validateMcpDiscovery` digesting\n// both sides is a real check, not a tautology; the mismatch and over-limit\n// connectors below serve deliberately wrong contracts so tests can pin the\n// fail-closed paths (CAP-009, SEC-013).\n// ---------------------------------------------------------------------------\n\n/** Framework-side hard bounds one docs-researcher assembly requests. */\nexport const docsMcpRequest = McpConnectionRequest.make({\n serverId: \"docs-content-mcp\",\n maxToolCount: 4,\n maxToolDescriptionBytes: 256,\n maxDiscoveryBytes: 16_384,\n connectTimeoutMillis: 1_000,\n});\n\nexport const docsMcpIdentity = McpServerIdentity.make({\n serverId: docsMcpRequest.serverId,\n implementation: McpSchema.Implementation.make({\n name: \"docs-researcher-content-fixture\",\n version: \"1.0.0\",\n }),\n});\n\nconst discoveredFetchDocument = McpSchema.Tool.make({\n name: FetchDocument.name,\n description: \"Fetch one bounded research document by its identifier.\",\n inputSchema: Tool.getJsonSchema(FetchDocument),\n});\n\nconst scriptedConnector = (tools: ReadonlyArray<McpSchema.Tool>): Layer.Layer<McpConnector> =>\n Layer.succeed(McpConnector)({\n connect: () =>\n Effect.acquireRelease(\n Effect.succeed({\n identity: docsMcpIdentity,\n capabilities: McpSchema.ServerCapabilities.make({}),\n tools,\n toolkit: DocContentToolkit,\n }),\n () => Effect.void,\n ),\n });\n\n/** The well-behaved scripted content server. */\nexport const docsMcpConnectorLayer: Layer.Layer<McpConnector> = scriptedConnector([\n discoveredFetchDocument,\n]);\n\n/** Serves a tool description exceeding `maxToolDescriptionBytes` (SEC-013 bound). */\nexport const docsMcpOversizedConnectorLayer: Layer.Layer<McpConnector> = scriptedConnector([\n McpSchema.Tool.make({\n name: discoveredFetchDocument.name,\n description: \"x\".repeat(1_024),\n inputSchema: discoveredFetchDocument.inputSchema,\n }),\n]);\n\n/** Serves a discovery schema that disagrees with the authored toolkit (drift fails closed). */\nexport const docsMcpMismatchedConnectorLayer: Layer.Layer<McpConnector> = scriptedConnector([\n McpSchema.Tool.make({\n name: discoveredFetchDocument.name,\n description: discoveredFetchDocument.description,\n inputSchema: { type: \"object\", properties: { url: { type: \"string\" } } },\n }),\n]);\n\nconst isJsonEqual = (left: unknown, right: unknown): boolean =>\n JSON.stringify(left) === JSON.stringify(right);\n\n/**\n * Bind DISCOVERY to AUTHORING: `validateMcpDiscovery` (inside `connectMcp`)\n * already proved the served discovery matches the connection's own Toolkit;\n * this check additionally proves that Toolkit is the exact toolkit the\n * doc-summarizer was AUTHORED against — same tool names, same derived JSON\n * schemas — so a connector cannot substitute a look-alike toolkit. The\n * docs-researcher harness runs it before any worker Binding registration and\n * fails closed on any drift.\n */\nexport const assertDiscoveryMatchesAuthoredToolkit = Effect.fn(\n \"DocsResearcher.assertDiscoveryMatchesAuthoredToolkit\",\n)(function* (connection: McpConnection): Effect.fn.Return<void, McpToolkitMismatch> {\n const authored = Object.values(DocContentToolkit.tools)\n .map((tool) => ({ name: tool.name, inputSchema: Tool.getJsonSchema(tool) }))\n .sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\n const discovered = Object.values(connection.toolkit.tools)\n .map((tool) => ({ name: tool.name, inputSchema: Tool.getJsonSchema(tool) }))\n .sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\n const matches =\n authored.length === discovered.length &&\n authored.every(\n (tool, index) =>\n tool.name === discovered[index]?.name &&\n isJsonEqual(tool.inputSchema, discovered[index]?.inputSchema),\n );\n if (!matches) {\n return yield* McpToolkitMismatch.make({\n serverId: connection.discovery.identity.serverId,\n message:\n \"The MCP-discovered toolkit does not match the doc-summarizer's authored content toolkit\",\n });\n }\n});\n\n/** Round-trip guard for encoded discovery values persisted as fixture evidence. */\nexport const DocsMcpDiscoveryEvidence = Schema.Struct({\n serverId: Schema.NonEmptyString,\n toolCount: Schema.Natural,\n encodedBytes: Schema.Natural,\n toolkitSchemaDigest: Schema.String,\n});\n","import {\n connectMcp,\n Redactor,\n SubagentReservationsMemoryLive,\n type McpDiscovery,\n type RedactedPreview,\n type RedactionError,\n} from \"@effect-agent/capabilities\";\nimport { Agent, type ConversationId } from \"@effect-agent/core\";\nimport {\n DefinitionDigests,\n DeploymentId,\n Digest,\n DurableWorkerBinding,\n Principal,\n ProducerId,\n type DurableSubmitOptions,\n type IdempotencyKey,\n type ResolvedBinding,\n} from \"@effect-agent/session\";\nimport { Crypto, Effect, Layer, Ref, Schema, Stream } from \"effect\";\nimport { LanguageModel, Model, type Response } from \"effect/unstable/ai\";\n\nimport { DeterministicIdGeneratorLayer } from \"../travel-planner/deterministic-layers.ts\";\nimport {\n DocsResearcher,\n DocSummarizer,\n DocumentLibrary,\n docContentToolkitLayer,\n docsSummaryHandlersLayer,\n encodedDocumentSummary,\n expectedResearchDigest,\n ResearchDigest,\n ResearchDocument,\n researchCorpusDocumentIds,\n researchDocumentFor,\n researchDocumentLookup,\n} from \"./definition.ts\";\nimport {\n assertDiscoveryMatchesAuthoredToolkit,\n docsMcpConnectorLayer,\n docsMcpRequest,\n} from \"./mcp.ts\";\n\n// ---------------------------------------------------------------------------\n// DN durable harness for the docs-researcher (P7 plan §6 agent #3), following\n// `makeDurableResearchHarness` conventions: invocation counters and captured\n// prompts live OUTSIDE the Model Layers so they survive Layer rebuilds across\n// Attempts and separate runtime handles over the same SQLite file.\n// ---------------------------------------------------------------------------\n\nexport const docsResearcherDeploymentId = Schema.decodeSync(DeploymentId)(\n \"docs-researcher-p7-deployment\",\n);\nexport const docsResearcherProducerId = Schema.decodeSync(ProducerId)(\n \"docs-researcher-p7-producer\",\n);\nexport const docsResearcherPrincipal = Schema.decodeSync(Principal)(\"docs-researcher-p7-principal\");\n\nconst digestOf = (pair: string) => Schema.decodeSync(Digest)(pair.repeat(32));\n\n/** Redacted, deterministic coordinator definition digests for this fixture version. */\nexport const docsCoordinatorDigests = DefinitionDigests.make({\n agent: digestOf(\"40\"),\n model: digestOf(\"41\"),\n tools: digestOf(\"42\"),\n});\n\n/** The child registration digests — byte-equal to `docsSummarizerDigestStrings` (SUB-023). */\nexport const docsSummarizerDigests = DefinitionDigests.make({\n agent: digestOf(\"50\"),\n model: digestOf(\"51\"),\n tools: digestOf(\"52\"),\n});\n\n/** Durable admission options for one docs-researcher Submission on one mission lane. */\nexport const docsResearcherSubmitOptions = (\n conversationId: ConversationId,\n idempotencyKey: IdempotencyKey,\n): DurableSubmitOptions => ({\n conversationId,\n principal: docsResearcherPrincipal,\n idempotencyKey,\n definitions: docsCoordinatorDigests,\n});\n\n/** The structural submit slice of the coordinator Binding (`DurableAgentRuntime.submit`). */\nexport const docsResearcherSubmitAgent = {\n definition: { id: DocsResearcher.id, input: DocsResearcher.input },\n} as const;\n\n/** The deterministic delegation Tool Call identity for one document. */\nexport const summarizeCallId = (documentId: string): string => `summarize-${documentId}`;\n\n/** The child's own scripted fetch Tool Call identity for one document. */\nexport const fetchCallId = (documentId: string): string => `fetch-${documentId}`;\n\nconst scriptedUsage = { inputTokens: { total: 96 }, outputTokens: { total: 64 } };\n\nconst summaryDelegationParts = (\n documentIds: ReadonlyArray<string>,\n): ReadonlyArray<Response.StreamPartEncoded> => [\n ...documentIds.map(\n (documentId): Response.StreamPartEncoded => ({\n type: \"tool-call\",\n id: summarizeCallId(documentId),\n name: \"delegate_document_summary\",\n params: { documentId },\n providerExecuted: false,\n }),\n ),\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst digestParts = (\n documentIds: ReadonlyArray<string>,\n): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"digest\" },\n {\n type: \"text-delta\",\n id: \"digest\",\n delta: JSON.stringify(Schema.encodeSync(ResearchDigest)(expectedResearchDigest(documentIds))),\n },\n { type: \"text-end\", id: \"digest\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\nconst fetchParts = (documentId: string): ReadonlyArray<Response.StreamPartEncoded> => [\n {\n type: \"tool-call\",\n id: fetchCallId(documentId),\n name: \"fetch_document\",\n params: { documentId },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst summaryParts = (documentId: string): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"document-summary\" },\n { type: \"text-delta\", id: \"document-summary\", delta: encodedDocumentSummary(documentId) },\n { type: \"text-end\", id: \"document-summary\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\n/**\n * One prompt-aware scripted model with externally observable counters. A DN\n * Attempt may resume on a fresh Layer build, so responses derive from the\n * committed history in the prompt — never from an in-Layer turn counter.\n */\nconst makeCountingModel = (\n name: string,\n decide: (promptJson: string) => Effect.Effect<ReadonlyArray<Response.StreamPartEncoded>>,\n) =>\n Effect.gen(function* () {\n const calls = yield* Ref.make(0);\n const prompts = yield* Ref.make<ReadonlyArray<string>>([]);\n const model = Model.make(\n \"scripted\",\n name,\n Layer.effect(\n LanguageModel.LanguageModel,\n LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (request) =>\n Stream.unwrap(\n Effect.gen(function* () {\n yield* Ref.update(calls, (value) => value + 1);\n const promptJson = JSON.stringify(request.prompt);\n yield* Ref.update(prompts, (previous) => [...previous, promptJson]);\n return Stream.fromIterable(yield* decide(promptJson));\n }),\n ),\n }),\n ),\n );\n return { model, calls: Ref.get(calls), prompts: Ref.get(prompts) };\n });\n\n/** Optional overrides for one docs-researcher harness. */\nexport interface DocsResearcherHarnessOptions {\n /** Documents to research; defaults to the full two-document corpus. */\n readonly documentIds?: ReadonlyArray<string> | undefined;\n}\n\n/** One durable coordinator/summarizer pair with observable counters and MCP evidence. */\nexport interface DocsResearcherHarness {\n /** Host registrations for `NodeDurableRuntimeOptions.bindings` (parent + child). */\n readonly bindings: ReadonlyArray<ResolvedBinding>;\n /** The validated MCP discovery the child toolkit registration was gated on. */\n readonly discovery: McpDiscovery;\n /** Total coordinator model invocations across every Attempt and runtime handle. */\n readonly parentModelCalls: Effect.Effect<number>;\n /** JSON-encoded coordinator prompts in request order. */\n readonly parentPrompts: Effect.Effect<ReadonlyArray<string>>;\n /** Total summarizer model invocations across every Attempt and runtime handle. */\n readonly childModelCalls: Effect.Effect<number>;\n /** JSON-encoded summarizer prompts in request order (context-isolation evidence). */\n readonly childPrompts: Effect.Effect<ReadonlyArray<string>>;\n /** MCP content-tool handler executions for one document (external side-effect record). */\n readonly fetchInvocations: (documentId: string) => Effect.Effect<number>;\n}\n\n/**\n * Build the docs-researcher harness. Order matters and is the point: the\n * child's content toolkit is only registered as a worker Binding AFTER the\n * MCP connector's bounded discovery validated the authored toolkit\n * byte-for-byte (`connectMcp` + `assertDiscoveryMatchesAuthoredToolkit`), so\n * \"the tools the summarizer runs are the tools discovery served\" is enforced\n * at assembly, not assumed. Content-tool execution then flows through the\n * counting `DocumentLibrary` — the scripted MCP server's content store.\n */\nexport const makeDocsResearcherHarness = (options?: DocsResearcherHarnessOptions) =>\n Effect.gen(function* () {\n const documentIds = options?.documentIds ?? researchCorpusDocumentIds;\n\n // MCP discovery gate (CAP-009): bounded, digest-verified, fail-closed.\n const discovery = yield* Effect.scoped(\n Effect.gen(function* () {\n const connection = yield* connectMcp(docsMcpRequest);\n yield* assertDiscoveryMatchesAuthoredToolkit(connection);\n return connection.discovery;\n }),\n ).pipe(Effect.provide(docsMcpConnectorLayer));\n\n const fetchCounts = yield* Ref.make<ReadonlyMap<string, number>>(new Map());\n const libraryLayer = Layer.succeed(\n DocumentLibrary,\n DocumentLibrary.of({\n fetch: (query) =>\n Ref.update(fetchCounts, (current) =>\n new Map(current).set(query.documentId, (current.get(query.documentId) ?? 0) + 1),\n ).pipe(Effect.andThen(researchDocumentLookup(query))),\n }),\n );\n const childToolkitLayer = docContentToolkitLayer.pipe(Layer.provideMerge(libraryLayer));\n\n const childModel = yield* makeCountingModel(\"doc-summarizer-p7\", (promptJson) =>\n Effect.suspend(() => {\n const documentId = documentIds.find((candidate) => promptJson.includes(candidate));\n if (documentId === undefined) {\n return Effect.die(new Error(\"The summarizer prompt names no corpus document\"));\n }\n return Effect.succeed(\n promptJson.includes(fetchCallId(documentId))\n ? summaryParts(documentId)\n : fetchParts(documentId),\n );\n }),\n );\n const childBinding = Agent.withModel(DocSummarizer, childModel.model);\n\n const firstCallId = summarizeCallId(documentIds[0] ?? \"durability-notes\");\n const parentModel = yield* makeCountingModel(\"docs-researcher-p7\", (promptJson) =>\n Effect.succeed(\n promptJson.includes(firstCallId)\n ? digestParts(documentIds)\n : summaryDelegationParts(documentIds),\n ),\n );\n const parentBinding = Agent.withModel(DocsResearcher, parentModel.model);\n\n const delegationLayer = docsSummaryHandlersLayer(childBinding).pipe(\n Layer.provide(\n Layer.mergeAll(\n childToolkitLayer,\n SubagentReservationsMemoryLive,\n DeterministicIdGeneratorLayer,\n ),\n ),\n );\n\n const parentResolved: ResolvedBinding = yield* DurableWorkerBinding.make(\n parentBinding,\n docsCoordinatorDigests,\n ).pipe(Effect.provide(delegationLayer));\n const childResolved: ResolvedBinding = yield* DurableWorkerBinding.make(\n childBinding,\n docsSummarizerDigests,\n ).pipe(Effect.provide(childToolkitLayer));\n\n const harness: DocsResearcherHarness = {\n bindings: [parentResolved, childResolved],\n discovery,\n parentModelCalls: parentModel.calls,\n parentPrompts: parentModel.prompts,\n childModelCalls: childModel.calls,\n childPrompts: childModel.prompts,\n fetchInvocations: (documentId) =>\n Ref.get(fetchCounts).pipe(Effect.map((current) => current.get(documentId) ?? 0)),\n };\n return harness;\n });\n\nconst encodeResearchDocument = Schema.encodeEffect(ResearchDocument);\n\n/**\n * The audit-surface preview of one fetched document: the raw document —\n * secret marker and all — passes through the configured structural `Redactor`\n * before anything may quote it outside the child Conversation (SEC-008,\n * CAP-013). Tests assert the preview keeps shape but no scalar content.\n */\nexport const redactedDocumentPreview = Effect.fn(\"DocsResearcher.redactedDocumentPreview\")(\n function* (documentId: string): Effect.fn.Return<RedactedPreview, RedactionError, Redactor> {\n const redactor = yield* Redactor;\n const encoded = yield* encodeResearchDocument(researchDocumentFor(documentId)).pipe(\n Effect.orDie,\n );\n return yield* redactor.redact(encoded);\n },\n);\n\n// Crypto is deliberately in the harness requirements (`connectMcp` digests\n// discovery): callers provide a platform Crypto Layer, keeping this fixture\n// platform-neutral.\nexport type DocsResearcherHarnessRequirements = Crypto.Crypto;\n","import { Agent, AgentPolicy } from \"@effect-agent/core\";\nimport { Context, Effect, Schema } from \"effect\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport {\n ActivityCatalog,\n FlightCatalog,\n LodgingCatalog,\n QuoteId,\n SearchActivities,\n SearchFlights,\n SearchLodging,\n TravelGuidance,\n TravelPlan,\n TripRequest,\n} from \"./definition.ts\";\n\nexport class ItineraryHoldRequest extends Schema.Class<ItineraryHoldRequest>(\n \"@effect-agent/testing/travel-planner/ItineraryHoldRequest\",\n)({\n quoteId: QuoteId,\n expiresInMinutes: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(60)),\n}) {}\n\nexport class ItineraryHold extends Schema.Class<ItineraryHold>(\n \"@effect-agent/testing/travel-planner/ItineraryHold\",\n)({\n holdId: Schema.NonEmptyString,\n quoteId: QuoteId,\n status: Schema.Literal(\"held\"),\n}) {}\n\nexport class ItineraryHoldUnavailable extends Schema.TaggedError<ItineraryHoldUnavailable>()(\n \"ItineraryHoldUnavailable\",\n {\n quoteId: QuoteId,\n message: Schema.String,\n },\n) {}\n\nexport class ItineraryHoldGateway extends Context.Service<\n ItineraryHoldGateway,\n {\n readonly hold: (\n request: ItineraryHoldRequest,\n ) => Effect.Effect<ItineraryHold, ItineraryHoldUnavailable>;\n }\n>()(\"@effect-agent/testing/travel-planner/ItineraryHoldGateway\") {}\n\n/**\n * The first mutating Travel Planner Tool. Effect AI marks it as approval-gated\n * so the engine must settle approval before acquiring a handler permit.\n */\nexport const HoldItinerary = Tool.make(\"hold_itinerary\", {\n parameters: ItineraryHoldRequest,\n success: ItineraryHold,\n failure: ItineraryHoldUnavailable,\n failureMode: \"error\",\n dependencies: [ItineraryHoldGateway],\n needsApproval: true,\n});\n\nexport const TravelPlannerPhase2Toolkit = Toolkit.make(\n SearchFlights,\n SearchLodging,\n SearchActivities,\n HoldItinerary,\n);\n\nexport const TravelPlannerPhase2ToolkitLayer = TravelPlannerPhase2Toolkit.toLayer({\n search_flights: (query) => Effect.flatMap(FlightCatalog, (catalog) => catalog.search(query)),\n search_lodging: (query) => Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(query)),\n search_activities: (query) => Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(query)),\n hold_itinerary: (request) =>\n Effect.flatMap(ItineraryHoldGateway, (gateway) => gateway.hold(request)),\n});\n\nexport const TravelPlannerPhase2 = Agent.define(\"travel-planner-phase-2\", {\n input: TripRequest,\n output: TravelPlan,\n instructions: (input) =>\n Effect.flatMap(TravelGuidance, (guidance) => guidance.instructions(input)),\n toolkit: TravelPlannerPhase2Toolkit,\n policy: AgentPolicy.make({\n maxTurns: 3,\n maxToolCalls: 4,\n maxDuration: \"30 seconds\",\n toolConcurrency: 3,\n tokenBudget: 2_048,\n }),\n description:\n \"Build a review-only itinerary and require approval before creating a temporary hold.\",\n metadata: { deploymentClass: \"E\", phase: \"P2\" },\n});\n","import { Schema } from \"effect\";\n\nimport type { ScriptedTurnInput } from \"../../scripted-model.ts\";\nimport { TravelPlan, TripRequest, type TravelPlan as TravelPlanValue } from \"./definition.ts\";\n\nconst usage = { inputTokens: { total: 128 }, outputTokens: { total: 96 } };\nexport const phase1Trip = Schema.decodeSync(TripRequest)({\n request:\n \"Plan a review-only London trip using the deterministic flight, lodging, and activity searches.\",\n origin: \"SFO\",\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n nights: 4,\n travelers: 2,\n budgetCents: 350_000,\n currency: \"USD\",\n});\n/** Backward-compatible fixture alias while consumers transition to the P1 name. */\nexport const phase0Trip = phase1Trip;\nexport const expectedTravelPlan: TravelPlanValue = Schema.decodeSync(TravelPlan)({\n itineraries: [\n {\n title: \"Westward light, eastbound overnight\",\n route: \"San Francisco → London\",\n dates: \"14–19 September 2026\",\n flight: \"EA 218 · nonstop · SFO 18:40 → LHR 13:05+1\",\n lodging: \"Bloomsbury House · refundable studio · 4 nights\",\n activities: [\"British Museum timed entry\", \"Thames evening walk\"],\n estimatedTotalCents: 284_000,\n currency: \"USD\",\n quoteId: \"quote-sfo-lhr-001\",\n assumptions: [\n \"Two travelers sharing one studio\",\n \"Quote is read-only availability, not a reservation\",\n ],\n unresolvedConstraints: [\n \"Traveler names and accessibility requests are intentionally omitted\",\n ],\n nextAction: \"review\",\n },\n ],\n});\n\nexport const phase1HappyPathTurns = [\n {\n _tag: \"Stream\",\n parts: [\n {\n type: \"tool-call\",\n id: \"flight-call-1\",\n name: \"search_flights\",\n params: { origin: \"SFO\", destination: \"LHR\", departOn: \"2026-09-14\", travelers: 2 },\n },\n {\n type: \"tool-call\",\n id: \"lodging-call-1\",\n name: \"search_lodging\",\n params: { destination: \"LHR\", departOn: \"2026-09-14\", nights: 4, travelers: 2 },\n },\n {\n type: \"tool-call\",\n id: \"activity-call-1\",\n name: \"search_activities\",\n params: { destination: \"LHR\", departOn: \"2026-09-14\", nights: 4, travelers: 2 },\n },\n { type: \"finish\", reason: \"tool-calls\", usage },\n ],\n termination: { _tag: \"Complete\" },\n },\n {\n _tag: \"Stream\",\n parts: [\n { type: \"text-start\", id: \"itinerary-json\" },\n {\n type: \"text-delta\",\n id: \"itinerary-json\",\n delta: JSON.stringify(Schema.encodeSync(TravelPlan)(expectedTravelPlan)),\n },\n { type: \"text-end\", id: \"itinerary-json\" },\n { type: \"finish\", reason: \"stop\", usage },\n ],\n termination: { _tag: \"Complete\" },\n },\n] satisfies readonly [ScriptedTurnInput, ScriptedTurnInput];\nexport const phase0HappyPathTurns = phase1HappyPathTurns;\n","import { AgentId, ConversationId, RunId, SubmissionId } from \"@effect-agent/core\";\nimport {\n BatchId,\n CanonicalBatch,\n ConversationCheckpoint,\n ConversationProjection,\n DefinitionDigests,\n DeploymentId,\n Digest,\n ProducerId,\n RecordEnvelope,\n RecordId,\n} from \"@effect-agent/session\";\nimport { Effect, Schema } from \"effect\";\n\nimport { TravelPlan, TripRequest } from \"./definition.ts\";\nimport { expectedTravelPlan, phase1Trip } from \"./scenarios.ts\";\n\n/**\n * The Phase 3 profile persists Conversation history but deliberately does not\n * claim durable admission or recovery of accepted work.\n */\nexport class TravelPlannerPersistenceProfile extends Schema.Class<TravelPlannerPersistenceProfile>(\n \"@effect-agent/testing/travel-planner/TravelPlannerPersistenceProfile\",\n)({\n deploymentClass: Schema.Literal(\"P\"),\n durableAcceptedWork: Schema.Literal(false),\n canonicalSchemaVersion: Schema.Literal(1),\n}) {}\n\nexport const phase3TravelPlannerProfile = TravelPlannerPersistenceProfile.make({\n deploymentClass: \"P\",\n durableAcceptedWork: false,\n canonicalSchemaVersion: 1,\n});\n\nexport const phase3TravelPlannerConversationId = Schema.decodeSync(ConversationId)(\n \"travel-planner-p3-conversation\",\n);\nexport const phase3TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-p3-producer\",\n);\nexport const phase3TravelPlannerRunId = Schema.decodeSync(RunId)(\"travel-planner-p3-run\");\n\nconst deploymentId = Schema.decodeSync(DeploymentId)(\"travel-planner-p3-scripted\");\nconst agentId = Schema.decodeSync(AgentId)(\"travel-planner\");\nconst submissionId = Schema.decodeSync(SubmissionId)(\"travel-planner-p3-submission\");\n\nconst digest = (character: string) => Schema.decodeSync(Digest)(character.repeat(64));\n\n/** Redacted, deterministic definition identities for the current fixture version. */\nexport const phase3TravelPlannerDefinitionDigests = DefinitionDigests.make({\n agent: digest(\"a\"),\n model: digest(\"b\"),\n tools: digest(\"c\"),\n});\n\nconst tripInput = Schema.encodeSync(TripRequest)(phase1Trip);\nconst travelPlanOutput = Schema.encodeSync(TravelPlan)(expectedTravelPlan);\n\nconst record = (recordId: string, createdAt: string, payload: unknown) =>\n Schema.decodeUnknownSync(RecordEnvelope)({\n recordId: Schema.decodeSync(RecordId)(recordId),\n family: \"conversation\",\n schemaVersion: 1,\n createdAt,\n deploymentId,\n payload,\n });\n\n/**\n * The first atomic append establishes the Conversation and records its input.\n * Its encoded value is the redacted current-version persistence fixture.\n */\nexport const phase3TravelPlannerInitialBatch = CanonicalBatch.make({\n batchId: Schema.decodeSync(BatchId)(\"travel-planner-p3-initial\"),\n producerId: phase3TravelPlannerProducerId,\n records: [\n record(\"travel-planner-p3-created\", \"2026-09-01T00:00:00.000Z\", {\n _tag: \"ConversationCreated\",\n agentId,\n definitions: phase3TravelPlannerDefinitionDigests,\n }),\n record(\"travel-planner-p3-input\", \"2026-09-01T00:00:01.000Z\", {\n _tag: \"UserInputRecorded\",\n submissionId,\n kind: \"user\",\n runId: phase3TravelPlannerRunId,\n input: tripInput,\n }),\n ],\n});\n\n/** The second append records the Schema-decoded itinerary and terminal Run result. */\nexport const phase3TravelPlannerCompletionBatch = CanonicalBatch.make({\n batchId: Schema.decodeSync(BatchId)(\"travel-planner-p3-completion\"),\n producerId: phase3TravelPlannerProducerId,\n records: [\n record(\"travel-planner-p3-model\", \"2026-09-01T00:00:02.000Z\", {\n _tag: \"ModelCompleted\",\n runId: phase3TravelPlannerRunId,\n output: travelPlanOutput,\n }),\n record(\"travel-planner-p3-completed\", \"2026-09-01T00:00:03.000Z\", {\n _tag: \"RunCompleted\",\n runId: phase3TravelPlannerRunId,\n output: travelPlanOutput,\n }),\n ],\n});\n\nexport const phase3TravelPlannerBatches = [\n phase3TravelPlannerInitialBatch,\n phase3TravelPlannerCompletionBatch,\n] as const;\n\n/** Portable current-version fixture; it contains no passenger identity or credentials. */\nexport const phase3TravelPlannerEncodedFixture = Schema.encodeSync(Schema.Array(CanonicalBatch))(\n phase3TravelPlannerBatches,\n);\n\nexport class TravelPlannerProjectionError extends Schema.TaggedError<TravelPlannerProjectionError>()(\n \"TravelPlannerProjectionError\",\n { message: Schema.String },\n) {}\n\n/** Decode the itinerary projection rebuilt from canonical model-completion records. */\nexport const travelPlanFromProjection = (\n projection: ConversationProjection,\n): Effect.Effect<TravelPlan, TravelPlannerProjectionError> => {\n const output = projection.modelOutputs.at(-1);\n if (output === undefined) {\n return Effect.fail(\n TravelPlannerProjectionError.make({\n message: \"The canonical projection has no completed Travel Planner model output.\",\n }),\n );\n }\n return Schema.decodeUnknownEffect(TravelPlan)(output).pipe(\n Effect.mapError((error) => TravelPlannerProjectionError.make({ message: error.message })),\n );\n};\n\n/** Build a disposable checkpoint bound to a validated canonical prefix. */\nexport const makePhase3TravelPlannerCheckpoint = (\n projection: ConversationProjection,\n): ConversationCheckpoint =>\n Schema.decodeSync(ConversationCheckpoint)({\n schemaVersion: 1,\n conversationId: projection.conversationId,\n throughSequence: projection.throughSequence,\n tailDigest: projection.tailDigest,\n engineVersion: \"phase-3-test-runtime\",\n agentDefinitionDigest: phase3TravelPlannerDefinitionDigests.agent,\n modelDigest: phase3TravelPlannerDefinitionDigests.model,\n toolDigest: phase3TravelPlannerDefinitionDigests.tools,\n state: Schema.encodeSync(ConversationProjection)(projection),\n createdAt: \"2026-09-01T00:00:04.000Z\",\n });\n","import { Context, Effect, Layer, Ref, Schema, Stream } from \"effect\";\nimport { AiError, LanguageModel, Response } from \"effect/unstable/ai\";\n\nconst ScriptedPartMetadata = Schema.Record(Schema.String, Schema.NullOr(Schema.Json));\nconst ScriptedPartBase = {\n metadata: Schema.optionalKey(ScriptedPartMetadata),\n};\nconst ScriptedToolCallPart = Schema.Struct({\n ...ScriptedPartBase,\n type: Schema.Literal(\"tool-call\"),\n id: Schema.String,\n name: Schema.String,\n params: Schema.Unknown,\n providerExecuted: Schema.optionalKey(Schema.Boolean),\n});\nconst ScriptedToolResultPart = Schema.Struct({\n ...ScriptedPartBase,\n type: Schema.Literal(\"tool-result\"),\n id: Schema.String,\n name: Schema.String,\n result: Schema.Unknown,\n isFailure: Schema.Boolean,\n providerExecuted: Schema.optionalKey(Schema.Boolean),\n preliminary: Schema.optionalKey(Schema.Boolean),\n});\n\n/**\n * Schema for encoded, non-streaming Effect AI response parts.\n *\n * Generic Tool payloads remain explicitly unknown here. `LanguageModel.make`\n * performs the toolkit-specific decode when the scripted response is consumed.\n */\nexport const ScriptedGeneratePart = Schema.Union([\n Schema.toEncoded(Response.TextPart),\n Schema.toEncoded(Response.ReasoningPart),\n Schema.toEncoded(Response.ReasoningDeltaPart),\n Schema.toEncoded(Response.ReasoningEndPart),\n ScriptedToolCallPart,\n ScriptedToolResultPart,\n Schema.toEncoded(Response.ToolApprovalRequestPart),\n Schema.toEncoded(Response.FilePart),\n Schema.toEncoded(Response.DocumentSourcePart),\n Schema.toEncoded(Response.UrlSourcePart),\n Schema.toEncoded(Response.ResponseMetadataPart),\n Schema.toEncoded(Response.FinishPart),\n]).annotate({ identifier: \"ScriptedGeneratePart\" });\nexport type ScriptedGeneratePart = typeof ScriptedGeneratePart.Type;\n\n/**\n * Schema for encoded Effect AI streaming response parts.\n */\nexport const ScriptedStreamPart = Schema.Union([\n Schema.toEncoded(Response.TextStartPart),\n Schema.toEncoded(Response.TextDeltaPart),\n Schema.toEncoded(Response.TextEndPart),\n Schema.toEncoded(Response.ReasoningStartPart),\n Schema.toEncoded(Response.ReasoningDeltaPart),\n Schema.toEncoded(Response.ReasoningEndPart),\n Schema.toEncoded(Response.ToolParamsStartPart),\n Schema.toEncoded(Response.ToolParamsDeltaPart),\n Schema.toEncoded(Response.ToolParamsEndPart),\n ScriptedToolCallPart,\n ScriptedToolResultPart,\n Schema.toEncoded(Response.ToolApprovalRequestPart),\n Schema.toEncoded(Response.FilePart),\n Schema.toEncoded(Response.DocumentSourcePart),\n Schema.toEncoded(Response.UrlSourcePart),\n Schema.toEncoded(Response.ResponseMetadataPart),\n Schema.toEncoded(Response.FinishPart),\n Schema.toEncoded(Response.ErrorPart),\n]).annotate({ identifier: \"ScriptedStreamPart\" });\nexport type ScriptedStreamPart = typeof ScriptedStreamPart.Type;\n\n/** Controls whether a scripted stream completes, fails, or waits for interruption. */\nexport const ScriptedStreamTermination = Schema.Union([\n Schema.TaggedStruct(\"Complete\", {}),\n Schema.TaggedStruct(\"Fail\", {\n description: Schema.String,\n }),\n Schema.TaggedStruct(\"Hang\", {}),\n]);\nexport type ScriptedStreamTermination = typeof ScriptedStreamTermination.Type;\n\n/** One non-streaming invocation and the encoded response parts it returns. */\nexport const ScriptedGenerateTurn = Schema.TaggedStruct(\"Generate\", {\n parts: Schema.Array(ScriptedGeneratePart),\n});\nexport type ScriptedGenerateTurn = typeof ScriptedGenerateTurn.Type;\n\n/** One streaming invocation with its encoded parts and terminal behavior. */\nexport const ScriptedStreamTurn = Schema.TaggedStruct(\"Stream\", {\n parts: Schema.Array(ScriptedStreamPart),\n termination: ScriptedStreamTermination,\n});\nexport type ScriptedStreamTurn = typeof ScriptedStreamTurn.Type;\n\n/**\n * Serializable grammar for one finite scripted provider invocation.\n */\nexport const ScriptedTurn = Schema.Union([ScriptedGenerateTurn, ScriptedStreamTurn]);\nexport type ScriptedTurn = typeof ScriptedTurn.Type;\n\nexport type ScriptedRequestKind = \"generate\" | \"stream\";\n\n/**\n * A request after Effect AI has normalized its prompt, tools, response format,\n * tool choice, span, and incremental-response fields.\n */\nexport interface ScriptedRequest {\n readonly kind: ScriptedRequestKind;\n readonly options: LanguageModel.ProviderOptions;\n}\n\n/** Optional request assertions and stream lifecycle effects for one scripted turn. */\nexport interface ScriptedTurnHooks {\n /** Runs against the normalized provider request before producing the response. */\n readonly assertRequest?: (\n request: LanguageModel.ProviderOptions,\n ) => Effect.Effect<void, AiError.AiError> | void;\n /** Runs immediately before the scripted stream begins emitting parts. */\n readonly onStreamStart?: Effect.Effect<void> | undefined;\n /** Runs when the scripted stream completes, fails, or is interrupted. */\n readonly onStreamFinalize?: Effect.Effect<void> | undefined;\n}\n\n/**\n * Runtime hooks are deliberately separate from the serializable turn grammar.\n */\nexport type ScriptedTurnInput = ScriptedTurn & ScriptedTurnHooks;\n\ninterface ScriptState {\n readonly remaining: ReadonlyArray<ScriptedTurnInput>;\n readonly requests: ReadonlyArray<ScriptedRequest>;\n}\n\nconst scriptedError = (method: string, description: string): AiError.AiError =>\n AiError.AiError.make({\n module: \"@effect-agent/testing/ScriptedModel\",\n method,\n reason: AiError.UnknownError.make({ description }),\n });\n\nconst runAssertion = Effect.fn(\"ScriptedModel.runAssertion\")((\n assertion: ScriptedTurnHooks[\"assertRequest\"],\n request: LanguageModel.ProviderOptions,\n): Effect.Effect<void, AiError.AiError> => {\n if (assertion === undefined) {\n return Effect.void;\n }\n return Effect.suspend(() => {\n const result = assertion(request);\n return Effect.isEffect(result) ? result : Effect.void;\n });\n});\n\nconst takeTurn = Effect.fn(\"ScriptedModel.takeTurn\")(\n (\n state: Ref.Ref<ScriptState>,\n kind: ScriptedRequestKind,\n options: LanguageModel.ProviderOptions,\n ): Effect.Effect<ScriptedTurnInput, AiError.AiError> =>\n Ref.modify(state, (current) => {\n const turn = current.remaining[0];\n if (turn === undefined) {\n return [\n undefined,\n {\n ...current,\n requests: [...current.requests, { kind, options }],\n },\n ] as const;\n }\n return [\n turn,\n {\n remaining: current.remaining.slice(1),\n requests: [...current.requests, { kind, options }],\n },\n ] as const;\n }).pipe(\n Effect.flatMap((turn) =>\n turn === undefined\n ? Effect.fail(scriptedError(kind, `Script exhausted before the ${kind} request`))\n : Effect.succeed(turn),\n ),\n ),\n);\n\nconst requireGenerateTurn = (\n turn: ScriptedTurnInput,\n): Effect.Effect<ScriptedGenerateTurn & ScriptedTurnHooks, AiError.AiError> =>\n turn._tag === \"Generate\"\n ? Effect.succeed(turn)\n : Effect.fail(scriptedError(\"generate\", `Expected a Generate turn but found ${turn._tag}`));\n\nconst requireStreamTurn = (\n turn: ScriptedTurnInput,\n): Effect.Effect<ScriptedStreamTurn & ScriptedTurnHooks, AiError.AiError> =>\n turn._tag === \"Stream\"\n ? Effect.succeed(turn)\n : Effect.fail(scriptedError(\"stream\", `Expected a Stream turn but found ${turn._tag}`));\n\nconst streamForTurn = (\n turn: ScriptedStreamTurn & ScriptedTurnHooks,\n): Stream.Stream<Response.StreamPartEncoded, AiError.AiError> => {\n let stream: Stream.Stream<Response.StreamPartEncoded, AiError.AiError> = Stream.fromIterable(\n turn.parts,\n );\n switch (turn.termination._tag) {\n case \"Complete\": {\n break;\n }\n case \"Fail\": {\n stream = stream.pipe(\n Stream.concat(Stream.fail(scriptedError(\"stream\", turn.termination.description))),\n );\n break;\n }\n case \"Hang\": {\n stream = stream.pipe(Stream.concat(Stream.never));\n break;\n }\n }\n if (turn.onStreamStart !== undefined) {\n stream = Stream.fromEffectDrain(turn.onStreamStart).pipe(Stream.concat(stream));\n }\n if (turn.onStreamFinalize !== undefined) {\n stream = stream.pipe(Stream.ensuring(turn.onStreamFinalize));\n }\n return stream;\n};\n\n/** Inspection service for a deterministic LanguageModel backed by finite scripted turns. */\nexport class ScriptedModel extends Context.Service<\n ScriptedModel,\n {\n /** Normalized provider requests captured in invocation order. */\n readonly requests: Effect.Effect<ReadonlyArray<ScriptedRequest>>;\n /** Number of scripted turns not yet consumed. */\n readonly remaining: Effect.Effect<number>;\n /** Fails with `AiError` when any scripted turns remain. */\n readonly assertExhausted: Effect.Effect<void, AiError.AiError>;\n }\n>()(\"@effect-agent/testing/ScriptedModel\") {\n /**\n * Provides the native Effect AI `LanguageModel` and this inspection service.\n * Supplying the extra inspection service does not add it to model-call\n * requirements. Each model invocation consumes one turn before assertion and\n * turn-kind validation.\n */\n static layer(\n turns: ReadonlyArray<ScriptedTurnInput>,\n ): Layer.Layer<LanguageModel.LanguageModel | ScriptedModel, never, never> {\n return Layer.effectContext(\n Effect.gen(function* () {\n const state = yield* Ref.make<ScriptState>({\n remaining: [...turns],\n requests: [],\n });\n\n const languageModel = yield* LanguageModel.make({\n generateText: (options) =>\n Effect.gen(function* () {\n const turn = yield* takeTurn(state, \"generate\", options);\n yield* runAssertion(turn.assertRequest, options);\n const generateTurn = yield* requireGenerateTurn(turn);\n return [...generateTurn.parts];\n }),\n streamText: (options) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const turn = yield* takeTurn(state, \"stream\", options);\n yield* runAssertion(turn.assertRequest, options);\n const streamTurn = yield* requireStreamTurn(turn);\n return streamForTurn(streamTurn);\n }),\n ),\n });\n\n const inspection = ScriptedModel.of({\n requests: Ref.get(state).pipe(Effect.map((current) => current.requests)),\n remaining: Ref.get(state).pipe(Effect.map((current) => current.remaining.length)),\n assertExhausted: Ref.get(state).pipe(\n Effect.flatMap((current) =>\n current.remaining.length === 0\n ? Effect.void\n : Effect.fail(\n scriptedError(\n \"assertExhausted\",\n `${current.remaining.length} scripted turn(s) remain`,\n ),\n ),\n ),\n ),\n });\n\n return Context.make(LanguageModel.LanguageModel, languageModel).pipe(\n Context.add(ScriptedModel, inspection),\n );\n }),\n );\n }\n}\n","import { Agent, AgentPolicy, type ConversationId } from \"@effect-agent/core\";\nimport { ToolExecutionClass } from \"@effect-agent/engine\";\nimport {\n CanonicalRecordEnvelope,\n DefinitionDigests,\n DeploymentId,\n Digest,\n Principal,\n ProducerId,\n type DurableSubmitOptions,\n type IdempotencyKey,\n type Receipt,\n} from \"@effect-agent/session\";\nimport { Effect, Layer, Schema } from \"effect\";\nimport { Model, Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport { ScriptedModel, type ScriptedTurnInput } from \"../../scripted-model.ts\";\nimport {\n ActivityCatalog,\n ActivityQuery,\n ActivitySearchResult,\n ActivityUnavailable,\n FlightCatalog,\n FlightOption,\n FlightQuery,\n FlightUnavailable,\n LodgingCatalog,\n LodgingOption,\n LodgingQuery,\n LodgingUnavailable,\n TravelGuidance,\n TravelPlan,\n TripRequest,\n} from \"./definition.ts\";\nimport {\n ActivityCatalogLayer,\n CatalogLifecycle,\n FlightCatalogLayer,\n LodgingCatalogLayer,\n TravelGuidanceLayer,\n} from \"./deterministic-layers.ts\";\nimport { phase1HappyPathTurns } from \"./scenarios.ts\";\n\n/**\n * The Phase 4 profile claims durable accepted work on the Node/SQLite runtime (deployment class\n * DN): once `submit` returns a Receipt, the Submission settles exactly once even across process\n * loss. The claim is limited to safe-to-repeat toolkits (D6): supplier booking is explicitly NOT\n * claimed safely replayable — replay-safe external mutation is P5 (Durable Tools) scope.\n */\nexport class TravelPlannerDurabilityProfile extends Schema.Class<TravelPlannerDurabilityProfile>(\n \"@effect-agent/testing/travel-planner/TravelPlannerDurabilityProfile\",\n)({\n deploymentClass: Schema.Literal(\"DN\"),\n durableAcceptedWork: Schema.Literal(true),\n canonicalSchemaVersion: Schema.Literal(1),\n /** Supplier booking replay safety is P5 (Durable Tools) scope; DN does not claim it. */\n supplierBookingReplaySafe: Schema.Literal(false),\n}) {}\n\nexport const phase4TravelPlannerProfile = TravelPlannerDurabilityProfile.make({\n deploymentClass: \"DN\",\n durableAcceptedWork: true,\n canonicalSchemaVersion: 1,\n supplierBookingReplaySafe: false,\n});\n\nexport const phase4TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-p4-deployment\",\n);\nexport const phase4TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-p4-producer\",\n);\nexport const phase4TravelPlannerPrincipal = Schema.decodeSync(Principal)(\n \"travel-planner-p4-principal\",\n);\n\nconst digest = (character: string) => Schema.decodeSync(Digest)(character.repeat(64));\n\n/** Redacted, deterministic definition identities for the current fixture version. */\nexport const phase4TravelPlannerDefinitionDigests = DefinitionDigests.make({\n agent: digest(\"d\"),\n model: digest(\"e\"),\n tools: digest(\"f\"),\n});\n\n/** Durable admission options for one Travel Planner Submission on one trip lane. */\nexport const phase4TravelPlannerSubmitOptions = (\n conversationId: ConversationId,\n idempotencyKey: IdempotencyKey,\n): DurableSubmitOptions => ({\n conversationId,\n principal: phase4TravelPlannerPrincipal,\n idempotencyKey,\n definitions: phase4TravelPlannerDefinitionDigests,\n});\n\n/**\n * The P4 read-only search Tools, calling the same deterministic catalogs as the P1 toolkit.\n *\n * The plain-Struct parameter shape is a historical remnant of the P4 carry-in workaround: since\n * the P5 engine fix, official history carries Schema-ENCODED Tool-call parameters, so class-typed\n * parameter codecs persist canonically too — the Structs simply need no change here. The\n * `ToolExecutionClass` `readonly` annotation is the deliberate P5 migration (plan §4.3): these\n * Tools perform no external mutation, so a crash between start and settlement is a free re-run\n * and they never enter the prepared/settled uncertainty protocol — keeping the P4 canonical\n * history byte-stable (an unannotated Tool fails closed to `uncertain`).\n */\nexport const DurableSearchFlights = Tool.make(\"search_flights\", {\n parameters: Schema.Struct(FlightQuery.fields),\n success: FlightOption,\n failure: FlightUnavailable,\n failureMode: \"error\",\n dependencies: [FlightCatalog],\n}).annotate(ToolExecutionClass, \"readonly\");\nexport const DurableSearchLodging = Tool.make(\"search_lodging\", {\n parameters: Schema.Struct(LodgingQuery.fields),\n success: LodgingOption,\n failure: LodgingUnavailable,\n failureMode: \"error\",\n dependencies: [LodgingCatalog],\n}).annotate(ToolExecutionClass, \"readonly\");\nexport const DurableSearchActivities = Tool.make(\"search_activities\", {\n parameters: Schema.Struct(ActivityQuery.fields),\n success: ActivitySearchResult,\n failure: ActivityUnavailable,\n failureMode: \"error\",\n dependencies: [ActivityCatalog],\n}).annotate(ToolExecutionClass, \"readonly\");\n\nexport const TravelPlannerPhase4Toolkit = Toolkit.make(\n DurableSearchFlights,\n DurableSearchLodging,\n DurableSearchActivities,\n);\n\nexport const TravelPlannerPhase4ToolkitLayer = TravelPlannerPhase4Toolkit.toLayer({\n search_flights: (query) =>\n Effect.flatMap(FlightCatalog, (catalog) => catalog.search(FlightQuery.make(query))),\n search_lodging: (query) =>\n Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(LodgingQuery.make(query))),\n search_activities: (query) =>\n Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(ActivityQuery.make(query))),\n});\n\n/**\n * The cumulative Travel Planner, Phase 4: the P1 planning behavior on the durable Node/SQLite\n * runtime. The searches are read-only and safe to repeat across Attempts (D6); supplier booking\n * is deliberately absent because DN does NOT claim replay-safe external mutation (P5 scope).\n */\nexport const TravelPlannerPhase4 = Agent.define(\"travel-planner-phase-4\", {\n input: TripRequest,\n output: TravelPlan,\n instructions: (input) =>\n Effect.flatMap(TravelGuidance, (guidance) => guidance.instructions(input)),\n toolkit: TravelPlannerPhase4Toolkit,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 3,\n maxDuration: \"30 seconds\",\n toolConcurrency: 3,\n }),\n description:\n \"Durably plan one review-only itinerary from safe-to-repeat deterministic searches; supplier booking is not claimed safely replayable.\",\n metadata: { deploymentClass: \"DN\", phase: \"P4\" },\n});\n\n/**\n * The P4 Agent Binding: the durable Travel Planner definition bound to a finite scripted model.\n * The scripted Layer is rebuilt per Run, so every Run of one Binding replays the same\n * deterministic script.\n */\nexport const makePhase4TravelPlannerAgent = (\n turns: ReadonlyArray<ScriptedTurnInput> = phase1HappyPathTurns,\n) =>\n Agent.withModel(\n TravelPlannerPhase4,\n Model.make(\"scripted\", \"travel-planner-phase-4\", ScriptedModel.layer(turns)),\n );\n\n/**\n * Everything a durable worker needs beyond the runtime stack, reusing the deterministic P1\n * travel-service Layers. The durable coordinator supplies its own deterministic `IdGenerator`,\n * so this Layer deliberately provides none.\n */\nexport const phase4TravelPlannerWorkerLayer = Layer.mergeAll(\n TravelPlannerPhase4ToolkitLayer,\n FlightCatalogLayer,\n LodgingCatalogLayer,\n ActivityCatalogLayer,\n TravelGuidanceLayer,\n).pipe(Layer.provide(CatalogLifecycle.layerNoDeps));\n\nexport class TravelPlannerDurableEvidenceError extends Schema.TaggedError<TravelPlannerDurableEvidenceError>()(\n \"TravelPlannerDurableEvidenceError\",\n { message: Schema.String },\n) {}\n\n/**\n * Decode the completed itinerary from the canonical `SubmissionSettled` record. Canonical history\n * is the outcome authority (DUR-015): the settled result — not any ledger cache — must decode\n * through the trip output schema.\n */\nexport const travelPlanFromDurableSettlement = Effect.fn(\n \"TravelPlannerPhase4.travelPlanFromDurableSettlement\",\n)(function* (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n): Effect.fn.Return<TravelPlan, TravelPlannerDurableEvidenceError> {\n const settlements = records.flatMap((envelope) =>\n envelope.record.payload._tag === \"SubmissionSettled\" ? [envelope.record.payload] : [],\n );\n const settled = settlements.at(0);\n if (settled === undefined) {\n return yield* TravelPlannerDurableEvidenceError.make({\n message: \"The canonical Conversation Log has no SubmissionSettled record.\",\n });\n }\n if (settled.outcome !== \"completed\" || settled.result === undefined) {\n return yield* TravelPlannerDurableEvidenceError.make({\n message: `The Submission settled ${settled.outcome} without a completed itinerary result.`,\n });\n }\n return yield* Schema.decodeUnknownEffect(TravelPlan)(settled.result).pipe(\n Effect.mapError((error) =>\n TravelPlannerDurableEvidenceError.make({\n message: `The settled result does not decode through the TravelPlan schema: ${error.message}`,\n }),\n ),\n );\n});\n\nconst encodeEvidence = Schema.encodeEffect(Schema.Array(CanonicalRecordEnvelope));\nconst decodeComparableJson = Schema.decodeUnknownEffect(Schema.Json);\n\n/**\n * Project canonical evidence into a Submission-identity-independent comparable form: batch\n * identity, canonical sequence, and the full encoded record, with the ledger-minted\n * `submissionId`/`receiptId` (and every identity derived from them: run, turn, batch, record,\n * and settlement ids) replaced by stable placeholders. Two Conversations whose normalized\n * evidence is equal took byte-equivalent canonical histories, so restart-equivalence can compare\n * a recovered run against an uninterrupted control run on a separate database.\n */\nexport const normalizeDurableTravelPlannerEvidence = Effect.fn(\n \"TravelPlannerPhase4.normalizeDurableTravelPlannerEvidence\",\n)(function* (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n receipt: Receipt,\n): Effect.fn.Return<Schema.Json, TravelPlannerDurableEvidenceError> {\n const encoded = yield* encodeEvidence(records).pipe(\n Effect.mapError((error) =>\n TravelPlannerDurableEvidenceError.make({\n message: `Canonical evidence failed to encode: ${error.message}`,\n }),\n ),\n );\n const comparable = encoded.map((envelope) => ({\n batchId: envelope.batchId,\n sequence: envelope.sequence,\n record: envelope.record,\n }));\n const substituted: unknown = JSON.parse(\n JSON.stringify(comparable)\n .replaceAll(receipt.submissionId, \"{submissionId}\")\n .replaceAll(receipt.receiptId, \"{receiptId}\"),\n );\n return yield* decodeComparableJson(substituted).pipe(\n Effect.mapError((error) =>\n TravelPlannerDurableEvidenceError.make({\n message: `Normalized evidence is not comparable JSON: ${error.message}`,\n }),\n ),\n );\n});\n","import { Agent, AgentPolicy, type ConversationId } from \"@effect-agent/core\";\nimport { DurableStep, DurableStepError, ToolExecutionClass } from \"@effect-agent/engine\";\nimport {\n DefinitionDigests,\n DeploymentId,\n Digest,\n PersistedJson,\n Principal,\n ProducerId,\n ReconciliationCompleted,\n ReconciliationSafeToRetry,\n ReconciliationUncertain,\n ToolReconciler,\n ToolReconcilerError,\n type CanonicalRecordEnvelope,\n type DurableSubmitOptions,\n type IdempotencyKey,\n} from \"@effect-agent/session\";\nimport { Effect, Layer, Option, Schema } from \"effect\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport {\n ActivityCatalog,\n ActivityQuery,\n AirportCode,\n FlightCatalog,\n FlightQuery,\n LodgingCatalog,\n LodgingQuery,\n QuoteId,\n TripRequest,\n} from \"./definition.ts\";\nimport {\n ActivityCatalogLayer,\n BookingRef,\n CatalogLifecycle,\n FlightCatalogLayer,\n LodgingCatalogLayer,\n SupplierBookingDesk,\n SupplierBookingRecord,\n SupplierUnavailable,\n} from \"./deterministic-layers.ts\";\nimport { DurableSearchActivities, DurableSearchFlights, DurableSearchLodging } from \"./phase4.ts\";\n\n/**\n * The Phase 5 profile extends the P4 `DN` claim to consequential supplier mutation: booking\n * Tools enter the prepared/settled uncertainty protocol, unresolved external effects stop at\n * Unknown Outcomes instead of replaying, Durable Steps replay recorded results, and queued\n * traveler input joins the active Run. Exactly-once EXTERNAL execution is still — deliberately —\n * not claimed (DUR-003): the supplier's own idempotency keys are what dedupe repeats.\n */\nexport class TravelPlannerBookingProfile extends Schema.Class<TravelPlannerBookingProfile>(\n \"@effect-agent/testing/travel-planner/TravelPlannerBookingProfile\",\n)({\n deploymentClass: Schema.Literal(\"DN\"),\n durableAcceptedWork: Schema.Literal(true),\n canonicalSchemaVersion: Schema.Literal(1),\n /** P5: supplier mutations get prepared/settled records, Unknown Outcomes, and reconciliation. */\n supplierBookingUncertaintyProtocol: Schema.Literal(true),\n /** P5: Durable Steps are exactly-once-RECORDED; their side effects stay at-least-once. */\n durableStepsRecorded: Schema.Literal(true),\n /** Never claimed at any phase (DUR-003). */\n exactlyOnceExternalEffects: Schema.Literal(false),\n}) {}\n\nexport const phase5TravelPlannerProfile = TravelPlannerBookingProfile.make({\n deploymentClass: \"DN\",\n durableAcceptedWork: true,\n canonicalSchemaVersion: 1,\n supplierBookingUncertaintyProtocol: true,\n durableStepsRecorded: true,\n exactlyOnceExternalEffects: false,\n});\n\nexport const phase5TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-p5-deployment\",\n);\nexport const phase5TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-p5-producer\",\n);\nexport const phase5TravelPlannerPrincipal = Schema.decodeSync(Principal)(\n \"travel-planner-p5-principal\",\n);\n\nconst digest = (character: string) => Schema.decodeSync(Digest)(character.repeat(64));\n\n/** Redacted, deterministic definition identities for the current fixture version. */\nexport const phase5TravelPlannerDefinitionDigests = DefinitionDigests.make({\n agent: digest(\"1\"),\n model: digest(\"2\"),\n tools: digest(\"3\"),\n});\n\n/** Durable admission options for one Travel Planner Submission on one trip lane. */\nexport const phase5TravelPlannerSubmitOptions = (\n conversationId: ConversationId,\n idempotencyKey: IdempotencyKey,\n): DurableSubmitOptions => ({\n conversationId,\n principal: phase5TravelPlannerPrincipal,\n idempotencyKey,\n definitions: phase5TravelPlannerDefinitionDigests,\n});\n\nexport const TravelerRef = Schema.NonEmptyString.pipe(\n Schema.brand(\"@effect-agent/testing/travel-planner/TravelerRef\"),\n);\nexport type TravelerRef = typeof TravelerRef.Type;\n\n/**\n * Class-shaped booking parameters with branded fields: since the P5 engine fix, official history\n * carries Schema-ENCODED Tool-call parameters, so class-typed parameter codecs persist\n * canonically end-to-end (the P4 Struct workaround is gone for new Tools).\n */\nexport class FlightBookingRequest extends Schema.Class<FlightBookingRequest>(\n \"FlightBookingRequest\",\n)({\n quoteId: QuoteId,\n travelerRef: TravelerRef,\n departOn: Schema.String,\n}) {}\n\nexport class SupplierBookingConfirmation extends Schema.Class<SupplierBookingConfirmation>(\n \"SupplierBookingConfirmation\",\n)({\n bookingRef: BookingRef,\n status: Schema.Literal(\"confirmed\"),\n detail: Schema.String,\n}) {}\n\nexport class CancelBookingRequest extends Schema.Class<CancelBookingRequest>(\n \"CancelBookingRequest\",\n)({\n bookingRef: BookingRef,\n travelerRef: TravelerRef,\n}) {}\n\nexport class CancellationConfirmation extends Schema.Class<CancellationConfirmation>(\n \"CancellationConfirmation\",\n)({\n bookingRef: BookingRef,\n status: Schema.Literal(\"cancelled\"),\n}) {}\n\nexport class ItineraryBookingRequest extends Schema.Class<ItineraryBookingRequest>(\n \"ItineraryBookingRequest\",\n)({\n quoteId: QuoteId,\n destination: AirportCode,\n nights: Schema.Int.check(Schema.isGreaterThan(0)),\n travelerRef: TravelerRef,\n}) {}\n\nexport class ItineraryConfirmation extends Schema.Class<ItineraryConfirmation>(\n \"ItineraryConfirmation\",\n)({\n flightBookingRef: BookingRef,\n lodgingBookingRef: BookingRef,\n confirmationCode: Schema.String,\n}) {}\n\n/** The P5 Run output: a booked (or explicitly not-booked) trip report. */\nexport class TravelBookingReport extends Schema.Class<TravelBookingReport>(\"TravelBookingReport\")({\n summary: Schema.String,\n bookingRefs: Schema.Array(BookingRef),\n}) {}\n\n/**\n * Supplier idempotency-key derivations. The handler owns key derivation (the `idempotent` and\n * `uncertain` execution classes carry no key), and the reconciler MUST use the same derivations\n * to query external truth — both sides are exported so they cannot drift.\n */\nexport const bookFlightIdempotencyKey = (toolCallId: string): string => `book-flight:${toolCallId}`;\nexport const itineraryStepIdempotencyKey = (toolCallId: string, stepName: string): string =>\n `${toolCallId}:${stepName}`;\n\n/**\n * Approval-gated supplier booking, explicitly `uncertain`: a crash after the call may have\n * mutated supplier state without a recorded outcome, so recovery must reconcile or stop at an\n * Unknown Outcome — never replay automatically (DUR-009, ADR-0004).\n */\nexport const BookFlight = Tool.make(\"book_flight\", {\n parameters: FlightBookingRequest,\n success: SupplierBookingConfirmation,\n failure: SupplierUnavailable,\n failureMode: \"error\",\n needsApproval: true,\n dependencies: [SupplierBookingDesk],\n}).annotate(ToolExecutionClass, \"uncertain\");\n\n/**\n * Approval-gated cancellation, annotated `idempotent`: the DECLARED external contract is that\n * cancellation is idempotent by `bookingRef` (the supplier desk enforces it), so recovery may\n * re-execute a prepared-but-unsettled cancel without reconciliation proof. Repeats stay\n * observable in the supplier call counters — the annotation never claims exactly-once execution.\n */\nexport const CancelBooking = Tool.make(\"cancel_booking\", {\n parameters: CancelBookingRequest,\n success: CancellationConfirmation,\n failure: SupplierUnavailable,\n failureMode: \"error\",\n needsApproval: true,\n dependencies: [SupplierBookingDesk],\n}).annotate(ToolExecutionClass, \"idempotent\");\n\n/**\n * The Durable Tool: declaring `DurableStep` in `dependencies` is what makes it durable\n * (CONTEXT.md). Its handler divides supplier mutation into three named Steps — `reserve-flight`,\n * `reserve-lodging`, `issue-confirmation` — each deriving its supplier idempotency key from\n * `(toolCallId, stepName)`, so re-entry after interruption replays recorded Step results and the\n * supplier dedupes any honestly-repeated call. The Tool itself carries no execution-class\n * annotation: it stays fail-closed `uncertain`, and `TravelSupplierReconcilerLayer` proves\n * re-entry safe from the keyed-Step construction instead.\n */\nexport const BookItinerary = Tool.make(\"book_itinerary\", {\n parameters: ItineraryBookingRequest,\n success: ItineraryConfirmation,\n failure: Schema.Union([SupplierUnavailable, DurableStepError]),\n failureMode: \"error\",\n dependencies: [DurableStep, SupplierBookingDesk],\n});\n\nexport const TravelPlannerPhase5Toolkit = Toolkit.make(\n DurableSearchFlights,\n DurableSearchLodging,\n DurableSearchActivities,\n BookFlight,\n CancelBooking,\n BookItinerary,\n);\n\nconst requireToolCallId = (\n toolName: string,\n toolCallId: string | undefined,\n): Effect.Effect<string, SupplierUnavailable> =>\n toolCallId === undefined\n ? Effect.fail(\n SupplierUnavailable.make({\n message: `${toolName} needs its stable Tool Call ID to derive the supplier idempotency key.`,\n }),\n )\n : Effect.succeed(toolCallId);\n\nexport const TravelPlannerPhase5ToolkitLayer = TravelPlannerPhase5Toolkit.toLayer({\n search_flights: (query) =>\n Effect.flatMap(FlightCatalog, (catalog) => catalog.search(FlightQuery.make(query))),\n search_lodging: (query) =>\n Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(LodgingQuery.make(query))),\n search_activities: (query) =>\n Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(ActivityQuery.make(query))),\n book_flight: (request, context) =>\n Effect.gen(function* () {\n const desk = yield* SupplierBookingDesk;\n const toolCallId = yield* requireToolCallId(\"book_flight\", context.toolCallId);\n const record = yield* desk.book({\n operation: \"book-flight\",\n idempotencyKey: bookFlightIdempotencyKey(toolCallId),\n detail: `flight ${request.quoteId} for ${request.travelerRef} on ${request.departOn}`,\n });\n return SupplierBookingConfirmation.make({\n bookingRef: record.bookingRef,\n status: \"confirmed\",\n detail: record.detail,\n });\n }),\n cancel_booking: (request) =>\n Effect.gen(function* () {\n const desk = yield* SupplierBookingDesk;\n const record = yield* desk.cancel(request.bookingRef);\n return CancellationConfirmation.make({\n bookingRef: record.bookingRef,\n status: \"cancelled\",\n });\n }),\n book_itinerary: (request, context) =>\n Effect.gen(function* () {\n const desk = yield* SupplierBookingDesk;\n const step = yield* DurableStep;\n const toolCallId = yield* requireToolCallId(\"book_itinerary\", context.toolCallId);\n const bookStep = (\n stepName: \"reserve-flight\" | \"reserve-lodging\" | \"issue-confirmation\",\n detail: string,\n ) =>\n step.do(\n stepName,\n SupplierBookingRecord,\n desk.book({\n operation: stepName,\n idempotencyKey: itineraryStepIdempotencyKey(toolCallId, stepName),\n detail,\n }),\n );\n const flight = yield* bookStep(\n \"reserve-flight\",\n `flight ${request.quoteId} for ${request.travelerRef}`,\n );\n const lodging = yield* bookStep(\n \"reserve-lodging\",\n `lodging ${request.destination} for ${request.nights} nights (${request.travelerRef})`,\n );\n const confirmation = yield* bookStep(\n \"issue-confirmation\",\n `itinerary confirmation for ${request.travelerRef}`,\n );\n return ItineraryConfirmation.make({\n flightBookingRef: flight.bookingRef,\n lodgingBookingRef: lodging.bookingRef,\n confirmationCode: confirmation.bookingRef,\n });\n }),\n});\n\nconst decodePersistedJson = Schema.decodeUnknownEffect(PersistedJson);\nconst encodeConfirmation = Schema.encodeEffect(SupplierBookingConfirmation);\n\n/**\n * The application reconciliation policy (durability §10): a claim about EXTERNAL truth, queried\n * from the supplier desk by the same idempotency-key derivations the handlers use.\n *\n * - `book_flight`: a confirmed booking under `book-flight:{toolCallId}` is recovered supplier\n * truth — `CompletedWithResult` settles it canonically without executing anything. Absence is\n * NOT proof the call never started (a real supplier write could be in flight), so the desk\n * answer stays fail-closed `Uncertain`.\n * - `book_itinerary`: every external mutation inside is a named Step whose supplier idempotency\n * key derives from `(toolCallId, stepName)`, so re-entry is provably safe by construction —\n * `SafeToRetry`. Committed Steps replay from their records; repeated calls dedupe at the desk.\n * - `cancel_booking`: declared `idempotent`, so the coordinator re-executes without consulting\n * this policy; if ever asked, the bookingRef contract makes `SafeToRetry` honest.\n * - anything else: fail-closed `Uncertain` (AGENTS rule 11).\n */\nexport const TravelSupplierReconcilerLayer: Layer.Layer<\n ToolReconciler,\n never,\n SupplierBookingDesk\n> = Layer.effect(\n ToolReconciler,\n Effect.gen(function* () {\n const desk = yield* SupplierBookingDesk;\n return ToolReconciler.of({\n reconcile: (evidence) =>\n Effect.gen(function* () {\n switch (evidence.toolName) {\n case \"book_flight\": {\n const key = bookFlightIdempotencyKey(evidence.toolCallId);\n const booking = yield* desk.lookup(key);\n if (Option.isSome(booking) && booking.value.status === \"confirmed\") {\n const confirmation = yield* encodeConfirmation(\n SupplierBookingConfirmation.make({\n bookingRef: booking.value.bookingRef,\n status: \"confirmed\",\n detail: booking.value.detail,\n }),\n ).pipe(Effect.flatMap(decodePersistedJson));\n return ReconciliationCompleted.make({ result: confirmation, isFailure: false });\n }\n return ReconciliationUncertain.make({\n reason: `The supplier desk shows no confirmed booking under ${key}; a write may still be in flight.`,\n });\n }\n case \"book_itinerary\":\n return ReconciliationSafeToRetry.make();\n case \"cancel_booking\":\n return ReconciliationSafeToRetry.make();\n default:\n return ReconciliationUncertain.make({\n reason: `No supplier reconciliation exists for ${evidence.toolName}.`,\n });\n }\n }).pipe(\n Effect.mapError((error) =>\n ToolReconcilerError.make({\n toolCallId: evidence.toolCallId,\n message: `Supplier reconciliation failed: ${error.message}`,\n }),\n ),\n ),\n });\n }),\n);\n\n/**\n * The cumulative Travel Planner, Phase 5: the durable planner now performs consequential\n * supplier mutation under the full uncertainty protocol — approval-gated uncertain booking,\n * idempotent-by-contract cancellation, and one Durable Tool whose Steps carry supplier\n * idempotency keys.\n */\nexport const TravelPlannerPhase5 = Agent.define(\"travel-planner-phase-5\", {\n input: TripRequest,\n output: TravelBookingReport,\n instructions: [\n \"You are the Effect Agent Travel Planner P5 booking fixture.\",\n \"Search with the read-only tools, then book with book_flight, book_itinerary, or\",\n \"cancel_booking exactly as scripted. Every consequential mutation is approval-gated\",\n \"or Step-structured. Return only a JSON object with summary and bookingRefs.\",\n ].join(\" \"),\n toolkit: TravelPlannerPhase5Toolkit,\n policy: AgentPolicy.make({\n maxTurns: 4,\n maxToolCalls: 6,\n maxDuration: \"30 seconds\",\n toolConcurrency: 2,\n }),\n description:\n \"Durably book one itinerary with prepared/settled supplier records, Unknown Outcomes, named Steps, and joined traveler input.\",\n metadata: { deploymentClass: \"DN\", phase: \"P5\" },\n});\n\nexport class TravelPlannerBookingEvidenceError extends Schema.TaggedError<TravelPlannerBookingEvidenceError>()(\n \"TravelPlannerBookingEvidenceError\",\n { message: Schema.String },\n) {}\n\nconst bookingResultRefs = (result: unknown): ReadonlyArray<string> => {\n if (typeof result !== \"object\" || result === null) return [];\n const refs: Array<string> = [];\n for (const [field, value] of Object.entries(result)) {\n if (\n typeof value === \"string\" &&\n (field === \"bookingRef\" ||\n field === \"flightBookingRef\" ||\n field === \"lodgingBookingRef\" ||\n field === \"confirmationCode\")\n ) {\n refs.push(value);\n }\n }\n return refs;\n};\n\nconst bookingToolNames = new Set([\"book_flight\", \"cancel_booking\", \"book_itinerary\"]);\n\n/**\n * Never-fabricate assertion (ROADMAP P5 exit gate): every successfully settled booking result in\n * canonical history must reference a booking that actually exists in the supplier store. A\n * `ToolCallSettled` whose bookingRef the supplier cannot produce would be a fabricated result —\n * the exact lie the uncertainty protocol exists to prevent.\n */\nexport const assertSettledBookingsExistAtSupplier = Effect.fn(\n \"TravelPlannerPhase5.assertSettledBookingsExistAtSupplier\",\n)(function* (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n): Effect.fn.Return<void, TravelPlannerBookingEvidenceError, SupplierBookingDesk> {\n const desk = yield* SupplierBookingDesk;\n const bookings = yield* desk.bookings;\n const knownRefs = new Set<string>(bookings.map((booking) => booking.bookingRef));\n for (const envelope of records) {\n const payload = envelope.record.payload;\n if (\n payload._tag !== \"ToolCallSettled\" ||\n payload.isFailure ||\n !bookingToolNames.has(payload.toolName)\n ) {\n continue;\n }\n for (const ref of bookingResultRefs(payload.result)) {\n if (!knownRefs.has(ref)) {\n return yield* TravelPlannerBookingEvidenceError.make({\n message: `Canonical record ${envelope.record.recordId} settled bookingRef ${ref}, which the supplier store cannot produce — a fabricated result.`,\n });\n }\n }\n }\n});\n\n/**\n * Everything a durable P5 worker needs beyond the runtime stack and the supplier desk: the\n * booking toolkit plus the deterministic P1 travel-service Layers. `SupplierBookingDesk` is\n * deliberately NOT provided here — tests own the desk's lifetime so its counters, bookings, and\n * crash windows survive Tool-Layer rebuilds across Attempts.\n */\nexport const phase5TravelPlannerWorkerLayer = Layer.mergeAll(\n TravelPlannerPhase5ToolkitLayer,\n FlightCatalogLayer,\n LodgingCatalogLayer,\n ActivityCatalogLayer,\n).pipe(Layer.provide(CatalogLifecycle.layerNoDeps));\n","import { Subagent, SubagentPolicy, SubagentRuntime } from \"@effect-agent/capabilities\";\nimport { Agent, AgentPolicy } from \"@effect-agent/core\";\nimport type { RuntimeBinding } from \"@effect-agent/engine\";\nimport { Context, Deferred, Effect, Layer, Ref, Schema, Stream } from \"effect\";\nimport { LanguageModel, Model, type Response, Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport type { ScriptedTurnInput } from \"../../scripted-model.ts\";\nimport { AirportCode } from \"./definition.ts\";\nimport { CatalogLifecycle } from \"./deterministic-layers.ts\";\n\n// ---------------------------------------------------------------------------\n// Destination Researcher: the S1 specialist child Agent\n// (spec/subagents.md §17 \"deterministic scripted Travel Planner specialist\n// delegation\"). The researcher is a normal Agent with one deterministic\n// travel-service Tool; it never becomes a second child loop (SUB-001/003).\n// ---------------------------------------------------------------------------\n\nexport class DestinationQuery extends Schema.Class<DestinationQuery>(\"DestinationQuery\")({\n destination: AirportCode,\n}) {}\n\nexport class DestinationFacts extends Schema.Class<DestinationFacts>(\"DestinationFacts\")({\n destination: AirportCode,\n highlights: Schema.Array(Schema.String),\n advisory: Schema.NonEmptyString,\n}) {}\n\nexport class DestinationGuideUnavailable extends Schema.TaggedError<DestinationGuideUnavailable>()(\n \"DestinationGuideUnavailable\",\n {\n destination: AirportCode,\n message: Schema.String,\n },\n) {}\n\nexport class DestinationGuide extends Context.Service<\n DestinationGuide,\n {\n readonly lookup: (\n query: DestinationQuery,\n ) => Effect.Effect<DestinationFacts, DestinationGuideUnavailable>;\n }\n>()(\"@effect-agent/testing/travel-planner/DestinationGuide\") {}\n\nexport const LookupDestination = Tool.make(\"lookup_destination\", {\n parameters: DestinationQuery,\n success: DestinationFacts,\n failure: DestinationGuideUnavailable,\n failureMode: \"error\",\n dependencies: [DestinationGuide],\n});\n\nexport const DestinationResearcherToolkit = Toolkit.make(LookupDestination);\nexport const DestinationResearcherToolkitLayer = DestinationResearcherToolkit.toLayer({\n lookup_destination: (query) => Effect.flatMap(DestinationGuide, (guide) => guide.lookup(query)),\n});\n\nexport class DestinationBrief extends Schema.Class<DestinationBrief>(\"DestinationBrief\")({\n destination: AirportCode,\n focus: Schema.NonEmptyString,\n}) {}\n\nexport class DestinationReport extends Schema.Class<DestinationReport>(\"DestinationReport\")({\n destination: AirportCode,\n highlights: Schema.Array(Schema.String),\n advisory: Schema.NonEmptyString,\n}) {}\n\nexport const DestinationResearcher = Agent.define(\"destination-researcher\", {\n input: DestinationBrief,\n output: DestinationReport,\n instructions:\n \"Consult lookup_destination exactly once for the briefed airport, then return only a JSON destination report.\",\n toolkit: DestinationResearcherToolkit,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 1,\n maxDuration: \"30 seconds\",\n toolConcurrency: 1,\n }),\n description: \"Research one candidate destination with the deterministic travel guide.\",\n metadata: { deploymentClass: \"E\", phase: \"S1\" },\n});\n\n// ---------------------------------------------------------------------------\n// Deterministic guide data and Layer (deterministic-layers.ts conventions).\n// ---------------------------------------------------------------------------\n\nconst decodeAirportCode = Schema.decodeSync(AirportCode);\n\nconst guideFacts = new Map<string, DestinationFacts>([\n [\n \"LHR\",\n DestinationFacts.make({\n destination: decodeAirportCode(\"LHR\"),\n highlights: [\"Barbican brutalism walk\", \"Kew glasshouse survey\"],\n advisory: \"London favors museum mornings and riverside evenings.\",\n }),\n ],\n [\n \"CDG\",\n DestinationFacts.make({\n destination: decodeAirportCode(\"CDG\"),\n highlights: [\"Marais passage crawl\", \"Seine bookstall loop\"],\n advisory: \"Paris rewards early galleries and late cafes.\",\n }),\n ],\n]);\n\n/** Deterministic guide lookup shared by the default and test-local guide Layers. */\nexport const destinationLookup = (\n query: DestinationQuery,\n): Effect.Effect<DestinationFacts, DestinationGuideUnavailable> => {\n const facts = guideFacts.get(query.destination);\n return facts === undefined\n ? Effect.fail(\n DestinationGuideUnavailable.make({\n destination: query.destination,\n message: \"No deterministic guide entry exists for this destination.\",\n }),\n )\n : Effect.succeed(facts);\n};\n\nconst requireDestinationFacts = (destination: string): DestinationFacts => {\n const facts = guideFacts.get(destination);\n if (facts === undefined) {\n throw new Error(`No deterministic guide entry exists for destination ${destination}`);\n }\n return facts;\n};\n\n/** The report the scripted researcher writes after consulting the guide. */\nexport const destinationReportFor = (destination: string): DestinationReport => {\n const facts = requireDestinationFacts(destination);\n return DestinationReport.make({\n destination: facts.destination,\n highlights: facts.highlights,\n advisory: facts.advisory,\n });\n};\n\nexport const encodedDestinationReport = (destination: string): string =>\n JSON.stringify(Schema.encodeSync(DestinationReport)(destinationReportFor(destination)));\n\nexport const DestinationGuideLayer = Layer.effect(\n DestinationGuide,\n Effect.gen(function* () {\n const lifecycle = yield* CatalogLifecycle;\n yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);\n return DestinationGuide.of({ lookup: destinationLookup });\n }),\n);\n\n/** Child-side construction requirements of the delegation handler Layer. */\nexport const DestinationResearchSupportLayer = Layer.mergeAll(\n DestinationResearcherToolkitLayer,\n DestinationGuideLayer,\n);\n\n// ---------------------------------------------------------------------------\n// Delegation Definition (spec/subagents.md §4): the coordinator sees exactly\n// one Effect AI Tool with explicit input/result projections and finite bounds.\n// ---------------------------------------------------------------------------\n\nexport class DestinationResearchRequest extends Schema.Class<DestinationResearchRequest>(\n \"DestinationResearchRequest\",\n)({\n destination: AirportCode,\n focus: Schema.NonEmptyString,\n}) {}\n\nexport class DestinationResearchFindings extends Schema.Class<DestinationResearchFindings>(\n \"DestinationResearchFindings\",\n)({\n destination: AirportCode,\n summary: Schema.NonEmptyString,\n}) {}\n\nexport class DestinationResearchFailed extends Schema.TaggedError<DestinationResearchFailed>()(\n \"DestinationResearchFailed\",\n {\n childErrorTag: Schema.NonEmptyString,\n },\n) {}\n\n/**\n * Deterministic delegation-admission choreography seam. `prepareInput` awaits\n * this gate before the handler reserves budget or spawns, so tests can order\n * concurrent delegation preflights without sleeps. It also keeps the\n * projection's construction requirements honestly visible in the handler\n * Layer's `R` (spec/subagents.md §4.1). The open Layer never waits.\n */\nexport class ResearchDispatchGate extends Context.Service<\n ResearchDispatchGate,\n { readonly awaitDispatch: (destination: string) => Effect.Effect<void> }\n>()(\"@effect-agent/testing/travel-planner/ResearchDispatchGate\") {\n static readonly layerOpen = Layer.succeed(\n this,\n ResearchDispatchGate.of({ awaitDispatch: () => Effect.void }),\n );\n}\n\n/**\n * Finite per-invocation bounds (SUB-009): each child may use two Turns and\n * one Tool Call; the parent Run may establish at most two children with at\n * most two running concurrently.\n */\nexport const destinationResearchPolicy = SubagentPolicy.make({\n maxChildren: 2,\n maxConcurrency: 2,\n maxTurns: 2,\n maxToolCalls: 1,\n maxDuration: \"10 seconds\",\n});\n\nexport const destinationResearchDelegation = Subagent.define(\"delegate_destination_research\", {\n description:\n \"Research one candidate destination with the deterministic travel guide and return a bounded finding.\",\n target: DestinationResearcher,\n parameters: DestinationResearchRequest,\n success: DestinationResearchFindings,\n failure: DestinationResearchFailed,\n prepareInput: (request) =>\n Effect.gen(function* () {\n const gate = yield* ResearchDispatchGate;\n yield* gate.awaitDispatch(request.destination);\n return DestinationBrief.make({\n destination: request.destination,\n focus: `research:${request.focus}`,\n });\n }),\n // The explicit declassification boundary (SUB-015): only the advisory\n // crosses to the parent; guide highlights stay in the child Conversation.\n projectResult: (report) =>\n Effect.succeed(\n DestinationResearchFindings.make({\n destination: report.destination,\n summary: report.advisory,\n }),\n ),\n policy: destinationResearchPolicy,\n});\n\n/** Total mapping from every expected child Run failure to the declared Tool failure (SUB-028). */\nexport const mapResearchChildFailure = (failure: {\n readonly _tag: string;\n}): DestinationResearchFailed => DestinationResearchFailed.make({ childErrorTag: failure._tag });\n\n/** Runtime wiring: pair the immutable delegation with one explicit child Binding. */\nexport const destinationResearchHandlersLayer = <Provider, ModelProvides, ModelRequires>(\n childBinding: RuntimeBinding<\n typeof DestinationBrief,\n typeof DestinationReport,\n string,\n Toolkit.Tools<typeof DestinationResearcherToolkit>,\n Provider,\n ModelProvides,\n ModelRequires\n >,\n) =>\n SubagentRuntime.layer(destinationResearchDelegation, childBinding, {\n mapChildFailure: mapResearchChildFailure,\n });\n\n// ---------------------------------------------------------------------------\n// Travel Coordinator: the parent Agent that delegates destination research.\n// ---------------------------------------------------------------------------\n\nexport class ResearchMission extends Schema.Class<ResearchMission>(\"ResearchMission\")({\n request: Schema.NonEmptyString,\n candidates: Schema.Array(AirportCode).check(Schema.isMinLength(1)),\n}) {}\n\nexport class DestinationRecommendation extends Schema.Class<DestinationRecommendation>(\n \"DestinationRecommendation\",\n)({\n destination: AirportCode,\n summary: Schema.NonEmptyString,\n}) {}\n\nexport class DestinationShortlist extends Schema.Class<DestinationShortlist>(\n \"DestinationShortlist\",\n)({\n recommendations: Schema.Array(DestinationRecommendation),\n nextAction: Schema.Literal(\"review\"),\n}) {}\n\n/** Parent-only transcript markers used to prove child context isolation (SUB-006/015). */\nexport const coordinatorConfidentialMarker = \"coordinator-vault-7q42\";\nexport const missionConfidentialMarker = \"traveler-dossier-19f\";\n\nexport const TravelCoordinatorToolkit = Toolkit.make(destinationResearchDelegation.tool);\n\nexport const TravelCoordinator = Agent.define(\"travel-coordinator\", {\n input: ResearchMission,\n output: DestinationShortlist,\n instructions: [\n \"You are the Effect Agent Travel Planner S1 delegation coordinator.\",\n `Coordinator-only context: ${coordinatorConfidentialMarker}.`,\n \"Call delegate_destination_research once per candidate in one Tool batch.\",\n \"Return only a JSON shortlist built from the delegated findings. This is read-only planning.\",\n ].join(\"\\n\"),\n toolkit: TravelCoordinatorToolkit,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 3,\n maxDuration: \"30 seconds\",\n toolConcurrency: 3,\n }),\n description:\n \"Coordinate bounded destination research through one declared attached delegation Tool.\",\n metadata: { deploymentClass: \"E\", phase: \"S1\" },\n});\n\nexport const researchMission = Schema.decodeSync(ResearchMission)({\n request: `Shortlist one September culture city; keep ${missionConfidentialMarker} inside the coordinator conversation.`,\n candidates: [\"LHR\", \"CDG\"],\n});\n\nexport const expectedDestinationShortlist = DestinationShortlist.make({\n recommendations: researchMission.candidates.map((destination) =>\n DestinationRecommendation.make({\n destination,\n summary: requireDestinationFacts(destination).advisory,\n }),\n ),\n nextAction: \"review\",\n});\n\n// ---------------------------------------------------------------------------\n// Scripted turns (scenarios.ts conventions).\n// ---------------------------------------------------------------------------\n\nconst scriptedUsage = { inputTokens: { total: 96 }, outputTokens: { total: 64 } };\n\nexport interface DestinationResearchCall {\n readonly id: string;\n readonly destination: string;\n readonly focus: string;\n}\n\n/** One coordinator Turn that declares the given delegation Tool Calls in order. */\nexport const coordinatorResearchTurn = (\n calls: ReadonlyArray<DestinationResearchCall>,\n): ScriptedTurnInput => ({\n _tag: \"Stream\",\n parts: [\n ...calls.map((call) => ({\n type: \"tool-call\" as const,\n id: call.id,\n name: \"delegate_destination_research\",\n params: { destination: call.destination, focus: call.focus },\n })),\n { type: \"finish\" as const, reason: \"tool-calls\" as const, usage: scriptedUsage },\n ],\n termination: { _tag: \"Complete\" },\n});\n\n/** The coordinator's final structured-output Turn. */\nexport const coordinatorShortlistTurn = (shortlist: DestinationShortlist): ScriptedTurnInput => ({\n _tag: \"Stream\",\n parts: [\n { type: \"text-start\", id: \"shortlist\" },\n {\n type: \"text-delta\",\n id: \"shortlist\",\n delta: JSON.stringify(Schema.encodeSync(DestinationShortlist)(shortlist)),\n },\n { type: \"text-end\", id: \"shortlist\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n ],\n termination: { _tag: \"Complete\" },\n});\n\n/** Static researcher script for single-child tests: one guide lookup, then the report. */\nexport const researcherHappyPathTurns = (\n destination: string,\n): readonly [ScriptedTurnInput, ScriptedTurnInput] => [\n {\n _tag: \"Stream\",\n parts: [\n {\n type: \"tool-call\",\n id: `lookup-${destination}`,\n name: \"lookup_destination\",\n params: { destination },\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n ],\n termination: { _tag: \"Complete\" },\n },\n {\n _tag: \"Stream\",\n parts: [\n { type: \"text-start\", id: \"destination-report\" },\n {\n type: \"text-delta\",\n id: \"destination-report\",\n delta: encodedDestinationReport(destination),\n },\n { type: \"text-end\", id: \"destination-report\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n ],\n termination: { _tag: \"Complete\" },\n },\n];\n\n// ---------------------------------------------------------------------------\n// Destination-keyed researcher model for parallel-children tests.\n// ---------------------------------------------------------------------------\n\n/**\n * Deterministic controls for parallel researcher children whose completions\n * are released in a caller-selected order (ReverseCompletionToolkitLayer\n * pattern). This is intentionally a test fixture: it uses no clock or sleep.\n */\nexport interface DestinationResearcherControls {\n /** Await the first model request of the child researching this destination. */\n readonly awaitStarted: (destination: string) => Effect.Effect<void>;\n /** Allow the child researching this destination to produce its final report. */\n readonly release: (destination: string) => Effect.Effect<void>;\n /** JSON-encoded first-Turn child prompts in arrival order (isolation evidence). */\n readonly prompts: Effect.Effect<ReadonlyArray<string>>;\n}\n\ninterface ResearcherGates {\n readonly started: Deferred.Deferred<void>;\n readonly release: Deferred.Deferred<void>;\n}\n\nconst researcherLookupParts = (destination: string): ReadonlyArray<Response.StreamPartEncoded> => [\n {\n type: \"tool-call\",\n id: `lookup-${destination}`,\n name: \"lookup_destination\",\n params: { destination },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst researcherReportParts = (destination: string): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"destination-report\" },\n { type: \"text-delta\", id: \"destination-report\", delta: encodedDestinationReport(destination) },\n { type: \"text-end\", id: \"destination-report\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\n/**\n * Build a deterministic researcher Model whose per-child behavior is keyed by\n * the destination named in the child's own prompt: Turn one records the\n * prompt, signals `started`, and calls the guide Tool; Turn two waits for the\n * caller's `release` before writing the report. Each child Run builds the\n * Model Layer inside its own scope, so one `CatalogLifecycle` acquisition and\n * finalization is observed per child — the same acquire/release counting the\n * catalog Layers use to prove interruption reaches every finalizer.\n */\nexport const makeDestinationResearcherModel = (destinations: ReadonlyArray<string>) =>\n Effect.gen(function* () {\n const lifecycle = yield* CatalogLifecycle;\n const prompts = yield* Ref.make<ReadonlyArray<string>>([]);\n const gates = new Map<string, ResearcherGates>();\n for (const destination of destinations) {\n gates.set(destination, {\n started: yield* Deferred.make<void>(),\n release: yield* Deferred.make<void>(),\n });\n }\n const gatesFor = (destination: string): Effect.Effect<ResearcherGates> =>\n Effect.suspend(() => {\n const entry = gates.get(destination);\n return entry === undefined\n ? Effect.die(new Error(`No researcher gates exist for destination ${destination}`))\n : Effect.succeed(entry);\n });\n const controls: DestinationResearcherControls = {\n awaitStarted: (destination) =>\n gatesFor(destination).pipe(Effect.flatMap((entry) => Deferred.await(entry.started))),\n release: (destination) =>\n gatesFor(destination).pipe(\n Effect.flatMap((entry) => Deferred.succeed(entry.release, undefined)),\n Effect.asVoid,\n ),\n prompts: Ref.get(prompts),\n };\n const model = Model.make(\n \"scripted\",\n \"destination-researcher-scripted\",\n Layer.effect(\n LanguageModel.LanguageModel,\n Effect.gen(function* () {\n yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);\n const turn = yield* Ref.make(0);\n return yield* LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (options) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const promptJson = JSON.stringify(options.prompt.content);\n const destination = destinations.find((candidate) =>\n promptJson.includes(candidate),\n );\n if (destination === undefined) {\n return yield* Effect.die(\n new Error(\"The researcher prompt names no scripted destination\"),\n );\n }\n const entry = yield* gatesFor(destination);\n const index = yield* Ref.getAndUpdate(turn, (value) => value + 1);\n if (index === 0) {\n yield* Ref.update(prompts, (previous) => [...previous, promptJson]);\n yield* Deferred.succeed(entry.started, undefined);\n return Stream.fromIterable(researcherLookupParts(destination));\n }\n yield* Deferred.await(entry.release);\n return Stream.fromIterable(researcherReportParts(destination));\n }),\n ),\n });\n }),\n ),\n );\n return { controls, model };\n });\n","import {\n delegationAllocationFromPolicy,\n SubagentReservationsMemoryLive,\n SubagentRuntime,\n} from \"@effect-agent/capabilities\";\nimport { Agent, type ConversationId } from \"@effect-agent/core\";\nimport type { RuntimeBinding } from \"@effect-agent/engine\";\nimport {\n DefinitionDigests,\n DeploymentId,\n Digest,\n DurableWorkerBinding,\n Principal,\n ProducerId,\n type DurableSubmitOptions,\n type IdempotencyKey,\n type ResolvedBinding,\n} from \"@effect-agent/session\";\nimport { Effect, Layer, Ref, Schema, Stream } from \"effect\";\nimport { LanguageModel, Model, type Response, type Toolkit } from \"effect/unstable/ai\";\n\nimport { DeterministicIdGeneratorLayer } from \"./deterministic-layers.ts\";\nimport {\n DestinationBrief,\n DestinationFacts,\n DestinationGuide,\n DestinationRecommendation,\n DestinationReport,\n DestinationResearcher,\n DestinationResearcherToolkit,\n DestinationResearcherToolkitLayer,\n destinationLookup,\n destinationReportFor,\n destinationResearchDelegation,\n destinationResearchPolicy,\n DestinationShortlist,\n encodedDestinationReport,\n mapResearchChildFailure,\n ResearchDispatchGate,\n TravelCoordinator,\n} from \"./subagents.ts\";\n\n// ---------------------------------------------------------------------------\n// S2 durability profile (spec/subagents.md §17): the S1 coordinator →\n// destination-researcher delegation re-run as ACCEPTED WORK on the Node/SQLite\n// runtime. The claim is `DN` durable attached Subagents only: establishment\n// and join are replay-safe by construction (SUB-016/SUB-019), a completed\n// child is never re-executed on a lost join acknowledgment, and NO claim of\n// exactly-once child external effects is made (rule 8; an unresolved ordinary\n// child Tool blocks as an Unknown Outcome instead, SUB-021). Cloudflare\n// equivalence is P6 scope and explicitly not claimed here.\n// ---------------------------------------------------------------------------\n\nexport class TravelPlannerSubagentDurabilityProfile extends Schema.Class<TravelPlannerSubagentDurabilityProfile>(\n \"@effect-agent/testing/travel-planner/TravelPlannerSubagentDurabilityProfile\",\n)({\n deploymentClass: Schema.Literal(\"DN\"),\n durableAttachedSubagents: Schema.Literal(true),\n canonicalSchemaVersion: Schema.Literal(1),\n /** Establishment/join replay converges on one child Receipt, Conversation, and join batch. */\n subagentReplaySafe: Schema.Literal(true),\n /** Never claimed (rule 8): child ordinary Tools stop at Unknown Outcomes, they do not replay. */\n childExternalEffectsExactlyOnce: Schema.Literal(false),\n /** The same conformance suite under DO eviction/alarms is P6 scope (spec §17 `DC`). */\n cloudflareEquivalence: Schema.Literal(false),\n}) {}\n\nexport const s2TravelPlannerProfile = TravelPlannerSubagentDurabilityProfile.make({\n deploymentClass: \"DN\",\n durableAttachedSubagents: true,\n canonicalSchemaVersion: 1,\n subagentReplaySafe: true,\n childExternalEffectsExactlyOnce: false,\n cloudflareEquivalence: false,\n});\n\nexport const s2TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-s2-deployment\",\n);\nexport const s2TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-s2-producer\",\n);\nexport const s2TravelPlannerPrincipal = Schema.decodeSync(Principal)(\"travel-planner-s2-principal\");\n\nconst digestOf = (character: string) => Schema.decodeSync(Digest)(character.repeat(64));\n\n/** Redacted, deterministic parent (coordinator) definition digests for this fixture version. */\nexport const s2CoordinatorDigests = DefinitionDigests.make({\n agent: digestOf(\"a\"),\n model: digestOf(\"b\"),\n tools: digestOf(\"c\"),\n});\n\n/**\n * The exact child Binding digest strings the application declares on\n * `SubagentRuntimeOptions.durable.targetDigests` AND the host registers with\n * the `AgentBindingResolver` for the researcher Binding. The coordinator\n * stores and verifies them byte-for-byte (SUB-023); a host registration under\n * different strings is a `ChildCompatibilityFailure`, never a substitution.\n */\nexport const s2ResearcherDigestStrings = {\n agent: \"d\".repeat(64),\n model: \"e\".repeat(64),\n tools: \"f\".repeat(64),\n} as const;\n\nexport const s2ResearcherDigests = DefinitionDigests.make({\n agent: Schema.decodeSync(Digest)(s2ResearcherDigestStrings.agent),\n model: Schema.decodeSync(Digest)(s2ResearcherDigestStrings.model),\n tools: Schema.decodeSync(Digest)(s2ResearcherDigestStrings.tools),\n});\n\n/** Durable admission options for one coordinator Submission on one mission lane. */\nexport const s2TravelPlannerSubmitOptions = (\n conversationId: ConversationId,\n idempotencyKey: IdempotencyKey,\n): DurableSubmitOptions => ({\n conversationId,\n principal: s2TravelPlannerPrincipal,\n idempotencyKey,\n definitions: s2CoordinatorDigests,\n});\n\n/** The structural submit slice of the coordinator Binding (`DurableAgentRuntime.submit`). */\nexport const s2CoordinatorSubmitAgent = {\n definition: { id: TravelCoordinator.id, input: TravelCoordinator.input },\n} as const;\n\n/**\n * The per-invocation reservation the durable handler computes from the S1\n * delegation policy (`delegationAllocationFromPolicy`): the conservation\n * evidence in the S2 tests checks the ledger reservation rows and the\n * canonical `SubagentJoined.finalAccounting` against exactly this value.\n */\nexport const durableResearchAllocation = delegationAllocationFromPolicy(destinationResearchPolicy);\n\n/** The one scripted delegation Tool Call id of the durable coordinator Run. */\nexport const durableResearchCallId = \"research-lhr-1\";\n\n/** The child's own scripted guide-lookup Tool Call id. */\nexport const durableChildLookupCallId = (destination: string): string => `lookup-${destination}`;\n\n/** The projected finding the parent joins (only the advisory crosses, SUB-015). */\nexport const durableResearchFinding = (destination: string) => ({\n destination: destinationReportFor(destination).destination,\n summary: destinationReportFor(destination).advisory,\n});\n\n/** The coordinator's expected final shortlist for one researched destination. */\nexport const durableResearchShortlist = (destination: string): DestinationShortlist =>\n DestinationShortlist.make({\n recommendations: [\n DestinationRecommendation.make({\n destination: destinationReportFor(destination).destination,\n summary: destinationReportFor(destination).advisory,\n }),\n ],\n nextAction: \"review\",\n });\n\n/**\n * The deterministic guide facts in encoded (wire) form: the \"supplier truth\"\n * an authorized operator records through `resolveUnknown` when a child guide\n * lookup stopped at an Unknown Outcome (DUR-017 — the framework never guesses\n * or replays it).\n */\nexport const encodedDestinationFacts = (destination: string): unknown => {\n const report = destinationReportFor(destination);\n return Schema.encodeSync(DestinationFacts)(\n DestinationFacts.make({\n destination: report.destination,\n highlights: report.highlights,\n advisory: report.advisory,\n }),\n );\n};\n\n// ---------------------------------------------------------------------------\n// Invocation-counting scripted models (the P5 SupplierBookingDesk counter\n// pattern): the call counter and captured prompts live OUTSIDE the Model\n// Layer, so they survive Layer rebuilds across Attempts and across separate\n// runtime handles over the same SQLite file — \"the child was never\n// re-executed\" is asserted, not assumed.\n// ---------------------------------------------------------------------------\n\nconst scriptedUsage = { inputTokens: { total: 96 }, outputTokens: { total: 64 } };\n\n/** One scripted model whose behavior is keyed by the global invocation index. */\nexport const makeInvocationCountingModel = (\n name: string,\n script: (call: number) => ReadonlyArray<Response.StreamPartEncoded>,\n) =>\n Effect.gen(function* () {\n const calls = yield* Ref.make(0);\n const prompts = yield* Ref.make<ReadonlyArray<string>>([]);\n const model = Model.make(\n \"scripted\",\n name,\n Layer.effect(\n LanguageModel.LanguageModel,\n LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (request) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const call = yield* Ref.getAndUpdate(calls, (value) => value + 1);\n yield* Ref.update(prompts, (previous) => [\n ...previous,\n JSON.stringify(request.prompt.content),\n ]);\n return Stream.fromIterable(script(call));\n }),\n ),\n }),\n ),\n );\n return { model, calls: Ref.get(calls), prompts: Ref.get(prompts) };\n });\n\nconst delegationTurnParts = (\n toolCallId: string,\n destination: string,\n focus: string,\n): ReadonlyArray<Response.StreamPartEncoded> => [\n {\n type: \"tool-call\",\n id: toolCallId,\n name: \"delegate_destination_research\",\n params: { destination, focus },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst shortlistParts = (\n shortlist: DestinationShortlist,\n): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"shortlist\" },\n {\n type: \"text-delta\",\n id: \"shortlist\",\n delta: JSON.stringify(Schema.encodeSync(DestinationShortlist)(shortlist)),\n },\n { type: \"text-end\", id: \"shortlist\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\nconst researcherLookupParts = (destination: string): ReadonlyArray<Response.StreamPartEncoded> => [\n {\n type: \"tool-call\",\n id: durableChildLookupCallId(destination),\n name: \"lookup_destination\",\n params: { destination },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst researcherReportParts = (destination: string): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"destination-report\" },\n { type: \"text-delta\", id: \"destination-report\", delta: encodedDestinationReport(destination) },\n { type: \"text-end\", id: \"destination-report\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\n// ---------------------------------------------------------------------------\n// Durable delegation wiring (S2): the SAME immutable S1 Delegation Definition\n// paired with one explicit child Binding, now carrying the construction-fixed\n// durable declaration. Under a durable coordinator the handler establishes an\n// accepted-work child instead of spawning an in-process fiber; without the\n// declaration a durable-mode invocation fails closed (WP5 contract).\n// ---------------------------------------------------------------------------\n\n/** Runtime wiring for the durable slice: the S1 delegation plus the S2 digest declaration. */\nexport const durableDestinationResearchHandlersLayer = <Provider, ModelProvides, ModelRequires>(\n childBinding: RuntimeBinding<\n typeof DestinationBrief,\n typeof DestinationReport,\n string,\n Toolkit.Tools<typeof DestinationResearcherToolkit>,\n Provider,\n ModelProvides,\n ModelRequires\n >,\n) =>\n SubagentRuntime.layer(destinationResearchDelegation, childBinding, {\n mapChildFailure: mapResearchChildFailure,\n durable: { targetDigests: s2ResearcherDigestStrings },\n });\n\n/** Optional overrides for one durable research harness. */\nexport interface DurableResearchHarnessOptions {\n /** Researched destination; defaults to \"LHR\". */\n readonly destination?: string | undefined;\n /** Delegation focus; defaults to \"museums\". */\n readonly focus?: string | undefined;\n /**\n * Digests the HOST registers the child Binding under; defaults to the exact\n * declared `s2ResearcherDigests`. Register different digests to force the\n * fail-closed `ChildCompatibilityFailure` path (SUB-023/SUB-032).\n */\n readonly childRegistrationDigests?: DefinitionDigests | undefined;\n}\n\n/** One durable coordinator/researcher pair with observable invocation counters. */\nexport interface DurableResearchHarness {\n /** Host registrations for `NodeDurableRuntimeOptions.bindings` (parent + child). */\n readonly bindings: ReadonlyArray<ResolvedBinding>;\n /** Total coordinator model invocations across every Attempt and runtime handle. */\n readonly parentModelCalls: Effect.Effect<number>;\n /** JSON-encoded coordinator prompts in request order. */\n readonly parentPrompts: Effect.Effect<ReadonlyArray<string>>;\n /** Total researcher model invocations across every Attempt and runtime handle. */\n readonly childModelCalls: Effect.Effect<number>;\n /** JSON-encoded researcher prompts in request order (context-isolation evidence). */\n readonly childPrompts: Effect.Effect<ReadonlyArray<string>>;\n /** Deterministic guide-lookup handler executions (ordinary child Tool side effects). */\n readonly guideInvocations: Effect.Effect<number>;\n}\n\n/**\n * Build the S2 Travel Planner harness: an invocation-counting scripted\n * coordinator (Turn 1 declares the one delegation call, Turn 2 writes the\n * shortlist), an invocation-counting scripted researcher (Turn 1 consults the\n * guide, Turn 2 writes the report), and both worker Bindings captured with\n * their requirement Contexts via `DurableWorkerBinding.make` under the exact\n * fixture digests. The returned `bindings` are plain values: they can be\n * registered with several `NodeDurableRuntime` stacks over the same SQLite\n * file while the counters keep counting across all of them.\n */\nexport const makeDurableResearchHarness = (options?: DurableResearchHarnessOptions) =>\n Effect.gen(function* () {\n const destination = options?.destination ?? \"LHR\";\n const focus = options?.focus ?? \"museums\";\n\n const guideInvocations = yield* Ref.make(0);\n const guideLayer = Layer.succeed(\n DestinationGuide,\n DestinationGuide.of({\n lookup: (query) =>\n Ref.update(guideInvocations, (count) => count + 1).pipe(\n Effect.andThen(destinationLookup(query)),\n ),\n }),\n );\n const childToolkitLayer = DestinationResearcherToolkitLayer.pipe(\n Layer.provideMerge(guideLayer),\n );\n\n const childModel = yield* makeInvocationCountingModel(\"destination-researcher-s2\", (call) =>\n call === 0 ? researcherLookupParts(destination) : researcherReportParts(destination),\n );\n const childBinding = Agent.withModel(DestinationResearcher, childModel.model);\n\n const parentModel = yield* makeInvocationCountingModel(\"travel-coordinator-s2\", (call) =>\n call === 0\n ? delegationTurnParts(durableResearchCallId, destination, focus)\n : shortlistParts(durableResearchShortlist(destination)),\n );\n const parentBinding = Agent.withModel(TravelCoordinator, parentModel.model);\n\n const delegationLayer = durableDestinationResearchHandlersLayer(childBinding).pipe(\n Layer.provide(\n Layer.mergeAll(\n childToolkitLayer,\n SubagentReservationsMemoryLive,\n DeterministicIdGeneratorLayer,\n ResearchDispatchGate.layerOpen,\n ),\n ),\n );\n\n const parentResolved: ResolvedBinding = yield* DurableWorkerBinding.make(\n parentBinding,\n s2CoordinatorDigests,\n ).pipe(Effect.provide(delegationLayer));\n const childResolved: ResolvedBinding = yield* DurableWorkerBinding.make(\n childBinding,\n options?.childRegistrationDigests ?? s2ResearcherDigests,\n ).pipe(Effect.provide(childToolkitLayer));\n\n const harness: DurableResearchHarness = {\n bindings: [parentResolved, childResolved],\n parentModelCalls: parentModel.calls,\n parentPrompts: parentModel.prompts,\n childModelCalls: childModel.calls,\n childPrompts: childModel.prompts,\n guideInvocations: Ref.get(guideInvocations),\n };\n return harness;\n });\n","import { SubagentReservationsMemoryLive } from \"@effect-agent/capabilities\";\nimport { Agent } from \"@effect-agent/core\";\nimport {\n DefinitionDigests,\n DeploymentId,\n Digest,\n DurableWorkerBinding,\n ProducerId,\n type CanonicalRecordEnvelope,\n type Receipt,\n type ResolvedBinding,\n type ToolReconciler,\n} from \"@effect-agent/session\";\nimport { Duration, Effect, Layer, Schema, Stream } from \"effect\";\nimport { LanguageModel, Model, type Response } from \"effect/unstable/ai\";\n\nimport { TravelPlan, TripRequest } from \"./definition.ts\";\nimport {\n DeterministicIdGeneratorLayer,\n SupplierBookingDesk,\n supplierBookingRefFor,\n} from \"./deterministic-layers.ts\";\nimport {\n TravelPlannerDurableEvidenceError,\n TravelPlannerPhase4,\n normalizeDurableTravelPlannerEvidence,\n phase4TravelPlannerDefinitionDigests,\n phase4TravelPlannerWorkerLayer,\n} from \"./phase4.ts\";\nimport {\n TravelPlannerPhase5,\n TravelSupplierReconcilerLayer,\n bookFlightIdempotencyKey,\n phase5TravelPlannerDefinitionDigests,\n phase5TravelPlannerWorkerLayer,\n} from \"./phase5.ts\";\nimport { expectedTravelPlan } from \"./scenarios.ts\";\nimport {\n durableDestinationResearchHandlersLayer,\n durableResearchCallId,\n durableResearchShortlist,\n s2CoordinatorDigests,\n s2ResearcherDigests,\n} from \"./subagents-durable.ts\";\nimport {\n DestinationGuide,\n DestinationResearcher,\n DestinationResearcherToolkitLayer,\n DestinationShortlist,\n ResearchDispatchGate,\n ResearchMission,\n TravelCoordinator,\n destinationLookup,\n encodedDestinationReport,\n} from \"./subagents.ts\";\n\n// ---------------------------------------------------------------------------\n// Phase 6 (P6): the SAME cumulative Travel Planner on the Cloudflare Durable\n// Object runtime, deployment class DC. This module is deliberately\n// platform-neutral (it imports no Cloudflare types): the worker Bindings it\n// builds are plain `ResolvedBinding` values a Conversation Object registers,\n// and the cross-platform evidence normal form is shared by the DN and DC\n// halves of the equivalence suite (plan §1.8, D-P6-6).\n// ---------------------------------------------------------------------------\n\n/**\n * The Phase 6 profile: the P4/P5/S2 Travel Planner claims re-earned on the Cloudflare Durable\n * Object runtime (deployment class `DC`), where eviction and alarm redelivery replace process\n * kill and restart as the exercised recovery path. `cloudflareEquivalence` is the claim the S2\n * fixture explicitly deferred to P6 (`TravelPlannerSubagentDurabilityProfile` pins it `false`\n * for `DN`): it flips to `true` here ONLY because the phase-6 suites assert byte-equal\n * cross-platform normalized canonical evidence against one committed golden. Exactly-once\n * EXTERNAL effects remain — deliberately — unclaimed on every platform (DUR-003).\n */\nexport class TravelPlannerCloudflareProfile extends Schema.Class<TravelPlannerCloudflareProfile>(\n \"@effect-agent/testing/travel-planner/TravelPlannerCloudflareProfile\",\n)({\n deploymentClass: Schema.Literal(\"DC\"),\n durableAcceptedWork: Schema.Literal(true),\n canonicalSchemaVersion: Schema.Literal(1),\n /** P5 semantics under DC recovery: prepared/settled records, Unknown Outcomes, approvals. */\n supplierBookingUncertaintyProtocol: Schema.Literal(true),\n /** S2 semantics under DC recovery: cross-Object establishment/join, completed child never re-runs. */\n durableAttachedSubagents: Schema.Literal(true),\n /** DN and DC produce byte-equal cross-platform normalized canonical evidence (one golden). */\n cloudflareEquivalence: Schema.Literal(true),\n /** Never claimed at any phase on any platform (DUR-003). */\n exactlyOnceExternalEffects: Schema.Literal(false),\n}) {}\n\nexport const phase6TravelPlannerProfile = TravelPlannerCloudflareProfile.make({\n deploymentClass: \"DC\",\n durableAcceptedWork: true,\n canonicalSchemaVersion: 1,\n supplierBookingUncertaintyProtocol: true,\n durableAttachedSubagents: true,\n cloudflareEquivalence: true,\n exactlyOnceExternalEffects: false,\n});\n\nexport const phase6TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-p6-deployment\",\n);\n/** Producer prefix of the DC host; each Object mints `{prefix}:{conversationId}`. */\nexport const phase6TravelPlannerProducerPrefix = \"travel-planner-p6-producer\";\n/** The full producer identity one DC Conversation Object mints for itself. */\nexport const phase6TravelPlannerProducerId = (conversationId: string): ProducerId =>\n Schema.decodeSync(ProducerId)(`${phase6TravelPlannerProducerPrefix}:${conversationId}`);\n\nconst digestOf = (character: string) => Schema.decodeSync(Digest)(character.repeat(64));\n\n/**\n * Registration digests of the GATED planner Binding: the same `TravelPlannerPhase4` definition\n * bound to a model whose first response waits on a test gate, addressable separately so the\n * admission-limits rows can hold a lane busy deterministically without touching the ordinary\n * planner registration.\n */\nexport const phase6GatedPlannerDefinitionDigests = DefinitionDigests.make({\n agent: digestOf(\"9\"),\n model: digestOf(\"8\"),\n tools: digestOf(\"7\"),\n});\n\n// ---------------------------------------------------------------------------\n// Cross-platform evidence normal form (plan §1.8, D-P6-6)\n// ---------------------------------------------------------------------------\n\n/** The run-specific identities the cross-platform normal form scrubs. */\nexport interface CrossPlatformEvidenceIdentity {\n /** The Conversation lane the evidence came from. */\n readonly conversationId: string;\n /** The host's deployment identity (`DeploymentId` on every record envelope). */\n readonly deploymentId: string;\n /** The full producer identity of the run (DN: configured; DC: `{prefix}:{conversationId}`). */\n readonly producerId: string;\n}\n\nconst decodeComparableJson = Schema.decodeUnknownEffect(Schema.Json);\n\n/** The base normal form's element shape, re-decoded so sequences can be renumbered. */\nconst ComparableEnvelope = Schema.Struct({\n batchId: Schema.String,\n sequence: Schema.Number,\n record: Schema.Json,\n});\nconst decodeComparableEnvelopes = Schema.decodeUnknownEffect(Schema.Array(ComparableEnvelope));\n\n/**\n * The CROSS-PLATFORM extension of `normalizeDurableTravelPlannerEvidence` (D-P6-6): after the\n * base normalization replaces the two ledger-minted identities (which also normalizes the\n * DC-format routable `{uuidv7}:{conversationId}` Submission identities and everything derived\n * from them), this form additionally scrubs everything that legitimately differs between a DN\n * process and a DC Durable Object over the same scenario:\n *\n * - `RepairAnnotated` audit records are dropped BEFORE normalization and the canonical\n * sequence is renumbered to the surviving order: repairs are DUR-013 evidence of recovery\n * itself, legally present in a recovered run and legally absent from an uninterrupted\n * control (on DC even a CLEAN run carries one, because every pass reconciles before it\n * claims, so the ready lane's input is applied through the recovery path). Canonical ORDER\n * is the durability §5 claim; sequence contiguity is a platform artifact of who appended;\n * - the Conversation identity (DC lanes mint unique names per test run);\n * - the deployment and producer identities (host configuration, not canonical semantics);\n * - `createdAt` commit timestamps (wall clock);\n * - 64-hex digests (they hash RAW content that legally embeds run-specific identity, so they\n * can never be byte-equal across runs; chain integrity is asserted separately by the\n * adapters and the convergence helpers).\n *\n * Two runs whose cross-platform normalized evidence is byte-equal took canonically equivalent\n * histories — the exact sense in which durability §5 permits storage differences while\n * requiring the same observable ordering. Both the DN and DC suites assert equality against\n * the one committed `phase6TravelPlannerGoldenEvidence`, so DN ≡ DC transitively.\n */\nexport const normalizeCrossPlatformTravelPlannerEvidence = Effect.fn(\n \"TravelPlannerPhase6.normalizeCrossPlatformTravelPlannerEvidence\",\n)(function* (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n receipt: Receipt,\n identity: CrossPlatformEvidenceIdentity,\n): Effect.fn.Return<Schema.Json, TravelPlannerDurableEvidenceError> {\n const canonical = records.filter(\n (envelope) => envelope.record.payload._tag !== \"RepairAnnotated\",\n );\n const base = yield* normalizeDurableTravelPlannerEvidence(canonical, receipt);\n const scrubbed: unknown = JSON.parse(\n JSON.stringify(base)\n .replaceAll(identity.producerId, \"{producerId}\")\n .replaceAll(identity.deploymentId, \"{deploymentId}\")\n .replaceAll(identity.conversationId, \"{conversationId}\")\n .replaceAll(/\\d{4}-\\d{2}-\\d{2}T[0-9:.]+Z/g, \"{timestamp}\")\n .replaceAll(/\"[0-9a-f]{64}\"/g, '\"{digest}\"'),\n );\n const comparable = yield* decodeComparableEnvelopes(scrubbed).pipe(\n Effect.mapError((error) =>\n TravelPlannerDurableEvidenceError.make({\n message: `Cross-platform normalized evidence lost the comparable shape: ${error.message}`,\n }),\n ),\n );\n const renumbered = comparable.map((entry, index) => ({\n batchId: entry.batchId,\n sequence: index + 1,\n record: entry.record,\n }));\n return yield* decodeComparableJson(renumbered).pipe(\n Effect.mapError((error) =>\n TravelPlannerDurableEvidenceError.make({\n message: `Cross-platform normalized evidence is not comparable JSON: ${error.message}`,\n }),\n ),\n );\n});\n\n// ---------------------------------------------------------------------------\n// Prompt-aware scripted models. A DC Attempt may resume on a FRESH Object\n// incarnation whose Layers (and any in-memory turn counter) were rebuilt, so\n// every phase-6 model derives its response purely from the committed history\n// in its prompt — the way a real model would — instead of from call order.\n// ---------------------------------------------------------------------------\n\nconst scriptedUsage = { inputTokens: { total: 128 }, outputTokens: { total: 96 } };\n\nconst promptAwareModel = (\n name: string,\n decide: (promptJson: string) => Stream.Stream<Response.StreamPartEncoded>,\n) =>\n Model.make(\n \"scripted\",\n name,\n Layer.effect(\n LanguageModel.LanguageModel,\n LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (options) =>\n Stream.unwrap(Effect.sync(() => decide(JSON.stringify(options.prompt)))),\n }),\n ),\n );\n\n/** The P1/P4 happy-path Tool Call identities (scenarios.ts, byte-stable since P1). */\nexport const phase6FlightCallId = \"flight-call-1\";\nexport const phase6LodgingCallId = \"lodging-call-1\";\nexport const phase6ActivityCallId = \"activity-call-1\";\n\n/** Turn 1 of the planner: the SAME three search declarations as `phase1HappyPathTurns`. */\nconst plannerSearchTurnParts: ReadonlyArray<Response.StreamPartEncoded> = [\n {\n type: \"tool-call\",\n id: phase6FlightCallId,\n name: \"search_flights\",\n params: { origin: \"SFO\", destination: \"LHR\", departOn: \"2026-09-14\", travelers: 2 },\n },\n {\n type: \"tool-call\",\n id: phase6LodgingCallId,\n name: \"search_lodging\",\n params: { destination: \"LHR\", departOn: \"2026-09-14\", nights: 4, travelers: 2 },\n },\n {\n type: \"tool-call\",\n id: phase6ActivityCallId,\n name: \"search_activities\",\n params: { destination: \"LHR\", departOn: \"2026-09-14\", nights: 4, travelers: 2 },\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\n/** Turn 2 of the planner: the SAME itinerary text as `phase1HappyPathTurns`. */\nconst plannerPlanTurnParts: ReadonlyArray<Response.StreamPartEncoded> = [\n { type: \"text-start\", id: \"itinerary-json\" },\n {\n type: \"text-delta\",\n id: \"itinerary-json\",\n delta: JSON.stringify(Schema.encodeSync(TravelPlan)(expectedTravelPlan)),\n },\n { type: \"text-end\", id: \"itinerary-json\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\nconst plannerDecide = (promptJson: string): Stream.Stream<Response.StreamPartEncoded> =>\n promptJson.includes(phase6FlightCallId)\n ? Stream.fromIterable(plannerPlanTurnParts)\n : Stream.fromIterable(plannerSearchTurnParts);\n\n/**\n * The P4 planner script (`phase1HappyPathTurns`) as a prompt-aware model: once the search\n * batch is committed history, every later request gets the plan — identical parts, so the DC\n * canonical evidence is byte-equivalent to the DN ScriptedModel run after normalization.\n */\nexport const phase6PlannerModel = promptAwareModel(\"travel-planner-phase-4\", plannerDecide);\n\n// ---------------------------------------------------------------------------\n// Deterministic test gate for the admission-limits rows. Module state is\n// intentionally NOT durable: it plays the external world's role (a slow\n// upstream model), never Conversation state.\n// ---------------------------------------------------------------------------\n\nconst releasedPlannerGates = new Set<string>();\n\n/** Release the gated planner model for one `[gate:...]` marker. */\nexport const releasePhase6PlannerGate = (marker: string): void => {\n releasedPlannerGates.add(marker);\n};\n\n/** Re-close one gate marker (fresh suites reuse markers safely). */\nexport const resetPhase6PlannerGate = (marker: string): void => {\n releasedPlannerGates.delete(marker);\n};\n\nconst awaitPlannerGate = (marker: string): Effect.Effect<void> =>\n Effect.gen(function* () {\n while (!releasedPlannerGates.has(marker)) {\n yield* Effect.sleep(Duration.millis(10));\n }\n });\n\nconst gateMarkerFromPrompt = (promptJson: string): string =>\n /\\[gate:([^\\]]+)\\]/.exec(promptJson)?.[1] ?? \"unknown-gate\";\n\n/** A trip whose request text carries the gate marker the gated model waits on. */\nexport const phase6GatedTrip = (marker: string): TripRequest =>\n Schema.decodeUnknownSync(TripRequest)({\n request: `Plan a review-only London trip, but wait for the concierge. [gate:${marker}]`,\n origin: \"SFO\",\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n nights: 4,\n travelers: 2,\n budgetCents: 350_000,\n currency: \"USD\",\n });\n\n/**\n * The SAME planner behavior with a hanging first response: the model waits on the released\n * gate before answering, keeping its lane durably busy so queue-depth admission limits can be\n * exercised deterministically.\n */\nexport const phase6GatedPlannerModel = Model.make(\n \"scripted\",\n \"travel-planner-phase-4-gated\",\n Layer.effect(\n LanguageModel.LanguageModel,\n LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (options) =>\n Stream.unwrap(\n Effect.sync(() => {\n const promptJson = JSON.stringify(options.prompt);\n return promptJson.includes(phase6FlightCallId)\n ? plannerDecide(promptJson)\n : Stream.fromEffectDrain(awaitPlannerGate(gateMarkerFromPrompt(promptJson))).pipe(\n Stream.concat(plannerDecide(promptJson)),\n );\n }),\n ),\n }),\n ),\n);\n\n// ---------------------------------------------------------------------------\n// P5 booking slice: the SAME phase-5 booking agent and supplier desk. The desk\n// is a module-level singleton because it IS the external supplier: like a real\n// supplier's ledger, its bookings and call counters survive `ctx.abort()` and\n// incarnation loss, which is exactly what the never-fabricate and\n// executed-once assertions measure.\n// ---------------------------------------------------------------------------\n\nconst sharedSupplierDesk = Effect.runSync(\n Effect.flatMap(SupplierBookingDesk, Effect.succeed).pipe(\n Effect.provide(SupplierBookingDesk.layer),\n ),\n);\n\n/** The shared external supplier desk instance (module-level external truth). */\nexport const phase6SupplierDesk = sharedSupplierDesk;\n\n/** Layer handing the shared desk to Bindings, reconcilers, and assertions. */\nexport const phase6SupplierDeskLayer: Layer.Layer<SupplierBookingDesk> = Layer.succeed(\n SupplierBookingDesk,\n sharedSupplierDesk,\n);\n\n/**\n * The REAL P5 supplier reconciliation policy over the shared desk, closed to no requirements\n * so a Conversation Object can install it directly: `book_flight` recovers only from supplier\n * truth (absence stays fail-closed `Uncertain` → durable Unknown Outcome), keyed Steps are\n * provably re-enterable.\n */\nexport const phase6SupplierReconcilerLayer: Layer.Layer<ToolReconciler> =\n TravelSupplierReconcilerLayer.pipe(Layer.provide(phase6SupplierDeskLayer));\n\nconst bookingMarkerFromPrompt = (promptJson: string): string =>\n /\\[case:([^\\]]+)\\]/.exec(promptJson)?.[1] ?? \"unknown-case\";\n\n/** The deterministic booking Tool Call identity for one `[case:...]` marker. */\nexport const phase6BookingToolCallId = (marker: string): string => `book-${marker}`;\n\n/** The bookingRef the supplier desk mints for one marker's approved booking. */\nexport const phase6BookingRef = (marker: string): string =>\n supplierBookingRefFor(bookFlightIdempotencyKey(phase6BookingToolCallId(marker)));\n\n/** A trip whose request text carries the per-lane booking case marker. */\nexport const phase6BookingTrip = (marker: string): TripRequest =>\n Schema.decodeUnknownSync(TripRequest)({\n request: `Book the approved London flight for the traveler. [case:${marker}]`,\n origin: \"SFO\",\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n nights: 4,\n travelers: 2,\n budgetCents: 350_000,\n currency: \"USD\",\n });\n\nconst bookingCallParts = (marker: string): ReadonlyArray<Response.StreamPartEncoded> => [\n {\n type: \"tool-call\",\n id: phase6BookingToolCallId(marker),\n name: \"book_flight\",\n params: {\n quoteId: \"quote-sfo-lhr-001\",\n travelerRef: `traveler-${marker}`,\n departOn: \"2026-09-14\",\n },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst bookingReportParts = (marker: string): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"booking-report\" },\n {\n type: \"text-delta\",\n id: \"booking-report\",\n delta: JSON.stringify({\n summary: \"trip booked\",\n bookingRefs: [phase6BookingRef(marker)],\n }),\n },\n { type: \"text-end\", id: \"booking-report\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\n/**\n * The P5 booking script as a prompt-aware model: request 1 declares the approval-gated\n * `book_flight` call (identity derived from the lane's `[case:...]` marker so supplier\n * idempotency keys never collide across lanes); once that call is committed history, the model\n * writes the booking report.\n */\nexport const phase6BookingModel = promptAwareModel(\"travel-planner-phase-5\", (promptJson) => {\n const marker = bookingMarkerFromPrompt(promptJson);\n return promptJson.includes(phase6BookingToolCallId(marker))\n ? Stream.fromIterable(bookingReportParts(marker))\n : Stream.fromIterable(bookingCallParts(marker));\n});\n\n// ---------------------------------------------------------------------------\n// S2 delegation slice: the SAME coordinator → destination-researcher pair.\n// The guide invocation counter is module state for the same reason as the\n// desk: it is the child's external side-effect record, and \"the completed\n// child never re-executes\" is asserted against it across evictions.\n// ---------------------------------------------------------------------------\n\nlet guideInvocations = 0;\n\n/** Deterministic guide-lookup handler executions across every incarnation. */\nexport const phase6GuideInvocationCount = (): number => guideInvocations;\n\nconst countingGuideLayer = Layer.succeed(\n DestinationGuide,\n DestinationGuide.of({\n lookup: (query) =>\n Effect.suspend(() => {\n guideInvocations += 1;\n return destinationLookup(query);\n }),\n }),\n);\n\n/** The one-candidate research mission of the DC delegation slice. */\nexport const phase6ResearchMission = Schema.decodeUnknownSync(ResearchMission)({\n request: \"Shortlist one September culture city for the DC delegation slice.\",\n candidates: [\"LHR\"],\n});\n\nexport const phase6ResearchDestination = \"LHR\";\n\n/** The child's scripted guide-lookup Tool Call identity. */\nexport const phase6ChildLookupCallId = `lookup-${phase6ResearchDestination}`;\n\nconst coordinatorDelegationParts: ReadonlyArray<Response.StreamPartEncoded> = [\n {\n type: \"tool-call\",\n id: durableResearchCallId,\n name: \"delegate_destination_research\",\n params: { destination: phase6ResearchDestination, focus: \"museums\" },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst coordinatorShortlistParts: ReadonlyArray<Response.StreamPartEncoded> = [\n { type: \"text-start\", id: \"shortlist\" },\n {\n type: \"text-delta\",\n id: \"shortlist\",\n delta: JSON.stringify(\n Schema.encodeSync(DestinationShortlist)(durableResearchShortlist(phase6ResearchDestination)),\n ),\n },\n { type: \"text-end\", id: \"shortlist\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\nconst researcherLookupParts: ReadonlyArray<Response.StreamPartEncoded> = [\n {\n type: \"tool-call\",\n id: phase6ChildLookupCallId,\n name: \"lookup_destination\",\n params: { destination: phase6ResearchDestination },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst researcherReportParts: ReadonlyArray<Response.StreamPartEncoded> = [\n { type: \"text-start\", id: \"destination-report\" },\n {\n type: \"text-delta\",\n id: \"destination-report\",\n delta: encodedDestinationReport(phase6ResearchDestination),\n },\n { type: \"text-end\", id: \"destination-report\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\n/** Prompt-aware S2 coordinator: delegation call first, shortlist once it is history. */\nexport const phase6CoordinatorModel = promptAwareModel(\"travel-coordinator-p6\", (promptJson) =>\n promptJson.includes(durableResearchCallId)\n ? Stream.fromIterable(coordinatorShortlistParts)\n : Stream.fromIterable(coordinatorDelegationParts),\n);\n\nlet researcherGateReleased = false;\n\n/** Allow the researcher's FIRST model response to proceed (sticky across incarnations). */\nexport const releasePhase6ResearcherGate = (): void => {\n researcherGateReleased = true;\n};\n\n/** Re-close the researcher gate (each delegation scenario starts gated). */\nexport const resetPhase6ResearcherGate = (): void => {\n researcherGateReleased = false;\n};\n\nconst awaitResearcherGate: Effect.Effect<void> = Effect.gen(function* () {\n while (!researcherGateReleased) {\n yield* Effect.sleep(Duration.millis(10));\n }\n});\n\n/**\n * Prompt-aware S2 researcher: guide lookup first, report once it is history. The FIRST\n * response waits on the researcher gate — a stand-in for real model latency. The child's own\n * Object may legally start its Attempt the moment its routed admission commits, while the\n * parent is still appending the lineage record into the child's log; a child whose first\n * batch commits during that window races the parent's append on one tail. Real models answer\n * in seconds, so establishment always wins that race in production; the gate reproduces that\n * timing deterministically instead of relying on scheduler luck.\n */\nexport const phase6ResearcherModel = promptAwareModel(\"destination-researcher-p6\", (promptJson) =>\n promptJson.includes(phase6ChildLookupCallId)\n ? Stream.fromIterable(researcherReportParts)\n : Stream.fromEffectDrain(awaitResearcherGate).pipe(\n Stream.concat(Stream.fromIterable(researcherLookupParts)),\n ),\n);\n\n// ---------------------------------------------------------------------------\n// Worker Binding registrations for the DC Conversation Object\n// ---------------------------------------------------------------------------\n\n/**\n * Every phase-6 Travel Planner worker Binding, captured with its requirement Contexts\n * (spec/subagents.md §11): the P4 planner and its gated twin, the P5 booking agent over the\n * shared supplier desk, and the S2 coordinator/researcher pair wired through the durable\n * delegation Layer. A Conversation Object registers these via its `bindings` option; the\n * capture runs once per incarnation, and everything stateful the assertions rely on (desk,\n * guide counter, gates) lives at module level so it survives incarnation loss.\n */\nexport const makePhase6TravelPlannerBindings: Effect.Effect<ReadonlyArray<ResolvedBinding>> =\n Effect.gen(function* () {\n const planner: ResolvedBinding = yield* DurableWorkerBinding.make(\n Agent.withModel(TravelPlannerPhase4, phase6PlannerModel),\n phase4TravelPlannerDefinitionDigests,\n ).pipe(Effect.provide(phase4TravelPlannerWorkerLayer));\n\n const gatedPlanner: ResolvedBinding = yield* DurableWorkerBinding.make(\n Agent.withModel(TravelPlannerPhase4, phase6GatedPlannerModel),\n phase6GatedPlannerDefinitionDigests,\n ).pipe(Effect.provide(phase4TravelPlannerWorkerLayer));\n\n const booking: ResolvedBinding = yield* DurableWorkerBinding.make(\n Agent.withModel(TravelPlannerPhase5, phase6BookingModel),\n phase5TravelPlannerDefinitionDigests,\n ).pipe(\n Effect.provide(\n phase5TravelPlannerWorkerLayer.pipe(Layer.provideMerge(phase6SupplierDeskLayer)),\n ),\n );\n\n const researcherBinding = Agent.withModel(DestinationResearcher, phase6ResearcherModel);\n const childToolkitLayer = DestinationResearcherToolkitLayer.pipe(\n Layer.provideMerge(countingGuideLayer),\n );\n\n const coordinator: ResolvedBinding = yield* DurableWorkerBinding.make(\n Agent.withModel(TravelCoordinator, phase6CoordinatorModel),\n s2CoordinatorDigests,\n ).pipe(\n Effect.provide(\n durableDestinationResearchHandlersLayer(researcherBinding).pipe(\n Layer.provide(\n Layer.mergeAll(\n childToolkitLayer,\n SubagentReservationsMemoryLive,\n DeterministicIdGeneratorLayer,\n ResearchDispatchGate.layerOpen,\n ),\n ),\n ),\n ),\n );\n\n const researcher: ResolvedBinding = yield* DurableWorkerBinding.make(\n researcherBinding,\n s2ResearcherDigests,\n ).pipe(Effect.provide(childToolkitLayer));\n\n return [planner, gatedPlanner, booking, coordinator, researcher];\n });\n\n// ---------------------------------------------------------------------------\n// The committed golden normalized-evidence fixture (D-P6-6)\n// ---------------------------------------------------------------------------\n\n/**\n * The committed cross-platform normalized canonical evidence of ONE uninterrupted Travel\n * Planner planning Submission (the P1/P4 happy path: canonical input, the search Turn, three\n * Tool settlements, the plan Turn, one Settlement). `travel-planner-phase6.test.ts` asserts\n * the DN run equals this value and `travel-planner-dc.test.ts` asserts the DC run equals this\n * value, so the two platforms' canonical outcomes are byte-equivalent transitively — the P6\n * exit gate \"Travel Planner produces equivalent canonical outcomes under DN and DC\".\n *\n * Regenerate ONLY when the Travel Planner scenario itself changes, by printing either suite's\n * normalized value; both suites must then agree on the new golden.\n */\nexport const phase6TravelPlannerGoldenEvidence: Schema.Json = [\n {\n batchId: \"conversation-created:{conversationId}\",\n sequence: 1,\n record: {\n recordId: \"conversation-created:{conversationId}\",\n family: \"conversation\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ConversationCreated\",\n agentId: \"travel-planner-phase-4\",\n definitions: {\n agent: \"{digest}\",\n model: \"{digest}\",\n tools: \"{digest}\",\n },\n },\n },\n },\n {\n batchId: \"submission-input:{submissionId}\",\n sequence: 2,\n record: {\n recordId: \"input:{submissionId}\",\n family: \"conversation\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"UserInputRecorded\",\n submissionId: \"{submissionId}\",\n kind: \"user\",\n runId: \"run:{submissionId}\",\n input: {\n request:\n \"Plan a review-only London trip using the deterministic flight, lodging, and activity searches.\",\n origin: \"SFO\",\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n nights: 4,\n travelers: 2,\n budgetCents: 350000,\n currency: \"USD\",\n },\n },\n },\n },\n {\n batchId: \"turn-response:run:{submissionId}:1\",\n sequence: 3,\n record: {\n recordId: \"model-response:run:{submissionId}:1\",\n family: \"conversation\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ModelResponseRecorded\",\n runId: \"run:{submissionId}\",\n turnId: \"turn:run:{submissionId}:1\",\n turn: 1,\n messages: {\n content: [\n {\n options: {},\n role: \"system\",\n content:\n 'You are the Effect Agent Travel Planner P1 interpreter fixture.\\nThe user asked: Plan a review-only London trip using the deterministic flight, lodging, and activity searches.\\nCall search_flights, search_lodging, and search_activities exactly once in one Tool batch.\\nThen return only a JSON object of exactly this shape, no prose:\\n{\"itineraries\": [{\"title\": \"<short itinerary name>\", \"route\": \"<origin-destination>\", \"dates\": \"<date range>\", \"flight\": \"<flight description from the Tool result>\", \"lodging\": \"<lodging description from the Tool result>\", \"activities\": [\"<activity>\", \"...\"], \"estimatedTotalCents\": <positive integer total in cents>, \"currency\": \"USD\", \"quoteId\": \"<quoteId from the flight Tool result>\", \"assumptions\": [\"<assumption>\", \"...\"], \"unresolvedConstraints\": [], \"nextAction\": \"review\"}]}\\nUse the Tool results verbatim; activity results may legitimately be an empty array.\\nThis is read-only planning. Require review before any mutation.',\n },\n {\n options: {},\n role: \"user\",\n content:\n '{\"request\":\"Plan a review-only London trip using the deterministic flight, lodging, and activity searches.\",\"origin\":\"SFO\",\"destination\":\"LHR\",\"departOn\":\"2026-09-14\",\"nights\":4,\"travelers\":2,\"budgetCents\":350000,\"currency\":\"USD\"}',\n },\n {\n options: {},\n role: \"assistant\",\n content: [\n {\n options: {},\n type: \"tool-call\",\n id: \"flight-call-1\",\n name: \"search_flights\",\n params: {\n origin: \"SFO\",\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n travelers: 2,\n },\n providerExecuted: false,\n },\n {\n options: {},\n type: \"tool-call\",\n id: \"lodging-call-1\",\n name: \"search_lodging\",\n params: {\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n nights: 4,\n travelers: 2,\n },\n providerExecuted: false,\n },\n {\n options: {},\n type: \"tool-call\",\n id: \"activity-call-1\",\n name: \"search_activities\",\n params: {\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n nights: 4,\n travelers: 2,\n },\n providerExecuted: false,\n },\n ],\n },\n ],\n },\n messagesDigest: \"{digest}\",\n },\n },\n },\n {\n batchId: \"turn-results:run:{submissionId}:1\",\n sequence: 4,\n record: {\n recordId: \"tool-settled:run:{submissionId}:1:flight-call-1\",\n family: \"conversation\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ToolCallSettled\",\n runId: \"run:{submissionId}\",\n toolCallId: \"flight-call-1\",\n toolName: \"search_flights\",\n result: {\n quoteId: \"quote-sfo-lhr-001\",\n flight: \"EA 218 · nonstop · SFO 18:40 → LHR 13:05+1\",\n estimatedCents: 180000,\n currency: \"USD\",\n },\n isFailure: false,\n },\n },\n },\n {\n batchId: \"turn-results:run:{submissionId}:1\",\n sequence: 5,\n record: {\n recordId: \"tool-settled:run:{submissionId}:1:lodging-call-1\",\n family: \"conversation\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ToolCallSettled\",\n runId: \"run:{submissionId}\",\n toolCallId: \"lodging-call-1\",\n toolName: \"search_lodging\",\n result: {\n lodging: \"Bloomsbury House · refundable studio · 4 nights\",\n estimatedCents: 104000,\n currency: \"USD\",\n },\n isFailure: false,\n },\n },\n },\n {\n batchId: \"turn-results:run:{submissionId}:1\",\n sequence: 6,\n record: {\n recordId: \"tool-settled:run:{submissionId}:1:activity-call-1\",\n family: \"conversation\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ToolCallSettled\",\n runId: \"run:{submissionId}\",\n toolCallId: \"activity-call-1\",\n toolName: \"search_activities\",\n result: {\n activities: [\"British Museum timed entry\", \"Thames evening walk\"],\n },\n isFailure: false,\n },\n },\n },\n {\n batchId: \"turn:run:{submissionId}:2\",\n sequence: 7,\n record: {\n recordId: \"model-response:run:{submissionId}:2\",\n family: \"conversation\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ModelResponseRecorded\",\n runId: \"run:{submissionId}\",\n turnId: \"turn:run:{submissionId}:2\",\n turn: 2,\n messages: {\n content: [\n {\n options: {},\n role: \"assistant\",\n content:\n '{\"itineraries\":[{\"title\":\"Westward light, eastbound overnight\",\"route\":\"San Francisco → London\",\"dates\":\"14–19 September 2026\",\"flight\":\"EA 218 · nonstop · SFO 18:40 → LHR 13:05+1\",\"lodging\":\"Bloomsbury House · refundable studio · 4 nights\",\"activities\":[\"British Museum timed entry\",\"Thames evening walk\"],\"estimatedTotalCents\":284000,\"currency\":\"USD\",\"quoteId\":\"quote-sfo-lhr-001\",\"assumptions\":[\"Two travelers sharing one studio\",\"Quote is read-only availability, not a reservation\"],\"unresolvedConstraints\":[\"Traveler names and accessibility requests are intentionally omitted\"],\"nextAction\":\"review\"}]}',\n },\n ],\n },\n messagesDigest: \"{digest}\",\n },\n },\n },\n {\n batchId: \"submission-settlement:{submissionId}\",\n sequence: 8,\n record: {\n recordId: \"settlement:{submissionId}\",\n family: \"conversation\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"SubmissionSettled\",\n submissionId: \"{submissionId}\",\n settlementId: \"settlement:{submissionId}\",\n receiptId: \"{receiptId}\",\n outcome: \"completed\",\n runId: \"run:{submissionId}\",\n result: {\n itineraries: [\n {\n title: \"Westward light, eastbound overnight\",\n route: \"San Francisco → London\",\n dates: \"14–19 September 2026\",\n flight: \"EA 218 · nonstop · SFO 18:40 → LHR 13:05+1\",\n lodging: \"Bloomsbury House · refundable studio · 4 nights\",\n activities: [\"British Museum timed entry\", \"Thames evening walk\"],\n estimatedTotalCents: 284000,\n currency: \"USD\",\n quoteId: \"quote-sfo-lhr-001\",\n assumptions: [\n \"Two travelers sharing one studio\",\n \"Quote is read-only availability, not a reservation\",\n ],\n unresolvedConstraints: [\n \"Traveler names and accessibility requests are intentionally omitted\",\n ],\n nextAction: \"review\",\n },\n ],\n },\n },\n },\n },\n];\n","import { Schema } from \"effect\";\n\n// ---------------------------------------------------------------------------\n// Phase 7 (P7): the Travel Planner as an INTERNAL agent with two explicit\n// profiles (ROADMAP P7 exit gate: \"Travel Planner ... retains a deterministic\n// offline conformance profile alongside its live integration profiles\").\n//\n// - The OFFLINE profile is the cumulative P1–P6/S1/S2 suite set that already\n// exists: scripted `LanguageModel`, deterministic supplier Layers,\n// controllable time and IDs, no network, no credentials. Nothing in P7\n// weakens it; this module only pins the claim as a Schema value so evidence\n// can cite one committed fact instead of prose.\n// - The LIVE profile is opt-in and test-side: a suite gates itself with\n// `describe.skipIf(...)` on the environment predicate below, so ordinary\n// `bun run test` never makes a network request and never needs a credential.\n// Live profiles bind live MODEL Layers only. No real travel supplier exists\n// to integrate, so the deterministic supplier desk is retained deliberately\n// and `liveSupplierLayers` is pinned `false` — the roadmap's \"selected\n// supplier Layers\" is honestly scoped to live-model-only (P7 plan decision\n// 9), recorded here rather than silently claimed.\n// ---------------------------------------------------------------------------\n\n/**\n * The P7 dual-profile claim, schema-first so the exact scope of \"live\n * integration profiles\" is a committed, decodable value:\n *\n * - `offlineConformanceDeterministic` / `offlineRequiresCredentials`: the\n * cumulative conformance suites stay deterministic and credential-free.\n * - `liveProfileOptIn`: live suites are excluded from ordinary gates by the\n * environment predicate (`phase7LiveProfileEnabled`), never by test-runner\n * configuration that could silently drift.\n * - `liveModelLayers` / `liveSupplierLayers`: live profiles exercise real\n * model Layers over the SAME deterministic supplier desk — no claim of a\n * live supplier integration is made anywhere (decision 9).\n * - `structurallyRedactedTranscripts`: transcript evidence a live profile\n * emits passes through the structural `Redactor` first (SEC-008,\n * testing.md §12: \"live model and supplier profiles are opt-in smoke or\n * release tests, rate-limited and structurally redacted\").\n * - `exactlyOnceExternalEffects`: never claimed at any phase (DUR-003).\n */\nexport class TravelPlannerPhase7Profile extends Schema.Class<TravelPlannerPhase7Profile>(\n \"@effect-agent/testing/travel-planner/TravelPlannerPhase7Profile\",\n)({\n phase: Schema.Literal(\"P7\"),\n offlineConformanceDeterministic: Schema.Literal(true),\n offlineRequiresCredentials: Schema.Literal(false),\n liveProfileOptIn: Schema.Literal(true),\n liveModelLayers: Schema.Literal(true),\n liveSupplierLayers: Schema.Literal(false),\n structurallyRedactedTranscripts: Schema.Literal(true),\n exactlyOnceExternalEffects: Schema.Literal(false),\n}) {}\n\nexport const phase7TravelPlannerProfile = TravelPlannerPhase7Profile.make({\n phase: \"P7\",\n offlineConformanceDeterministic: true,\n offlineRequiresCredentials: false,\n liveProfileOptIn: true,\n liveModelLayers: true,\n liveSupplierLayers: false,\n structurallyRedactedTranscripts: true,\n exactlyOnceExternalEffects: false,\n});\n\n/**\n * The one opt-in switch for EVERY live profile in this repository. `\"1\"` is\n * the only enabling value: an unset, empty, or differently-truthy value keeps\n * the suite skipped, so CI and ordinary developer runs stay offline.\n */\nexport const PHASE7_LIVE_GATE_ENV = \"EFFECT_AGENT_LIVE\";\n\n/** The credential a Travel Planner live-model profile additionally requires. */\nexport const PHASE7_LIVE_CREDENTIAL_ENV = \"OPENAI_API_KEY\";\n\n/** Structural shape of `process.env` without importing Node types here. */\nexport interface Phase7LiveGateEnvironment {\n readonly [name: string]: string | undefined;\n}\n\n/**\n * The test-side live gate (P7 plan §6: no test-side live-gating pattern\n * existed before this — the demo gates at serve time via\n * `Config.redacted(\"OPENAI_API_KEY\")`). Suites use it as\n * `describe.skipIf(!phase7LiveProfileEnabled(process.env))`, which keeps the\n * live block out of ordinary gates while the SAME file's ungated tests keep\n * pinning the profile schema on every run.\n */\nexport const phase7LiveProfileEnabled = (env: Phase7LiveGateEnvironment): boolean =>\n env[PHASE7_LIVE_GATE_ENV] === \"1\" && (env[PHASE7_LIVE_CREDENTIAL_ENV] ?? \"\") !== \"\";\n\n// ---------------------------------------------------------------------------\n// Authoring friction note (WP7 input; real observations from wiring the P7\n// live profile onto the existing Travel Planner):\n//\n// 1. There was no framework-owned place to put a test-side live gate: every\n// earlier profile was either always-deterministic or gated at serve time\n// inside an application. The predicate had to be invented here as a plain\n// exported function because `packages/testing/src` must stay\n// platform-neutral and cannot read `process.env` itself — fine, but the\n// split (fixture exports the predicate, the example test applies it to\n// `process.env`) is a convention a future author has to discover by\n// reading this file rather than a typed seam.\n// 2. Capturing a structurally redacted transcript from a live Run takes\n// manual assembly: collect `RunEvent`s, `Schema.encode` each one, pass the\n// encoded value through `Redactor.redact`. Nothing composes those three\n// steps, and nothing type-level stops a test from logging the RAW event by\n// accident. A `redactedTranscript(events)` helper in capabilities (or an\n// engine stream combinator) would make the safe path the short path.\n// 3. Binding a live model to the existing definition was pleasantly trivial\n// (`Agent.withModel` + the upstream client Layer): no friction to report\n// on the authoring surface itself for plain ephemeral runs.\n// ---------------------------------------------------------------------------\n"],"mappings":";;;;;;;;;;;AAmJA,MAAa,0BAAgE;CAC3E;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;AAYA,MAAa,4BAA4E;CACvF;CACA;CACA;AACF;;AAGA,MAAa,4BACX,UACmD;CACnD,MAAM,wBAAQ,IAAI,IAAqC;CACvD,KAAK,MAAM,OAAO,OAChB,IAAI,IAAI,gBAAgB,MAAM,IAAI,IAAI,QAAQ;CAEhD,OAAO,gCAAgC,SAAS,QAAQ,aAAa,CAAC,MAAM,IAAI,QAAQ,CAAC,CAAC,CAAC,KAAK;AAClG;AAMA,MAAM,QAAQ,OAAO,WAAW,MAAM,CAAC,CAAC,IAAI,OAAO,EAAE,CAAC;AACtD,MAAM,UAAU,kBAAkB,KAAK;CAAE,OAAO;CAAO,OAAO;CAAO,OAAO;AAAM,CAAC;AACnF,MAAM,uBAAuB;CAC3B,OAAO,IAAI,OAAO,EAAE;CACpB,OAA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AAM;IACN,cAAc;IACd,cAAc;IACd,WAAW;IACX,SAAS;IACT,OAAO;IACP,QAAQ,EACN,aAAa,CACX;KACE,OAAO;KACP,OAAO;KACP,OAAO;KACP,QAAQ;KACR,SAAS;KACT,YAAY,CAAC,8BAA8B,qBAAqB;KAChE,qBAAqB;KACrB,UAAU;KACV,SAAS;KACT,aAAa,CACX,oCACA,oDACF;KACA,uBAAuB,CACrB,qEACF;KACA,YAAY;IACd,CACF,EACF;GACF;EACF;CACF;AACF;;;;;;;;;;;;;;;;;;;;;ACl3BA,IAAa,6BAAb,cAAgD,OAAO,MACrD,iEACF,CAAC,CAAC;CACA,OAAO,OAAO,QAAQ,IAAI;CAC1B,iCAAiC,OAAO,QAAQ,IAAI;CACpD,4BAA4B,OAAO,QAAQ,KAAK;CAChD,kBAAkB,OAAO,QAAQ,IAAI;CACrC,iBAAiB,OAAO,QAAQ,IAAI;CACpC,oBAAoB,OAAO,QAAQ,KAAK;CACxC,iCAAiC,OAAO,QAAQ,IAAI;CACpD,4BAA4B,OAAO,QAAQ,KAAK;AAClD,CAAC,CAAC,CAAC,CAAC;AAEJ,MAAa,6BAA6B,2BAA2B,KAAK;CACxE,OAAO;CACP,iCAAiC;CACjC,4BAA4B;CAC5B,kBAAkB;CAClB,iBAAiB;CACjB,oBAAoB;CACpB,iCAAiC;CACjC,4BAA4B;AAC9B,CAAC;;;;;;AAOD,MAAa,uBAAuB;;AAGpC,MAAa,6BAA6B;;;;;;;;;AAe1C,MAAa,4BAA4B,QACvC,IAAA,yBAA8B,QAAQ,IAAA,qBAAmC,QAAQ"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["decodeConversationId","decodeIdempotencyKey","decodeToolCallId","usage","finalParts","toolCallPart","toolTurn","policy","plainDefinition","Itinerary","BookApproval","approvalDefinition","childDefinition","coordinatorDefinition","delegationSupport","usage","Itinerary","digestOf","scriptedUsage","digest","digest","decodeComparableJson","scriptedUsage","researcherLookupParts","researcherReportParts","digestOf","scriptedUsage","researcherLookupParts","researcherReportParts"],"sources":["../src/certification.ts","../src/chaos.ts","../src/code-executor-conformance.ts","../src/code-executor-substitute.ts","../src/fixtures/docs-researcher/definition.ts","../src/fixtures/travel-planner/definition.ts","../src/fixtures/travel-planner/deterministic-layers.ts","../src/fixtures/docs-researcher/mcp.ts","../src/fixtures/docs-researcher/harness.ts","../src/fixtures/travel-planner/phase2.ts","../src/fixtures/travel-planner/scenarios.ts","../src/fixtures/travel-planner/phase3.ts","../src/scripted-model.ts","../src/fixtures/travel-planner/phase4.ts","../src/fixtures/travel-planner/phase5.ts","../src/fixtures/travel-planner/subagents.ts","../src/fixtures/travel-planner/subagents-durable.ts","../src/fixtures/travel-planner/phase6.ts","../src/fixtures/travel-planner/phase7.ts"],"sourcesContent":["import {\n Subagent,\n SubagentPolicy,\n SubagentReservationsMemoryLive,\n SubagentRuntime,\n} from \"@effect-agent/capabilities\";\nimport {\n Agent,\n AgentPolicy,\n ConversationId,\n IdGenerator,\n RunId,\n ToolCallId,\n TurnId,\n type AgentId,\n type SubmissionId,\n} from \"@effect-agent/core\";\nimport { DurableStep, DurableStepError } from \"@effect-agent/engine\";\nimport {\n AgentBindingResolver,\n ApprovalDecisionCommand,\n CertificationCaseResult,\n CertificationReport,\n CertificationSweepResult,\n CertificationTierThreeReport,\n CertifiedAdapterIdentity,\n ConversationExportRequest,\n ConversationStore,\n DefinitionDigests,\n DeploymentId,\n Digest,\n DurableAgentRuntime,\n DurableRuntimeConfig,\n DurableRuntimeFailpoint,\n DurableRuntimeFailpointError,\n DurableRuntimeFailpointLocation,\n DurableRuntimeFailpointTestControl,\n DurableWorkerBinding,\n IdempotencyKey,\n LoadCheckpointRequest,\n Principal,\n ProducerId,\n ResolutionSafeToRetry,\n SubmissionLedger,\n SubmissionLookupById,\n ToolReconciler,\n UnknownResolutionCommand,\n WakeScheduler,\n DEFAULT_OWNERSHIP_LEASE_DURATION,\n certifyPorts,\n childConversationIdFor,\n verifyConversationInvariants,\n type BatchId,\n type CertificationScenario,\n type DurableSubmitFailure,\n type DurableSubmitOptions,\n type Receipt,\n type ResolvedBinding,\n type SubmissionSnapshot,\n} from \"@effect-agent/session\";\nimport {\n Cause,\n Clock,\n Crypto,\n DateTime,\n Duration,\n Effect,\n Exit,\n Layer,\n Option,\n Ref,\n Schema,\n Stream,\n} from \"effect\";\nimport { TestClock } from \"effect/testing\";\nimport { LanguageModel, Model, Tool, Toolkit, type Response } from \"effect/unstable/ai\";\n\n/**\n * P7 WP2 — `certifyDurableAdapters` (plan §1): the one certification entry point a durable\n * adapter pair runs to earn a Schema-encoded certificate.\n *\n * - **Tier 1 — port contract**: the two shared conformance case arrays, verbatim, through\n * `certifyPorts` (TEST-004/STORE-010).\n * - **Tier 2 — coordinator protocol + failpoint convergence**: the durable coordinator is\n * assembled over the CANDIDATE Layer pair with a scripted deterministic model; every\n * `DurableRuntimeFailpointLocation` is armed one-shot across the six scenario shapes\n * (plain / uncertain-tool / durable-steps / approval / join / delegation). After the injected\n * fault the runner asserts the state stays CLASSIFIABLE (recovery + the public unblocking\n * operations `resolveUnknown`/`resolveApproval` are the only levers used) and that the\n * re-drive CONVERGES to `verifyConversationInvariants` with `requireAllSettled` — including a\n * fully discharged digest-chain check, because the runner captures per-batch producer\n * identity at append time.\n * - **Tier 3 — real loss lever**: recorded honestly. A durable adapter either supplies a\n * `CertificationCrashLever` executed in this run, cites its committed real-loss evidence\n * (process-kill / eviction suites), or the certificate says `not-exercised`. A non-durable\n * reference adapter records `not-applicable`.\n *\n * The runner is adapter-neutral and platform-neutral: it imports nothing Node-only, so the\n * same entry point runs under `@effect/vitest` on Node and inside workerd (storage-cloudflare's\n * in-workerd runner). It must run under a TestClock (Tier 1 drives lease expiry through\n * virtual time), and requires only `Crypto.Crypto` from the environment.\n */\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * A real-loss lever supplied by an adapter that wants Tier 3 exercised IN this certification\n * run (kill/evict/reopen around a designated row subset). Rows report with\n * `suite: \"real-loss\"`. Failures must be captured per-row — the lever's error channel is\n * `never` so a certificate is always produced.\n */\nexport type CertificationCrashLever = Effect.Effect<ReadonlyArray<CertificationCaseResult>>;\n\nexport interface CertifyDurableAdaptersOptions<LedgerE = never, StoreE = never> {\n /** Adapter pair identity named by the certificate (durability is read from the ledger). */\n readonly adapter: {\n readonly name: string;\n readonly version?: string | undefined;\n };\n /**\n * The candidate Layer pair. When both ports must share one connection root (the ADR-0011\n * \"same file\" rule), pass the SAME combined Layer instance for both fields — Layer\n * memoization builds it once. A candidate may require `Crypto.Crypto` (the memory reference\n * does); the certification's own environment supplies nothing else.\n */\n readonly submissionLedger: Layer.Layer<SubmissionLedger, LedgerE, Crypto.Crypto>;\n readonly conversationStore: Layer.Layer<ConversationStore, StoreE, Crypto.Crypto>;\n /** Defaults to `WakeScheduler.layerNoop`; the runner re-drives lanes explicitly. */\n readonly wakeScheduler?: Layer.Layer<WakeScheduler> | undefined;\n /** Executes Tier 3 in this run; takes precedence over `tierThreeEvidence`. */\n readonly crashLever?: CertificationCrashLever | undefined;\n /** Repository-relative citations of committed real-loss suites (Tier 3 `recorded-evidence`). */\n readonly tierThreeEvidence?: ReadonlyArray<string> | undefined;\n /**\n * The candidate ledger's configured ownership lease (defaults to the D5 default, 30s).\n * Every Tier-2 re-drive round advances the TestClock past this lease before reclaiming:\n * a live lease may block ALL new claims (the SQL adapters do; the memory reference also\n * allows same-producer reclaim), so the adapter-NEUTRAL recovery lever after a mid-Attempt\n * fault is lease expiry — exactly the documented D5 liveness mechanism, driven through\n * virtual time.\n */\n readonly ownershipLeaseDuration?: Duration.Duration | undefined;\n}\n\n/** The six Tier-2 scenario shapes in sweep order. */\nexport const CERTIFICATION_SCENARIOS: ReadonlyArray<CertificationScenario> = [\n \"plain\",\n \"uncertain-tool\",\n \"durable-steps\",\n \"approval\",\n \"join\",\n \"delegation\",\n];\n\n/**\n * Coordinator failpoint locations that none of the six scenario shapes can reach, recorded\n * honestly instead of silently claimed: all three sit on operator/abort paths the shapes do\n * not take. They are pinned in-process by the P5/S2 suites\n * (`packages/testing/test/durable-tools.test.ts` \"resolveUnknown is idempotent across the\n * intent failpoint\", `durable-runtime.test.ts` abort rows,\n * `durable-subagents.test.ts` abort propagation) and by the process-kill/eviction crash\n * matrices. Runner tests assert the observed never-fired set equals EXACTLY this list, so a\n * protocol change that silently stops exercising a location fails the certification.\n */\nexport const TIER2_UNREACHED_LOCATIONS: ReadonlyArray<DurableRuntimeFailpointLocation> = [\n \"abort:after-intent\",\n // Compaction requires a `contextTokenLimit` policy plus prior-Run history\n // none of the six scenario shapes carries; pinned in-process by the\n // RUN-026 rows in `packages/testing/test/durable-runtime.test.ts`\n // (compaction failpoint idempotence across re-drive).\n \"compaction:after-canonical-append\",\n \"resolve:after-intent\",\n \"subagent:after-child-abort-intent\",\n];\n\n/** Locations of `tier2` rows whose armed fault never fired in ANY scenario, sorted. */\nexport const tier2NeverFiredLocations = (\n tier2: ReadonlyArray<CertificationSweepResult>,\n): ReadonlyArray<DurableRuntimeFailpointLocation> => {\n const fired = new Set<DurableRuntimeFailpointLocation>();\n for (const row of tier2) {\n if (row.failpointFired) fired.add(row.location);\n }\n return DurableRuntimeFailpointLocation.literals.filter((location) => !fired.has(location)).sort();\n};\n\n// ---------------------------------------------------------------------------\n// Deterministic fixtures (scripted prompt-shape models, agents, delegation)\n// ---------------------------------------------------------------------------\n\nconst SHA_A = Schema.decodeSync(Digest)(\"a\".repeat(64));\nconst DIGESTS = DefinitionDigests.make({ agent: SHA_A, model: SHA_A, tools: SHA_A });\nconst CHILD_DIGEST_STRINGS = {\n agent: \"b\".repeat(64),\n model: \"c\".repeat(64),\n tools: \"d\".repeat(64),\n} as const;\nconst CHILD_DIGESTS = DefinitionDigests.make({\n agent: Schema.decodeSync(Digest)(CHILD_DIGEST_STRINGS.agent),\n model: Schema.decodeSync(Digest)(CHILD_DIGEST_STRINGS.model),\n tools: Schema.decodeSync(Digest)(CHILD_DIGEST_STRINGS.tools),\n});\nconst PRINCIPAL = Schema.decodeSync(Principal)(\"principal-certification\");\nconst decodeConversationId = Schema.decodeSync(ConversationId);\nconst decodeIdempotencyKey = Schema.decodeSync(IdempotencyKey);\nconst decodeToolCallId = Schema.decodeSync(ToolCallId);\n\nconst usage = { inputTokens: {}, outputTokens: {} };\n\nconst finalParts = (text: string): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"answer\" },\n { type: \"text-delta\", id: \"answer\", delta: text },\n { type: \"text-end\", id: \"answer\" },\n { type: \"finish\", reason: \"stop\", usage },\n];\n\nconst toolCallPart = (id: string, name: string, params: unknown): Response.StreamPartEncoded => ({\n type: \"tool-call\",\n id,\n name,\n params,\n providerExecuted: false,\n});\n\nconst toolTurn = (\n ...calls: ReadonlyArray<Response.StreamPartEncoded>\n): ReadonlyArray<Response.StreamPartEncoded> => [\n ...calls,\n { type: \"finish\", reason: \"tool-calls\", usage },\n];\n\n/**\n * Stateless scripted model that decides by PROMPT SHAPE instead of call count: while the\n * prompt carries no committed tool result the model declares `toolParts` (when given),\n * otherwise it answers with the final text. Deciding on the canonical prompt keeps every cell\n * deterministic regardless of where the injected fault fell — a re-invoked Turn re-declares\n * the same batch and a resumed batch flows into the final answer, so every scenario always\n * exercises its tool path and always converges.\n */\nconst promptShapeModel = (\n name: string,\n finalText: string,\n toolParts?: ReadonlyArray<Response.StreamPartEncoded>,\n) =>\n Model.make(\n \"scripted\",\n name,\n Layer.effect(\n LanguageModel.LanguageModel,\n LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (request) => {\n const hasToolResult = request.prompt.content.some((message) => message.role === \"tool\");\n const parts =\n toolParts === undefined || hasToolResult ? finalParts(finalText) : toolParts;\n return Stream.fromIterable(parts);\n },\n }),\n ),\n );\n\nconst policy = AgentPolicy.make({\n maxTurns: 4,\n maxToolCalls: 4,\n maxDuration: \"30 seconds\",\n toolConcurrency: 2,\n});\n\nconst QuestionInput = Schema.Struct({ question: Schema.String });\nconst AnswerOutput = Schema.Struct({ answer: Schema.String });\n\n/** plain / join: no tools — the pure Turn/submission/join seams. */\nconst plainDefinition = Agent.define(\"certify-plain\", {\n input: QuestionInput,\n output: AnswerOutput,\n instructions: \"Answer as JSON.\",\n toolkit: Toolkit.empty,\n policy,\n});\n\n/** uncertain-tool: unannotated → fail-closed `uncertain`, enters the prepared/settled protocol. */\nconst Book = Tool.make(\"book\", {\n parameters: Schema.Struct({ ref: Schema.String }),\n success: Schema.Struct({ confirmation: Schema.String }),\n});\nconst bookToolkit = Toolkit.make(Book);\nconst uncertainDefinition = Agent.define(\"certify-uncertain\", {\n input: QuestionInput,\n output: AnswerOutput,\n instructions: \"Book it.\",\n toolkit: bookToolkit,\n policy,\n});\n\n/** durable-steps: declaring `DurableStep` as a dependency is what makes the Tool durable. */\nconst Itinerary = Tool.make(\"itinerary\", {\n parameters: Schema.Struct({ ref: Schema.String }),\n success: Schema.Struct({ state: Schema.String }),\n failure: DurableStepError,\n dependencies: [DurableStep],\n});\nconst itineraryToolkit = Toolkit.make(Itinerary);\nconst stepsDefinition = Agent.define(\"certify-steps\", {\n input: QuestionInput,\n output: AnswerOutput,\n instructions: \"Reserve the itinerary.\",\n toolkit: itineraryToolkit,\n policy,\n});\n\n/** approval: fail-closed — no `DurableApprovalResolver` Layer, so undecided approvals suspend. */\nconst BookApproval = Tool.make(\"book\", {\n parameters: Schema.Struct({ ref: Schema.String }),\n success: Schema.Struct({ confirmation: Schema.String }),\n needsApproval: true,\n});\nconst approvalToolkit = Toolkit.make(BookApproval);\nconst approvalDefinition = Agent.define(\"certify-approval\", {\n input: QuestionInput,\n output: AnswerOutput,\n instructions: \"Book after approval.\",\n toolkit: approvalToolkit,\n policy,\n});\n\n/** delegation: durable attached child plus an ordinary uncertain sibling in ONE batch. */\nconst childDefinition = Agent.define(\"certify-child\", {\n input: QuestionInput,\n output: AnswerOutput,\n instructions: \"Answer as JSON.\",\n toolkit: Toolkit.empty,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 1,\n maxDuration: \"30 seconds\",\n toolConcurrency: 1,\n }),\n});\n\nclass CertifyDelegationFailed extends Schema.TaggedError<CertifyDelegationFailed>()(\n \"CertifyDelegationFailed\",\n { childErrorTag: Schema.String },\n) {}\n\nconst researchDelegation = Subagent.define(\"delegate_research\", {\n description: \"Research one bounded question and return findings.\",\n target: childDefinition,\n parameters: Schema.Struct({ topic: Schema.String }),\n success: Schema.Struct({ summary: Schema.String }),\n failure: CertifyDelegationFailed,\n prepareInput: ({ topic }) => Effect.succeed({ question: `research:${topic}` }),\n projectResult: (output) => Effect.succeed({ summary: `finding:${output.answer}` }),\n policy: SubagentPolicy.make({\n maxChildren: 2,\n maxConcurrency: 2,\n maxTurns: 4,\n maxToolCalls: 4,\n maxDuration: \"10 seconds\",\n }),\n});\n\nconst Lookup = Tool.make(\"lookup\", {\n parameters: Schema.Struct({ key: Schema.String }),\n success: Schema.Struct({ value: Schema.String }),\n});\n\nconst coordinatorDefinition = Agent.define(\"certify-coordinator\", {\n input: Schema.Struct({ mission: Schema.String }),\n output: Schema.Struct({ report: Schema.String }),\n instructions: \"Delegate and look up, then answer as JSON.\",\n toolkit: Toolkit.make(researchDelegation.tool, Lookup),\n policy: AgentPolicy.make({\n maxTurns: 4,\n maxToolCalls: 3,\n maxDuration: \"30 seconds\",\n toolConcurrency: 2,\n }),\n});\n\nconst mapChildFailure = (failure: { readonly _tag: string }) =>\n CertifyDelegationFailed.make({ childErrorTag: failure._tag });\n\nconst DELEGATE_CALL = decodeToolCallId(\"delegate-1\");\n\n/** Fixture-only identity source consumed by the delegation Layer's ephemeral capture. */\nconst identifiers = Layer.effect(\n IdGenerator,\n Effect.gen(function* () {\n const counter = yield* Ref.make(0);\n const next = <A>(decode: (value: string) => A, prefix: string) =>\n Ref.getAndUpdate(counter, (value) => value + 1).pipe(\n Effect.map((value) => decode(`${prefix}-${value}`)),\n );\n return {\n nextConversationId: next(decodeConversationId, \"certify-fixture-conversation\"),\n nextRunId: next(Schema.decodeSync(RunId), \"certify-fixture-run\"),\n nextTurnId: next(Schema.decodeSync(TurnId), \"certify-fixture-turn\"),\n };\n }),\n);\n\nconst delegationSupport = Layer.mergeAll(SubagentReservationsMemoryLive, identifiers);\n\n// ---------------------------------------------------------------------------\n// Tier 2 — scenario cells\n// ---------------------------------------------------------------------------\n\ninterface CertificationCell {\n readonly resolver: (typeof AgentBindingResolver)[\"Service\"];\n /** Idempotent submission batch — safe to replay verbatim after a submit-boundary fault. */\n readonly submit: Effect.Effect<ReadonlyArray<Receipt>, DurableSubmitFailure, DurableAgentRuntime>;\n /** All lanes of the cell in drive order, computed from the (possibly replayed) receipts. */\n readonly lanes: (receipts: ReadonlyArray<Receipt>) => ReadonlyArray<ConversationId>;\n}\n\nconst submitOptionsFor = (slug: string, conversationId: ConversationId): DurableSubmitOptions => ({\n conversationId,\n principal: PRINCIPAL,\n idempotencyKey: decodeIdempotencyKey(`certify-key-${slug}`),\n definitions: DIGESTS,\n});\n\n/** One single-agent cell: one lane, one Submission, one registered exact-digest binding. */\nconst makeSingleAgentCell = (\n definition: { readonly id: AgentId; readonly input: typeof QuestionInput },\n resolved: ResolvedBinding,\n slug: string,\n): CertificationCell => {\n const conversationId = decodeConversationId(`certify-${slug}`);\n const submit = Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n const receipt = yield* runtime.submit(\n { definition: { id: definition.id, input: definition.input } },\n { question: `certify ${slug}` },\n submitOptionsFor(slug, conversationId),\n );\n return [receipt];\n });\n return {\n resolver: AgentBindingResolver.fromBindings([resolved]),\n submit,\n lanes: () => [conversationId],\n };\n};\n\nconst makeCell = Effect.fn(\"Certification.makeCell\")(function* (\n scenario: CertificationScenario,\n slug: string,\n) {\n switch (scenario) {\n case \"plain\": {\n const binding = Agent.withModel(\n plainDefinition,\n promptShapeModel(\"certify-plain\", '{\"answer\":\"done\"}'),\n );\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS);\n return makeSingleAgentCell(plainDefinition, resolved, slug);\n }\n case \"uncertain-tool\": {\n const binding = Agent.withModel(\n uncertainDefinition,\n promptShapeModel(\n \"certify-uncertain\",\n '{\"answer\":\"booked\"}',\n toolTurn(toolCallPart(\"book-1\", \"book\", { ref: `r-${slug}` })),\n ),\n );\n const toolLayer = bookToolkit.toLayer({\n book: ({ ref }) => Effect.succeed({ confirmation: `confirmed-${ref}` }),\n });\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(\n Effect.provide(toolLayer),\n );\n return makeSingleAgentCell(uncertainDefinition, resolved, slug);\n }\n case \"durable-steps\": {\n const binding = Agent.withModel(\n stepsDefinition,\n promptShapeModel(\n \"certify-steps\",\n '{\"answer\":\"reserved\"}',\n toolTurn(toolCallPart(\"itinerary-1\", \"itinerary\", { ref: `trip-${slug}` })),\n ),\n );\n const toolLayer = itineraryToolkit.toLayer({\n itinerary: ({ ref }) =>\n Effect.gen(function* () {\n const step = yield* DurableStep;\n const flight = yield* step.do(\n \"reserve-flight\",\n Schema.String,\n Effect.succeed(`flight-${ref}`),\n );\n const lodging = yield* step.do(\n \"reserve-lodging\",\n Schema.String,\n Effect.succeed(`lodging-${ref}`),\n );\n return { state: `${flight}+${lodging}` };\n }),\n });\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(\n Effect.provide(toolLayer),\n );\n return makeSingleAgentCell(stepsDefinition, resolved, slug);\n }\n case \"approval\": {\n const binding = Agent.withModel(\n approvalDefinition,\n promptShapeModel(\n \"certify-approval\",\n '{\"answer\":\"approved\"}',\n toolTurn(toolCallPart(\"book-1\", \"book\", { ref: `r-${slug}` })),\n ),\n );\n const toolLayer = approvalToolkit.toLayer({\n book: ({ ref }) => Effect.succeed({ confirmation: `confirmed-${ref}` }),\n });\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(\n Effect.provide(toolLayer),\n );\n return makeSingleAgentCell(approvalDefinition, resolved, slug);\n }\n case \"join\": {\n const binding = Agent.withModel(\n plainDefinition,\n promptShapeModel(\"certify-join\", '{\"answer\":\"host answer\"}'),\n );\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS);\n const conversationId = decodeConversationId(`certify-${slug}`);\n const submitOne = (key: string, question: string) =>\n Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n return yield* runtime.submit(\n { definition: { id: plainDefinition.id, input: plainDefinition.input } },\n { question },\n {\n conversationId,\n principal: PRINCIPAL,\n idempotencyKey: decodeIdempotencyKey(key),\n definitions: DIGESTS,\n },\n );\n });\n const cell: CertificationCell = {\n resolver: AgentBindingResolver.fromBindings([resolved]),\n submit: Effect.gen(function* () {\n const host = yield* submitOne(`certify-key-${slug}-host`, \"host question\");\n const queued = yield* submitOne(`certify-key-${slug}-queued`, \"queued question\");\n return [host, queued];\n }),\n lanes: () => [conversationId],\n };\n return cell;\n }\n case \"delegation\": {\n const childBinding = Agent.withModel(\n childDefinition,\n promptShapeModel(\"certify-child\", '{\"answer\":\"child-answer\"}'),\n );\n const parentBinding = Agent.withModel(\n coordinatorDefinition,\n promptShapeModel(\n \"certify-parent\",\n '{\"report\":\"done\"}',\n toolTurn(\n toolCallPart(\"delegate-1\", \"delegate_research\", { topic: \"paris\" }),\n toolCallPart(\"lookup-1\", \"lookup\", { key: \"hotels\" }),\n ),\n ),\n );\n const delegationLayer = SubagentRuntime.layer(researchDelegation, childBinding, {\n mapChildFailure,\n durable: { targetDigests: CHILD_DIGEST_STRINGS },\n }).pipe(Layer.provide(delegationSupport));\n const lookupLayer = Toolkit.make(Lookup).toLayer({\n lookup: ({ key }) => Effect.succeed({ value: `found-${key}` }),\n });\n const parentResolved = yield* DurableWorkerBinding.make(parentBinding, DIGESTS).pipe(\n Effect.provide(Layer.mergeAll(delegationLayer, lookupLayer)),\n );\n const childResolved = yield* DurableWorkerBinding.make(childBinding, CHILD_DIGESTS);\n const conversationId = decodeConversationId(`certify-${slug}`);\n const cell: CertificationCell = {\n resolver: AgentBindingResolver.fromBindings([parentResolved, childResolved]),\n submit: Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n const receipt = yield* runtime.submit(\n { definition: { id: coordinatorDefinition.id, input: coordinatorDefinition.input } },\n { mission: \"plan\" },\n submitOptionsFor(slug, conversationId),\n );\n return [receipt];\n }),\n lanes: (receipts) => {\n const parent = receipts.at(0);\n return parent === undefined\n ? [conversationId]\n : [conversationId, childConversationIdFor(parent.submissionId, DELEGATE_CALL)];\n },\n };\n return cell;\n }\n }\n});\n\n/** Maximum recovery/drive/unblock rounds before a cell is reported non-convergent. */\nconst MAX_REDRIVE_ROUNDS = 8;\n\n/**\n * Verify one lane after convergence: canonical export + every lane Submission the ledger or\n * the log names (the same collection rule as the admin `verify` member), fed to the shared\n * invariant checker in convergence mode WITH the captured per-batch producer directory, so\n * the digest chain is fully recomputed instead of skipped.\n */\nconst verifyLane = Effect.fn(\"Certification.verifyLane\")(function* (\n lane: ConversationId,\n batchProducers: ReadonlyMap<BatchId, ProducerId>,\n) {\n const store = yield* ConversationStore;\n const ledger = yield* SubmissionLedger;\n const exported = yield* store.export(ConversationExportRequest.make({ conversationId: lane }));\n const rows = new Map<SubmissionId, SubmissionSnapshot>();\n const nonterminal = yield* Stream.runCollect(ledger.scanNonterminal);\n for (const submission of nonterminal) {\n if (submission.conversationId === lane) rows.set(submission.submissionId, submission);\n }\n const named = new Set<SubmissionId>();\n for (const envelope of exported.records) {\n const payload = envelope.record.payload;\n if (\n payload._tag === \"UserInputRecorded\" ||\n payload._tag === \"SubmissionSettled\" ||\n payload._tag === \"AbortRequested\"\n ) {\n named.add(payload.submissionId);\n }\n }\n for (const submissionId of named) {\n if (rows.has(submissionId)) continue;\n const found = yield* ledger.lookup(SubmissionLookupById.make({ submissionId }));\n if (Option.isSome(found) && found.value.conversationId === lane) {\n rows.set(submissionId, found.value);\n }\n }\n const checkpoint = yield* store.loadCheckpoint(\n LoadCheckpointRequest.make({ conversationId: lane }),\n );\n return yield* verifyConversationInvariants({\n export: exported,\n submissions: [...rows.values()],\n batchProducers,\n checkpoint: Option.getOrUndefined(checkpoint),\n requireAllSettled: true,\n });\n});\n\nconst failureTagOf = <E>(cause: Cause.Cause<E>): string => {\n const failure = Cause.findErrorOption(cause);\n if (Option.isSome(failure)) {\n const error: unknown = failure.value;\n if (typeof error === \"object\" && error !== null && \"_tag\" in error) {\n return String((error as { _tag: unknown })._tag);\n }\n return String(error).slice(0, 256);\n }\n return \"defect\";\n};\n\n/** One Tier-2 sweep cell: arm `location` one-shot, drive `scenario`, converge, verify. */\nconst runSweepCell = Effect.fn(\"Certification.runSweepCell\")(function* (\n scenario: CertificationScenario,\n location: DurableRuntimeFailpointLocation,\n batchProducers: ReadonlyMap<BatchId, ProducerId>,\n leaseAdvance: Duration.Duration,\n) {\n const runtime = yield* DurableAgentRuntime;\n const ledger = yield* SubmissionLedger;\n const control = yield* DurableRuntimeFailpointTestControl;\n const slug = `${scenario}-${location.replaceAll(\":\", \"-\")}`;\n\n const failed = (detail: string, fired: boolean): CertificationSweepResult =>\n CertificationSweepResult.make({\n scenario,\n location,\n failpointFired: fired,\n status: \"failed\",\n digestChainVerified: false,\n detail: detail.slice(0, 4_096),\n });\n\n const cell = yield* makeCell(scenario, slug);\n\n // One-shot arm: the fault fires at most once anywhere in the cell (initial drive OR a\n // re-drive round's public unblocking operation), modelling one crash at this boundary.\n const fired = yield* Ref.make(false);\n yield* control.setHandler((hit) =>\n hit !== location\n ? Effect.void\n : Ref.getAndSet(fired, true).pipe(\n Effect.flatMap((already) =>\n already\n ? Effect.void\n : Effect.fail(DurableRuntimeFailpointError.make({ location: hit })),\n ),\n ),\n );\n\n // Submissions are idempotent (DUR-001): one replay recovers a submit-boundary fault.\n let receipts: ReadonlyArray<Receipt>;\n const firstSubmit = yield* Effect.exit(cell.submit);\n if (Exit.isSuccess(firstSubmit)) {\n receipts = firstSubmit.value;\n } else {\n const secondSubmit = yield* Effect.exit(cell.submit);\n if (Exit.isFailure(secondSubmit)) {\n yield* control.clear;\n return failed(\n `submission replay did not recover: ${failureTagOf(secondSubmit.cause)}`,\n yield* Ref.get(fired),\n );\n }\n receipts = secondSubmit.value;\n }\n const lanes = cell.lanes(receipts);\n\n const driveLane = (lane: ConversationId) =>\n runtime\n .processConversationResolved(lane)\n .pipe(Effect.provideService(AgentBindingResolver, cell.resolver));\n\n const allSettled = Effect.gen(function* () {\n for (const receipt of receipts) {\n const snapshot = yield* ledger.lookup(\n SubmissionLookupById.make({ submissionId: receipt.submissionId }),\n );\n if (Option.isNone(snapshot) || snapshot.value.state !== \"settled\") return false;\n }\n return true;\n });\n\n // Re-drive to convergence using ONLY public operations: worker drives, recovery passes,\n // and the authorized DUR-017/approval unblocking paths chosen from `explainConversation`.\n let converged = false;\n for (let round = 0; round < MAX_REDRIVE_ROUNDS && !converged; round++) {\n // Expire any lease a faulted Attempt left behind (D5): virtual time is the\n // adapter-neutral reclaim lever — a live lease may block every new claim.\n yield* TestClock.adjust(leaseAdvance);\n yield* Effect.exit(runtime.runRecovery);\n for (const lane of lanes) {\n yield* Effect.exit(driveLane(lane));\n }\n for (const lane of lanes) {\n const explains = yield* Effect.exit(runtime.explainConversation(lane));\n if (Exit.isFailure(explains)) continue;\n for (const explanation of explains.value) {\n for (const unknown of explanation.evidence.unknownCalls) {\n if (unknown.resolved) continue;\n yield* Effect.exit(\n runtime.resolveUnknown(\n UnknownResolutionCommand.make({\n submissionId: explanation.submission.submissionId,\n toolCallId: unknown.toolCallId,\n author: \"certification-runner\",\n reason: `re-drive after injected fault at ${location}`,\n resolution: ResolutionSafeToRetry.make(),\n }),\n ),\n );\n }\n for (const pending of explanation.evidence.approvalsPending) {\n const decided = explanation.evidence.approvalDecisions.some(\n (decision) => decision.toolCallId === pending.toolCallId,\n );\n if (decided) continue;\n yield* Effect.exit(\n runtime.resolveApproval(\n ApprovalDecisionCommand.make({\n submissionId: explanation.submission.submissionId,\n toolCallId: pending.toolCallId,\n decision: \"approved\",\n resolver: \"certification-runner\",\n reason: `re-drive after injected fault at ${location}`,\n }),\n ),\n );\n }\n }\n }\n const settled = yield* Effect.exit(allSettled);\n converged = Exit.isSuccess(settled) && settled.value;\n }\n yield* control.clear;\n const wasFired = yield* Ref.get(fired);\n\n if (!converged) {\n return failed(`did not converge within ${MAX_REDRIVE_ROUNDS} re-drive rounds`, wasFired);\n }\n\n // Every lane of the cell must verify in convergence mode with a recomputed digest chain.\n let digestChainVerified = true;\n const failedChecks: Array<string> = [];\n for (const lane of lanes) {\n const verdict = yield* Effect.exit(verifyLane(lane, batchProducers));\n if (Exit.isFailure(verdict)) {\n return failed(`lane ${lane} could not be verified: ${failureTagOf(verdict.cause)}`, wasFired);\n }\n for (const check of verdict.value.checks) {\n if (check.status === \"failed\") {\n failedChecks.push(\n `${lane}:${check.name}${check.detail === undefined ? \"\" : ` (${check.detail})`}`,\n );\n }\n if (check.name === \"digest-chain\" && check.status !== \"passed\") {\n digestChainVerified = false;\n }\n }\n }\n if (failedChecks.length > 0 || !digestChainVerified) {\n return failed(\n failedChecks.length > 0\n ? `invariant checks failed: ${failedChecks.join(\"; \")}`\n : \"the digest chain was not fully recomputed\",\n wasFired,\n );\n }\n\n return CertificationSweepResult.make({\n scenario,\n location,\n failpointFired: wasFired,\n status: wasFired ? \"converged\" : \"not-triggered\",\n digestChainVerified,\n });\n});\n\n// ---------------------------------------------------------------------------\n// Tier 3 — real loss lever record\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the Tier-3 record honestly (plan §1): a non-durable reference adapter has no real\n * loss to exercise (`not-applicable`); a supplied lever runs NOW (`exercised`); committed\n * real-loss citations are recorded (`recorded-evidence`); otherwise the certificate says\n * `not-exercised` — a scoped statement, never a silent claim.\n */\nexport const resolveTierThree = Effect.fn(\"Certification.resolveTierThree\")(function* (\n durability: CertifiedAdapterIdentity[\"durability\"],\n options: {\n readonly crashLever?: CertificationCrashLever | undefined;\n readonly tierThreeEvidence?: ReadonlyArray<string> | undefined;\n },\n): Effect.fn.Return<CertificationTierThreeReport, never> {\n if (durability === \"non-durable\") {\n return CertificationTierThreeReport.make({\n status: \"not-applicable\",\n evidence: [],\n cases: [],\n detail:\n \"the adapter declares non-durable state (reference/conformance adapter); there is no real loss to exercise\",\n });\n }\n if (options.crashLever !== undefined) {\n const cases = yield* options.crashLever;\n return CertificationTierThreeReport.make({\n status: \"exercised\",\n evidence: options.tierThreeEvidence ?? [],\n cases,\n });\n }\n if (options.tierThreeEvidence !== undefined && options.tierThreeEvidence.length > 0) {\n return CertificationTierThreeReport.make({\n status: \"recorded-evidence\",\n evidence: options.tierThreeEvidence,\n cases: [],\n });\n }\n return CertificationTierThreeReport.make({\n status: \"not-exercised\",\n evidence: [],\n cases: [],\n detail:\n \"no crash lever was supplied and no committed real-loss evidence was cited; Tier 3 is NOT discharged for this adapter\",\n });\n});\n\n// ---------------------------------------------------------------------------\n// Entry point\n// ---------------------------------------------------------------------------\n\nconst nowUtc: Effect.Effect<DateTime.Utc> = Effect.map(Clock.currentTimeMillis, (millis) =>\n DateTime.toUtc(DateTime.makeUnsafe(millis)),\n);\n\n/**\n * Certify one durable adapter pair (plan §1, §8 WP2). Runs Tier 2 FIRST over pristine\n * storage (each cell converges to all-settled before the next starts, so the recovery scan\n * never sees foreign leftovers), then Tier 1's port contract cases (whose lanes deliberately\n * end in every nonterminal shape), then records Tier 3. Requires `Crypto.Crypto` and a\n * TestClock-backed environment; the candidate Layers are built exactly once.\n */\nexport const certifyDurableAdapters = <LedgerE = never, StoreE = never>(\n options: CertifyDurableAdaptersOptions<LedgerE, StoreE>,\n): Effect.Effect<CertificationReport, LedgerE | StoreE, Crypto.Crypto> => {\n const batchProducers = new Map<BatchId, ProducerId>();\n // Interpose the candidate store with an append-time capture of each batch's producer\n // identity — the one value the ConversationStore port deliberately does not export — so\n // Tier 2's invariant verification recomputes the FULL digest chain instead of skipping it.\n const capturingStore = Layer.effect(ConversationStore)(\n Effect.gen(function* () {\n const inner = yield* ConversationStore;\n return ConversationStore.of({\n ...inner,\n append: (request) =>\n Effect.sync(() => {\n batchProducers.set(request.batch.batchId, request.batch.producerId);\n }).pipe(Effect.andThen(inner.append(request))),\n });\n }),\n ).pipe(Layer.provide(options.conversationStore));\n\n const support = Layer.mergeAll(\n options.submissionLedger,\n capturingStore,\n options.wakeScheduler ?? WakeScheduler.layerNoop,\n DurableRuntimeFailpoint.layerTest,\n ToolReconciler.uncertain,\n DurableRuntimeConfig.layer({\n deploymentId: Schema.decodeSync(DeploymentId)(\"deployment-certification\"),\n producerId: Schema.decodeSync(ProducerId)(\"producer-certification\"),\n settlementPollInterval: Duration.millis(50),\n leaseRenewalInterval: Duration.seconds(5),\n abortPollInterval: Duration.millis(50),\n }),\n );\n const environment = DurableAgentRuntime.layer.pipe(Layer.provideMerge(support));\n\n const leaseAdvance = Duration.millis(\n Duration.toMillis(options.ownershipLeaseDuration ?? DEFAULT_OWNERSHIP_LEASE_DURATION) + 1_000,\n );\n\n const program = Effect.gen(function* () {\n const ledger = yield* SubmissionLedger;\n\n // Tier 2 — coordinator failpoint convergence sweep.\n const tier2: Array<CertificationSweepResult> = [];\n for (const scenario of CERTIFICATION_SCENARIOS) {\n for (const location of DurableRuntimeFailpointLocation.literals) {\n tier2.push(yield* runSweepCell(scenario, location, batchProducers, leaseAdvance));\n }\n }\n\n // Tier 1 — the shared port contract suites, verbatim.\n const tier1 = yield* certifyPorts();\n\n // Tier 3 — the real loss lever record.\n const capabilities = yield* ledger.capabilities;\n const tier3 = yield* resolveTierThree(capabilities.durability, options);\n\n const generatedAt = yield* nowUtc;\n const ok =\n tier1.every((result) => result.status === \"passed\") &&\n tier2.every((result) => result.status !== \"failed\") &&\n tier3.cases.every((result) => result.status === \"passed\");\n\n return CertificationReport.make({\n format: \"effect-agent/certification@1\",\n adapter: CertifiedAdapterIdentity.make({\n name: options.adapter.name,\n ...(options.adapter.version === undefined ? {} : { version: options.adapter.version }),\n durability: capabilities.durability,\n }),\n generatedAt,\n tier1,\n tier2,\n tier3,\n ok,\n });\n });\n\n return program.pipe(Effect.provide(environment));\n};\n","import {\n Subagent,\n SubagentPolicy,\n SubagentReservationsMemoryLive,\n SubagentRuntime,\n} from \"@effect-agent/capabilities\";\nimport {\n Agent,\n AgentPolicy,\n ConversationId,\n IdGenerator,\n RunId,\n SubmissionId,\n ToolCallId,\n TurnId,\n} from \"@effect-agent/core\";\nimport { DurableStep, DurableStepError, ToolExecutionClass } from \"@effect-agent/engine\";\nimport {\n AbortCommand,\n AgentBindingResolver,\n ApprovalDecisionCommand,\n ConversationExportRequest,\n ConversationStore,\n DefinitionDigests,\n Digest,\n DurableAgentRuntime,\n DurableRuntimeConfig,\n DurableRuntimeFailpointError,\n DurableRuntimeFailpointLocation,\n DurableRuntimeFailpointTestControl,\n DurableWorkerBinding,\n IdempotencyKey,\n ObligationThresholds,\n Principal,\n ResolutionAbortSubmission,\n ResolutionCompletedWithResult,\n ResolutionNeverHappened,\n SubmissionLedger,\n SubmissionLookupById,\n UnknownResolutionCommand,\n childConversationIdFor,\n verifyConversationInvariants,\n type CanonicalRecordEnvelope,\n type BatchId,\n type ProducerId,\n type Receipt,\n type ResolvedBinding,\n type Settlement,\n type SubmissionSnapshot,\n type UnknownResolution,\n} from \"@effect-agent/session\";\nimport { Cause, Effect, Exit, Layer, Option, Ref, Schema, Stream } from \"effect\";\nimport { FastCheck } from \"effect/testing\";\nimport { LanguageModel, Model, Prompt, Tool, Toolkit, type Response } from \"effect/unstable/ai\";\n\n/**\n * P7 WP4 chaos machinery (plan §5): a Schema-first `ChaosPlan`, a seeded generator over\n * `effect/testing/FastCheck` (already inside the pinned Effect — no new dependency), and a\n * deterministic runner that drives the durable coordinator over whatever adapter pair the test\n * provides. Every plan ends in the SAME claims the crash matrices make:\n *\n * 1. `verifyConversationInvariants` in convergence mode over every touched Conversation (the\n * shared WP1 checker — one set of claims for admin verify, certification, chaos, and soak);\n * 2. `scanObligations` returning ZERO entries (everything settled; nothing invisibly stuck);\n * 3. supplier non-fabrication wherever the deterministic desk was in play (durability §10: no\n * canonical Tool success exists that the external store did not actually produce).\n *\n * Replay contract: the memory/SQLite chaos tests derive every plan from one root seed\n * (`CHAOS_SEED` env override; see `chaosSeedFromEnv`) and print that seed plus the failing\n * plan's own seed in the failure output, so any red run is replayable byte-for-byte.\n */\n\n// ---------------------------------------------------------------------------\n// ChaosPlan schema\n// ---------------------------------------------------------------------------\n\n/** The six durable scenario flavors a chaos lane can exercise (plan §5). */\nexport const ChaosScenarioKind = Schema.Literals([\n \"plain\",\n \"uncertain-tool\",\n \"durable-steps\",\n \"approval\",\n \"join\",\n \"delegation\",\n]);\nexport type ChaosScenarioKind = typeof ChaosScenarioKind.Type;\n\nconst LaneIndex = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(7));\n\n/** One Submission of a plan: which lane it queues into and that lane's scenario flavor. */\nexport class ChaosSubmissionSpec extends Schema.Class<ChaosSubmissionSpec>(\n \"@effect-agent/testing/ChaosSubmissionSpec\",\n)({\n lane: LaneIndex,\n /** The lane's flavor; the FIRST spec of a lane fixes the lane's agent. */\n kind: ChaosScenarioKind,\n}) {}\n\n/** How the runner resolves a durable Unknown Outcome it encounters (DUR-017 driver). */\nexport const ChaosResolutionKind = Schema.Literals([\n /** The call provably never started: the batch resumes and executes it. */\n \"never-happened\",\n /**\n * Recovered supplier truth: resolve with the EXACT value the desk produced. Falls back to\n * `never-happened` when the desk holds no value for the call, so the runner never fabricates.\n */\n \"completed-from-supplier\",\n /** Unresolvable: route into the abort path (settles aborted, audit retained). */\n \"abort-submission\",\n]);\nexport type ChaosResolutionKind = typeof ChaosResolutionKind.Type;\n\nexport const ChaosApprovalDecision = Schema.Literals([\"approved\", \"denied\"]);\nexport type ChaosApprovalDecision = typeof ChaosApprovalDecision.Type;\n\nconst BoundedAdapterArm = Schema.String.check(Schema.isMaxLength(128));\n\n/**\n * One seeded chaos plan (plan §5): the full fault schedule is data, so a failing run replays\n * from the plan alone. `failpointArms` are coordinator locations; `adapterArms` are\n * adapter-owned location names the adapter test validates (the memory runner has none).\n */\nexport class ChaosPlan extends Schema.Class<ChaosPlan>(\"@effect-agent/testing/ChaosPlan\")({\n /** Identifies this plan in failure output; derived from the root seed plus the plan index. */\n seed: Schema.Int,\n /** Lane count; submissions address lanes `0..lanes-1`. */\n lanes: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(8)),\n submissions: Schema.NonEmptyArray(ChaosSubmissionSpec),\n /** Coordinator failpoint arms, consumed one per round (each fails every hit that round). */\n failpointArms: Schema.Array(DurableRuntimeFailpointLocation),\n /** Adapter-owned failpoint arms (e.g. SQLite `ledger:*`/`append:*` locations). */\n adapterArms: Schema.Array(BoundedAdapterArm),\n /** Flattened submission indices to abort mid-plan (modulo the submission count). */\n abortInjections: Schema.Array(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n /** Resolution choices for Unknown Outcomes, indexed deterministically per open call. */\n resolutionInjections: Schema.Array(ChaosResolutionKind),\n /** Approval decisions for suspended approval lanes, indexed deterministically per call. */\n approvalDecisions: Schema.Array(ChaosApprovalDecision),\n}) {}\n\n/** Per-lane verification result inside a plan report. */\nexport class ChaosLaneReport extends Schema.Class<ChaosLaneReport>(\n \"@effect-agent/testing/ChaosLaneReport\",\n)({\n conversationId: ConversationId,\n kind: ChaosScenarioKind,\n submissionCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Verdict of `verifyConversationInvariants` in convergence mode. */\n verified: Schema.Boolean,\n}) {}\n\n/** The Schema-first outcome of one executed chaos plan. */\nexport class ChaosPlanReport extends Schema.Class<ChaosPlanReport>(\n \"@effect-agent/testing/ChaosPlanReport\",\n)({\n seed: Schema.Int,\n rounds: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n lanes: Schema.Array(ChaosLaneReport),\n /** `scanObligations` entries after convergence — MUST be zero. */\n openObligations: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\n/** Typed convergence/verification failure of one chaos plan (never a bare defect). */\nexport class ChaosConvergenceFailure extends Schema.TaggedError<ChaosConvergenceFailure>()(\n \"ChaosConvergenceFailure\",\n {\n seed: Schema.Int,\n message: Schema.String.check(Schema.isMaxLength(16_384)),\n },\n) {}\n\n// ---------------------------------------------------------------------------\n// Seeded generation\n// ---------------------------------------------------------------------------\n\n/** Default root seed for chaos suites; override with the `CHAOS_SEED` environment variable. */\nexport const DEFAULT_CHAOS_SEED = 20260813;\n\n/** The root seed for this run: `CHAOS_SEED` when set to an integer, the default otherwise. */\nexport const chaosSeedFromEnv = (env: Record<string, string | undefined>): number => {\n const raw = env[\"CHAOS_SEED\"];\n if (raw === undefined || raw === \"\") return DEFAULT_CHAOS_SEED;\n const parsed = Number.parseInt(raw, 10);\n return Number.isSafeInteger(parsed) ? parsed : DEFAULT_CHAOS_SEED;\n};\n\nexport interface ChaosGeneratorOptions {\n /** Root seed (print this in failure output for replay). */\n readonly seed: number;\n /** How many plans to derive. */\n readonly count: number;\n /** Adapter failpoint location names available to arm (empty for memory). */\n readonly adapterArms?: ReadonlyArray<string> | undefined;\n}\n\ninterface GeneratedLane {\n readonly kind: ChaosScenarioKind;\n readonly depth: number;\n}\n\nconst laneArbitrary: FastCheck.Arbitrary<GeneratedLane> = FastCheck.constantFrom<ChaosScenarioKind>(\n \"plain\",\n \"uncertain-tool\",\n \"durable-steps\",\n \"approval\",\n \"join\",\n \"delegation\",\n).chain(\n (kind): FastCheck.Arbitrary<GeneratedLane> =>\n kind === \"join\"\n ? FastCheck.integer({ min: 2, max: 3 }).map((depth): GeneratedLane => ({ kind, depth }))\n : kind === \"plain\"\n ? FastCheck.integer({ min: 1, max: 2 }).map((depth): GeneratedLane => ({ kind, depth }))\n : FastCheck.constant<GeneratedLane>({ kind, depth: 1 }),\n);\n\ninterface ChaosPlanShape {\n readonly lanes: number;\n readonly submissions: readonly [ChaosSubmissionSpec, ...Array<ChaosSubmissionSpec>];\n readonly failpointArms: ReadonlyArray<DurableRuntimeFailpointLocation>;\n readonly adapterArms: ReadonlyArray<string>;\n readonly abortInjections: ReadonlyArray<number>;\n readonly resolutionInjections: ReadonlyArray<ChaosResolutionKind>;\n readonly approvalDecisions: ReadonlyArray<ChaosApprovalDecision>;\n}\n\nconst planShapeArbitrary = (\n adapterArms: ReadonlyArray<string>,\n): FastCheck.Arbitrary<ChaosPlanShape> =>\n FastCheck.record({\n lanes: FastCheck.array(laneArbitrary, { minLength: 1, maxLength: 3 }),\n failpointArms: FastCheck.uniqueArray(\n FastCheck.constantFrom(...DurableRuntimeFailpointLocation.literals),\n { maxLength: 3 },\n ),\n adapterArms:\n adapterArms.length === 0\n ? FastCheck.constant<Array<string>>([])\n : FastCheck.uniqueArray(FastCheck.constantFrom(...adapterArms), { maxLength: 2 }),\n abortInjections: FastCheck.uniqueArray(FastCheck.integer({ min: 0, max: 15 }), {\n maxLength: 2,\n }),\n resolutionInjections: FastCheck.array(\n FastCheck.constantFrom<ChaosResolutionKind>(\n \"never-happened\",\n \"completed-from-supplier\",\n \"abort-submission\",\n ),\n { maxLength: 4 },\n ),\n approvalDecisions: FastCheck.array(\n FastCheck.constantFrom<ChaosApprovalDecision>(\"approved\", \"denied\"),\n { maxLength: 2 },\n ),\n }).map((shape) => {\n const submissions = shape.lanes.flatMap((lane, index) =>\n Array.from({ length: lane.depth }, () =>\n ChaosSubmissionSpec.make({ lane: index, kind: lane.kind }),\n ),\n );\n const [first, ...rest] = submissions;\n // `lanes` >= 1 and every lane has depth >= 1, so `first` always exists.\n if (first === undefined) throw new Error(\"chaos generator produced an empty plan\");\n return {\n lanes: shape.lanes.length,\n submissions: [first, ...rest] as const,\n failpointArms: shape.failpointArms,\n adapterArms: shape.adapterArms,\n abortInjections: shape.abortInjections,\n resolutionInjections: shape.resolutionInjections,\n approvalDecisions: shape.approvalDecisions,\n };\n });\n\n/**\n * Derive `count` chaos plans deterministically from one root seed. The same\n * `{seed, count, adapterArms}` triple always yields byte-identical plans, so a failure line\n * `CHAOS_SEED=<seed>` replays the exact schedule.\n */\nexport const generateChaosPlans = (options: ChaosGeneratorOptions): ReadonlyArray<ChaosPlan> => {\n const sampled = FastCheck.sample(planShapeArbitrary(options.adapterArms ?? []), {\n seed: options.seed,\n numRuns: options.count,\n });\n return sampled.map((shape, index) =>\n ChaosPlan.make({ ...shape, seed: (Math.imul(options.seed, 31) + index) | 0 }),\n );\n};\n\n/** Deterministic PRNG for the runner's small ordering choices (lane drive order). */\nconst mulberry32 = (seed: number): (() => number) => {\n let state = seed | 0;\n return () => {\n state = (state + 0x6d2b79f5) | 0;\n let t = Math.imul(state ^ (state >>> 15), 1 | state);\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n};\n\n// ---------------------------------------------------------------------------\n// Lane fixtures (agents, scripted models, deterministic desk)\n// ---------------------------------------------------------------------------\n\nconst usage = { inputTokens: {}, outputTokens: {} };\n\nconst finalParts = (text: string): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"answer\" },\n { type: \"text-delta\", id: \"answer\", delta: text },\n { type: \"text-end\", id: \"answer\" },\n { type: \"finish\", reason: \"stop\", usage },\n];\n\nconst toolTurn = (\n ...calls: ReadonlyArray<Response.StreamPartEncoded>\n): ReadonlyArray<Response.StreamPartEncoded> => [\n ...calls,\n { type: \"finish\", reason: \"tool-calls\", usage },\n];\n\nconst toolCallPart = (id: string, name: string, params: unknown): Response.StreamPartEncoded => ({\n type: \"tool-call\",\n id,\n name,\n params,\n providerExecuted: false,\n});\n\n/**\n * Prompt-shaped scripted model: the response depends ONLY on the request prompt, so it stays\n * deterministic across Attempt re-invocations, batch resumes, and joined steering — no counter\n * to drift when chaos re-enters a Turn.\n */\nconst promptScriptedModel = (\n label: string,\n script: (prompt: Prompt.Prompt) => ReadonlyArray<Response.StreamPartEncoded>,\n) =>\n Model.make(\n \"scripted\",\n label,\n Layer.effect(\n LanguageModel.LanguageModel,\n LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (request) => Stream.fromIterable(script(request.prompt)),\n }),\n ),\n );\n\nconst lastRole = (prompt: Prompt.Prompt): string | undefined => prompt.content.at(-1)?.role;\n\nconst policy = AgentPolicy.make({\n maxTurns: 3,\n maxToolCalls: 4,\n maxDuration: \"30 seconds\",\n toolConcurrency: 2,\n});\n\nconst PlainInput = Schema.Struct({ question: Schema.String });\nconst PlainOutput = Schema.Struct({ answer: Schema.String });\n\nconst plainDefinition = Agent.define(\"chaos-plain\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Answer as JSON.\",\n toolkit: Toolkit.empty,\n policy,\n});\n\n/** Unannotated → fail-closed `uncertain`: enters the prepared/settled protocol (DUR-009). */\nconst BookUncertain = Tool.make(\"book\", {\n parameters: Schema.Struct({ ref: Schema.String }),\n success: Schema.Struct({ confirmation: Schema.String }),\n});\nconst bookTools = Toolkit.make(BookUncertain);\nconst bookDefinition = Agent.define(\"chaos-book\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Book it.\",\n toolkit: bookTools,\n policy,\n});\n\nconst BookApproval = Tool.make(\"book\", {\n parameters: Schema.Struct({ ref: Schema.String }),\n success: Schema.Struct({ confirmation: Schema.String }),\n needsApproval: true,\n});\nconst approvalTools = Toolkit.make(BookApproval);\nconst approvalDefinition = Agent.define(\"chaos-approval\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Book after approval.\",\n toolkit: approvalTools,\n policy,\n});\n\nconst Itinerary = Tool.make(\"itinerary\", {\n parameters: Schema.Struct({ ref: Schema.String }),\n success: Schema.Struct({ state: Schema.String }),\n failure: DurableStepError,\n dependencies: [DurableStep],\n}).annotate(ToolExecutionClass, \"uncertain\");\nconst itineraryTools = Toolkit.make(Itinerary);\nconst itineraryDefinition = Agent.define(\"chaos-itinerary\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Reserve the itinerary.\",\n toolkit: itineraryTools,\n policy,\n});\n\nconst childDefinition = Agent.define(\"chaos-child\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Answer as JSON.\",\n toolkit: Toolkit.empty,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 1,\n maxDuration: \"30 seconds\",\n toolConcurrency: 1,\n }),\n});\n\nclass ChaosDelegationFailed extends Schema.TaggedError<ChaosDelegationFailed>()(\n \"ChaosDelegationFailed\",\n { childErrorTag: Schema.String },\n) {}\n\nconst chaosDelegation = Subagent.define(\"delegate_chaos\", {\n description: \"Delegate one bounded chaos question.\",\n target: childDefinition,\n parameters: Schema.Struct({ topic: Schema.String }),\n success: Schema.Struct({ summary: Schema.String }),\n failure: ChaosDelegationFailed,\n prepareInput: ({ topic }) => Effect.succeed({ question: `chaos:${topic}` }),\n projectResult: (output) => Effect.succeed({ summary: `finding:${output.answer}` }),\n policy: SubagentPolicy.make({\n maxChildren: 2,\n maxConcurrency: 2,\n maxTurns: 4,\n maxToolCalls: 4,\n maxDuration: \"30 seconds\",\n }),\n});\n\nconst coordinatorDefinition = Agent.define(\"chaos-coordinator\", {\n input: Schema.Struct({ mission: Schema.String }),\n output: Schema.Struct({ report: Schema.String }),\n instructions: \"Delegate, then report as JSON.\",\n toolkit: Toolkit.make(chaosDelegation.tool),\n policy,\n});\n\nconst DELEGATE_CALL_ID = \"chaos-delegate-1\";\n\nconst HEX = \"0123456789abcdef\";\nconst decodeDigest = Schema.decodeSync(Digest);\nconst laneDigests = (lane: number): DefinitionDigests => {\n const digest = decodeDigest(HEX[lane % 8]!.repeat(64));\n return DefinitionDigests.make({ agent: digest, model: digest, tools: digest });\n};\nconst childDigestStrings = (lane: number) => {\n const char = HEX[8 + (lane % 8)]!;\n return { agent: char.repeat(64), model: char.repeat(64), tools: char.repeat(64) } as const;\n};\nconst childLaneDigests = (lane: number): DefinitionDigests => {\n const strings = childDigestStrings(lane);\n return DefinitionDigests.make({\n agent: decodeDigest(strings.agent),\n model: decodeDigest(strings.model),\n tools: decodeDigest(strings.tools),\n });\n};\n\nconst CHAOS_PRINCIPAL = Schema.decodeSync(Principal)(\"principal-chaos\");\nconst decodeConversationId = Schema.decodeSync(ConversationId);\nconst decodeIdempotencyKey = Schema.decodeSync(IdempotencyKey);\nconst decodeToolCallId = Schema.decodeSync(ToolCallId);\nconst decodeRunId = Schema.decodeSync(RunId);\nconst decodeTurnId = Schema.decodeSync(TurnId);\n\n/** Fixture-only identity source consumed by the delegation Layer's ephemeral capture. */\nconst chaosIdentifiers = Layer.effect(\n IdGenerator,\n Effect.gen(function* () {\n const counter = yield* Ref.make(0);\n const next = <A>(decode: (value: string) => A, prefix: string) =>\n Ref.getAndUpdate(counter, (value) => value + 1).pipe(\n Effect.map((value) => decode(`${prefix}-${value}`)),\n );\n return {\n nextConversationId: next(decodeConversationId, \"chaos-fixture-conversation\"),\n nextRunId: next(decodeRunId, \"chaos-fixture-run\"),\n nextTurnId: next(decodeTurnId, \"chaos-fixture-turn\"),\n };\n }),\n);\n\nconst delegationSupport = Layer.mergeAll(SubagentReservationsMemoryLive, chaosIdentifiers);\n\n/**\n * The deterministic external desk of one plan: every produced value is recorded so the final\n * non-fabrication sweep can prove each canonical Tool success came from here (durability §10).\n */\ninterface ChaosDesk {\n readonly produced: Effect.Effect<ReadonlySet<string>>;\n readonly record: (value: string) => Effect.Effect<void>;\n}\n\nconst makeChaosDesk: Effect.Effect<ChaosDesk> = Effect.gen(function* () {\n const produced = yield* Ref.make<ReadonlySet<string>>(new Set());\n return {\n produced: Ref.get(produced),\n record: (value: string) => Ref.update(produced, (current) => new Set(current).add(value)),\n };\n});\n\nconst bookConfirmation = (ref: string): string => `confirmed-${ref}`;\nconst flightValue = (ref: string): string => `flight-${ref}`;\nconst lodgingValue = (ref: string): string => `lodging-${ref}`;\n\n// ---------------------------------------------------------------------------\n// Runner\n// ---------------------------------------------------------------------------\n\n/** Adapter-owned failpoint control the SQLite runner supplies; memory has none. */\nexport interface ChaosAdapterFailpoints {\n readonly arm: (location: string) => Effect.Effect<void>;\n readonly clear: Effect.Effect<void>;\n}\n\nexport interface ChaosRunOptions {\n readonly adapterFailpoints?: ChaosAdapterFailpoints | undefined;\n /**\n * Executed at the end of every round. Adapters whose ownership leases block every new claim\n * until expiry (the SQLite ledger's D5 semantics — expiry only revokes the liveness\n * assumption; producer epochs stay the correctness fence) pass a deterministic\n * `TestClock.adjust` here so a dead Attempt's lane becomes reclaimable next round. The memory\n * ledger needs nothing: it allows same-producer reclaim under a live lease.\n */\n readonly betweenRounds?: Effect.Effect<void> | undefined;\n}\n\n/** Success → Some; typed failure → None (chaos tolerates it); defect → rethrown loudly. */\nconst tolerateTyped = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<Option.Option<A>, never, R> =>\n effect.pipe(\n Effect.exit,\n Effect.flatMap((exit) => {\n if (Exit.isSuccess(exit)) return Effect.succeed(Option.some(exit.value));\n if (Option.isSome(Cause.findErrorOption(exit.cause))) {\n return Effect.succeed(Option.none<A>());\n }\n return Effect.die(new Error(`chaos step died: ${Cause.pretty(exit.cause)}`));\n }),\n );\n\ninterface LaneFixture {\n readonly index: number;\n readonly kind: ChaosScenarioKind;\n readonly conversationId: ConversationId;\n readonly ref: string;\n readonly deskInPlay: boolean;\n readonly submissionIndexes: ReadonlyArray<number>;\n readonly submitOne: (flatIndex: number) => Effect.Effect<Receipt, unknown>;\n readonly drives: (\n firstReceipt: Receipt | undefined,\n ) => ReadonlyArray<Effect.Effect<ReadonlyArray<Settlement>, unknown>>;\n readonly childConversationOf: (firstReceipt: Receipt) => ConversationId | undefined;\n}\n\ninterface SubmissionState {\n readonly flatIndex: number;\n readonly lane: LaneFixture;\n receipt: Receipt | undefined;\n}\n\nconst scriptFor = (\n kind: ChaosScenarioKind,\n ref: string,\n): ((prompt: Prompt.Prompt) => ReadonlyArray<Response.StreamPartEncoded>) => {\n switch (kind) {\n case \"plain\":\n case \"join\":\n return () => finalParts('{\"answer\":\"chaos\"}');\n case \"uncertain-tool\":\n case \"approval\":\n return (prompt) =>\n lastRole(prompt) === \"tool\"\n ? finalParts('{\"answer\":\"booked\"}')\n : toolTurn(toolCallPart(`book-${ref}`, \"book\", { ref }));\n case \"durable-steps\":\n return (prompt) =>\n lastRole(prompt) === \"tool\"\n ? finalParts('{\"answer\":\"reserved\"}')\n : toolTurn(toolCallPart(`itinerary-${ref}`, \"itinerary\", { ref }));\n case \"delegation\":\n return (prompt) =>\n lastRole(prompt) === \"tool\"\n ? finalParts('{\"report\":\"done\"}')\n : toolTurn(toolCallPart(DELEGATE_CALL_ID, \"delegate_chaos\", { topic: ref }));\n }\n};\n\nconst makeLaneFixture = Effect.fn(\"Chaos.makeLaneFixture\")(function* (\n plan: ChaosPlan,\n laneIndex: number,\n kind: ChaosScenarioKind,\n submissionIndexes: ReadonlyArray<number>,\n desk: ChaosDesk,\n) {\n const runtime = yield* DurableAgentRuntime;\n const conversationId = decodeConversationId(`chaos-${plan.seed}-lane-${laneIndex}`);\n const ref = `ref-l${laneIndex}`;\n const script = scriptFor(kind, ref);\n const model = promptScriptedModel(`chaos-${kind}-${laneIndex}`, script);\n const digests = laneDigests(laneIndex);\n\n const submitOptionsFor = (flatIndex: number) => ({\n conversationId,\n principal: CHAOS_PRINCIPAL,\n idempotencyKey: decodeIdempotencyKey(`chaos-${plan.seed}-s${flatIndex}`),\n definitions: digests,\n });\n\n const bookToolLayerFor = (tools: typeof bookTools | typeof approvalTools) =>\n tools.toLayer({\n book: ({ ref: called }) =>\n desk\n .record(bookConfirmation(called))\n .pipe(Effect.as({ confirmation: bookConfirmation(called) })),\n });\n\n const plainLaneFixture = (\n deskInPlay: boolean,\n drive: Effect.Effect<ReadonlyArray<Settlement>, unknown>,\n submitOne: (flatIndex: number) => Effect.Effect<Receipt, unknown>,\n ): LaneFixture => ({\n index: laneIndex,\n kind,\n conversationId,\n ref,\n deskInPlay,\n submissionIndexes,\n submitOne,\n drives: () => [drive],\n childConversationOf: () => undefined,\n });\n\n switch (kind) {\n case \"plain\":\n case \"join\": {\n const agent = Agent.withModel(plainDefinition, model);\n return plainLaneFixture(\n false,\n runtime.processConversation(agent, conversationId),\n (flatIndex) =>\n runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)),\n );\n }\n case \"uncertain-tool\": {\n const agent = Agent.withModel(bookDefinition, model);\n return plainLaneFixture(\n true,\n runtime\n .processConversation(agent, conversationId)\n .pipe(Effect.provide(bookToolLayerFor(bookTools))),\n (flatIndex) =>\n runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)),\n );\n }\n case \"approval\": {\n const agent = Agent.withModel(approvalDefinition, model);\n return plainLaneFixture(\n true,\n runtime\n .processConversation(agent, conversationId)\n .pipe(Effect.provide(bookToolLayerFor(approvalTools))),\n (flatIndex) =>\n runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)),\n );\n }\n case \"durable-steps\": {\n const agent = Agent.withModel(itineraryDefinition, model);\n const toolLayer = itineraryTools.toLayer({\n itinerary: ({ ref: called }) =>\n Effect.gen(function* () {\n const step = yield* DurableStep;\n const flight = yield* step.do(\n \"reserve-flight\",\n Schema.String,\n desk.record(flightValue(called)).pipe(Effect.as(flightValue(called))),\n );\n const lodging = yield* step.do(\n \"reserve-lodging\",\n Schema.String,\n desk.record(lodgingValue(called)).pipe(Effect.as(lodgingValue(called))),\n );\n return { state: `${flight}+${lodging}` };\n }),\n });\n return plainLaneFixture(\n true,\n runtime.processConversation(agent, conversationId).pipe(Effect.provide(toolLayer)),\n (flatIndex) =>\n runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)),\n );\n }\n case \"delegation\": {\n const parentBinding = Agent.withModel(coordinatorDefinition, model);\n const childModel = promptScriptedModel(`chaos-child-${laneIndex}`, () =>\n finalParts('{\"answer\":\"child\"}'),\n );\n const childBinding = Agent.withModel(childDefinition, childModel);\n const delegationLayer = SubagentRuntime.layer(chaosDelegation, childBinding, {\n mapChildFailure: (failure) => ChaosDelegationFailed.make({ childErrorTag: failure._tag }),\n durable: { targetDigests: childDigestStrings(laneIndex) },\n }).pipe(Layer.provide(delegationSupport));\n const parentResolved: ResolvedBinding = yield* DurableWorkerBinding.make(\n parentBinding,\n digests,\n ).pipe(Effect.provide(delegationLayer));\n const childResolved: ResolvedBinding = yield* DurableWorkerBinding.make(\n childBinding,\n childLaneDigests(laneIndex),\n );\n const resolver = AgentBindingResolver.fromBindings([parentResolved, childResolved]);\n const driveResolved = (conversation: ConversationId) =>\n runtime\n .processConversationResolved(conversation)\n .pipe(Effect.provideService(AgentBindingResolver, resolver));\n const fixture: LaneFixture = {\n index: laneIndex,\n kind,\n conversationId,\n ref,\n deskInPlay: false,\n submissionIndexes,\n submitOne: (flatIndex) =>\n runtime.submit(\n { definition: { id: coordinatorDefinition.id, input: coordinatorDefinition.input } },\n { mission: `chaos ${flatIndex}` },\n submitOptionsFor(flatIndex),\n ),\n drives: (firstReceipt) => {\n const drives: Array<Effect.Effect<ReadonlyArray<Settlement>, unknown>> = [\n driveResolved(conversationId),\n ];\n if (firstReceipt !== undefined) {\n drives.push(\n driveResolved(\n childConversationIdFor(\n firstReceipt.submissionId,\n decodeToolCallId(DELEGATE_CALL_ID),\n ),\n ),\n );\n }\n return drives;\n },\n childConversationOf: (firstReceipt) =>\n childConversationIdFor(firstReceipt.submissionId, decodeToolCallId(DELEGATE_CALL_ID)),\n };\n return fixture;\n }\n }\n});\n\n/** Stable per-call index into an injection list (identical across resolution passes). */\nconst injectionIndex = (submissionFlatIndex: number, callId: string, length: number): number => {\n let hash = submissionFlatIndex + 1;\n for (const char of callId) hash = (Math.imul(hash, 31) + char.charCodeAt(0)) | 0;\n return ((hash % length) + length) % length;\n};\n\nconst resolutionFor = (\n kind: ChaosResolutionKind,\n toolName: string,\n ref: string,\n produced: ReadonlySet<string>,\n): UnknownResolution => {\n switch (kind) {\n case \"abort-submission\":\n return ResolutionAbortSubmission.make();\n case \"completed-from-supplier\": {\n if (toolName === \"book\" && produced.has(bookConfirmation(ref))) {\n return ResolutionCompletedWithResult.make({\n result: { confirmation: bookConfirmation(ref) },\n isFailure: false,\n });\n }\n if (\n toolName === \"itinerary\" &&\n produced.has(flightValue(ref)) &&\n produced.has(lodgingValue(ref))\n ) {\n return ResolutionCompletedWithResult.make({\n result: { state: `${flightValue(ref)}+${lodgingValue(ref)}` },\n isFailure: false,\n });\n }\n // The desk never produced a value for this call — resolving \"completed\" would fabricate.\n return ResolutionNeverHappened.make();\n }\n case \"never-happened\":\n return ResolutionNeverHappened.make();\n }\n};\n\n/** Drive one DUR-017 pass: resolve Unknown Outcomes and pending approvals from the plan. */\nconst resolutionPass = Effect.fn(\"Chaos.resolutionPass\")(function* (\n plan: ChaosPlan,\n states: ReadonlyArray<SubmissionState>,\n desk: ChaosDesk,\n) {\n const runtime = yield* DurableAgentRuntime;\n const ledger = yield* SubmissionLedger;\n const produced = yield* desk.produced;\n const nonterminal = yield* tolerateTyped(Stream.runCollect(ledger.scanNonterminal));\n if (Option.isNone(nonterminal)) return;\n const byId = new Map<SubmissionId, SubmissionState>();\n for (const state of states) {\n if (state.receipt !== undefined) byId.set(state.receipt.submissionId, state);\n }\n for (const row of nonterminal.value) {\n if (row.state !== \"unknown\" && row.state !== \"suspended\") continue;\n const state = byId.get(row.submissionId);\n const explanation = yield* tolerateTyped(runtime.explain(row.submissionId));\n if (Option.isNone(explanation)) continue;\n const flatIndex = state?.flatIndex ?? 0;\n const ref = state?.lane.ref ?? \"ref-child\";\n if (row.state === \"unknown\") {\n for (const call of explanation.value.evidence.unknownCalls) {\n if (call.resolved) continue;\n const kind =\n plan.resolutionInjections.length === 0\n ? \"never-happened\"\n : plan.resolutionInjections[\n injectionIndex(flatIndex, call.toolCallId, plan.resolutionInjections.length)\n ]!;\n yield* tolerateTyped(\n runtime.resolveUnknown(\n UnknownResolutionCommand.make({\n submissionId: row.submissionId,\n toolCallId: call.toolCallId,\n author: \"chaos-runner\",\n reason: `chaos plan ${plan.seed} resolution (${kind})`,\n resolution: resolutionFor(kind, call.toolName, ref, produced),\n }),\n ),\n );\n }\n } else {\n for (const pending of explanation.value.evidence.approvalsPending) {\n const decision =\n plan.approvalDecisions.length === 0\n ? \"approved\"\n : plan.approvalDecisions[\n injectionIndex(flatIndex, pending.toolCallId, plan.approvalDecisions.length)\n ]!;\n yield* tolerateTyped(\n runtime.resolveApproval(\n ApprovalDecisionCommand.make({\n submissionId: row.submissionId,\n toolCallId: pending.toolCallId,\n decision,\n resolver: \"chaos-runner\",\n reason: `chaos plan ${plan.seed} approval (${decision})`,\n }),\n ),\n );\n }\n }\n }\n});\n\nconst submissionIdsNamedBy = (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n): ReadonlySet<SubmissionId> => {\n const named = new Set<SubmissionId>();\n for (const envelope of records) {\n const payload = envelope.record.payload;\n if (\n payload._tag === \"UserInputRecorded\" ||\n payload._tag === \"SubmissionSettled\" ||\n payload._tag === \"AbortRequested\"\n ) {\n named.add(payload.submissionId);\n }\n }\n return named;\n};\n\n/**\n * The final non-fabrication sweep (durability §10): every canonical Tool success recorded on a\n * desk-backed lane must be a value the desk actually produced.\n */\nconst BookResult = Schema.Struct({ confirmation: Schema.String });\nconst ItineraryResult = Schema.Struct({ state: Schema.String });\nconst decodeBookResult = Schema.decodeUnknownOption(BookResult);\nconst decodeItineraryResult = Schema.decodeUnknownOption(ItineraryResult);\nconst decodeStepOutput = Schema.decodeUnknownOption(Schema.String);\n\nconst assertNoFabrication = (\n plan: ChaosPlan,\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n produced: ReadonlySet<string>,\n): Effect.Effect<void, ChaosConvergenceFailure> => {\n const fabricated: Array<string> = [];\n const requireProduced = (value: string, label: string): void => {\n if (!produced.has(value)) fabricated.push(`${label} \"${value}\"`);\n };\n for (const envelope of records) {\n const payload = envelope.record.payload;\n if (payload._tag === \"ToolCallSettled\" && !payload.isFailure) {\n if (payload.toolName === \"book\") {\n const result = decodeBookResult(payload.result);\n if (Option.isSome(result)) requireProduced(result.value.confirmation, \"book result\");\n }\n if (payload.toolName === \"itinerary\") {\n const result = decodeItineraryResult(payload.result);\n if (Option.isSome(result)) {\n for (const part of result.value.state.split(\"+\")) {\n requireProduced(part, \"itinerary step result\");\n }\n }\n }\n }\n if (payload._tag === \"ToolStepSettled\") {\n const output = decodeStepOutput(payload.output);\n if (Option.isSome(output)) requireProduced(output.value, \"step output\");\n }\n }\n return fabricated.length === 0\n ? Effect.void\n : Effect.fail(\n ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `fabricated Tool results absent from the desk: ${fabricated.join(\", \")}`,\n }),\n );\n};\n\n/**\n * Execute one chaos plan against whatever adapters the ambient Layer provides and end in the\n * shared invariant claims. Deterministic: same plan + same adapters → same schedule.\n */\nexport const runChaosPlan = Effect.fn(\"Chaos.runChaosPlan\")(function* (\n plan: ChaosPlan,\n options?: ChaosRunOptions,\n) {\n const runtime = yield* DurableAgentRuntime;\n const ledger = yield* SubmissionLedger;\n const store = yield* ConversationStore;\n const config = yield* DurableRuntimeConfig;\n const failpoints = yield* DurableRuntimeFailpointTestControl;\n const random = mulberry32(plan.seed);\n const desk = yield* makeChaosDesk;\n\n // Lane fixtures: the FIRST spec of each lane fixes the lane's agent kind.\n const laneKinds = new Map<number, ChaosScenarioKind>();\n const laneSubmissions = new Map<number, Array<number>>();\n plan.submissions.forEach((spec, flatIndex) => {\n const lane = spec.lane % plan.lanes;\n if (!laneKinds.has(lane)) laneKinds.set(lane, spec.kind);\n const list = laneSubmissions.get(lane) ?? [];\n list.push(flatIndex);\n laneSubmissions.set(lane, list);\n });\n const lanes: Array<LaneFixture> = [];\n for (const [lane, kind] of laneKinds) {\n lanes.push(yield* makeLaneFixture(plan, lane, kind, laneSubmissions.get(lane) ?? [], desk));\n }\n\n const states: Array<SubmissionState> = plan.submissions.map((spec, flatIndex) => ({\n flatIndex,\n lane: lanes.find((fixture) => fixture.index === spec.lane % plan.lanes)!,\n receipt: undefined,\n }));\n const appliedAborts = new Set<number>();\n\n type ArmEntry =\n | { readonly family: \"coordinator\"; readonly location: DurableRuntimeFailpointLocation }\n | { readonly family: \"adapter\"; readonly location: string };\n const armQueue: Array<ArmEntry> = [\n ...plan.failpointArms.map((location): ArmEntry => ({ family: \"coordinator\", location })),\n ...plan.adapterArms.map((location): ArmEntry => ({ family: \"adapter\", location })),\n ];\n\n const allSettled = Effect.gen(function* () {\n if (states.some((state) => state.receipt === undefined)) return false;\n const nonterminal = yield* tolerateTyped(Stream.runCollect(ledger.scanNonterminal));\n return Option.isSome(nonterminal) && Array.from(nonterminal.value).length === 0;\n });\n\n const maxRounds = armQueue.length + states.length * 2 + 12;\n let rounds = 0;\n let converged = false;\n for (let round = 0; round < maxRounds; round++) {\n rounds = round + 1;\n const arm = armQueue[round];\n if (arm?.family === \"coordinator\") {\n const location = arm.location;\n yield* failpoints.setHandler((hit) =>\n hit === location\n ? Effect.fail(DurableRuntimeFailpointError.make({ location: hit }))\n : Effect.void,\n );\n } else if (arm?.family === \"adapter\" && options?.adapterFailpoints !== undefined) {\n yield* options.adapterFailpoints.arm(arm.location);\n }\n\n // Admission chaos: pending submissions retry under the active arm until a Receipt lands;\n // the identical (conversation, principal, key) triple reattaches, never duplicates.\n for (const state of states) {\n if (state.receipt !== undefined) continue;\n const receipt = yield* tolerateTyped(state.lane.submitOne(state.flatIndex));\n if (Option.isSome(receipt)) state.receipt = receipt.value;\n }\n\n // Drive every lane (and discovered child lanes) in seeded order under the active arm.\n const order = [...lanes].sort(() => random() - 0.5);\n for (const lane of order) {\n const firstFlat = lane.submissionIndexes[0];\n const firstReceipt = firstFlat === undefined ? undefined : states[firstFlat]?.receipt;\n for (const drive of lane.drives(firstReceipt)) {\n yield* tolerateTyped(drive);\n }\n }\n\n // Abort injections fire once, while arms may still be active (abort:after-intent etc.).\n if (round >= 1) {\n for (const rawIndex of plan.abortInjections) {\n const index = rawIndex % states.length;\n if (appliedAborts.has(index)) continue;\n const receipt = states[index]?.receipt;\n if (receipt === undefined) continue;\n appliedAborts.add(index);\n yield* tolerateTyped(\n runtime.abort(\n AbortCommand.make({\n submissionId: receipt.submissionId,\n author: \"chaos-runner\",\n reason: `chaos plan ${plan.seed} abort injection`,\n }),\n ),\n );\n }\n }\n\n // First resolution pass runs under the arm so resolve:* locations can fire.\n yield* resolutionPass(plan, states, desk);\n\n yield* failpoints.clear;\n if (options?.adapterFailpoints !== undefined) yield* options.adapterFailpoints.clear;\n\n yield* tolerateTyped(runtime.runRecovery);\n // Second, unarmed pass guarantees forward progress for newly marked Unknown lanes.\n yield* resolutionPass(plan, states, desk);\n\n if (yield* allSettled) {\n converged = true;\n break;\n }\n if (options?.betweenRounds !== undefined) yield* options.betweenRounds;\n }\n\n if (!converged) {\n const nonterminal = yield* tolerateTyped(Stream.runCollect(ledger.scanNonterminal));\n const detail = Option.isSome(nonterminal)\n ? Array.from(nonterminal.value)\n .map((row: SubmissionSnapshot) => `${row.submissionId}(${row.state})`)\n .join(\", \")\n : \"ledger scan failed\";\n return yield* ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `plan did not converge within ${maxRounds} rounds; nonterminal: [${detail}]; pending receipts: ${states.filter((state) => state.receipt === undefined).length}`,\n });\n }\n\n // Final claims: the shared invariant checker per touched Conversation, in convergence mode,\n // with the full digest chain (single known producer), plus the desk non-fabrication sweep.\n const produced = yield* desk.produced;\n const laneReports: Array<ChaosLaneReport> = [];\n const verifyConversation = Effect.fn(\"Chaos.verifyConversation\")(function* (\n conversationId: ConversationId,\n kind: ChaosScenarioKind,\n deskInPlay: boolean,\n ) {\n const exported = yield* store.export(ConversationExportRequest.make({ conversationId })).pipe(\n Effect.mapError((error) =>\n ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `export of ${conversationId} failed: ${String(error)}`,\n }),\n ),\n );\n const rows: Array<SubmissionSnapshot> = [];\n for (const submissionId of submissionIdsNamedBy(exported.records)) {\n const found = yield* ledger.lookup(SubmissionLookupById.make({ submissionId })).pipe(\n Effect.mapError((error) =>\n ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `lookup of ${submissionId} failed: ${String(error)}`,\n }),\n ),\n );\n if (Option.isSome(found)) rows.push(found.value);\n }\n const batchProducers = new Map<BatchId, ProducerId>(\n exported.records.map((envelope) => [envelope.batchId, config.producerId]),\n );\n const report = yield* verifyConversationInvariants({\n export: exported,\n submissions: rows,\n batchProducers,\n requireAllSettled: true,\n });\n if (!report.ok) {\n const failed = report.checks\n .filter((check) => check.status === \"failed\")\n .map((check) => `${check.name}: ${check.detail ?? \"failed\"}`)\n .join(\"; \");\n return yield* ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `invariants failed for ${conversationId} (${kind}): ${failed}`,\n });\n }\n if (deskInPlay) {\n yield* assertNoFabrication(plan, exported.records, produced);\n }\n laneReports.push(\n ChaosLaneReport.make({\n conversationId,\n kind,\n submissionCount: rows.length,\n verified: report.ok,\n }),\n );\n });\n\n for (const lane of lanes) {\n yield* verifyConversation(lane.conversationId, lane.kind, lane.deskInPlay);\n // Delegation lanes: verify every materialized child Conversation too.\n for (const flatIndex of lane.submissionIndexes) {\n const receipt = states[flatIndex]?.receipt;\n if (receipt === undefined) continue;\n const child = lane.childConversationOf(receipt);\n if (child === undefined) continue;\n const childExport = yield* Effect.exit(\n store.export(ConversationExportRequest.make({ conversationId: child })),\n );\n if (Exit.isSuccess(childExport) && childExport.value.records.length > 0) {\n yield* verifyConversation(child, \"plain\", false);\n }\n }\n }\n\n const obligations = yield* runtime\n .scanObligations(ObligationThresholds.make({ agingSeconds: 0, overdueSeconds: 0 }))\n .pipe(\n Effect.mapError((error) =>\n ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `scanObligations failed: ${String(error)}`,\n }),\n ),\n );\n if (obligations.entries.length > 0) {\n return yield* ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `open obligations after convergence: ${obligations.entries\n .map((entry) => `${entry.submissionId}(${entry.blockedOn})`)\n .join(\", \")}`,\n });\n }\n\n return ChaosPlanReport.make({\n seed: plan.seed,\n rounds,\n lanes: laneReports,\n openObligations: obligations.entries.length,\n });\n});\n","import {\n CodeExecutionError,\n CodeExecutionHost,\n CodeExecutionLimits,\n CodeExecutionNamespace,\n CodeExecutionRequest,\n CodeExecutionResult,\n CodeExecutor,\n CodeHostCall,\n CodeHostCallFailure,\n CodeHostCallResult,\n CodeHostCallSuccess,\n NetworkAllowlist,\n NetworkDisabled,\n SandboxImplementation,\n} from \"@effect-agent/sandbox\";\nimport { Deferred, Duration, Effect, Fiber, Schema } from \"effect\";\n\n/**\n * Shared `CodeExecutor` conformance (TEST-015). Every adapter — the\n * deterministic `unisolated` substitute and each isolated adapter — runs\n * `codeExecutorConformanceCases` verbatim. Enforcement cases that only genuine\n * isolation can prove (ambient network denial, synchronous CPU runaway\n * termination) are NOT here; they belong to isolated adapters only\n * (testing spec §8.1).\n *\n * Cases assume the live `Clock` (the wall-clock case uses a short real\n * deadline) and take one fresh executor pass per case, so a suite may share\n * one executor Layer across cases.\n */\nexport class CodeExecutorConformanceViolation extends Schema.TaggedError<CodeExecutorConformanceViolation>()(\n \"CodeExecutorConformanceViolation\",\n {\n caseName: Schema.String,\n message: Schema.String,\n },\n) {}\n\nexport interface CodeExecutorConformanceCase {\n readonly name: string;\n readonly run: Effect.Effect<void, CodeExecutorConformanceViolation, CodeExecutor>;\n}\n\nexport interface CodeExecutorConformanceOptions {\n /** The posture the adapter under test must stamp on results and errors. */\n readonly implementation: SandboxImplementation;\n}\n\nconst baseLimits = CodeExecutionLimits.make({\n maxSourceBytes: 64 * 1024,\n maxWallTime: Duration.seconds(10),\n maxLogBytes: 16 * 1024,\n maxResultBytes: 64 * 1024,\n maxHostCalls: 8,\n maxHostCallArgumentBytes: 16 * 1024,\n maxHostCallResultBytes: 32 * 1024,\n});\n\nconst warehouseNamespace = CodeExecutionNamespace.make({\n name: \"warehouse\",\n methods: [\"query\", \"count\"],\n});\n\nconst makeRequest = (\n source: string,\n overrides?: {\n readonly limits?: CodeExecutionLimits;\n readonly namespaces?: ReadonlyArray<CodeExecutionNamespace>;\n readonly network?: CodeExecutionRequest[\"network\"];\n },\n): CodeExecutionRequest =>\n CodeExecutionRequest.make({\n language: \"javascript\",\n source,\n namespaces: overrides?.namespaces ?? [],\n network: overrides?.network ?? NetworkDisabled.make(),\n limits: overrides?.limits ?? baseLimits,\n });\n\nconst unusedHost: CodeExecutionHost[\"Service\"] = {\n call: () =>\n Effect.die(\n new Error(\"this conformance case expected no host call to reach the CodeExecutionHost\"),\n ),\n};\n\nconst respondingHost = (\n respond: (call: CodeHostCall) => CodeHostCallResult,\n): { readonly host: CodeExecutionHost[\"Service\"]; readonly calls: Array<CodeHostCall> } => {\n const calls: Array<CodeHostCall> = [];\n return {\n calls,\n host: {\n call: (call) =>\n Effect.sync(() => {\n calls.push(call);\n return respond(call);\n }),\n },\n };\n};\n\nconst runPass = (\n request: CodeExecutionRequest,\n host: CodeExecutionHost[\"Service\"],\n): Effect.Effect<CodeExecutionResult, CodeExecutionError, CodeExecutor> =>\n Effect.gen(function* () {\n const executor = yield* CodeExecutor;\n return yield* executor\n .execute(request)\n .pipe(Effect.provideService(CodeExecutionHost, CodeExecutionHost.of(host)));\n }).pipe(Effect.scoped);\n\nconst violation = (caseName: string, message: string) =>\n CodeExecutorConformanceViolation.make({ caseName, message });\n\nconst preview = (value: unknown): string => {\n try {\n return JSON.stringify(value)?.slice(0, 200) ?? String(value).slice(0, 200);\n } catch {\n return String(value).slice(0, 200);\n }\n};\n\nconst expectSuccess = (\n caseName: string,\n request: CodeExecutionRequest,\n host: CodeExecutionHost[\"Service\"],\n check: (result: CodeExecutionResult) => string | undefined,\n): Effect.Effect<void, CodeExecutorConformanceViolation, CodeExecutor> =>\n runPass(request, host).pipe(\n Effect.mapError((error) =>\n violation(caseName, `expected success, got ${error._tag}: ${preview(error)}`),\n ),\n Effect.flatMap((result) => {\n const complaint = check(result);\n return complaint === undefined ? Effect.void : Effect.fail(violation(caseName, complaint));\n }),\n );\n\nconst expectFailure = (\n caseName: string,\n request: CodeExecutionRequest,\n host: CodeExecutionHost[\"Service\"],\n tag: CodeExecutionError[\"_tag\"],\n check?: (error: CodeExecutionError) => string | undefined,\n): Effect.Effect<void, CodeExecutorConformanceViolation, CodeExecutor> =>\n runPass(request, host).pipe(\n Effect.flip,\n Effect.mapError((result) =>\n violation(caseName, `expected ${tag}, but the pass succeeded with ${preview(result.value)}`),\n ),\n Effect.flatMap((error) => {\n if (error._tag !== tag) {\n return Effect.fail(\n violation(caseName, `expected ${tag}, got ${error._tag}: ${preview(error)}`),\n );\n }\n const complaint = check?.(error);\n return complaint === undefined ? Effect.void : Effect.fail(violation(caseName, complaint));\n }),\n );\n\nexport const codeExecutorConformanceCases = (\n options: CodeExecutorConformanceOptions,\n): ReadonlyArray<CodeExecutorConformanceCase> => {\n const posture = options.implementation;\n return [\n {\n name: \"TEST-015 executes bounded JSON computation and returns the program value\",\n run: expectSuccess(\n \"TEST-015 executes bounded JSON computation and returns the program value\",\n makeRequest(\n \"async () => { const xs = [1, 2, 3].map((n) => n * 2); return { xs, sum: xs.reduce((a, b) => a + b, 0) }; }\",\n ),\n unusedHost,\n (result) =>\n JSON.stringify(result.value) === JSON.stringify({ xs: [2, 4, 6], sum: 12 })\n ? undefined\n : `unexpected program value ${preview(result.value)}`,\n ),\n },\n {\n name: \"CAP-015 reports its isolation posture honestly in results and errors\",\n run: Effect.gen(function* () {\n const caseName = \"CAP-015 reports its isolation posture honestly in results and errors\";\n const result = yield* runPass(makeRequest(\"async () => 1\"), unusedHost).pipe(\n Effect.mapError((error) => violation(caseName, `expected success, got ${error._tag}`)),\n );\n if (\n result.implementation.isolation !== posture.isolation ||\n result.implementation.identity !== posture.identity\n ) {\n return yield* violation(\n caseName,\n `result posture ${preview(result.implementation)} does not match the declared ${preview(posture)}`,\n );\n }\n const error = yield* runPass(makeRequest(\"async () => {\"), unusedHost).pipe(\n Effect.flip,\n Effect.mapError(() => violation(caseName, \"expected the invalid-source pass to fail\")),\n );\n // Every expected execution failure carries the posture; an adapter\n // omitting the field must fail this case, not slip past a probe.\n if (\n error.implementation === undefined ||\n error.implementation.isolation !== posture.isolation ||\n error.implementation.identity !== posture.identity\n ) {\n return yield* violation(\n caseName,\n `error posture ${preview(error.implementation)} does not match the declared ${preview(posture)}`,\n );\n }\n }),\n },\n {\n name: \"TEST-015 routes host calls through the CodeExecutionHost in program order\",\n run: Effect.gen(function* () {\n const caseName =\n \"TEST-015 routes host calls through the CodeExecutionHost in program order\";\n const { host, calls } = respondingHost((call) =>\n call.method === \"query\"\n ? CodeHostCallSuccess.make({ value: { rows: [1, 2, 3] } })\n : CodeHostCallSuccess.make({ value: 3 }),\n );\n const result = yield* runPass(\n makeRequest(\n \"async () => { const q = await warehouse.query({ sql: 'select' }); const c = await warehouse.count({ table: 't' }); return { rows: q.rows, count: c }; }\",\n { namespaces: [warehouseNamespace] },\n ),\n host,\n ).pipe(\n Effect.mapError((error) =>\n violation(caseName, `expected success, got ${error._tag}: ${preview(error)}`),\n ),\n );\n if (JSON.stringify(result.value) !== JSON.stringify({ rows: [1, 2, 3], count: 3 })) {\n return yield* violation(caseName, `unexpected value ${preview(result.value)}`);\n }\n const observed = calls.map((call) => `${call.namespace}.${call.method}`);\n if (JSON.stringify(observed) !== JSON.stringify([\"warehouse.query\", \"warehouse.count\"])) {\n return yield* violation(caseName, `unexpected host call order ${preview(observed)}`);\n }\n if (result.resourceUse.hostCalls !== 2) {\n return yield* violation(\n caseName,\n `expected 2 accounted host calls, got ${result.resourceUse.hostCalls}`,\n );\n }\n }),\n },\n {\n name: \"TEST-015 a caught failed host call lets the program branch on the envelope\",\n run: expectSuccess(\n \"TEST-015 a caught failed host call lets the program branch on the envelope\",\n makeRequest(\n \"async () => { try { await warehouse.query({ sql: 'x' }); return 'unreachable'; } catch (envelope) { return { caught: envelope }; } }\",\n { namespaces: [warehouseNamespace] },\n ),\n respondingHost(() =>\n CodeHostCallFailure.make({ error: { _tag: \"ToolInputError\", message: \"bad input\" } }),\n ).host,\n (result) =>\n JSON.stringify(result.value) ===\n JSON.stringify({ caught: { _tag: \"ToolInputError\", message: \"bad input\" } })\n ? undefined\n : `the envelope did not round-trip: ${preview(result.value)}`,\n ),\n },\n {\n name: \"TEST-015 an uncaught failed host call fails the program with the envelope\",\n run: expectFailure(\n \"TEST-015 an uncaught failed host call fails the program with the envelope\",\n makeRequest(\"async () => warehouse.query({ sql: 'x' })\", {\n namespaces: [warehouseNamespace],\n }),\n respondingHost(() =>\n CodeHostCallFailure.make({ error: { _tag: \"PolicyDenied\", message: \"denied\" } }),\n ).host,\n \"CodeProgramFailedError\",\n (error) =>\n error._tag === \"CodeProgramFailedError\" &&\n error.reason === \"rejected\" &&\n JSON.stringify(error.thrown) ===\n JSON.stringify({ _tag: \"PolicyDenied\", message: \"denied\" })\n ? undefined\n : `unexpected failure detail ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 fails typed on syntactically invalid source\",\n run: expectFailure(\n \"TEST-015 fails typed on syntactically invalid source\",\n makeRequest(\"async () => {\"),\n unusedHost,\n \"CodeSourceError\",\n (error) =>\n error._tag === \"CodeSourceError\" && error.reason === \"invalid\"\n ? undefined\n : `expected reason invalid, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 fails typed when the expression is not one async function\",\n run: expectFailure(\n \"TEST-015 fails typed when the expression is not one async function\",\n makeRequest(\"1 + 1\"),\n unusedHost,\n \"CodeSourceError\",\n (error) =>\n error._tag === \"CodeSourceError\" && error.reason === \"not-a-function\"\n ? undefined\n : `expected reason not-a-function, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 fails typed on source larger than the declared byte limit\",\n run: expectFailure(\n \"TEST-015 fails typed on source larger than the declared byte limit\",\n makeRequest(`async () => \"${\"x\".repeat(2_000)}\"`, {\n limits: CodeExecutionLimits.make({ ...baseLimits, maxSourceBytes: 256 }),\n }),\n unusedHost,\n \"CodeSourceError\",\n (error) =>\n error._tag === \"CodeSourceError\" && error.reason === \"oversized\"\n ? undefined\n : `expected reason oversized, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 terminates a never-settling program at the wall-clock deadline\",\n run: expectFailure(\n \"TEST-015 terminates a never-settling program at the wall-clock deadline\",\n makeRequest(\"async () => { await new Promise(() => {}); return 1; }\", {\n limits: CodeExecutionLimits.make({ ...baseLimits, maxWallTime: Duration.millis(250) }),\n }),\n unusedHost,\n \"CodeExecutionTimeoutError\",\n ),\n },\n {\n name: \"TEST-015 fails typed when console output exceeds its byte budget\",\n run: expectFailure(\n \"TEST-015 fails typed when console output exceeds its byte budget\",\n makeRequest(\n \"async () => { for (let i = 0; i < 64; i += 1) { console.log('x'.repeat(256)); } return 1; }\",\n { limits: CodeExecutionLimits.make({ ...baseLimits, maxLogBytes: 2_048 }) },\n ),\n unusedHost,\n \"CodeOutputLimitError\",\n (error) =>\n error._tag === \"CodeOutputLimitError\" && error.surface === \"logs\"\n ? undefined\n : `expected surface logs, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 fails typed when the final result exceeds its byte budget\",\n run: expectFailure(\n \"TEST-015 fails typed when the final result exceeds its byte budget\",\n makeRequest(\"async () => 'y'.repeat(4096)\", {\n limits: CodeExecutionLimits.make({ ...baseLimits, maxResultBytes: 1_024 }),\n }),\n unusedHost,\n \"CodeOutputLimitError\",\n (error) =>\n error._tag === \"CodeOutputLimitError\" && error.surface === \"result\"\n ? undefined\n : `expected surface result, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 fails typed when host calls exceed the executor cap\",\n run: Effect.gen(function* () {\n const caseName = \"TEST-015 fails typed when host calls exceed the executor cap\";\n const { host, calls } = respondingHost(() => CodeHostCallSuccess.make({ value: null }));\n yield* expectFailure(\n caseName,\n makeRequest(\n \"async () => { await warehouse.query({}); await warehouse.query({}); await warehouse.query({}); return 1; }\",\n {\n namespaces: [warehouseNamespace],\n limits: CodeExecutionLimits.make({ ...baseLimits, maxHostCalls: 2 }),\n },\n ),\n host,\n \"CodeHostCallLimitError\",\n );\n // The cap is enforced before dispatch: the over-limit call must never\n // have reached the host, or an unauthorized side effect already ran.\n if (calls.length !== 2) {\n return yield* violation(\n caseName,\n `expected exactly 2 dispatched host calls under a cap of 2, observed ${calls.length}`,\n );\n }\n }),\n },\n {\n name: \"TEST-015 fails typed on a host outcome outside the protocol schema\",\n run: expectFailure(\n \"TEST-015 fails typed on a host outcome outside the protocol schema\",\n makeRequest(\"async () => warehouse.query({})\", { namespaces: [warehouseNamespace] }),\n {\n call: () => Effect.succeed({ bogus: true } as unknown as CodeHostCallResult),\n },\n \"CodeExecutionProtocolError\",\n ),\n },\n {\n name: \"TEST-015 surfaces an uncaught program throw with its bounded log capture\",\n run: expectFailure(\n \"TEST-015 surfaces an uncaught program throw with its bounded log capture\",\n makeRequest(\n \"async () => { console.log('before the failure'); throw new Error('deliberate'); }\",\n ),\n unusedHost,\n \"CodeProgramFailedError\",\n (error) =>\n error._tag === \"CodeProgramFailedError\" &&\n error.reason === \"threw\" &&\n error.logs.some((line) => line.includes(\"before the failure\"))\n ? undefined\n : `expected a threw failure carrying the log capture, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 fails typed when the program returns a non-JSON value\",\n run: expectFailure(\n \"TEST-015 fails typed when the program returns a non-JSON value\",\n makeRequest(\"async () => (() => 1)\"),\n unusedHost,\n \"CodeProgramFailedError\",\n (error) =>\n error._tag === \"CodeProgramFailedError\" && error.reason === \"non-json-result\"\n ? undefined\n : `expected reason non-json-result, got ${preview(error)}`,\n ),\n },\n {\n name: \"CAP-015 rejects a network allowlist it cannot enforce with a typed unsupported error\",\n run: expectFailure(\n \"CAP-015 rejects a network allowlist it cannot enforce with a typed unsupported error\",\n makeRequest(\"async () => 1\", {\n network: NetworkAllowlist.make({ domains: [\"example.com\"], ports: [443] }),\n }),\n unusedHost,\n \"CodeExecutorUnsupportedError\",\n (error) =>\n error._tag === \"CodeExecutorUnsupportedError\" && error.feature === \"network\"\n ? undefined\n : `expected feature network, got ${preview(error)}`,\n ),\n },\n {\n name: \"TEST-015 interruption reaches in-flight host calls and pass teardown\",\n run: Effect.gen(function* () {\n const caseName = \"TEST-015 interruption reaches in-flight host calls and pass teardown\";\n const started = yield* Deferred.make<void>();\n const witness = { hostCallInterrupted: false };\n const host: CodeExecutionHost[\"Service\"] = {\n call: () =>\n Deferred.succeed(started, undefined).pipe(\n Effect.andThen(Effect.never),\n Effect.ensuring(\n Effect.sync(() => {\n witness.hostCallInterrupted = true;\n }),\n ),\n ),\n };\n const fiber = yield* runPass(\n makeRequest(\"async () => warehouse.query({})\", { namespaces: [warehouseNamespace] }),\n host,\n ).pipe(Effect.forkChild);\n // Guard against a broken adapter that settles the pass without ever\n // reaching the host: the case must report a violation, not hang.\n const winner = yield* Effect.raceFirst(\n Deferred.await(started).pipe(Effect.as(\"started\" as const)),\n Fiber.join(fiber).pipe(Effect.exit, Effect.as(\"exited\" as const)),\n );\n if (winner === \"exited\") {\n return yield* violation(\n caseName,\n \"the pass settled before any host call reached the CodeExecutionHost\",\n );\n }\n yield* Fiber.interrupt(fiber);\n if (!witness.hostCallInterrupted) {\n return yield* violation(\n caseName,\n \"interrupting the pass did not interrupt the in-flight host call\",\n );\n }\n }),\n },\n ];\n};\n","import {\n CodeExecutionHost,\n CodeExecutionLimits,\n CodeExecutionNamespace,\n CodeExecutionProtocolError,\n CodeExecutionRequest,\n CodeExecutionResourceUse,\n CodeExecutionResult,\n CodeExecutionTimeoutError,\n CodeExecutor,\n type CodeExecutorExecute,\n CodeExecutorUnsupportedError,\n CodeHostCall,\n CodeHostCallLimitError,\n CodeHostCallResult,\n CodeOutputLimitError,\n CodeProgramFailedError,\n CodeSourceError,\n SandboxImplementation,\n} from \"@effect-agent/sandbox\";\nimport { Clock, Duration, Effect, Fiber, Layer, Option, Queue, Schema } from \"effect\";\n\n/**\n * The deterministic in-process executor substitute (C1 of ADR-0017). It runs\n * the generated program on the host JavaScript engine with best-effort global\n * shadowing only, so it self-identifies as `unisolated` and is never a\n * security boundary (CAP-010, CAP-015). It exists to prove the public\n * `CodeExecutor` contract and to drive deterministic capability tests.\n */\nexport const inProcessCodeExecutorImplementation = SandboxImplementation.make({\n isolation: \"unisolated\",\n identity: \"in-process-javascript\",\n});\n\n// These two caps mirror the wire schema bounds (`BoundedLogs` is at most\n// 4096 lines of at most 16 KiB each): capture must stay inside what\n// `CodeExecutionResult` can carry. A line over the per-line cap is truncated\n// with an explicit `…` marker; exceeding either the byte budget or the line\n// cap fails the pass typed.\nconst MAX_LOG_LINES = 4_096;\nconst MAX_LOG_LINE_CHARACTERS = 16_000;\nconst MAX_THROWN_CHARACTERS = 4_000;\n\nconst utf8ByteLength = (value: string): number => new TextEncoder().encode(value).byteLength;\n\n/**\n * Ambient globals shadowed inside the harness. Shadowing blocks the obvious\n * identifier paths only; a determined program can still escape, which is\n * exactly why this executor reports `unisolated` and the isolated network and\n * CPU enforcement conformance cases run only against isolated adapters.\n */\nconst shadowedGlobals = [\n \"fetch\",\n \"process\",\n \"require\",\n \"module\",\n \"exports\",\n \"global\",\n \"globalThis\",\n \"XMLHttpRequest\",\n \"WebSocket\",\n \"Deno\",\n \"Bun\",\n] as const;\n\nclass LogLimitSignal {\n constructor(readonly observed: number) {}\n}\n\nclass EvaluationThrew {\n constructor(readonly inner: unknown) {}\n}\n\nclass NotAFunction {\n constructor(readonly actual: string) {}\n}\n\ninterface LogCapture {\n readonly lines: Array<string>;\n bytes: number;\n}\n\n/**\n * Total, defect-free rendering of untrusted values: a hostile Proxy can throw\n * from property access, `toString`, and `Symbol.toPrimitive`, and an expected\n * program failure must never escape the typed channel as a defect while its\n * diagnostics are being serialized.\n */\nconst formatLogValue = (value: unknown): string => {\n try {\n if (typeof value === \"string\") {\n return value;\n }\n return JSON.stringify(value) ?? String(value);\n } catch {\n try {\n return String(value);\n } catch {\n return \"[unprintable value]\";\n }\n }\n};\n\nconst makeConsole = (capture: LogCapture, limits: CodeExecutionLimits) => {\n const write = (...values: ReadonlyArray<unknown>): void => {\n const joined = values.map(formatLogValue).join(\" \");\n const line =\n joined.length > MAX_LOG_LINE_CHARACTERS\n ? `${joined.slice(0, MAX_LOG_LINE_CHARACTERS - 1)}…`\n : joined;\n const bytes = utf8ByteLength(line);\n if (capture.lines.length >= MAX_LOG_LINES || capture.bytes + bytes > limits.maxLogBytes) {\n throw new LogLimitSignal(capture.bytes + bytes);\n }\n capture.lines.push(line);\n capture.bytes += bytes;\n };\n return { debug: write, error: write, info: write, log: write, warn: write };\n};\n\ninterface PendingHostCall {\n readonly namespace: string;\n readonly method: string;\n readonly argument: unknown;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n}\n\nconst buildNamespaceObject = (\n namespace: CodeExecutionNamespace,\n offer: (pending: PendingHostCall) => void,\n): Record<string, unknown> => {\n const methods: Record<string, unknown> = {};\n for (const method of namespace.methods) {\n methods[method] = (argument: unknown) =>\n new Promise((resolve, reject) => {\n offer({ namespace: namespace.name, method, argument, resolve, reject });\n });\n }\n return methods;\n};\n\nconst boundedText = (value: unknown): string => {\n try {\n const text = value instanceof Error ? `${value.name}: ${value.message}` : formatLogValue(value);\n return text.slice(0, MAX_THROWN_CHARACTERS);\n } catch {\n return \"[unserializable thrown value]\";\n }\n};\n\n/** Schema decoding of hostile values may itself throw through trap getters. */\nconst safeDecodeJson = (value: unknown): Option.Option<Schema.Json> => {\n try {\n return Schema.decodeUnknownOption(Schema.Json)(value);\n } catch {\n return Option.none();\n }\n};\n\nconst boundedThrown = (value: unknown): Schema.Json => {\n const decoded = safeDecodeJson(value);\n if (Option.isSome(decoded)) {\n try {\n const encoded = JSON.stringify(decoded.value);\n if (encoded !== undefined && encoded.length <= MAX_THROWN_CHARACTERS) {\n return decoded.value;\n }\n } catch {\n // fall through to the bounded string form\n }\n }\n return boundedText(value);\n};\n\nconst encodedJsonByteLength = (value: Schema.Json): number | undefined => {\n try {\n const encoded = JSON.stringify(value);\n return encoded === undefined ? undefined : utf8ByteLength(encoded);\n } catch {\n return undefined;\n }\n};\n\n/** Host outcomes are protocol input; a hostile value must not defect mid-decode. */\nconst decodeHostOutcome = (value: unknown): Option.Option<CodeHostCallResult> => {\n try {\n return Schema.decodeUnknownOption(CodeHostCallResult)(value);\n } catch {\n return Option.none();\n }\n};\n\nconst validateRequest = (\n request: CodeExecutionRequest,\n): Effect.Effect<void, CodeExecutorUnsupportedError | CodeSourceError> =>\n Effect.gen(function* () {\n if (request.network._tag !== \"NetworkDisabled\") {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: inProcessCodeExecutorImplementation,\n feature: \"network\",\n message:\n \"The unisolated in-process executor cannot enforce an egress allowlist; only NetworkDisabled is accepted, and even that is shadowed rather than enforced\",\n });\n }\n if (request.limits.cpuMillis !== undefined) {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: inProcessCodeExecutorImplementation,\n feature: \"cpu-limit\",\n message:\n \"The unisolated in-process executor shares the host engine and cannot enforce a CPU limit\",\n });\n }\n const reservedNames = new Set<string>([...shadowedGlobals, \"console\"]);\n const seen = new Set<string>();\n for (const namespace of request.namespaces) {\n if (reservedNames.has(namespace.name) || seen.has(namespace.name)) {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: inProcessCodeExecutorImplementation,\n feature: \"namespaces\",\n message: `Namespace ${namespace.name} collides with a harness binding or another namespace`,\n });\n }\n seen.add(namespace.name);\n }\n const sourceBytes = utf8ByteLength(request.source);\n if (sourceBytes > request.limits.maxSourceBytes) {\n return yield* CodeSourceError.make({\n implementation: inProcessCodeExecutorImplementation,\n reason: \"oversized\",\n message: `Source is ${sourceBytes} bytes; the request allows ${request.limits.maxSourceBytes}`,\n });\n }\n });\n\nconst serveHostCalls = (\n host: CodeExecutionHost[\"Service\"],\n queue: Queue.Queue<PendingHostCall>,\n limits: CodeExecutionLimits,\n capture: LogCapture,\n counter: { calls: number },\n): Effect.Effect<\n never,\n CodeHostCallLimitError | CodeOutputLimitError | CodeExecutionProtocolError\n> =>\n Effect.gen(function* () {\n while (true) {\n const pending = yield* Queue.take(queue);\n counter.calls += 1;\n if (counter.calls > limits.maxHostCalls) {\n return yield* CodeHostCallLimitError.make({\n implementation: inProcessCodeExecutorImplementation,\n limit: limits.maxHostCalls,\n logs: [...capture.lines],\n });\n }\n const argument = safeDecodeJson(pending.argument);\n if (Option.isNone(argument)) {\n pending.reject(new TypeError(\"host call arguments must be JSON values\"));\n continue;\n }\n const argumentBytes = encodedJsonByteLength(argument.value);\n if (argumentBytes === undefined || argumentBytes > limits.maxHostCallArgumentBytes) {\n return yield* CodeOutputLimitError.make({\n implementation: inProcessCodeExecutorImplementation,\n surface: \"host-call-argument\",\n limit: limits.maxHostCallArgumentBytes,\n observed: argumentBytes ?? 0,\n logs: [...capture.lines],\n });\n }\n const rawOutcome = yield* host.call(\n CodeHostCall.make({\n namespace: pending.namespace,\n method: pending.method,\n argument: argument.value,\n }),\n );\n const outcome = decodeHostOutcome(rawOutcome);\n if (Option.isNone(outcome)) {\n return yield* CodeExecutionProtocolError.make({\n implementation: inProcessCodeExecutorImplementation,\n message: \"The execution host returned a value outside the CodeHostCallResult schema\",\n });\n }\n if (outcome.value._tag === \"CodeHostCallFailure\") {\n pending.reject(outcome.value.error);\n continue;\n }\n const resultBytes = encodedJsonByteLength(outcome.value.value);\n if (resultBytes === undefined || resultBytes > limits.maxHostCallResultBytes) {\n return yield* CodeOutputLimitError.make({\n implementation: inProcessCodeExecutorImplementation,\n surface: \"host-call-result\",\n limit: limits.maxHostCallResultBytes,\n observed: resultBytes ?? 0,\n logs: [...capture.lines],\n });\n }\n pending.resolve(outcome.value.value);\n }\n });\n\nconst classifyProgramFailure = (\n thrown: unknown,\n limits: CodeExecutionLimits,\n capture: LogCapture,\n): CodeOutputLimitError | CodeSourceError | CodeProgramFailedError => {\n const inner = thrown instanceof EvaluationThrew ? thrown.inner : thrown;\n if (inner instanceof LogLimitSignal) {\n return CodeOutputLimitError.make({\n implementation: inProcessCodeExecutorImplementation,\n surface: \"logs\",\n limit: limits.maxLogBytes,\n observed: inner.observed,\n logs: [...capture.lines],\n });\n }\n if (inner instanceof NotAFunction) {\n return CodeSourceError.make({\n implementation: inProcessCodeExecutorImplementation,\n reason: \"not-a-function\",\n message: `The source expression evaluated to ${inner.actual}; it must evaluate to one async function`,\n });\n }\n // An async function converts a body-level `throw` into a rejection, so the\n // split is by value shape: exception-like values read as `threw`, plain\n // rejection values (an uncaught host failure envelope) read as `rejected`.\n const reason = thrown instanceof EvaluationThrew || inner instanceof Error ? \"threw\" : \"rejected\";\n return CodeProgramFailedError.make({\n implementation: inProcessCodeExecutorImplementation,\n reason,\n thrown: boundedThrown(inner),\n message: boundedText(inner),\n logs: [...capture.lines],\n });\n};\n\nconst executeInProcess: CodeExecutorExecute = Effect.fn(\"InProcessCodeExecutor.execute\")(\n function* (request) {\n yield* validateRequest(request);\n const host = yield* CodeExecutionHost;\n const capture: LogCapture = { lines: [], bytes: 0 };\n const counter = { calls: 0 };\n const queue = yield* Queue.unbounded<PendingHostCall>();\n\n const factory = yield* Effect.try({\n try: () =>\n new Function(\n ...shadowedGlobals,\n \"console\",\n ...request.namespaces.map((namespace) => namespace.name),\n `\"use strict\";\\nreturn (\\n${request.source}\\n);`,\n ),\n catch: (cause) =>\n CodeSourceError.make({\n implementation: inProcessCodeExecutorImplementation,\n reason: \"invalid\",\n message: boundedText(cause),\n }),\n });\n\n const harnessConsole = makeConsole(capture, request.limits);\n // Admission is enforced at call creation, not only at the single-consumer\n // dequeue: a burst of unawaited calls can enqueue at most one entry past\n // the cap (the entry the server fails the pass on); everything beyond is\n // rejected synchronously, so the queue stays bounded against hostile\n // programs.\n let issuedHostCalls = 0;\n const namespaceObjects = request.namespaces.map((namespace) =>\n buildNamespaceObject(namespace, (pending) => {\n issuedHostCalls += 1;\n if (issuedHostCalls > request.limits.maxHostCalls + 1) {\n pending.reject(new Error(`host-call limit of ${request.limits.maxHostCalls} exceeded`));\n return;\n }\n Queue.offerUnsafe(queue, pending);\n }),\n );\n\n const server = yield* serveHostCalls(host, queue, request.limits, capture, counter).pipe(\n Effect.forkScoped,\n );\n\n const program = Effect.tryPromise({\n try: async () => {\n let candidate: unknown;\n try {\n candidate = factory(\n ...shadowedGlobals.map(() => undefined),\n harnessConsole,\n ...namespaceObjects,\n );\n } catch (cause) {\n throw new EvaluationThrew(cause);\n }\n if (typeof candidate !== \"function\") {\n throw new EvaluationThrew(new NotAFunction(typeof candidate));\n }\n let outcome: unknown;\n try {\n outcome = (candidate as () => unknown)();\n } catch (cause) {\n throw new EvaluationThrew(cause);\n }\n return await Promise.resolve(outcome);\n },\n catch: (thrown) => classifyProgramFailure(thrown, request.limits, capture),\n });\n\n const startedAt = yield* Clock.currentTimeMillis;\n // The wall-clock deadline interrupts only at asynchronous suspension\n // points: a synchronous runaway shares the host thread and cannot be\n // stopped in-process — exactly why the platform CPU enforcement cases\n // belong to isolated adapters only (testing spec §8.1). The server fiber\n // is interrupted when the pass settles so no host call outlives the\n // program that issued it.\n const returned = yield* Effect.raceFirst(program, Fiber.join(server)).pipe(\n Effect.timeoutOrElse({\n duration: request.limits.maxWallTime,\n orElse: () =>\n CodeExecutionTimeoutError.make({\n implementation: inProcessCodeExecutorImplementation,\n kind: \"wall-clock\",\n maxWallTime: request.limits.maxWallTime,\n logs: [...capture.lines],\n }),\n }),\n Effect.ensuring(Fiber.interrupt(server)),\n );\n const finishedAt = yield* Clock.currentTimeMillis;\n\n // An unawaited burst can outrun the server: the program may return before\n // the over-limit entry is dequeued, so the admission counter is the\n // authority — a pass that ISSUED more calls than the cap fails even when\n // its promise settled first.\n if (issuedHostCalls > request.limits.maxHostCalls) {\n return yield* CodeHostCallLimitError.make({\n implementation: inProcessCodeExecutorImplementation,\n limit: request.limits.maxHostCalls,\n logs: [...capture.lines],\n });\n }\n\n const value = yield* Schema.decodeUnknownEffect(Schema.Json)(returned).pipe(\n Effect.mapError(() =>\n CodeProgramFailedError.make({\n implementation: inProcessCodeExecutorImplementation,\n reason: \"non-json-result\",\n thrown: null,\n message: \"The program must return a JSON value\",\n logs: [...capture.lines],\n }),\n ),\n );\n const resultBytes = encodedJsonByteLength(value);\n if (resultBytes === undefined || resultBytes > request.limits.maxResultBytes) {\n return yield* CodeOutputLimitError.make({\n implementation: inProcessCodeExecutorImplementation,\n surface: \"result\",\n limit: request.limits.maxResultBytes,\n observed: resultBytes ?? 0,\n logs: [...capture.lines],\n });\n }\n\n return CodeExecutionResult.make({\n implementation: inProcessCodeExecutorImplementation,\n value,\n logs: [...capture.lines],\n resourceUse: CodeExecutionResourceUse.make({\n wallTime: Duration.millis(Math.max(0, finishedAt - startedAt)),\n hostCalls: counter.calls,\n logBytes: capture.bytes,\n resultBytes,\n }),\n });\n },\n);\n\n/**\n * Layer providing the unisolated in-process `CodeExecutor` substitute. The\n * per-pass `CodeExecutionHost` stays in the caller's requirement channel, the\n * same as every real adapter.\n */\nexport const inProcessCodeExecutorLayer: Layer.Layer<CodeExecutor> = Layer.succeed(CodeExecutor)(\n CodeExecutor.of({ execute: executeInProcess }),\n);\n","import { Subagent, SubagentPolicy, SubagentRuntime } from \"@effect-agent/capabilities\";\nimport { Agent, AgentPolicy } from \"@effect-agent/core\";\nimport type { RuntimeBinding } from \"@effect-agent/engine\";\nimport { Context, Effect, Schema } from \"effect\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\n\n// ---------------------------------------------------------------------------\n// Docs Researcher (P7 internal agent #3, plan §6): a coordinator that\n// delegates per-document summarization to a doc-summarizer child through the\n// S2 durable delegation surface, with the child's content tools served —\n// and validated — through the MCP connector against a scripted MCP fixture.\n// The corpus, tools, and both Agent Definitions are deterministic fixtures in\n// the travel-planner style so DN tests (and any later DC assembly) reuse them.\n// ---------------------------------------------------------------------------\n\nexport const ResearchDocumentId = Schema.NonEmptyString.check(Schema.isMaxLength(64)).pipe(\n Schema.brand(\"@effect-agent/testing/docs-researcher/ResearchDocumentId\"),\n);\nexport type ResearchDocumentId = typeof ResearchDocumentId.Type;\n\nconst BoundedTitle = Schema.NonEmptyString.check(Schema.isMaxLength(120));\nconst BoundedBody = Schema.NonEmptyString.check(Schema.isMaxLength(16 * 1024));\n/** Bounded summary text: the ONLY child-derived text that may cross to the parent. */\nexport const BoundedSummary = Schema.NonEmptyString.check(Schema.isMaxLength(240));\n\nexport class DocumentQuery extends Schema.Class<DocumentQuery>(\"DocumentQuery\")({\n documentId: ResearchDocumentId,\n}) {}\n\n/** One bounded research document as the MCP content server exposes it. */\nexport class ResearchDocument extends Schema.Class<ResearchDocument>(\"ResearchDocument\")({\n documentId: ResearchDocumentId,\n title: BoundedTitle,\n body: BoundedBody,\n}) {}\n\nexport class DocumentUnavailable extends Schema.TaggedError<DocumentUnavailable>()(\n \"DocumentUnavailable\",\n {\n documentId: ResearchDocumentId,\n message: Schema.String,\n },\n) {}\n\n/** The content store behind the scripted MCP server. */\nexport class DocumentLibrary extends Context.Service<\n DocumentLibrary,\n {\n readonly fetch: (query: DocumentQuery) => Effect.Effect<ResearchDocument, DocumentUnavailable>;\n }\n>()(\"@effect-agent/testing/docs-researcher/DocumentLibrary\") {}\n\n/**\n * The one content tool the doc-summarizer child uses. Its authored JSON\n * schema is what MCP discovery must serve byte-for-byte: the scripted MCP\n * fixture derives its discovery entry from `Tool.getJsonSchema(FetchDocument)`\n * and `validateMcpDiscovery` re-derives and digests both sides (CAP-009).\n */\nexport const FetchDocument = Tool.make(\"fetch_document\", {\n description: \"Fetch one bounded research document by its identifier.\",\n parameters: DocumentQuery,\n success: ResearchDocument,\n failure: DocumentUnavailable,\n failureMode: \"error\",\n dependencies: [DocumentLibrary],\n});\n\nexport const DocContentToolkit = Toolkit.make(FetchDocument);\nexport const docContentToolkitLayer = DocContentToolkit.toLayer({\n fetch_document: (query) => Effect.flatMap(DocumentLibrary, (library) => library.fetch(query)),\n});\n\n// ---------------------------------------------------------------------------\n// Deterministic corpus. Every body deliberately embeds BOTH a secret marker\n// and a distinctive body phrase: the tests assert that neither ever reaches\n// the parent Conversation, the parent prompts, or a redacted preview — only\n// the bounded summary crosses the delegation boundary (SUB-015, SEC-008).\n// ---------------------------------------------------------------------------\n\n/** Never allowed outside a child Conversation or an unredacted fixture value. */\nexport const docsDocumentBodySecret = \"docs-vault-secret-771\";\n\nconst decodeDocumentId = Schema.decodeSync(ResearchDocumentId);\n\ninterface CorpusEntry {\n readonly document: ResearchDocument;\n readonly bodyPhrase: string;\n readonly summary: string;\n}\n\nconst corpusEntries = new Map<string, CorpusEntry>(\n [\n {\n documentId: \"durability-notes\",\n title: \"Durability protocol notes\",\n bodyPhrase: \"amber-ledger-passage\",\n summary:\n \"Settlement results are recorded exactly once while external side effects stay at-least-once.\",\n },\n {\n documentId: \"subagent-notes\",\n title: \"Subagent join notes\",\n bodyPhrase: \"cobalt-join-corridor\",\n summary: \"A parent joins only the verified settlement of its own established child.\",\n },\n ].map((entry) => [\n entry.documentId,\n {\n document: ResearchDocument.make({\n documentId: decodeDocumentId(entry.documentId),\n title: entry.title,\n body: `${entry.bodyPhrase}: internal working notes. ${docsDocumentBodySecret}. ${entry.summary} Raw notes stay inside the child Conversation.`,\n }),\n bodyPhrase: entry.bodyPhrase,\n summary: entry.summary,\n },\n ]),\n);\n\n/** The corpus document ids in canonical fixture order. */\nexport const researchCorpusDocumentIds: ReadonlyArray<ResearchDocumentId> = [\n decodeDocumentId(\"durability-notes\"),\n decodeDocumentId(\"subagent-notes\"),\n];\n\nconst requireCorpusEntry = (documentId: string): CorpusEntry => {\n const entry = corpusEntries.get(documentId);\n if (entry === undefined) {\n throw new Error(`No deterministic corpus entry exists for document ${documentId}`);\n }\n return entry;\n};\n\n/** Deterministic library lookup shared by the scripted MCP content handlers. */\nexport const researchDocumentLookup = (\n query: DocumentQuery,\n): Effect.Effect<ResearchDocument, DocumentUnavailable> => {\n const entry = corpusEntries.get(query.documentId);\n return entry === undefined\n ? Effect.fail(\n DocumentUnavailable.make({\n documentId: query.documentId,\n message: \"No deterministic corpus entry exists for this document.\",\n }),\n )\n : Effect.succeed(entry.document);\n};\n\n/** The full fixture document (body includes the secret marker — child-side only). */\nexport const researchDocumentFor = (documentId: string): ResearchDocument =>\n requireCorpusEntry(documentId).document;\n\n/** The distinctive body phrase used by context-isolation assertions. */\nexport const documentBodyPhrase = (documentId: string): string =>\n requireCorpusEntry(documentId).bodyPhrase;\n\n// ---------------------------------------------------------------------------\n// Doc Summarizer: the child Agent Definition. Its toolkit is the authored\n// `DocContentToolkit`; the harness registers its worker Binding only after\n// MCP discovery validates that exact toolkit (mcp.ts).\n// ---------------------------------------------------------------------------\n\nexport class SummaryBrief extends Schema.Class<SummaryBrief>(\"SummaryBrief\")({\n documentId: ResearchDocumentId,\n focus: Schema.NonEmptyString,\n}) {}\n\nexport class DocumentSummary extends Schema.Class<DocumentSummary>(\"DocumentSummary\")({\n documentId: ResearchDocumentId,\n summary: BoundedSummary,\n}) {}\n\n/** The summary the scripted child writes after fetching the document. */\nexport const documentSummaryFor = (documentId: string): DocumentSummary =>\n DocumentSummary.make({\n documentId: requireCorpusEntry(documentId).document.documentId,\n summary: requireCorpusEntry(documentId).summary,\n });\n\nexport const encodedDocumentSummary = (documentId: string): string =>\n JSON.stringify(Schema.encodeSync(DocumentSummary)(documentSummaryFor(documentId)));\n\nexport const DocSummarizer = Agent.define(\"doc-summarizer\", {\n input: SummaryBrief,\n output: DocumentSummary,\n instructions:\n \"Fetch the briefed document with fetch_document exactly once, then return only a JSON document summary. Never copy raw notes or secrets into the summary.\",\n toolkit: DocContentToolkit,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 1,\n maxDuration: \"30 seconds\",\n toolConcurrency: 1,\n }),\n description: \"Summarize one bounded research document fetched through MCP content tools.\",\n metadata: { deploymentClass: \"DN\", phase: \"P7\" },\n});\n\n// ---------------------------------------------------------------------------\n// Delegation Definition: the coordinator sees exactly one Tool with explicit\n// projections and finite bounds. `projectResult` is the declassification\n// boundary (SUB-015): only the bounded summary crosses; the fetched body —\n// secret marker included — stays in the child Conversation.\n// ---------------------------------------------------------------------------\n\nexport class SummaryRequest extends Schema.Class<SummaryRequest>(\"SummaryRequest\")({\n documentId: ResearchDocumentId,\n}) {}\n\nexport class SummaryFinding extends Schema.Class<SummaryFinding>(\"SummaryFinding\")({\n documentId: ResearchDocumentId,\n summary: BoundedSummary,\n}) {}\n\nexport class DocumentSummaryFailed extends Schema.TaggedError<DocumentSummaryFailed>()(\n \"DocumentSummaryFailed\",\n {\n childErrorTag: Schema.NonEmptyString,\n },\n) {}\n\n/** Finite per-invocation bounds (SUB-009): one fetch per child, two children per Run. */\nexport const documentSummaryPolicy = SubagentPolicy.make({\n maxChildren: 2,\n maxConcurrency: 2,\n maxTurns: 2,\n maxToolCalls: 1,\n maxDuration: \"10 seconds\",\n});\n\nexport const delegateDocumentSummary = Subagent.define(\"delegate_document_summary\", {\n description:\n \"Summarize one research document through the doc-summarizer child and return a bounded finding.\",\n target: DocSummarizer,\n parameters: SummaryRequest,\n success: SummaryFinding,\n failure: DocumentSummaryFailed,\n prepareInput: (request) =>\n Effect.succeed(\n SummaryBrief.make({\n documentId: request.documentId,\n focus: \"summarize:durability-claims\",\n }),\n ),\n projectResult: (summary) =>\n Effect.succeed(\n SummaryFinding.make({\n documentId: summary.documentId,\n summary: summary.summary,\n }),\n ),\n policy: documentSummaryPolicy,\n});\n\n/** Total mapping from every expected child Run failure to the declared Tool failure (SUB-028). */\nexport const mapSummaryChildFailure = (failure: { readonly _tag: string }): DocumentSummaryFailed =>\n DocumentSummaryFailed.make({ childErrorTag: failure._tag });\n\n/** The exact digest strings the durable declaration AND host registration must share (SUB-023). */\nexport const docsSummarizerDigestStrings = {\n agent: \"50\".repeat(32),\n model: \"51\".repeat(32),\n tools: \"52\".repeat(32),\n} as const;\n\n/** Runtime wiring: the immutable delegation plus one explicit child Binding (S2 declaration). */\nexport const docsSummaryHandlersLayer = <Provider, ModelProvides, ModelRequires>(\n childBinding: RuntimeBinding<\n typeof SummaryBrief,\n typeof DocumentSummary,\n string,\n Toolkit.Tools<typeof DocContentToolkit>,\n Provider,\n ModelProvides,\n ModelRequires\n >,\n) =>\n SubagentRuntime.layer(delegateDocumentSummary, childBinding, {\n mapChildFailure: mapSummaryChildFailure,\n durable: { targetDigests: docsSummarizerDigestStrings },\n });\n\n// ---------------------------------------------------------------------------\n// Docs Researcher: the parent Agent Definition.\n// ---------------------------------------------------------------------------\n\nexport class ResearchRequest extends Schema.Class<ResearchRequest>(\"ResearchRequest\")({\n question: Schema.NonEmptyString,\n documentIds: Schema.Array(ResearchDocumentId).check(Schema.isMinLength(1)),\n}) {}\n\nexport class ResearchDigest extends Schema.Class<ResearchDigest>(\"ResearchDigest\")({\n findings: Schema.Array(SummaryFinding),\n nextAction: Schema.Literal(\"review\"),\n}) {}\n\n/** Parent-only transcript markers proving child context isolation (SUB-006/SUB-015). */\nexport const docsCoordinatorConfidentialMarker = \"docs-coordinator-vault-19x\";\nexport const docsMissionConfidentialMarker = \"docs-mission-dossier-42f\";\n\nexport const DocsResearcherToolkit = Toolkit.make(delegateDocumentSummary.tool);\n\nexport const DocsResearcher = Agent.define(\"docs-researcher\", {\n input: ResearchRequest,\n output: ResearchDigest,\n instructions: [\n \"You are the Effect Agent P7 docs-researcher coordinator.\",\n `Coordinator-only context: ${docsCoordinatorConfidentialMarker}.`,\n \"Call delegate_document_summary once per requested document in one Tool batch.\",\n \"Return only a JSON digest built from the delegated findings. This is read-only research.\",\n ].join(\"\\n\"),\n toolkit: DocsResearcherToolkit,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 2,\n maxDuration: \"30 seconds\",\n toolConcurrency: 2,\n }),\n description: \"Coordinate per-document summarization through one declared delegation Tool.\",\n metadata: { deploymentClass: \"DN\", phase: \"P7\" },\n});\n\n/** The default two-document research mission. */\nexport const researchMissionRequest = ResearchRequest.make({\n question: `Summarize the durability and subagent notes; keep ${docsMissionConfidentialMarker} inside the coordinator conversation.`,\n documentIds: researchCorpusDocumentIds,\n});\n\n/** The coordinator's expected final digest for the given documents. */\nexport const expectedResearchDigest = (\n documentIds: ReadonlyArray<string> = researchCorpusDocumentIds,\n): ResearchDigest =>\n ResearchDigest.make({\n findings: documentIds.map((documentId) => {\n const summary = documentSummaryFor(documentId);\n return SummaryFinding.make({\n documentId: summary.documentId,\n summary: summary.summary,\n });\n }),\n nextAction: \"review\",\n });\n","import { Agent, AgentPolicy } from \"@effect-agent/core\";\nimport { Context, Effect, Schema } from \"effect\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\n\nexport const AirportCode = Schema.NonEmptyString.pipe(\n Schema.brand(\"@effect-agent/testing/travel-planner/AirportCode\"),\n);\nexport type AirportCode = typeof AirportCode.Type;\n\nexport const QuoteId = Schema.NonEmptyString.pipe(\n Schema.brand(\"@effect-agent/testing/travel-planner/QuoteId\"),\n);\nexport type QuoteId = typeof QuoteId.Type;\n\nexport class TripRequest extends Schema.Class<TripRequest>(\"TripRequest\")({\n request: Schema.NonEmptyString,\n origin: AirportCode,\n destination: AirportCode,\n departOn: Schema.String,\n nights: Schema.Int.check(Schema.isGreaterThan(0)),\n travelers: Schema.Int.check(Schema.isGreaterThan(0)),\n budgetCents: Schema.Int.check(Schema.isGreaterThan(0)),\n currency: Schema.Literal(\"USD\"),\n}) {}\n\nexport class FlightQuery extends Schema.Class<FlightQuery>(\"FlightQuery\")({\n origin: AirportCode,\n destination: AirportCode,\n departOn: Schema.String,\n travelers: Schema.Int.check(Schema.isGreaterThan(0)),\n}) {}\n\nexport class LodgingQuery extends Schema.Class<LodgingQuery>(\"LodgingQuery\")({\n destination: AirportCode,\n departOn: Schema.String,\n nights: Schema.Int.check(Schema.isGreaterThan(0)),\n travelers: Schema.Int.check(Schema.isGreaterThan(0)),\n}) {}\n\nexport class ActivityQuery extends Schema.Class<ActivityQuery>(\"ActivityQuery\")({\n destination: AirportCode,\n departOn: Schema.String,\n nights: Schema.Int.check(Schema.isGreaterThan(0)),\n travelers: Schema.Int.check(Schema.isGreaterThan(0)),\n}) {}\n\nexport class FlightOption extends Schema.Class<FlightOption>(\"FlightOption\")({\n quoteId: QuoteId,\n flight: Schema.String,\n estimatedCents: Schema.Int.check(Schema.isGreaterThan(0)),\n currency: Schema.Literal(\"USD\"),\n}) {}\n\nexport class LodgingOption extends Schema.Class<LodgingOption>(\"LodgingOption\")({\n lodging: Schema.String,\n estimatedCents: Schema.Int.check(Schema.isGreaterThan(0)),\n currency: Schema.Literal(\"USD\"),\n}) {}\n\n/** A successful empty activity search is distinct from supplier unavailability. */\nexport class ActivitySearchResult extends Schema.Class<ActivitySearchResult>(\n \"ActivitySearchResult\",\n)({\n activities: Schema.Array(Schema.String),\n}) {}\n\nexport class Itinerary extends Schema.Class<Itinerary>(\"Itinerary\")({\n title: Schema.String,\n route: Schema.String,\n dates: Schema.String,\n flight: Schema.String,\n lodging: Schema.String,\n activities: Schema.Array(Schema.String),\n estimatedTotalCents: Schema.Int.check(Schema.isGreaterThan(0)),\n currency: Schema.Literal(\"USD\"),\n quoteId: QuoteId,\n assumptions: Schema.Array(Schema.String),\n unresolvedConstraints: Schema.Array(Schema.String),\n nextAction: Schema.Literal(\"review\"),\n}) {}\n\nexport class TravelPlan extends Schema.Class<TravelPlan>(\"TravelPlan\")({\n itineraries: Schema.Array(Itinerary),\n}) {}\n\nconst unavailableFields = { query: Schema.String, message: Schema.String };\nexport class FlightUnavailable extends Schema.TaggedError<FlightUnavailable>()(\n \"FlightUnavailable\",\n unavailableFields,\n) {}\nexport class LodgingUnavailable extends Schema.TaggedError<LodgingUnavailable>()(\n \"LodgingUnavailable\",\n unavailableFields,\n) {}\nexport class ActivityUnavailable extends Schema.TaggedError<ActivityUnavailable>()(\n \"ActivityUnavailable\",\n unavailableFields,\n) {}\nexport class GuidanceFailure extends Schema.TaggedError<GuidanceFailure>()(\"GuidanceFailure\", {\n message: Schema.String,\n}) {}\n\nexport class FlightCatalog extends Context.Service<\n FlightCatalog,\n { readonly search: (query: FlightQuery) => Effect.Effect<FlightOption, FlightUnavailable> }\n>()(\"@effect-agent/testing/travel-planner/FlightCatalog\") {}\nexport class LodgingCatalog extends Context.Service<\n LodgingCatalog,\n { readonly search: (query: LodgingQuery) => Effect.Effect<LodgingOption, LodgingUnavailable> }\n>()(\"@effect-agent/testing/travel-planner/LodgingCatalog\") {}\nexport class ActivityCatalog extends Context.Service<\n ActivityCatalog,\n {\n readonly search: (\n query: ActivityQuery,\n ) => Effect.Effect<ActivitySearchResult, ActivityUnavailable>;\n }\n>()(\"@effect-agent/testing/travel-planner/ActivityCatalog\") {}\nexport class TravelGuidance extends Context.Service<\n TravelGuidance,\n { readonly instructions: (input: TripRequest) => Effect.Effect<string, GuidanceFailure> }\n>()(\"@effect-agent/testing/travel-planner/TravelGuidance\") {}\n\nexport const SearchFlights = Tool.make(\"search_flights\", {\n parameters: FlightQuery,\n success: FlightOption,\n failure: FlightUnavailable,\n failureMode: \"error\",\n dependencies: [FlightCatalog],\n});\nexport const SearchLodging = Tool.make(\"search_lodging\", {\n parameters: LodgingQuery,\n success: LodgingOption,\n failure: LodgingUnavailable,\n failureMode: \"error\",\n dependencies: [LodgingCatalog],\n});\nexport const SearchActivities = Tool.make(\"search_activities\", {\n parameters: ActivityQuery,\n success: ActivitySearchResult,\n failure: ActivityUnavailable,\n failureMode: \"error\",\n dependencies: [ActivityCatalog],\n});\n\nexport const TravelPlannerToolkit = Toolkit.make(SearchFlights, SearchLodging, SearchActivities);\nexport const TravelPlannerToolkitLayer = TravelPlannerToolkit.toLayer({\n search_flights: (query) => Effect.flatMap(FlightCatalog, (catalog) => catalog.search(query)),\n search_lodging: (query) => Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(query)),\n search_activities: (query) => Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(query)),\n});\n\nexport const TravelPlanner = Agent.define(\"travel-planner\", {\n input: TripRequest,\n output: TravelPlan,\n instructions: (input) =>\n Effect.flatMap(TravelGuidance, (guidance) => guidance.instructions(input)),\n toolkit: TravelPlannerToolkit,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 3,\n maxDuration: \"30 seconds\",\n toolConcurrency: 3,\n }),\n description: \"Build one review-only itinerary from bounded parallel deterministic searches.\",\n metadata: { deploymentClass: \"E\", phase: \"P1\" },\n});\n","import { ConversationId, IdGenerator, RunId, TurnId } from \"@effect-agent/core\";\nimport { Context, Deferred, Effect, Layer, Option, Ref, Schema } from \"effect\";\n\nimport {\n ActivityCatalog,\n ActivitySearchResult,\n ActivityUnavailable,\n FlightCatalog,\n FlightOption,\n FlightUnavailable,\n LodgingCatalog,\n LodgingOption,\n LodgingUnavailable,\n QuoteId,\n TravelGuidance,\n TravelPlannerToolkit,\n TravelPlannerToolkitLayer,\n} from \"./definition.ts\";\n\nexport class CatalogLifecycleCounts extends Schema.Class<CatalogLifecycleCounts>(\n \"CatalogLifecycleCounts\",\n)({\n acquired: Schema.Natural,\n finalized: Schema.Natural,\n}) {}\nexport class CatalogLifecycle extends Context.Service<\n CatalogLifecycle,\n {\n readonly markAcquired: Effect.Effect<void>;\n readonly markFinalized: Effect.Effect<void>;\n readonly counts: Effect.Effect<CatalogLifecycleCounts>;\n }\n>()(\"@effect-agent/testing/travel-planner/CatalogLifecycle\") {\n static readonly layerNoDeps = Layer.effect(\n this,\n Effect.gen(function* () {\n const acquired = yield* Ref.make(0);\n const finalized = yield* Ref.make(0);\n return CatalogLifecycle.of({\n markAcquired: Ref.update(acquired, (n) => n + 1),\n markFinalized: Ref.update(finalized, (n) => n + 1),\n counts: Effect.all({ acquired: Ref.get(acquired), finalized: Ref.get(finalized) }).pipe(\n Effect.map((counts) => CatalogLifecycleCounts.make(counts)),\n ),\n });\n }),\n );\n}\n\nconst flight = FlightOption.make({\n quoteId: Schema.decodeSync(QuoteId)(\"quote-sfo-lhr-001\"),\n flight: \"EA 218 · nonstop · SFO 18:40 → LHR 13:05+1\",\n estimatedCents: 180_000,\n currency: \"USD\",\n});\nconst lodging = LodgingOption.make({\n lodging: \"Bloomsbury House · refundable studio · 4 nights\",\n estimatedCents: 104_000,\n currency: \"USD\",\n});\nconst activities = ActivitySearchResult.make({\n activities: [\"British Museum timed entry\", \"Thames evening walk\"],\n});\n\n/**\n * Deterministic controls for a Tool batch whose completions are released in a\n * caller-selected order. This is intentionally a test fixture: it uses no\n * clock or sleep and lets engine scheduler tests prove parallel starts and\n * declaration-order prompt materialization.\n */\nexport interface TravelPlannerCompletionControls {\n readonly flightStarted: Effect.Effect<void>;\n readonly lodgingStarted: Effect.Effect<void>;\n readonly activityStarted: Effect.Effect<void>;\n readonly releaseFlight: Effect.Effect<void>;\n readonly releaseLodging: Effect.Effect<void>;\n readonly releaseActivity: Effect.Effect<void>;\n}\n\nexport const ReverseCompletionToolkitLayer = Effect.gen(function* () {\n const flightStarted = yield* Deferred.make<void>();\n const lodgingStarted = yield* Deferred.make<void>();\n const activityStarted = yield* Deferred.make<void>();\n const releaseFlight = yield* Deferred.make<void>();\n const releaseLodging = yield* Deferred.make<void>();\n const releaseActivity = yield* Deferred.make<void>();\n const awaitRelease = <A>(\n started: Deferred.Deferred<void>,\n release: Deferred.Deferred<void>,\n value: A,\n ) =>\n Deferred.succeed(started, undefined).pipe(\n Effect.andThen(Deferred.await(release)),\n Effect.as(value),\n );\n return {\n controls: {\n flightStarted: Deferred.await(flightStarted),\n lodgingStarted: Deferred.await(lodgingStarted),\n activityStarted: Deferred.await(activityStarted),\n releaseFlight: Deferred.succeed(releaseFlight, undefined).pipe(Effect.asVoid),\n releaseLodging: Deferred.succeed(releaseLodging, undefined).pipe(Effect.asVoid),\n releaseActivity: Deferred.succeed(releaseActivity, undefined).pipe(Effect.asVoid),\n },\n layer: TravelPlannerToolkit.toLayer({\n search_flights: () => awaitRelease(flightStarted, releaseFlight, flight),\n search_lodging: () => awaitRelease(lodgingStarted, releaseLodging, lodging),\n search_activities: () => awaitRelease(activityStarted, releaseActivity, activities),\n }),\n };\n});\n\nexport const FlightCatalogLayer = Layer.effect(\n FlightCatalog,\n Effect.gen(function* () {\n const lifecycle = yield* CatalogLifecycle;\n yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);\n return FlightCatalog.of({\n search: (query) =>\n query.origin === query.destination\n ? Effect.fail(\n FlightUnavailable.make({\n query: `${query.origin}-${query.destination}`,\n message: \"Origin and destination must differ.\",\n }),\n )\n : Effect.succeed(flight),\n });\n }),\n);\nexport const LodgingCatalogLayer = Layer.effect(\n LodgingCatalog,\n Effect.gen(function* () {\n const lifecycle = yield* CatalogLifecycle;\n yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);\n return LodgingCatalog.of({\n search: (query) =>\n query.nights < 1\n ? Effect.fail(\n LodgingUnavailable.make({\n query: query.destination,\n message: \"At least one night is required.\",\n }),\n )\n : Effect.succeed(lodging),\n });\n }),\n);\nexport const ActivityCatalogLayer = Layer.effect(\n ActivityCatalog,\n Effect.gen(function* () {\n const lifecycle = yield* CatalogLifecycle;\n yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);\n return ActivityCatalog.of({\n search: (query) =>\n query.destination === \"\"\n ? Effect.fail(\n ActivityUnavailable.make({\n query: query.destination,\n message: \"Destination is required.\",\n }),\n )\n : Effect.succeed(activities),\n });\n }),\n);\n/** Stable supplier-side booking identity, minted deterministically from the idempotency key. */\nexport const BookingRef = Schema.NonEmptyString.pipe(\n Schema.brand(\"@effect-agent/testing/travel-planner/BookingRef\"),\n);\nexport type BookingRef = typeof BookingRef.Type;\n\n/** The supplier desk operations the P5 booking Tools and Steps invoke. */\nexport const SupplierOperation = Schema.Literals([\n \"book-flight\",\n \"cancel-booking\",\n \"reserve-flight\",\n \"reserve-lodging\",\n \"issue-confirmation\",\n]);\nexport type SupplierOperation = typeof SupplierOperation.Type;\n\n/**\n * One row of external supplier truth. The desk deduplicates by `idempotencyKey` — replaying a\n * call with the same key returns this exact record without creating a second booking — which is\n * precisely the honesty model of DUR-010: the framework never makes an external call\n * exactly-once; the supplier's idempotency key does.\n */\nexport class SupplierBookingRecord extends Schema.Class<SupplierBookingRecord>(\n \"@effect-agent/testing/travel-planner/SupplierBookingRecord\",\n)({\n bookingRef: BookingRef,\n idempotencyKey: Schema.NonEmptyString,\n operation: SupplierOperation,\n detail: Schema.NonEmptyString,\n status: Schema.Literals([\"confirmed\", \"cancelled\"]),\n}) {}\n\nexport class SupplierUnavailable extends Schema.TaggedError<SupplierUnavailable>()(\n \"SupplierUnavailable\",\n { message: Schema.String },\n) {}\n\nexport interface SupplierBookRequest {\n readonly operation: SupplierOperation;\n readonly idempotencyKey: string;\n readonly detail: string;\n}\n\n/** Controls returned by an armed crash window (`holdAfterWrite`). */\nexport interface SupplierHoldControls {\n /** Resolves once the armed call has performed its supplier write and is blocked. */\n readonly held: Effect.Effect<void>;\n /** Releases the blocked call (tests that interrupt the Attempt never call this). */\n readonly release: Effect.Effect<void>;\n}\n\n/** The desk-internal idempotency key of one cancellation: cancel is idempotent by bookingRef. */\nexport const cancelBookingIdempotencyKey = (bookingRef: string): string =>\n `cancel-booking:${bookingRef}`;\n\n/** The deterministic bookingRef the desk mints for one idempotency key. */\nexport const supplierBookingRefFor = (idempotencyKey: string): BookingRef =>\n Schema.decodeSync(BookingRef)(`ref:${idempotencyKey}`);\n\ninterface SupplierHoldWindow {\n readonly held: Deferred.Deferred<void>;\n readonly release: Deferred.Deferred<void>;\n}\n\ninterface SupplierDeskState {\n readonly bookings: ReadonlyMap<string, SupplierBookingRecord>;\n readonly counts: ReadonlyMap<string, number>;\n readonly holds: ReadonlyMap<string, SupplierHoldWindow>;\n}\n\n/**\n * The deterministic in-memory supplier: an idempotency-keyed booking store with per-key call\n * counters and injectable crash windows.\n *\n * - `book`/`cancel` always count the call (at-least-once execution stays observable), then\n * dedupe the external effect by idempotency key — the supplier-side contract the P5 Tools and\n * Steps rely on.\n * - `holdAfterWrite` arms a one-shot crash window: the next call with that key performs its\n * supplier write, signals `held`, and never returns. Interrupting the Attempt at that point\n * models \"the external effect happened but no outcome was recorded\" without any wall clock.\n * - `bookings`/`lookup` expose external truth for the reconciler and for never-fabricate\n * assertions.\n */\nexport class SupplierBookingDesk extends Context.Service<\n SupplierBookingDesk,\n {\n readonly book: (\n request: SupplierBookRequest,\n ) => Effect.Effect<SupplierBookingRecord, SupplierUnavailable>;\n readonly cancel: (\n bookingRef: BookingRef,\n ) => Effect.Effect<SupplierBookingRecord, SupplierUnavailable>;\n readonly lookup: (\n idempotencyKey: string,\n ) => Effect.Effect<Option.Option<SupplierBookingRecord>>;\n readonly bookings: Effect.Effect<ReadonlyArray<SupplierBookingRecord>>;\n readonly callCount: (idempotencyKey: string) => Effect.Effect<number>;\n readonly holdAfterWrite: (idempotencyKey: string) => Effect.Effect<SupplierHoldControls>;\n }\n>()(\"@effect-agent/testing/travel-planner/SupplierBookingDesk\") {\n static readonly layer: Layer.Layer<SupplierBookingDesk> = Layer.effect(\n this,\n Effect.gen(function* () {\n const state = yield* Ref.make<SupplierDeskState>({\n bookings: new Map(),\n counts: new Map(),\n holds: new Map(),\n });\n\n const enterHold = (hold: Option.Option<SupplierHoldWindow>) =>\n Option.isSome(hold)\n ? Deferred.succeed(hold.value.held, undefined).pipe(\n Effect.andThen(Deferred.await(hold.value.release)),\n )\n : Effect.void;\n\n const book = (request: SupplierBookRequest) =>\n Ref.modify(state, (current) => {\n const counts = new Map(current.counts).set(\n request.idempotencyKey,\n (current.counts.get(request.idempotencyKey) ?? 0) + 1,\n );\n const existing = current.bookings.get(request.idempotencyKey);\n const record =\n existing ??\n SupplierBookingRecord.make({\n bookingRef: supplierBookingRefFor(request.idempotencyKey),\n idempotencyKey: request.idempotencyKey,\n operation: request.operation,\n detail: request.detail,\n status: \"confirmed\",\n });\n const bookings =\n existing === undefined\n ? new Map(current.bookings).set(request.idempotencyKey, record)\n : current.bookings;\n const hold = Option.fromNullishOr(current.holds.get(request.idempotencyKey));\n const holds = Option.isSome(hold)\n ? (() => {\n const next = new Map(current.holds);\n next.delete(request.idempotencyKey);\n return next;\n })()\n : current.holds;\n return [\n { record, hold },\n { bookings, counts, holds },\n ] as const;\n }).pipe(Effect.flatMap(({ hold, record }) => enterHold(hold).pipe(Effect.as(record))));\n\n const cancel = (bookingRef: BookingRef) =>\n Ref.modify(state, (current) => {\n const key = cancelBookingIdempotencyKey(bookingRef);\n const counts = new Map(current.counts).set(key, (current.counts.get(key) ?? 0) + 1);\n const existingEntry = [...current.bookings.entries()].find(\n ([, record]) => record.bookingRef === bookingRef,\n );\n if (existingEntry === undefined) {\n return [\n { record: Option.none<SupplierBookingRecord>(), hold: Option.none() },\n { ...current, counts },\n ] as const;\n }\n const [storeKey, existing] = existingEntry;\n const cancelled =\n existing.status === \"cancelled\"\n ? existing\n : SupplierBookingRecord.make({ ...existing, status: \"cancelled\" });\n const bookings = new Map(current.bookings).set(storeKey, cancelled);\n const hold = Option.fromNullishOr(current.holds.get(key));\n const holds = Option.isSome(hold)\n ? (() => {\n const next = new Map(current.holds);\n next.delete(key);\n return next;\n })()\n : current.holds;\n return [\n { record: Option.some(cancelled), hold },\n { bookings, counts, holds },\n ] as const;\n }).pipe(\n Effect.flatMap(({ hold, record }) =>\n Option.isNone(record)\n ? Effect.fail(\n SupplierUnavailable.make({\n message: `The supplier desk has no booking under ${bookingRef}.`,\n }),\n )\n : enterHold(hold).pipe(Effect.as(record.value)),\n ),\n );\n\n return SupplierBookingDesk.of({\n book,\n cancel,\n lookup: (idempotencyKey) =>\n Ref.get(state).pipe(\n Effect.map((current) => Option.fromNullishOr(current.bookings.get(idempotencyKey))),\n ),\n bookings: Ref.get(state).pipe(Effect.map((current) => [...current.bookings.values()])),\n callCount: (idempotencyKey) =>\n Ref.get(state).pipe(Effect.map((current) => current.counts.get(idempotencyKey) ?? 0)),\n holdAfterWrite: (idempotencyKey) =>\n Effect.gen(function* () {\n const held = yield* Deferred.make<void>();\n const release = yield* Deferred.make<void>();\n yield* Ref.update(state, (current) => ({\n ...current,\n holds: new Map(current.holds).set(idempotencyKey, { held, release }),\n }));\n return {\n held: Deferred.await(held),\n release: Deferred.succeed(release, undefined).pipe(Effect.asVoid),\n };\n }),\n });\n }),\n );\n}\n\nexport const TravelGuidanceLayer = Layer.succeed(\n TravelGuidance,\n TravelGuidance.of({\n instructions: (input) =>\n Effect.succeed(\n [\n \"You are the Effect Agent Travel Planner P1 interpreter fixture.\",\n `The user asked: ${input.request}`,\n \"Call search_flights, search_lodging, and search_activities exactly once in one Tool batch.\",\n \"Then return only a JSON object of exactly this shape, no prose:\",\n '{\"itineraries\": [{\"title\": \"<short itinerary name>\", \"route\": \"<origin-destination>\", \"dates\": \"<date range>\", \"flight\": \"<flight description from the Tool result>\", \"lodging\": \"<lodging description from the Tool result>\", \"activities\": [\"<activity>\", \"...\"], \"estimatedTotalCents\": <positive integer total in cents>, \"currency\": \"USD\", \"quoteId\": \"<quoteId from the flight Tool result>\", \"assumptions\": [\"<assumption>\", \"...\"], \"unresolvedConstraints\": [], \"nextAction\": \"review\"}]}',\n \"Use the Tool results verbatim; activity results may legitimately be an empty array.\",\n \"This is read-only planning. Require review before any mutation.\",\n ].join(\"\\n\"),\n ),\n }),\n);\nexport const DeterministicIdGeneratorLayer = Layer.effect(\n IdGenerator,\n Effect.gen(function* () {\n const conversation = yield* Ref.make(0);\n const run = yield* Ref.make(0);\n const turn = yield* Ref.make(0);\n return IdGenerator.of({\n nextConversationId: Ref.updateAndGet(conversation, (n) => n + 1).pipe(\n Effect.map((n) => Schema.decodeSync(ConversationId)(`conversation-${n}`)),\n ),\n nextRunId: Ref.updateAndGet(run, (n) => n + 1).pipe(\n Effect.map((n) => Schema.decodeSync(RunId)(`run-${n}`)),\n ),\n nextTurnId: Ref.updateAndGet(turn, (n) => n + 1).pipe(\n Effect.map((n) => Schema.decodeSync(TurnId)(`turn-${n}`)),\n ),\n });\n }),\n);\nexport const TravelPlannerRuntimeLayer = Layer.mergeAll(\n TravelPlannerToolkitLayer,\n FlightCatalogLayer,\n LodgingCatalogLayer,\n ActivityCatalogLayer,\n TravelGuidanceLayer,\n DeterministicIdGeneratorLayer,\n).pipe(Layer.provide(CatalogLifecycle.layerNoDeps));\n","import {\n McpConnectionRequest,\n McpConnector,\n McpServerIdentity,\n McpToolkitMismatch,\n type McpConnection,\n} from \"@effect-agent/capabilities\";\nimport { Effect, Layer, Schema } from \"effect\";\nimport { Tool } from \"effect/unstable/ai\";\nimport * as McpSchema from \"effect/unstable/ai/McpSchema\";\n\nimport { DocContentToolkit, FetchDocument } from \"./definition.ts\";\n\n// ---------------------------------------------------------------------------\n// Scripted MCP fixture: a deterministic `McpConnector` adapter that serves the\n// doc-summarizer's content tool. Discovery entries are DERIVED from the\n// authored Tool (`Tool.getJsonSchema`), so `validateMcpDiscovery` digesting\n// both sides is a real check, not a tautology; the mismatch and over-limit\n// connectors below serve deliberately wrong contracts so tests can pin the\n// fail-closed paths (CAP-009, SEC-013).\n// ---------------------------------------------------------------------------\n\n/** Framework-side hard bounds one docs-researcher assembly requests. */\nexport const docsMcpRequest = McpConnectionRequest.make({\n serverId: \"docs-content-mcp\",\n maxToolCount: 4,\n maxToolDescriptionBytes: 256,\n maxDiscoveryBytes: 16_384,\n connectTimeoutMillis: 1_000,\n});\n\nexport const docsMcpIdentity = McpServerIdentity.make({\n serverId: docsMcpRequest.serverId,\n implementation: McpSchema.Implementation.make({\n name: \"docs-researcher-content-fixture\",\n version: \"1.0.0\",\n }),\n});\n\nconst discoveredFetchDocument = McpSchema.Tool.make({\n name: FetchDocument.name,\n description: \"Fetch one bounded research document by its identifier.\",\n inputSchema: Tool.getJsonSchema(FetchDocument),\n});\n\nconst scriptedConnector = (tools: ReadonlyArray<McpSchema.Tool>): Layer.Layer<McpConnector> =>\n Layer.succeed(McpConnector)({\n connect: () =>\n Effect.acquireRelease(\n Effect.succeed({\n identity: docsMcpIdentity,\n capabilities: McpSchema.ServerCapabilities.make({}),\n tools,\n toolkit: DocContentToolkit,\n }),\n () => Effect.void,\n ),\n });\n\n/** The well-behaved scripted content server. */\nexport const docsMcpConnectorLayer: Layer.Layer<McpConnector> = scriptedConnector([\n discoveredFetchDocument,\n]);\n\n/** Serves a tool description exceeding `maxToolDescriptionBytes` (SEC-013 bound). */\nexport const docsMcpOversizedConnectorLayer: Layer.Layer<McpConnector> = scriptedConnector([\n McpSchema.Tool.make({\n name: discoveredFetchDocument.name,\n description: \"x\".repeat(1_024),\n inputSchema: discoveredFetchDocument.inputSchema,\n }),\n]);\n\n/** Serves a discovery schema that disagrees with the authored toolkit (drift fails closed). */\nexport const docsMcpMismatchedConnectorLayer: Layer.Layer<McpConnector> = scriptedConnector([\n McpSchema.Tool.make({\n name: discoveredFetchDocument.name,\n description: discoveredFetchDocument.description,\n inputSchema: { type: \"object\", properties: { url: { type: \"string\" } } },\n }),\n]);\n\nconst isJsonEqual = (left: unknown, right: unknown): boolean =>\n JSON.stringify(left) === JSON.stringify(right);\n\n/**\n * Bind DISCOVERY to AUTHORING: `validateMcpDiscovery` (inside `connectMcp`)\n * already proved the served discovery matches the connection's own Toolkit;\n * this check additionally proves that Toolkit is the exact toolkit the\n * doc-summarizer was AUTHORED against — same tool names, same derived JSON\n * schemas — so a connector cannot substitute a look-alike toolkit. The\n * docs-researcher harness runs it before any worker Binding registration and\n * fails closed on any drift.\n */\nexport const assertDiscoveryMatchesAuthoredToolkit = Effect.fn(\n \"DocsResearcher.assertDiscoveryMatchesAuthoredToolkit\",\n)(function* (connection: McpConnection): Effect.fn.Return<void, McpToolkitMismatch> {\n const authored = Object.values(DocContentToolkit.tools)\n .map((tool) => ({ name: tool.name, inputSchema: Tool.getJsonSchema(tool) }))\n .sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\n const discovered = Object.values(connection.toolkit.tools)\n .map((tool) => ({ name: tool.name, inputSchema: Tool.getJsonSchema(tool) }))\n .sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\n const matches =\n authored.length === discovered.length &&\n authored.every(\n (tool, index) =>\n tool.name === discovered[index]?.name &&\n isJsonEqual(tool.inputSchema, discovered[index]?.inputSchema),\n );\n if (!matches) {\n return yield* McpToolkitMismatch.make({\n serverId: connection.discovery.identity.serverId,\n message:\n \"The MCP-discovered toolkit does not match the doc-summarizer's authored content toolkit\",\n });\n }\n});\n\n/** Round-trip guard for encoded discovery values persisted as fixture evidence. */\nexport const DocsMcpDiscoveryEvidence = Schema.Struct({\n serverId: Schema.NonEmptyString,\n toolCount: Schema.Natural,\n encodedBytes: Schema.Natural,\n toolkitSchemaDigest: Schema.String,\n});\n","import {\n connectMcp,\n Redactor,\n SubagentReservationsMemoryLive,\n type McpDiscovery,\n type RedactedPreview,\n type RedactionError,\n} from \"@effect-agent/capabilities\";\nimport { Agent, type ConversationId } from \"@effect-agent/core\";\nimport {\n DefinitionDigests,\n DeploymentId,\n Digest,\n DurableWorkerBinding,\n Principal,\n ProducerId,\n type DurableSubmitOptions,\n type IdempotencyKey,\n type ResolvedBinding,\n} from \"@effect-agent/session\";\nimport { Crypto, Effect, Layer, Ref, Schema, Stream } from \"effect\";\nimport { LanguageModel, Model, type Response } from \"effect/unstable/ai\";\n\nimport { DeterministicIdGeneratorLayer } from \"../travel-planner/deterministic-layers.ts\";\nimport {\n DocsResearcher,\n DocSummarizer,\n DocumentLibrary,\n docContentToolkitLayer,\n docsSummaryHandlersLayer,\n encodedDocumentSummary,\n expectedResearchDigest,\n ResearchDigest,\n ResearchDocument,\n researchCorpusDocumentIds,\n researchDocumentFor,\n researchDocumentLookup,\n} from \"./definition.ts\";\nimport {\n assertDiscoveryMatchesAuthoredToolkit,\n docsMcpConnectorLayer,\n docsMcpRequest,\n} from \"./mcp.ts\";\n\n// ---------------------------------------------------------------------------\n// DN durable harness for the docs-researcher (P7 plan §6 agent #3), following\n// `makeDurableResearchHarness` conventions: invocation counters and captured\n// prompts live OUTSIDE the Model Layers so they survive Layer rebuilds across\n// Attempts and separate runtime handles over the same SQLite file.\n// ---------------------------------------------------------------------------\n\nexport const docsResearcherDeploymentId = Schema.decodeSync(DeploymentId)(\n \"docs-researcher-p7-deployment\",\n);\nexport const docsResearcherProducerId = Schema.decodeSync(ProducerId)(\n \"docs-researcher-p7-producer\",\n);\nexport const docsResearcherPrincipal = Schema.decodeSync(Principal)(\"docs-researcher-p7-principal\");\n\nconst digestOf = (pair: string) => Schema.decodeSync(Digest)(pair.repeat(32));\n\n/** Redacted, deterministic coordinator definition digests for this fixture version. */\nexport const docsCoordinatorDigests = DefinitionDigests.make({\n agent: digestOf(\"40\"),\n model: digestOf(\"41\"),\n tools: digestOf(\"42\"),\n});\n\n/** The child registration digests — byte-equal to `docsSummarizerDigestStrings` (SUB-023). */\nexport const docsSummarizerDigests = DefinitionDigests.make({\n agent: digestOf(\"50\"),\n model: digestOf(\"51\"),\n tools: digestOf(\"52\"),\n});\n\n/** Durable admission options for one docs-researcher Submission on one mission lane. */\nexport const docsResearcherSubmitOptions = (\n conversationId: ConversationId,\n idempotencyKey: IdempotencyKey,\n): DurableSubmitOptions => ({\n conversationId,\n principal: docsResearcherPrincipal,\n idempotencyKey,\n definitions: docsCoordinatorDigests,\n});\n\n/** The structural submit slice of the coordinator Binding (`DurableAgentRuntime.submit`). */\nexport const docsResearcherSubmitAgent = {\n definition: { id: DocsResearcher.id, input: DocsResearcher.input },\n} as const;\n\n/** The deterministic delegation Tool Call identity for one document. */\nexport const summarizeCallId = (documentId: string): string => `summarize-${documentId}`;\n\n/** The child's own scripted fetch Tool Call identity for one document. */\nexport const fetchCallId = (documentId: string): string => `fetch-${documentId}`;\n\nconst scriptedUsage = { inputTokens: { total: 96 }, outputTokens: { total: 64 } };\n\nconst summaryDelegationParts = (\n documentIds: ReadonlyArray<string>,\n): ReadonlyArray<Response.StreamPartEncoded> => [\n ...documentIds.map(\n (documentId): Response.StreamPartEncoded => ({\n type: \"tool-call\",\n id: summarizeCallId(documentId),\n name: \"delegate_document_summary\",\n params: { documentId },\n providerExecuted: false,\n }),\n ),\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst digestParts = (\n documentIds: ReadonlyArray<string>,\n): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"digest\" },\n {\n type: \"text-delta\",\n id: \"digest\",\n delta: JSON.stringify(Schema.encodeSync(ResearchDigest)(expectedResearchDigest(documentIds))),\n },\n { type: \"text-end\", id: \"digest\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\nconst fetchParts = (documentId: string): ReadonlyArray<Response.StreamPartEncoded> => [\n {\n type: \"tool-call\",\n id: fetchCallId(documentId),\n name: \"fetch_document\",\n params: { documentId },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst summaryParts = (documentId: string): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"document-summary\" },\n { type: \"text-delta\", id: \"document-summary\", delta: encodedDocumentSummary(documentId) },\n { type: \"text-end\", id: \"document-summary\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\n/**\n * One prompt-aware scripted model with externally observable counters. A DN\n * Attempt may resume on a fresh Layer build, so responses derive from the\n * committed history in the prompt — never from an in-Layer turn counter.\n */\nconst makeCountingModel = (\n name: string,\n decide: (promptJson: string) => Effect.Effect<ReadonlyArray<Response.StreamPartEncoded>>,\n) =>\n Effect.gen(function* () {\n const calls = yield* Ref.make(0);\n const prompts = yield* Ref.make<ReadonlyArray<string>>([]);\n const model = Model.make(\n \"scripted\",\n name,\n Layer.effect(\n LanguageModel.LanguageModel,\n LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (request) =>\n Stream.unwrap(\n Effect.gen(function* () {\n yield* Ref.update(calls, (value) => value + 1);\n const promptJson = JSON.stringify(request.prompt);\n yield* Ref.update(prompts, (previous) => [...previous, promptJson]);\n return Stream.fromIterable(yield* decide(promptJson));\n }),\n ),\n }),\n ),\n );\n return { model, calls: Ref.get(calls), prompts: Ref.get(prompts) };\n });\n\n/** Optional overrides for one docs-researcher harness. */\nexport interface DocsResearcherHarnessOptions {\n /** Documents to research; defaults to the full two-document corpus. */\n readonly documentIds?: ReadonlyArray<string> | undefined;\n}\n\n/** One durable coordinator/summarizer pair with observable counters and MCP evidence. */\nexport interface DocsResearcherHarness {\n /** Host registrations for `NodeDurableRuntimeOptions.bindings` (parent + child). */\n readonly bindings: ReadonlyArray<ResolvedBinding>;\n /** The validated MCP discovery the child toolkit registration was gated on. */\n readonly discovery: McpDiscovery;\n /** Total coordinator model invocations across every Attempt and runtime handle. */\n readonly parentModelCalls: Effect.Effect<number>;\n /** JSON-encoded coordinator prompts in request order. */\n readonly parentPrompts: Effect.Effect<ReadonlyArray<string>>;\n /** Total summarizer model invocations across every Attempt and runtime handle. */\n readonly childModelCalls: Effect.Effect<number>;\n /** JSON-encoded summarizer prompts in request order (context-isolation evidence). */\n readonly childPrompts: Effect.Effect<ReadonlyArray<string>>;\n /** MCP content-tool handler executions for one document (external side-effect record). */\n readonly fetchInvocations: (documentId: string) => Effect.Effect<number>;\n}\n\n/**\n * Build the docs-researcher harness. Order matters and is the point: the\n * child's content toolkit is only registered as a worker Binding AFTER the\n * MCP connector's bounded discovery validated the authored toolkit\n * byte-for-byte (`connectMcp` + `assertDiscoveryMatchesAuthoredToolkit`), so\n * \"the tools the summarizer runs are the tools discovery served\" is enforced\n * at assembly, not assumed. Content-tool execution then flows through the\n * counting `DocumentLibrary` — the scripted MCP server's content store.\n */\nexport const makeDocsResearcherHarness = (options?: DocsResearcherHarnessOptions) =>\n Effect.gen(function* () {\n const documentIds = options?.documentIds ?? researchCorpusDocumentIds;\n\n // MCP discovery gate (CAP-009): bounded, digest-verified, fail-closed.\n const discovery = yield* Effect.scoped(\n Effect.gen(function* () {\n const connection = yield* connectMcp(docsMcpRequest);\n yield* assertDiscoveryMatchesAuthoredToolkit(connection);\n return connection.discovery;\n }),\n ).pipe(Effect.provide(docsMcpConnectorLayer));\n\n const fetchCounts = yield* Ref.make<ReadonlyMap<string, number>>(new Map());\n const libraryLayer = Layer.succeed(\n DocumentLibrary,\n DocumentLibrary.of({\n fetch: (query) =>\n Ref.update(fetchCounts, (current) =>\n new Map(current).set(query.documentId, (current.get(query.documentId) ?? 0) + 1),\n ).pipe(Effect.andThen(researchDocumentLookup(query))),\n }),\n );\n const childToolkitLayer = docContentToolkitLayer.pipe(Layer.provideMerge(libraryLayer));\n\n const childModel = yield* makeCountingModel(\"doc-summarizer-p7\", (promptJson) =>\n Effect.suspend(() => {\n const documentId = documentIds.find((candidate) => promptJson.includes(candidate));\n if (documentId === undefined) {\n return Effect.die(new Error(\"The summarizer prompt names no corpus document\"));\n }\n return Effect.succeed(\n promptJson.includes(fetchCallId(documentId))\n ? summaryParts(documentId)\n : fetchParts(documentId),\n );\n }),\n );\n const childBinding = Agent.withModel(DocSummarizer, childModel.model);\n\n const firstCallId = summarizeCallId(documentIds[0] ?? \"durability-notes\");\n const parentModel = yield* makeCountingModel(\"docs-researcher-p7\", (promptJson) =>\n Effect.succeed(\n promptJson.includes(firstCallId)\n ? digestParts(documentIds)\n : summaryDelegationParts(documentIds),\n ),\n );\n const parentBinding = Agent.withModel(DocsResearcher, parentModel.model);\n\n const delegationLayer = docsSummaryHandlersLayer(childBinding).pipe(\n Layer.provide(\n Layer.mergeAll(\n childToolkitLayer,\n SubagentReservationsMemoryLive,\n DeterministicIdGeneratorLayer,\n ),\n ),\n );\n\n const parentResolved: ResolvedBinding = yield* DurableWorkerBinding.make(\n parentBinding,\n docsCoordinatorDigests,\n ).pipe(Effect.provide(delegationLayer));\n const childResolved: ResolvedBinding = yield* DurableWorkerBinding.make(\n childBinding,\n docsSummarizerDigests,\n ).pipe(Effect.provide(childToolkitLayer));\n\n const harness: DocsResearcherHarness = {\n bindings: [parentResolved, childResolved],\n discovery,\n parentModelCalls: parentModel.calls,\n parentPrompts: parentModel.prompts,\n childModelCalls: childModel.calls,\n childPrompts: childModel.prompts,\n fetchInvocations: (documentId) =>\n Ref.get(fetchCounts).pipe(Effect.map((current) => current.get(documentId) ?? 0)),\n };\n return harness;\n });\n\nconst encodeResearchDocument = Schema.encodeEffect(ResearchDocument);\n\n/**\n * The audit-surface preview of one fetched document: the raw document —\n * secret marker and all — passes through the configured structural `Redactor`\n * before anything may quote it outside the child Conversation (SEC-008,\n * CAP-013). Tests assert the preview keeps shape but no scalar content.\n */\nexport const redactedDocumentPreview = Effect.fn(\"DocsResearcher.redactedDocumentPreview\")(\n function* (documentId: string): Effect.fn.Return<RedactedPreview, RedactionError, Redactor> {\n const redactor = yield* Redactor;\n const encoded = yield* encodeResearchDocument(researchDocumentFor(documentId)).pipe(\n Effect.orDie,\n );\n return yield* redactor.redact(encoded);\n },\n);\n\n// Crypto is deliberately in the harness requirements (`connectMcp` digests\n// discovery): callers provide a platform Crypto Layer, keeping this fixture\n// platform-neutral.\nexport type DocsResearcherHarnessRequirements = Crypto.Crypto;\n","import { Agent, AgentPolicy } from \"@effect-agent/core\";\nimport { Context, Effect, Schema } from \"effect\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport {\n ActivityCatalog,\n FlightCatalog,\n LodgingCatalog,\n QuoteId,\n SearchActivities,\n SearchFlights,\n SearchLodging,\n TravelGuidance,\n TravelPlan,\n TripRequest,\n} from \"./definition.ts\";\n\nexport class ItineraryHoldRequest extends Schema.Class<ItineraryHoldRequest>(\n \"@effect-agent/testing/travel-planner/ItineraryHoldRequest\",\n)({\n quoteId: QuoteId,\n expiresInMinutes: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(60)),\n}) {}\n\nexport class ItineraryHold extends Schema.Class<ItineraryHold>(\n \"@effect-agent/testing/travel-planner/ItineraryHold\",\n)({\n holdId: Schema.NonEmptyString,\n quoteId: QuoteId,\n status: Schema.Literal(\"held\"),\n}) {}\n\nexport class ItineraryHoldUnavailable extends Schema.TaggedError<ItineraryHoldUnavailable>()(\n \"ItineraryHoldUnavailable\",\n {\n quoteId: QuoteId,\n message: Schema.String,\n },\n) {}\n\nexport class ItineraryHoldGateway extends Context.Service<\n ItineraryHoldGateway,\n {\n readonly hold: (\n request: ItineraryHoldRequest,\n ) => Effect.Effect<ItineraryHold, ItineraryHoldUnavailable>;\n }\n>()(\"@effect-agent/testing/travel-planner/ItineraryHoldGateway\") {}\n\n/**\n * The first mutating Travel Planner Tool. Effect AI marks it as approval-gated\n * so the engine must settle approval before acquiring a handler permit.\n */\nexport const HoldItinerary = Tool.make(\"hold_itinerary\", {\n parameters: ItineraryHoldRequest,\n success: ItineraryHold,\n failure: ItineraryHoldUnavailable,\n failureMode: \"error\",\n dependencies: [ItineraryHoldGateway],\n needsApproval: true,\n});\n\nexport const TravelPlannerPhase2Toolkit = Toolkit.make(\n SearchFlights,\n SearchLodging,\n SearchActivities,\n HoldItinerary,\n);\n\nexport const TravelPlannerPhase2ToolkitLayer = TravelPlannerPhase2Toolkit.toLayer({\n search_flights: (query) => Effect.flatMap(FlightCatalog, (catalog) => catalog.search(query)),\n search_lodging: (query) => Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(query)),\n search_activities: (query) => Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(query)),\n hold_itinerary: (request) =>\n Effect.flatMap(ItineraryHoldGateway, (gateway) => gateway.hold(request)),\n});\n\nexport const TravelPlannerPhase2 = Agent.define(\"travel-planner-phase-2\", {\n input: TripRequest,\n output: TravelPlan,\n instructions: (input) =>\n Effect.flatMap(TravelGuidance, (guidance) => guidance.instructions(input)),\n toolkit: TravelPlannerPhase2Toolkit,\n policy: AgentPolicy.make({\n maxTurns: 3,\n maxToolCalls: 4,\n maxDuration: \"30 seconds\",\n toolConcurrency: 3,\n tokenBudget: 2_048,\n }),\n description:\n \"Build a review-only itinerary and require approval before creating a temporary hold.\",\n metadata: { deploymentClass: \"E\", phase: \"P2\" },\n});\n","import { Schema } from \"effect\";\n\nimport type { ScriptedTurnInput } from \"../../scripted-model.ts\";\nimport { TravelPlan, TripRequest, type TravelPlan as TravelPlanValue } from \"./definition.ts\";\n\nconst usage = { inputTokens: { total: 128 }, outputTokens: { total: 96 } };\nexport const phase1Trip = Schema.decodeSync(TripRequest)({\n request:\n \"Plan a review-only London trip using the deterministic flight, lodging, and activity searches.\",\n origin: \"SFO\",\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n nights: 4,\n travelers: 2,\n budgetCents: 350_000,\n currency: \"USD\",\n});\n/** Backward-compatible fixture alias while consumers transition to the P1 name. */\nexport const phase0Trip = phase1Trip;\nexport const expectedTravelPlan: TravelPlanValue = Schema.decodeSync(TravelPlan)({\n itineraries: [\n {\n title: \"Westward light, eastbound overnight\",\n route: \"San Francisco → London\",\n dates: \"14–19 September 2026\",\n flight: \"EA 218 · nonstop · SFO 18:40 → LHR 13:05+1\",\n lodging: \"Bloomsbury House · refundable studio · 4 nights\",\n activities: [\"British Museum timed entry\", \"Thames evening walk\"],\n estimatedTotalCents: 284_000,\n currency: \"USD\",\n quoteId: \"quote-sfo-lhr-001\",\n assumptions: [\n \"Two travelers sharing one studio\",\n \"Quote is read-only availability, not a reservation\",\n ],\n unresolvedConstraints: [\n \"Traveler names and accessibility requests are intentionally omitted\",\n ],\n nextAction: \"review\",\n },\n ],\n});\n\nexport const phase1HappyPathTurns = [\n {\n _tag: \"Stream\",\n parts: [\n {\n type: \"tool-call\",\n id: \"flight-call-1\",\n name: \"search_flights\",\n params: { origin: \"SFO\", destination: \"LHR\", departOn: \"2026-09-14\", travelers: 2 },\n },\n {\n type: \"tool-call\",\n id: \"lodging-call-1\",\n name: \"search_lodging\",\n params: { destination: \"LHR\", departOn: \"2026-09-14\", nights: 4, travelers: 2 },\n },\n {\n type: \"tool-call\",\n id: \"activity-call-1\",\n name: \"search_activities\",\n params: { destination: \"LHR\", departOn: \"2026-09-14\", nights: 4, travelers: 2 },\n },\n { type: \"finish\", reason: \"tool-calls\", usage },\n ],\n termination: { _tag: \"Complete\" },\n },\n {\n _tag: \"Stream\",\n parts: [\n { type: \"text-start\", id: \"itinerary-json\" },\n {\n type: \"text-delta\",\n id: \"itinerary-json\",\n delta: JSON.stringify(Schema.encodeSync(TravelPlan)(expectedTravelPlan)),\n },\n { type: \"text-end\", id: \"itinerary-json\" },\n { type: \"finish\", reason: \"stop\", usage },\n ],\n termination: { _tag: \"Complete\" },\n },\n] satisfies readonly [ScriptedTurnInput, ScriptedTurnInput];\nexport const phase0HappyPathTurns = phase1HappyPathTurns;\n","import { AgentId, ConversationId, RunId, SubmissionId } from \"@effect-agent/core\";\nimport {\n BatchId,\n CanonicalBatch,\n ConversationCheckpoint,\n ConversationProjection,\n DefinitionDigests,\n DeploymentId,\n Digest,\n ProducerId,\n RecordEnvelope,\n RecordId,\n} from \"@effect-agent/session\";\nimport { Effect, Schema } from \"effect\";\n\nimport { TravelPlan, TripRequest } from \"./definition.ts\";\nimport { expectedTravelPlan, phase1Trip } from \"./scenarios.ts\";\n\n/**\n * The Phase 3 profile persists Conversation history but deliberately does not\n * claim durable admission or recovery of accepted work.\n */\nexport class TravelPlannerPersistenceProfile extends Schema.Class<TravelPlannerPersistenceProfile>(\n \"@effect-agent/testing/travel-planner/TravelPlannerPersistenceProfile\",\n)({\n deploymentClass: Schema.Literal(\"P\"),\n durableAcceptedWork: Schema.Literal(false),\n canonicalSchemaVersion: Schema.Literal(1),\n}) {}\n\nexport const phase3TravelPlannerProfile = TravelPlannerPersistenceProfile.make({\n deploymentClass: \"P\",\n durableAcceptedWork: false,\n canonicalSchemaVersion: 1,\n});\n\nexport const phase3TravelPlannerConversationId = Schema.decodeSync(ConversationId)(\n \"travel-planner-p3-conversation\",\n);\nexport const phase3TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-p3-producer\",\n);\nexport const phase3TravelPlannerRunId = Schema.decodeSync(RunId)(\"travel-planner-p3-run\");\n\nconst deploymentId = Schema.decodeSync(DeploymentId)(\"travel-planner-p3-scripted\");\nconst agentId = Schema.decodeSync(AgentId)(\"travel-planner\");\nconst submissionId = Schema.decodeSync(SubmissionId)(\"travel-planner-p3-submission\");\n\nconst digest = (character: string) => Schema.decodeSync(Digest)(character.repeat(64));\n\n/** Redacted, deterministic definition identities for the current fixture version. */\nexport const phase3TravelPlannerDefinitionDigests = DefinitionDigests.make({\n agent: digest(\"a\"),\n model: digest(\"b\"),\n tools: digest(\"c\"),\n});\n\nconst tripInput = Schema.encodeSync(TripRequest)(phase1Trip);\nconst travelPlanOutput = Schema.encodeSync(TravelPlan)(expectedTravelPlan);\n\nconst record = (recordId: string, createdAt: string, payload: unknown) =>\n Schema.decodeUnknownSync(RecordEnvelope)({\n recordId: Schema.decodeSync(RecordId)(recordId),\n family: \"conversation\",\n schemaVersion: 1,\n createdAt,\n deploymentId,\n payload,\n });\n\n/**\n * The first atomic append establishes the Conversation and records its input.\n * Its encoded value is the redacted current-version persistence fixture.\n */\nexport const phase3TravelPlannerInitialBatch = CanonicalBatch.make({\n batchId: Schema.decodeSync(BatchId)(\"travel-planner-p3-initial\"),\n producerId: phase3TravelPlannerProducerId,\n records: [\n record(\"travel-planner-p3-created\", \"2026-09-01T00:00:00.000Z\", {\n _tag: \"ConversationCreated\",\n agentId,\n definitions: phase3TravelPlannerDefinitionDigests,\n }),\n record(\"travel-planner-p3-input\", \"2026-09-01T00:00:01.000Z\", {\n _tag: \"UserInputRecorded\",\n submissionId,\n kind: \"user\",\n runId: phase3TravelPlannerRunId,\n input: tripInput,\n }),\n ],\n});\n\n/** The second append records the Schema-decoded itinerary and terminal Run result. */\nexport const phase3TravelPlannerCompletionBatch = CanonicalBatch.make({\n batchId: Schema.decodeSync(BatchId)(\"travel-planner-p3-completion\"),\n producerId: phase3TravelPlannerProducerId,\n records: [\n record(\"travel-planner-p3-model\", \"2026-09-01T00:00:02.000Z\", {\n _tag: \"ModelCompleted\",\n runId: phase3TravelPlannerRunId,\n output: travelPlanOutput,\n }),\n record(\"travel-planner-p3-completed\", \"2026-09-01T00:00:03.000Z\", {\n _tag: \"RunCompleted\",\n runId: phase3TravelPlannerRunId,\n output: travelPlanOutput,\n }),\n ],\n});\n\nexport const phase3TravelPlannerBatches = [\n phase3TravelPlannerInitialBatch,\n phase3TravelPlannerCompletionBatch,\n] as const;\n\n/** Portable current-version fixture; it contains no passenger identity or credentials. */\nexport const phase3TravelPlannerEncodedFixture = Schema.encodeSync(Schema.Array(CanonicalBatch))(\n phase3TravelPlannerBatches,\n);\n\nexport class TravelPlannerProjectionError extends Schema.TaggedError<TravelPlannerProjectionError>()(\n \"TravelPlannerProjectionError\",\n { message: Schema.String },\n) {}\n\n/** Decode the itinerary projection rebuilt from canonical model-completion records. */\nexport const travelPlanFromProjection = (\n projection: ConversationProjection,\n): Effect.Effect<TravelPlan, TravelPlannerProjectionError> => {\n const output = projection.modelOutputs.at(-1);\n if (output === undefined) {\n return Effect.fail(\n TravelPlannerProjectionError.make({\n message: \"The canonical projection has no completed Travel Planner model output.\",\n }),\n );\n }\n return Schema.decodeUnknownEffect(TravelPlan)(output).pipe(\n Effect.mapError((error) => TravelPlannerProjectionError.make({ message: error.message })),\n );\n};\n\n/** Build a disposable checkpoint bound to a validated canonical prefix. */\nexport const makePhase3TravelPlannerCheckpoint = (\n projection: ConversationProjection,\n): ConversationCheckpoint =>\n Schema.decodeSync(ConversationCheckpoint)({\n schemaVersion: 1,\n conversationId: projection.conversationId,\n throughSequence: projection.throughSequence,\n tailDigest: projection.tailDigest,\n engineVersion: \"phase-3-test-runtime\",\n agentDefinitionDigest: phase3TravelPlannerDefinitionDigests.agent,\n modelDigest: phase3TravelPlannerDefinitionDigests.model,\n toolDigest: phase3TravelPlannerDefinitionDigests.tools,\n state: Schema.encodeSync(ConversationProjection)(projection),\n createdAt: \"2026-09-01T00:00:04.000Z\",\n });\n","import { Context, Effect, Layer, Ref, Schema, Stream } from \"effect\";\nimport { AiError, LanguageModel, Response } from \"effect/unstable/ai\";\n\nconst ScriptedPartMetadata = Schema.Record(Schema.String, Schema.NullOr(Schema.Json));\nconst ScriptedPartBase = {\n metadata: Schema.optionalKey(ScriptedPartMetadata),\n};\nconst ScriptedToolCallPart = Schema.Struct({\n ...ScriptedPartBase,\n type: Schema.Literal(\"tool-call\"),\n id: Schema.String,\n name: Schema.String,\n params: Schema.Unknown,\n providerExecuted: Schema.optionalKey(Schema.Boolean),\n});\nconst ScriptedToolResultPart = Schema.Struct({\n ...ScriptedPartBase,\n type: Schema.Literal(\"tool-result\"),\n id: Schema.String,\n name: Schema.String,\n result: Schema.Unknown,\n isFailure: Schema.Boolean,\n providerExecuted: Schema.optionalKey(Schema.Boolean),\n preliminary: Schema.optionalKey(Schema.Boolean),\n});\n\n/**\n * Schema for encoded, non-streaming Effect AI response parts.\n *\n * Generic Tool payloads remain explicitly unknown here. `LanguageModel.make`\n * performs the toolkit-specific decode when the scripted response is consumed.\n */\nexport const ScriptedGeneratePart = Schema.Union([\n Schema.toEncoded(Response.TextPart),\n Schema.toEncoded(Response.ReasoningPart),\n Schema.toEncoded(Response.ReasoningDeltaPart),\n Schema.toEncoded(Response.ReasoningEndPart),\n ScriptedToolCallPart,\n ScriptedToolResultPart,\n Schema.toEncoded(Response.ToolApprovalRequestPart),\n Schema.toEncoded(Response.FilePart),\n Schema.toEncoded(Response.DocumentSourcePart),\n Schema.toEncoded(Response.UrlSourcePart),\n Schema.toEncoded(Response.ResponseMetadataPart),\n Schema.toEncoded(Response.FinishPart),\n]).annotate({ identifier: \"ScriptedGeneratePart\" });\nexport type ScriptedGeneratePart = typeof ScriptedGeneratePart.Type;\n\n/**\n * Schema for encoded Effect AI streaming response parts.\n */\nexport const ScriptedStreamPart = Schema.Union([\n Schema.toEncoded(Response.TextStartPart),\n Schema.toEncoded(Response.TextDeltaPart),\n Schema.toEncoded(Response.TextEndPart),\n Schema.toEncoded(Response.ReasoningStartPart),\n Schema.toEncoded(Response.ReasoningDeltaPart),\n Schema.toEncoded(Response.ReasoningEndPart),\n Schema.toEncoded(Response.ToolParamsStartPart),\n Schema.toEncoded(Response.ToolParamsDeltaPart),\n Schema.toEncoded(Response.ToolParamsEndPart),\n ScriptedToolCallPart,\n ScriptedToolResultPart,\n Schema.toEncoded(Response.ToolApprovalRequestPart),\n Schema.toEncoded(Response.FilePart),\n Schema.toEncoded(Response.DocumentSourcePart),\n Schema.toEncoded(Response.UrlSourcePart),\n Schema.toEncoded(Response.ResponseMetadataPart),\n Schema.toEncoded(Response.FinishPart),\n Schema.toEncoded(Response.ErrorPart),\n]).annotate({ identifier: \"ScriptedStreamPart\" });\nexport type ScriptedStreamPart = typeof ScriptedStreamPart.Type;\n\n/** Controls whether a scripted stream completes, fails, or waits for interruption. */\nexport const ScriptedStreamTermination = Schema.Union([\n Schema.TaggedStruct(\"Complete\", {}),\n Schema.TaggedStruct(\"Fail\", {\n description: Schema.String,\n }),\n Schema.TaggedStruct(\"Hang\", {}),\n]);\nexport type ScriptedStreamTermination = typeof ScriptedStreamTermination.Type;\n\n/** One non-streaming invocation and the encoded response parts it returns. */\nexport const ScriptedGenerateTurn = Schema.TaggedStruct(\"Generate\", {\n parts: Schema.Array(ScriptedGeneratePart),\n});\nexport type ScriptedGenerateTurn = typeof ScriptedGenerateTurn.Type;\n\n/** One streaming invocation with its encoded parts and terminal behavior. */\nexport const ScriptedStreamTurn = Schema.TaggedStruct(\"Stream\", {\n parts: Schema.Array(ScriptedStreamPart),\n termination: ScriptedStreamTermination,\n});\nexport type ScriptedStreamTurn = typeof ScriptedStreamTurn.Type;\n\n/**\n * Serializable grammar for one finite scripted provider invocation.\n */\nexport const ScriptedTurn = Schema.Union([ScriptedGenerateTurn, ScriptedStreamTurn]);\nexport type ScriptedTurn = typeof ScriptedTurn.Type;\n\nexport type ScriptedRequestKind = \"generate\" | \"stream\";\n\n/**\n * A request after Effect AI has normalized its prompt, tools, response format,\n * tool choice, span, and incremental-response fields.\n */\nexport interface ScriptedRequest {\n readonly kind: ScriptedRequestKind;\n readonly options: LanguageModel.ProviderOptions;\n}\n\n/** Optional request assertions and stream lifecycle effects for one scripted turn. */\nexport interface ScriptedTurnHooks {\n /** Runs against the normalized provider request before producing the response. */\n readonly assertRequest?: (\n request: LanguageModel.ProviderOptions,\n ) => Effect.Effect<void, AiError.AiError> | void;\n /** Runs immediately before the scripted stream begins emitting parts. */\n readonly onStreamStart?: Effect.Effect<void> | undefined;\n /** Runs when the scripted stream completes, fails, or is interrupted. */\n readonly onStreamFinalize?: Effect.Effect<void> | undefined;\n}\n\n/**\n * Runtime hooks are deliberately separate from the serializable turn grammar.\n */\nexport type ScriptedTurnInput = ScriptedTurn & ScriptedTurnHooks;\n\ninterface ScriptState {\n readonly remaining: ReadonlyArray<ScriptedTurnInput>;\n readonly requests: ReadonlyArray<ScriptedRequest>;\n}\n\nconst scriptedError = (method: string, description: string): AiError.AiError =>\n AiError.AiError.make({\n module: \"@effect-agent/testing/ScriptedModel\",\n method,\n reason: AiError.UnknownError.make({ description }),\n });\n\nconst runAssertion = Effect.fn(\"ScriptedModel.runAssertion\")((\n assertion: ScriptedTurnHooks[\"assertRequest\"],\n request: LanguageModel.ProviderOptions,\n): Effect.Effect<void, AiError.AiError> => {\n if (assertion === undefined) {\n return Effect.void;\n }\n return Effect.suspend(() => {\n const result = assertion(request);\n return Effect.isEffect(result) ? result : Effect.void;\n });\n});\n\nconst takeTurn = Effect.fn(\"ScriptedModel.takeTurn\")(\n (\n state: Ref.Ref<ScriptState>,\n kind: ScriptedRequestKind,\n options: LanguageModel.ProviderOptions,\n ): Effect.Effect<ScriptedTurnInput, AiError.AiError> =>\n Ref.modify(state, (current) => {\n const turn = current.remaining[0];\n if (turn === undefined) {\n return [\n undefined,\n {\n ...current,\n requests: [...current.requests, { kind, options }],\n },\n ] as const;\n }\n return [\n turn,\n {\n remaining: current.remaining.slice(1),\n requests: [...current.requests, { kind, options }],\n },\n ] as const;\n }).pipe(\n Effect.flatMap((turn) =>\n turn === undefined\n ? Effect.fail(scriptedError(kind, `Script exhausted before the ${kind} request`))\n : Effect.succeed(turn),\n ),\n ),\n);\n\nconst requireGenerateTurn = (\n turn: ScriptedTurnInput,\n): Effect.Effect<ScriptedGenerateTurn & ScriptedTurnHooks, AiError.AiError> =>\n turn._tag === \"Generate\"\n ? Effect.succeed(turn)\n : Effect.fail(scriptedError(\"generate\", `Expected a Generate turn but found ${turn._tag}`));\n\nconst requireStreamTurn = (\n turn: ScriptedTurnInput,\n): Effect.Effect<ScriptedStreamTurn & ScriptedTurnHooks, AiError.AiError> =>\n turn._tag === \"Stream\"\n ? Effect.succeed(turn)\n : Effect.fail(scriptedError(\"stream\", `Expected a Stream turn but found ${turn._tag}`));\n\nconst streamForTurn = (\n turn: ScriptedStreamTurn & ScriptedTurnHooks,\n): Stream.Stream<Response.StreamPartEncoded, AiError.AiError> => {\n let stream: Stream.Stream<Response.StreamPartEncoded, AiError.AiError> = Stream.fromIterable(\n turn.parts,\n );\n switch (turn.termination._tag) {\n case \"Complete\": {\n break;\n }\n case \"Fail\": {\n stream = stream.pipe(\n Stream.concat(Stream.fail(scriptedError(\"stream\", turn.termination.description))),\n );\n break;\n }\n case \"Hang\": {\n stream = stream.pipe(Stream.concat(Stream.never));\n break;\n }\n }\n if (turn.onStreamStart !== undefined) {\n stream = Stream.fromEffectDrain(turn.onStreamStart).pipe(Stream.concat(stream));\n }\n if (turn.onStreamFinalize !== undefined) {\n stream = stream.pipe(Stream.ensuring(turn.onStreamFinalize));\n }\n return stream;\n};\n\n/** Inspection service for a deterministic LanguageModel backed by finite scripted turns. */\nexport class ScriptedModel extends Context.Service<\n ScriptedModel,\n {\n /** Normalized provider requests captured in invocation order. */\n readonly requests: Effect.Effect<ReadonlyArray<ScriptedRequest>>;\n /** Number of scripted turns not yet consumed. */\n readonly remaining: Effect.Effect<number>;\n /** Fails with `AiError` when any scripted turns remain. */\n readonly assertExhausted: Effect.Effect<void, AiError.AiError>;\n }\n>()(\"@effect-agent/testing/ScriptedModel\") {\n /**\n * Provides the native Effect AI `LanguageModel` and this inspection service.\n * Supplying the extra inspection service does not add it to model-call\n * requirements. Each model invocation consumes one turn before assertion and\n * turn-kind validation.\n */\n static layer(\n turns: ReadonlyArray<ScriptedTurnInput>,\n ): Layer.Layer<LanguageModel.LanguageModel | ScriptedModel, never, never> {\n return Layer.effectContext(\n Effect.gen(function* () {\n const state = yield* Ref.make<ScriptState>({\n remaining: [...turns],\n requests: [],\n });\n\n const languageModel = yield* LanguageModel.make({\n generateText: (options) =>\n Effect.gen(function* () {\n const turn = yield* takeTurn(state, \"generate\", options);\n yield* runAssertion(turn.assertRequest, options);\n const generateTurn = yield* requireGenerateTurn(turn);\n return [...generateTurn.parts];\n }),\n streamText: (options) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const turn = yield* takeTurn(state, \"stream\", options);\n yield* runAssertion(turn.assertRequest, options);\n const streamTurn = yield* requireStreamTurn(turn);\n return streamForTurn(streamTurn);\n }),\n ),\n });\n\n const inspection = ScriptedModel.of({\n requests: Ref.get(state).pipe(Effect.map((current) => current.requests)),\n remaining: Ref.get(state).pipe(Effect.map((current) => current.remaining.length)),\n assertExhausted: Ref.get(state).pipe(\n Effect.flatMap((current) =>\n current.remaining.length === 0\n ? Effect.void\n : Effect.fail(\n scriptedError(\n \"assertExhausted\",\n `${current.remaining.length} scripted turn(s) remain`,\n ),\n ),\n ),\n ),\n });\n\n return Context.make(LanguageModel.LanguageModel, languageModel).pipe(\n Context.add(ScriptedModel, inspection),\n );\n }),\n );\n }\n}\n","import { Agent, AgentPolicy, type ConversationId } from \"@effect-agent/core\";\nimport { ToolExecutionClass } from \"@effect-agent/engine\";\nimport {\n CanonicalRecordEnvelope,\n DefinitionDigests,\n DeploymentId,\n Digest,\n Principal,\n ProducerId,\n type DurableSubmitOptions,\n type IdempotencyKey,\n type Receipt,\n} from \"@effect-agent/session\";\nimport { Effect, Layer, Schema } from \"effect\";\nimport { Model, Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport { ScriptedModel, type ScriptedTurnInput } from \"../../scripted-model.ts\";\nimport {\n ActivityCatalog,\n ActivityQuery,\n ActivitySearchResult,\n ActivityUnavailable,\n FlightCatalog,\n FlightOption,\n FlightQuery,\n FlightUnavailable,\n LodgingCatalog,\n LodgingOption,\n LodgingQuery,\n LodgingUnavailable,\n TravelGuidance,\n TravelPlan,\n TripRequest,\n} from \"./definition.ts\";\nimport {\n ActivityCatalogLayer,\n CatalogLifecycle,\n FlightCatalogLayer,\n LodgingCatalogLayer,\n TravelGuidanceLayer,\n} from \"./deterministic-layers.ts\";\nimport { phase1HappyPathTurns } from \"./scenarios.ts\";\n\n/**\n * The Phase 4 profile claims durable accepted work on the Node/SQLite runtime (deployment class\n * DN): once `submit` returns a Receipt, the Submission settles exactly once even across process\n * loss. The claim is limited to safe-to-repeat toolkits (D6): supplier booking is explicitly NOT\n * claimed safely replayable — replay-safe external mutation is P5 (Durable Tools) scope.\n */\nexport class TravelPlannerDurabilityProfile extends Schema.Class<TravelPlannerDurabilityProfile>(\n \"@effect-agent/testing/travel-planner/TravelPlannerDurabilityProfile\",\n)({\n deploymentClass: Schema.Literal(\"DN\"),\n durableAcceptedWork: Schema.Literal(true),\n canonicalSchemaVersion: Schema.Literal(1),\n /** Supplier booking replay safety is P5 (Durable Tools) scope; DN does not claim it. */\n supplierBookingReplaySafe: Schema.Literal(false),\n}) {}\n\nexport const phase4TravelPlannerProfile = TravelPlannerDurabilityProfile.make({\n deploymentClass: \"DN\",\n durableAcceptedWork: true,\n canonicalSchemaVersion: 1,\n supplierBookingReplaySafe: false,\n});\n\nexport const phase4TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-p4-deployment\",\n);\nexport const phase4TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-p4-producer\",\n);\nexport const phase4TravelPlannerPrincipal = Schema.decodeSync(Principal)(\n \"travel-planner-p4-principal\",\n);\n\nconst digest = (character: string) => Schema.decodeSync(Digest)(character.repeat(64));\n\n/** Redacted, deterministic definition identities for the current fixture version. */\nexport const phase4TravelPlannerDefinitionDigests = DefinitionDigests.make({\n agent: digest(\"d\"),\n model: digest(\"e\"),\n tools: digest(\"f\"),\n});\n\n/** Durable admission options for one Travel Planner Submission on one trip lane. */\nexport const phase4TravelPlannerSubmitOptions = (\n conversationId: ConversationId,\n idempotencyKey: IdempotencyKey,\n): DurableSubmitOptions => ({\n conversationId,\n principal: phase4TravelPlannerPrincipal,\n idempotencyKey,\n definitions: phase4TravelPlannerDefinitionDigests,\n});\n\n/**\n * The P4 read-only search Tools, calling the same deterministic catalogs as the P1 toolkit.\n *\n * The plain-Struct parameter shape is a historical remnant of the P4 carry-in workaround: since\n * the P5 engine fix, official history carries Schema-ENCODED Tool-call parameters, so class-typed\n * parameter codecs persist canonically too — the Structs simply need no change here. The\n * `ToolExecutionClass` `readonly` annotation is the deliberate P5 migration (plan §4.3): these\n * Tools perform no external mutation, so a crash between start and settlement is a free re-run\n * and they never enter the prepared/settled uncertainty protocol — keeping the P4 canonical\n * history byte-stable (an unannotated Tool fails closed to `uncertain`).\n */\nexport const DurableSearchFlights = Tool.make(\"search_flights\", {\n parameters: Schema.Struct(FlightQuery.fields),\n success: FlightOption,\n failure: FlightUnavailable,\n failureMode: \"error\",\n dependencies: [FlightCatalog],\n}).annotate(ToolExecutionClass, \"readonly\");\nexport const DurableSearchLodging = Tool.make(\"search_lodging\", {\n parameters: Schema.Struct(LodgingQuery.fields),\n success: LodgingOption,\n failure: LodgingUnavailable,\n failureMode: \"error\",\n dependencies: [LodgingCatalog],\n}).annotate(ToolExecutionClass, \"readonly\");\nexport const DurableSearchActivities = Tool.make(\"search_activities\", {\n parameters: Schema.Struct(ActivityQuery.fields),\n success: ActivitySearchResult,\n failure: ActivityUnavailable,\n failureMode: \"error\",\n dependencies: [ActivityCatalog],\n}).annotate(ToolExecutionClass, \"readonly\");\n\nexport const TravelPlannerPhase4Toolkit = Toolkit.make(\n DurableSearchFlights,\n DurableSearchLodging,\n DurableSearchActivities,\n);\n\nexport const TravelPlannerPhase4ToolkitLayer = TravelPlannerPhase4Toolkit.toLayer({\n search_flights: (query) =>\n Effect.flatMap(FlightCatalog, (catalog) => catalog.search(FlightQuery.make(query))),\n search_lodging: (query) =>\n Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(LodgingQuery.make(query))),\n search_activities: (query) =>\n Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(ActivityQuery.make(query))),\n});\n\n/**\n * The cumulative Travel Planner, Phase 4: the P1 planning behavior on the durable Node/SQLite\n * runtime. The searches are read-only and safe to repeat across Attempts (D6); supplier booking\n * is deliberately absent because DN does NOT claim replay-safe external mutation (P5 scope).\n */\nexport const TravelPlannerPhase4 = Agent.define(\"travel-planner-phase-4\", {\n input: TripRequest,\n output: TravelPlan,\n instructions: (input) =>\n Effect.flatMap(TravelGuidance, (guidance) => guidance.instructions(input)),\n toolkit: TravelPlannerPhase4Toolkit,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 3,\n maxDuration: \"30 seconds\",\n toolConcurrency: 3,\n }),\n description:\n \"Durably plan one review-only itinerary from safe-to-repeat deterministic searches; supplier booking is not claimed safely replayable.\",\n metadata: { deploymentClass: \"DN\", phase: \"P4\" },\n});\n\n/**\n * The P4 Agent Binding: the durable Travel Planner definition bound to a finite scripted model.\n * The scripted Layer is rebuilt per Run, so every Run of one Binding replays the same\n * deterministic script.\n */\nexport const makePhase4TravelPlannerAgent = (\n turns: ReadonlyArray<ScriptedTurnInput> = phase1HappyPathTurns,\n) =>\n Agent.withModel(\n TravelPlannerPhase4,\n Model.make(\"scripted\", \"travel-planner-phase-4\", ScriptedModel.layer(turns)),\n );\n\n/**\n * Everything a durable worker needs beyond the runtime stack, reusing the deterministic P1\n * travel-service Layers. The durable coordinator supplies its own deterministic `IdGenerator`,\n * so this Layer deliberately provides none.\n */\nexport const phase4TravelPlannerWorkerLayer = Layer.mergeAll(\n TravelPlannerPhase4ToolkitLayer,\n FlightCatalogLayer,\n LodgingCatalogLayer,\n ActivityCatalogLayer,\n TravelGuidanceLayer,\n).pipe(Layer.provide(CatalogLifecycle.layerNoDeps));\n\nexport class TravelPlannerDurableEvidenceError extends Schema.TaggedError<TravelPlannerDurableEvidenceError>()(\n \"TravelPlannerDurableEvidenceError\",\n { message: Schema.String },\n) {}\n\n/**\n * Decode the completed itinerary from the canonical `SubmissionSettled` record. Canonical history\n * is the outcome authority (DUR-015): the settled result — not any ledger cache — must decode\n * through the trip output schema.\n */\nexport const travelPlanFromDurableSettlement = Effect.fn(\n \"TravelPlannerPhase4.travelPlanFromDurableSettlement\",\n)(function* (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n): Effect.fn.Return<TravelPlan, TravelPlannerDurableEvidenceError> {\n const settlements = records.flatMap((envelope) =>\n envelope.record.payload._tag === \"SubmissionSettled\" ? [envelope.record.payload] : [],\n );\n const settled = settlements.at(0);\n if (settled === undefined) {\n return yield* TravelPlannerDurableEvidenceError.make({\n message: \"The canonical Conversation Log has no SubmissionSettled record.\",\n });\n }\n if (settled.outcome !== \"completed\" || settled.result === undefined) {\n return yield* TravelPlannerDurableEvidenceError.make({\n message: `The Submission settled ${settled.outcome} without a completed itinerary result.`,\n });\n }\n return yield* Schema.decodeUnknownEffect(TravelPlan)(settled.result).pipe(\n Effect.mapError((error) =>\n TravelPlannerDurableEvidenceError.make({\n message: `The settled result does not decode through the TravelPlan schema: ${error.message}`,\n }),\n ),\n );\n});\n\nconst encodeEvidence = Schema.encodeEffect(Schema.Array(CanonicalRecordEnvelope));\nconst decodeComparableJson = Schema.decodeUnknownEffect(Schema.Json);\n\n/**\n * Project canonical evidence into a Submission-identity-independent comparable form: batch\n * identity, canonical sequence, and the full encoded record, with the ledger-minted\n * `submissionId`/`receiptId` (and every identity derived from them: run, turn, batch, record,\n * and settlement ids) replaced by stable placeholders. Two Conversations whose normalized\n * evidence is equal took byte-equivalent canonical histories, so restart-equivalence can compare\n * a recovered run against an uninterrupted control run on a separate database.\n */\nexport const normalizeDurableTravelPlannerEvidence = Effect.fn(\n \"TravelPlannerPhase4.normalizeDurableTravelPlannerEvidence\",\n)(function* (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n receipt: Receipt,\n): Effect.fn.Return<Schema.Json, TravelPlannerDurableEvidenceError> {\n const encoded = yield* encodeEvidence(records).pipe(\n Effect.mapError((error) =>\n TravelPlannerDurableEvidenceError.make({\n message: `Canonical evidence failed to encode: ${error.message}`,\n }),\n ),\n );\n const comparable = encoded.map((envelope) => ({\n batchId: envelope.batchId,\n sequence: envelope.sequence,\n record: envelope.record,\n }));\n const substituted: unknown = JSON.parse(\n JSON.stringify(comparable)\n .replaceAll(receipt.submissionId, \"{submissionId}\")\n .replaceAll(receipt.receiptId, \"{receiptId}\"),\n );\n return yield* decodeComparableJson(substituted).pipe(\n Effect.mapError((error) =>\n TravelPlannerDurableEvidenceError.make({\n message: `Normalized evidence is not comparable JSON: ${error.message}`,\n }),\n ),\n );\n});\n","import { Agent, AgentPolicy, type ConversationId } from \"@effect-agent/core\";\nimport { DurableStep, DurableStepError, ToolExecutionClass } from \"@effect-agent/engine\";\nimport {\n DefinitionDigests,\n DeploymentId,\n Digest,\n PersistedJson,\n Principal,\n ProducerId,\n ReconciliationCompleted,\n ReconciliationSafeToRetry,\n ReconciliationUncertain,\n ToolReconciler,\n ToolReconcilerError,\n type CanonicalRecordEnvelope,\n type DurableSubmitOptions,\n type IdempotencyKey,\n} from \"@effect-agent/session\";\nimport { Effect, Layer, Option, Schema } from \"effect\";\nimport { Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport {\n ActivityCatalog,\n ActivityQuery,\n AirportCode,\n FlightCatalog,\n FlightQuery,\n LodgingCatalog,\n LodgingQuery,\n QuoteId,\n TripRequest,\n} from \"./definition.ts\";\nimport {\n ActivityCatalogLayer,\n BookingRef,\n CatalogLifecycle,\n FlightCatalogLayer,\n LodgingCatalogLayer,\n SupplierBookingDesk,\n SupplierBookingRecord,\n SupplierUnavailable,\n} from \"./deterministic-layers.ts\";\nimport { DurableSearchActivities, DurableSearchFlights, DurableSearchLodging } from \"./phase4.ts\";\n\n/**\n * The Phase 5 profile extends the P4 `DN` claim to consequential supplier mutation: booking\n * Tools enter the prepared/settled uncertainty protocol, unresolved external effects stop at\n * Unknown Outcomes instead of replaying, Durable Steps replay recorded results, and queued\n * traveler input joins the active Run. Exactly-once EXTERNAL execution is still — deliberately —\n * not claimed (DUR-003): the supplier's own idempotency keys are what dedupe repeats.\n */\nexport class TravelPlannerBookingProfile extends Schema.Class<TravelPlannerBookingProfile>(\n \"@effect-agent/testing/travel-planner/TravelPlannerBookingProfile\",\n)({\n deploymentClass: Schema.Literal(\"DN\"),\n durableAcceptedWork: Schema.Literal(true),\n canonicalSchemaVersion: Schema.Literal(1),\n /** P5: supplier mutations get prepared/settled records, Unknown Outcomes, and reconciliation. */\n supplierBookingUncertaintyProtocol: Schema.Literal(true),\n /** P5: Durable Steps are exactly-once-RECORDED; their side effects stay at-least-once. */\n durableStepsRecorded: Schema.Literal(true),\n /** Never claimed at any phase (DUR-003). */\n exactlyOnceExternalEffects: Schema.Literal(false),\n}) {}\n\nexport const phase5TravelPlannerProfile = TravelPlannerBookingProfile.make({\n deploymentClass: \"DN\",\n durableAcceptedWork: true,\n canonicalSchemaVersion: 1,\n supplierBookingUncertaintyProtocol: true,\n durableStepsRecorded: true,\n exactlyOnceExternalEffects: false,\n});\n\nexport const phase5TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-p5-deployment\",\n);\nexport const phase5TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-p5-producer\",\n);\nexport const phase5TravelPlannerPrincipal = Schema.decodeSync(Principal)(\n \"travel-planner-p5-principal\",\n);\n\nconst digest = (character: string) => Schema.decodeSync(Digest)(character.repeat(64));\n\n/** Redacted, deterministic definition identities for the current fixture version. */\nexport const phase5TravelPlannerDefinitionDigests = DefinitionDigests.make({\n agent: digest(\"1\"),\n model: digest(\"2\"),\n tools: digest(\"3\"),\n});\n\n/** Durable admission options for one Travel Planner Submission on one trip lane. */\nexport const phase5TravelPlannerSubmitOptions = (\n conversationId: ConversationId,\n idempotencyKey: IdempotencyKey,\n): DurableSubmitOptions => ({\n conversationId,\n principal: phase5TravelPlannerPrincipal,\n idempotencyKey,\n definitions: phase5TravelPlannerDefinitionDigests,\n});\n\nexport const TravelerRef = Schema.NonEmptyString.pipe(\n Schema.brand(\"@effect-agent/testing/travel-planner/TravelerRef\"),\n);\nexport type TravelerRef = typeof TravelerRef.Type;\n\n/**\n * Class-shaped booking parameters with branded fields: since the P5 engine fix, official history\n * carries Schema-ENCODED Tool-call parameters, so class-typed parameter codecs persist\n * canonically end-to-end (the P4 Struct workaround is gone for new Tools).\n */\nexport class FlightBookingRequest extends Schema.Class<FlightBookingRequest>(\n \"FlightBookingRequest\",\n)({\n quoteId: QuoteId,\n travelerRef: TravelerRef,\n departOn: Schema.String,\n}) {}\n\nexport class SupplierBookingConfirmation extends Schema.Class<SupplierBookingConfirmation>(\n \"SupplierBookingConfirmation\",\n)({\n bookingRef: BookingRef,\n status: Schema.Literal(\"confirmed\"),\n detail: Schema.String,\n}) {}\n\nexport class CancelBookingRequest extends Schema.Class<CancelBookingRequest>(\n \"CancelBookingRequest\",\n)({\n bookingRef: BookingRef,\n travelerRef: TravelerRef,\n}) {}\n\nexport class CancellationConfirmation extends Schema.Class<CancellationConfirmation>(\n \"CancellationConfirmation\",\n)({\n bookingRef: BookingRef,\n status: Schema.Literal(\"cancelled\"),\n}) {}\n\nexport class ItineraryBookingRequest extends Schema.Class<ItineraryBookingRequest>(\n \"ItineraryBookingRequest\",\n)({\n quoteId: QuoteId,\n destination: AirportCode,\n nights: Schema.Int.check(Schema.isGreaterThan(0)),\n travelerRef: TravelerRef,\n}) {}\n\nexport class ItineraryConfirmation extends Schema.Class<ItineraryConfirmation>(\n \"ItineraryConfirmation\",\n)({\n flightBookingRef: BookingRef,\n lodgingBookingRef: BookingRef,\n confirmationCode: Schema.String,\n}) {}\n\n/** The P5 Run output: a booked (or explicitly not-booked) trip report. */\nexport class TravelBookingReport extends Schema.Class<TravelBookingReport>(\"TravelBookingReport\")({\n summary: Schema.String,\n bookingRefs: Schema.Array(BookingRef),\n}) {}\n\n/**\n * Supplier idempotency-key derivations. The handler owns key derivation (the `idempotent` and\n * `uncertain` execution classes carry no key), and the reconciler MUST use the same derivations\n * to query external truth — both sides are exported so they cannot drift.\n */\nexport const bookFlightIdempotencyKey = (toolCallId: string): string => `book-flight:${toolCallId}`;\nexport const itineraryStepIdempotencyKey = (toolCallId: string, stepName: string): string =>\n `${toolCallId}:${stepName}`;\n\n/**\n * Approval-gated supplier booking, explicitly `uncertain`: a crash after the call may have\n * mutated supplier state without a recorded outcome, so recovery must reconcile or stop at an\n * Unknown Outcome — never replay automatically (DUR-009, ADR-0004).\n */\nexport const BookFlight = Tool.make(\"book_flight\", {\n parameters: FlightBookingRequest,\n success: SupplierBookingConfirmation,\n failure: SupplierUnavailable,\n failureMode: \"error\",\n needsApproval: true,\n dependencies: [SupplierBookingDesk],\n}).annotate(ToolExecutionClass, \"uncertain\");\n\n/**\n * Approval-gated cancellation, annotated `idempotent`: the DECLARED external contract is that\n * cancellation is idempotent by `bookingRef` (the supplier desk enforces it), so recovery may\n * re-execute a prepared-but-unsettled cancel without reconciliation proof. Repeats stay\n * observable in the supplier call counters — the annotation never claims exactly-once execution.\n */\nexport const CancelBooking = Tool.make(\"cancel_booking\", {\n parameters: CancelBookingRequest,\n success: CancellationConfirmation,\n failure: SupplierUnavailable,\n failureMode: \"error\",\n needsApproval: true,\n dependencies: [SupplierBookingDesk],\n}).annotate(ToolExecutionClass, \"idempotent\");\n\n/**\n * The Durable Tool: declaring `DurableStep` in `dependencies` is what makes it durable\n * (CONTEXT.md). Its handler divides supplier mutation into three named Steps — `reserve-flight`,\n * `reserve-lodging`, `issue-confirmation` — each deriving its supplier idempotency key from\n * `(toolCallId, stepName)`, so re-entry after interruption replays recorded Step results and the\n * supplier dedupes any honestly-repeated call. The Tool itself carries no execution-class\n * annotation: it stays fail-closed `uncertain`, and `TravelSupplierReconcilerLayer` proves\n * re-entry safe from the keyed-Step construction instead.\n */\nexport const BookItinerary = Tool.make(\"book_itinerary\", {\n parameters: ItineraryBookingRequest,\n success: ItineraryConfirmation,\n failure: Schema.Union([SupplierUnavailable, DurableStepError]),\n failureMode: \"error\",\n dependencies: [DurableStep, SupplierBookingDesk],\n});\n\nexport const TravelPlannerPhase5Toolkit = Toolkit.make(\n DurableSearchFlights,\n DurableSearchLodging,\n DurableSearchActivities,\n BookFlight,\n CancelBooking,\n BookItinerary,\n);\n\nconst requireToolCallId = (\n toolName: string,\n toolCallId: string | undefined,\n): Effect.Effect<string, SupplierUnavailable> =>\n toolCallId === undefined\n ? Effect.fail(\n SupplierUnavailable.make({\n message: `${toolName} needs its stable Tool Call ID to derive the supplier idempotency key.`,\n }),\n )\n : Effect.succeed(toolCallId);\n\nexport const TravelPlannerPhase5ToolkitLayer = TravelPlannerPhase5Toolkit.toLayer({\n search_flights: (query) =>\n Effect.flatMap(FlightCatalog, (catalog) => catalog.search(FlightQuery.make(query))),\n search_lodging: (query) =>\n Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(LodgingQuery.make(query))),\n search_activities: (query) =>\n Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(ActivityQuery.make(query))),\n book_flight: (request, context) =>\n Effect.gen(function* () {\n const desk = yield* SupplierBookingDesk;\n const toolCallId = yield* requireToolCallId(\"book_flight\", context.toolCallId);\n const record = yield* desk.book({\n operation: \"book-flight\",\n idempotencyKey: bookFlightIdempotencyKey(toolCallId),\n detail: `flight ${request.quoteId} for ${request.travelerRef} on ${request.departOn}`,\n });\n return SupplierBookingConfirmation.make({\n bookingRef: record.bookingRef,\n status: \"confirmed\",\n detail: record.detail,\n });\n }),\n cancel_booking: (request) =>\n Effect.gen(function* () {\n const desk = yield* SupplierBookingDesk;\n const record = yield* desk.cancel(request.bookingRef);\n return CancellationConfirmation.make({\n bookingRef: record.bookingRef,\n status: \"cancelled\",\n });\n }),\n book_itinerary: (request, context) =>\n Effect.gen(function* () {\n const desk = yield* SupplierBookingDesk;\n const step = yield* DurableStep;\n const toolCallId = yield* requireToolCallId(\"book_itinerary\", context.toolCallId);\n const bookStep = (\n stepName: \"reserve-flight\" | \"reserve-lodging\" | \"issue-confirmation\",\n detail: string,\n ) =>\n step.do(\n stepName,\n SupplierBookingRecord,\n desk.book({\n operation: stepName,\n idempotencyKey: itineraryStepIdempotencyKey(toolCallId, stepName),\n detail,\n }),\n );\n const flight = yield* bookStep(\n \"reserve-flight\",\n `flight ${request.quoteId} for ${request.travelerRef}`,\n );\n const lodging = yield* bookStep(\n \"reserve-lodging\",\n `lodging ${request.destination} for ${request.nights} nights (${request.travelerRef})`,\n );\n const confirmation = yield* bookStep(\n \"issue-confirmation\",\n `itinerary confirmation for ${request.travelerRef}`,\n );\n return ItineraryConfirmation.make({\n flightBookingRef: flight.bookingRef,\n lodgingBookingRef: lodging.bookingRef,\n confirmationCode: confirmation.bookingRef,\n });\n }),\n});\n\nconst decodePersistedJson = Schema.decodeUnknownEffect(PersistedJson);\nconst encodeConfirmation = Schema.encodeEffect(SupplierBookingConfirmation);\n\n/**\n * The application reconciliation policy (durability §10): a claim about EXTERNAL truth, queried\n * from the supplier desk by the same idempotency-key derivations the handlers use.\n *\n * - `book_flight`: a confirmed booking under `book-flight:{toolCallId}` is recovered supplier\n * truth — `CompletedWithResult` settles it canonically without executing anything. Absence is\n * NOT proof the call never started (a real supplier write could be in flight), so the desk\n * answer stays fail-closed `Uncertain`.\n * - `book_itinerary`: every external mutation inside is a named Step whose supplier idempotency\n * key derives from `(toolCallId, stepName)`, so re-entry is provably safe by construction —\n * `SafeToRetry`. Committed Steps replay from their records; repeated calls dedupe at the desk.\n * - `cancel_booking`: declared `idempotent`, so the coordinator re-executes without consulting\n * this policy; if ever asked, the bookingRef contract makes `SafeToRetry` honest.\n * - anything else: fail-closed `Uncertain` (AGENTS rule 11).\n */\nexport const TravelSupplierReconcilerLayer: Layer.Layer<\n ToolReconciler,\n never,\n SupplierBookingDesk\n> = Layer.effect(\n ToolReconciler,\n Effect.gen(function* () {\n const desk = yield* SupplierBookingDesk;\n return ToolReconciler.of({\n reconcile: (evidence) =>\n Effect.gen(function* () {\n switch (evidence.toolName) {\n case \"book_flight\": {\n const key = bookFlightIdempotencyKey(evidence.toolCallId);\n const booking = yield* desk.lookup(key);\n if (Option.isSome(booking) && booking.value.status === \"confirmed\") {\n const confirmation = yield* encodeConfirmation(\n SupplierBookingConfirmation.make({\n bookingRef: booking.value.bookingRef,\n status: \"confirmed\",\n detail: booking.value.detail,\n }),\n ).pipe(Effect.flatMap(decodePersistedJson));\n return ReconciliationCompleted.make({ result: confirmation, isFailure: false });\n }\n return ReconciliationUncertain.make({\n reason: `The supplier desk shows no confirmed booking under ${key}; a write may still be in flight.`,\n });\n }\n case \"book_itinerary\":\n return ReconciliationSafeToRetry.make();\n case \"cancel_booking\":\n return ReconciliationSafeToRetry.make();\n default:\n return ReconciliationUncertain.make({\n reason: `No supplier reconciliation exists for ${evidence.toolName}.`,\n });\n }\n }).pipe(\n Effect.mapError((error) =>\n ToolReconcilerError.make({\n toolCallId: evidence.toolCallId,\n message: `Supplier reconciliation failed: ${error.message}`,\n }),\n ),\n ),\n });\n }),\n);\n\n/**\n * The cumulative Travel Planner, Phase 5: the durable planner now performs consequential\n * supplier mutation under the full uncertainty protocol — approval-gated uncertain booking,\n * idempotent-by-contract cancellation, and one Durable Tool whose Steps carry supplier\n * idempotency keys.\n */\nexport const TravelPlannerPhase5 = Agent.define(\"travel-planner-phase-5\", {\n input: TripRequest,\n output: TravelBookingReport,\n instructions: [\n \"You are the Effect Agent Travel Planner P5 booking fixture.\",\n \"Search with the read-only tools, then book with book_flight, book_itinerary, or\",\n \"cancel_booking exactly as scripted. Every consequential mutation is approval-gated\",\n \"or Step-structured. Return only a JSON object with summary and bookingRefs.\",\n ].join(\" \"),\n toolkit: TravelPlannerPhase5Toolkit,\n policy: AgentPolicy.make({\n maxTurns: 4,\n maxToolCalls: 6,\n maxDuration: \"30 seconds\",\n toolConcurrency: 2,\n }),\n description:\n \"Durably book one itinerary with prepared/settled supplier records, Unknown Outcomes, named Steps, and joined traveler input.\",\n metadata: { deploymentClass: \"DN\", phase: \"P5\" },\n});\n\nexport class TravelPlannerBookingEvidenceError extends Schema.TaggedError<TravelPlannerBookingEvidenceError>()(\n \"TravelPlannerBookingEvidenceError\",\n { message: Schema.String },\n) {}\n\nconst bookingResultRefs = (result: unknown): ReadonlyArray<string> => {\n if (typeof result !== \"object\" || result === null) return [];\n const refs: Array<string> = [];\n for (const [field, value] of Object.entries(result)) {\n if (\n typeof value === \"string\" &&\n (field === \"bookingRef\" ||\n field === \"flightBookingRef\" ||\n field === \"lodgingBookingRef\" ||\n field === \"confirmationCode\")\n ) {\n refs.push(value);\n }\n }\n return refs;\n};\n\nconst bookingToolNames = new Set([\"book_flight\", \"cancel_booking\", \"book_itinerary\"]);\n\n/**\n * Never-fabricate assertion (ROADMAP P5 exit gate): every successfully settled booking result in\n * canonical history must reference a booking that actually exists in the supplier store. A\n * `ToolCallSettled` whose bookingRef the supplier cannot produce would be a fabricated result —\n * the exact lie the uncertainty protocol exists to prevent.\n */\nexport const assertSettledBookingsExistAtSupplier = Effect.fn(\n \"TravelPlannerPhase5.assertSettledBookingsExistAtSupplier\",\n)(function* (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n): Effect.fn.Return<void, TravelPlannerBookingEvidenceError, SupplierBookingDesk> {\n const desk = yield* SupplierBookingDesk;\n const bookings = yield* desk.bookings;\n const knownRefs = new Set<string>(bookings.map((booking) => booking.bookingRef));\n for (const envelope of records) {\n const payload = envelope.record.payload;\n if (\n payload._tag !== \"ToolCallSettled\" ||\n payload.isFailure ||\n !bookingToolNames.has(payload.toolName)\n ) {\n continue;\n }\n for (const ref of bookingResultRefs(payload.result)) {\n if (!knownRefs.has(ref)) {\n return yield* TravelPlannerBookingEvidenceError.make({\n message: `Canonical record ${envelope.record.recordId} settled bookingRef ${ref}, which the supplier store cannot produce — a fabricated result.`,\n });\n }\n }\n }\n});\n\n/**\n * Everything a durable P5 worker needs beyond the runtime stack and the supplier desk: the\n * booking toolkit plus the deterministic P1 travel-service Layers. `SupplierBookingDesk` is\n * deliberately NOT provided here — tests own the desk's lifetime so its counters, bookings, and\n * crash windows survive Tool-Layer rebuilds across Attempts.\n */\nexport const phase5TravelPlannerWorkerLayer = Layer.mergeAll(\n TravelPlannerPhase5ToolkitLayer,\n FlightCatalogLayer,\n LodgingCatalogLayer,\n ActivityCatalogLayer,\n).pipe(Layer.provide(CatalogLifecycle.layerNoDeps));\n","import { Subagent, SubagentPolicy, SubagentRuntime } from \"@effect-agent/capabilities\";\nimport { Agent, AgentPolicy } from \"@effect-agent/core\";\nimport type { RuntimeBinding } from \"@effect-agent/engine\";\nimport { Context, Deferred, Effect, Layer, Ref, Schema, Stream } from \"effect\";\nimport { LanguageModel, Model, type Response, Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport type { ScriptedTurnInput } from \"../../scripted-model.ts\";\nimport { AirportCode } from \"./definition.ts\";\nimport { CatalogLifecycle } from \"./deterministic-layers.ts\";\n\n// ---------------------------------------------------------------------------\n// Destination Researcher: the S1 specialist child Agent\n// (spec/subagents.md §17 \"deterministic scripted Travel Planner specialist\n// delegation\"). The researcher is a normal Agent with one deterministic\n// travel-service Tool; it never becomes a second child loop (SUB-001/003).\n// ---------------------------------------------------------------------------\n\nexport class DestinationQuery extends Schema.Class<DestinationQuery>(\"DestinationQuery\")({\n destination: AirportCode,\n}) {}\n\nexport class DestinationFacts extends Schema.Class<DestinationFacts>(\"DestinationFacts\")({\n destination: AirportCode,\n highlights: Schema.Array(Schema.String),\n advisory: Schema.NonEmptyString,\n}) {}\n\nexport class DestinationGuideUnavailable extends Schema.TaggedError<DestinationGuideUnavailable>()(\n \"DestinationGuideUnavailable\",\n {\n destination: AirportCode,\n message: Schema.String,\n },\n) {}\n\nexport class DestinationGuide extends Context.Service<\n DestinationGuide,\n {\n readonly lookup: (\n query: DestinationQuery,\n ) => Effect.Effect<DestinationFacts, DestinationGuideUnavailable>;\n }\n>()(\"@effect-agent/testing/travel-planner/DestinationGuide\") {}\n\nexport const LookupDestination = Tool.make(\"lookup_destination\", {\n parameters: DestinationQuery,\n success: DestinationFacts,\n failure: DestinationGuideUnavailable,\n failureMode: \"error\",\n dependencies: [DestinationGuide],\n});\n\nexport const DestinationResearcherToolkit = Toolkit.make(LookupDestination);\nexport const DestinationResearcherToolkitLayer = DestinationResearcherToolkit.toLayer({\n lookup_destination: (query) => Effect.flatMap(DestinationGuide, (guide) => guide.lookup(query)),\n});\n\nexport class DestinationBrief extends Schema.Class<DestinationBrief>(\"DestinationBrief\")({\n destination: AirportCode,\n focus: Schema.NonEmptyString,\n}) {}\n\nexport class DestinationReport extends Schema.Class<DestinationReport>(\"DestinationReport\")({\n destination: AirportCode,\n highlights: Schema.Array(Schema.String),\n advisory: Schema.NonEmptyString,\n}) {}\n\nexport const DestinationResearcher = Agent.define(\"destination-researcher\", {\n input: DestinationBrief,\n output: DestinationReport,\n instructions:\n \"Consult lookup_destination exactly once for the briefed airport, then return only a JSON destination report.\",\n toolkit: DestinationResearcherToolkit,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 1,\n maxDuration: \"30 seconds\",\n toolConcurrency: 1,\n }),\n description: \"Research one candidate destination with the deterministic travel guide.\",\n metadata: { deploymentClass: \"E\", phase: \"S1\" },\n});\n\n// ---------------------------------------------------------------------------\n// Deterministic guide data and Layer (deterministic-layers.ts conventions).\n// ---------------------------------------------------------------------------\n\nconst decodeAirportCode = Schema.decodeSync(AirportCode);\n\nconst guideFacts = new Map<string, DestinationFacts>([\n [\n \"LHR\",\n DestinationFacts.make({\n destination: decodeAirportCode(\"LHR\"),\n highlights: [\"Barbican brutalism walk\", \"Kew glasshouse survey\"],\n advisory: \"London favors museum mornings and riverside evenings.\",\n }),\n ],\n [\n \"CDG\",\n DestinationFacts.make({\n destination: decodeAirportCode(\"CDG\"),\n highlights: [\"Marais passage crawl\", \"Seine bookstall loop\"],\n advisory: \"Paris rewards early galleries and late cafes.\",\n }),\n ],\n]);\n\n/** Deterministic guide lookup shared by the default and test-local guide Layers. */\nexport const destinationLookup = (\n query: DestinationQuery,\n): Effect.Effect<DestinationFacts, DestinationGuideUnavailable> => {\n const facts = guideFacts.get(query.destination);\n return facts === undefined\n ? Effect.fail(\n DestinationGuideUnavailable.make({\n destination: query.destination,\n message: \"No deterministic guide entry exists for this destination.\",\n }),\n )\n : Effect.succeed(facts);\n};\n\nconst requireDestinationFacts = (destination: string): DestinationFacts => {\n const facts = guideFacts.get(destination);\n if (facts === undefined) {\n throw new Error(`No deterministic guide entry exists for destination ${destination}`);\n }\n return facts;\n};\n\n/** The report the scripted researcher writes after consulting the guide. */\nexport const destinationReportFor = (destination: string): DestinationReport => {\n const facts = requireDestinationFacts(destination);\n return DestinationReport.make({\n destination: facts.destination,\n highlights: facts.highlights,\n advisory: facts.advisory,\n });\n};\n\nexport const encodedDestinationReport = (destination: string): string =>\n JSON.stringify(Schema.encodeSync(DestinationReport)(destinationReportFor(destination)));\n\nexport const DestinationGuideLayer = Layer.effect(\n DestinationGuide,\n Effect.gen(function* () {\n const lifecycle = yield* CatalogLifecycle;\n yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);\n return DestinationGuide.of({ lookup: destinationLookup });\n }),\n);\n\n/** Child-side construction requirements of the delegation handler Layer. */\nexport const DestinationResearchSupportLayer = Layer.mergeAll(\n DestinationResearcherToolkitLayer,\n DestinationGuideLayer,\n);\n\n// ---------------------------------------------------------------------------\n// Delegation Definition (spec/subagents.md §4): the coordinator sees exactly\n// one Effect AI Tool with explicit input/result projections and finite bounds.\n// ---------------------------------------------------------------------------\n\nexport class DestinationResearchRequest extends Schema.Class<DestinationResearchRequest>(\n \"DestinationResearchRequest\",\n)({\n destination: AirportCode,\n focus: Schema.NonEmptyString,\n}) {}\n\nexport class DestinationResearchFindings extends Schema.Class<DestinationResearchFindings>(\n \"DestinationResearchFindings\",\n)({\n destination: AirportCode,\n summary: Schema.NonEmptyString,\n}) {}\n\nexport class DestinationResearchFailed extends Schema.TaggedError<DestinationResearchFailed>()(\n \"DestinationResearchFailed\",\n {\n childErrorTag: Schema.NonEmptyString,\n },\n) {}\n\n/**\n * Deterministic delegation-admission choreography seam. `prepareInput` awaits\n * this gate before the handler reserves budget or spawns, so tests can order\n * concurrent delegation preflights without sleeps. It also keeps the\n * projection's construction requirements honestly visible in the handler\n * Layer's `R` (spec/subagents.md §4.1). The open Layer never waits.\n */\nexport class ResearchDispatchGate extends Context.Service<\n ResearchDispatchGate,\n { readonly awaitDispatch: (destination: string) => Effect.Effect<void> }\n>()(\"@effect-agent/testing/travel-planner/ResearchDispatchGate\") {\n static readonly layerOpen = Layer.succeed(\n this,\n ResearchDispatchGate.of({ awaitDispatch: () => Effect.void }),\n );\n}\n\n/**\n * Finite per-invocation bounds (SUB-009): each child may use two Turns and\n * one Tool Call; the parent Run may establish at most two children with at\n * most two running concurrently.\n */\nexport const destinationResearchPolicy = SubagentPolicy.make({\n maxChildren: 2,\n maxConcurrency: 2,\n maxTurns: 2,\n maxToolCalls: 1,\n maxDuration: \"10 seconds\",\n});\n\nexport const destinationResearchDelegation = Subagent.define(\"delegate_destination_research\", {\n description:\n \"Research one candidate destination with the deterministic travel guide and return a bounded finding.\",\n target: DestinationResearcher,\n parameters: DestinationResearchRequest,\n success: DestinationResearchFindings,\n failure: DestinationResearchFailed,\n prepareInput: (request) =>\n Effect.gen(function* () {\n const gate = yield* ResearchDispatchGate;\n yield* gate.awaitDispatch(request.destination);\n return DestinationBrief.make({\n destination: request.destination,\n focus: `research:${request.focus}`,\n });\n }),\n // The explicit declassification boundary (SUB-015): only the advisory\n // crosses to the parent; guide highlights stay in the child Conversation.\n projectResult: (report) =>\n Effect.succeed(\n DestinationResearchFindings.make({\n destination: report.destination,\n summary: report.advisory,\n }),\n ),\n policy: destinationResearchPolicy,\n});\n\n/** Total mapping from every expected child Run failure to the declared Tool failure (SUB-028). */\nexport const mapResearchChildFailure = (failure: {\n readonly _tag: string;\n}): DestinationResearchFailed => DestinationResearchFailed.make({ childErrorTag: failure._tag });\n\n/** Runtime wiring: pair the immutable delegation with one explicit child Binding. */\nexport const destinationResearchHandlersLayer = <Provider, ModelProvides, ModelRequires>(\n childBinding: RuntimeBinding<\n typeof DestinationBrief,\n typeof DestinationReport,\n string,\n Toolkit.Tools<typeof DestinationResearcherToolkit>,\n Provider,\n ModelProvides,\n ModelRequires\n >,\n) =>\n SubagentRuntime.layer(destinationResearchDelegation, childBinding, {\n mapChildFailure: mapResearchChildFailure,\n });\n\n// ---------------------------------------------------------------------------\n// Travel Coordinator: the parent Agent that delegates destination research.\n// ---------------------------------------------------------------------------\n\nexport class ResearchMission extends Schema.Class<ResearchMission>(\"ResearchMission\")({\n request: Schema.NonEmptyString,\n candidates: Schema.Array(AirportCode).check(Schema.isMinLength(1)),\n}) {}\n\nexport class DestinationRecommendation extends Schema.Class<DestinationRecommendation>(\n \"DestinationRecommendation\",\n)({\n destination: AirportCode,\n summary: Schema.NonEmptyString,\n}) {}\n\nexport class DestinationShortlist extends Schema.Class<DestinationShortlist>(\n \"DestinationShortlist\",\n)({\n recommendations: Schema.Array(DestinationRecommendation),\n nextAction: Schema.Literal(\"review\"),\n}) {}\n\n/** Parent-only transcript markers used to prove child context isolation (SUB-006/015). */\nexport const coordinatorConfidentialMarker = \"coordinator-vault-7q42\";\nexport const missionConfidentialMarker = \"traveler-dossier-19f\";\n\nexport const TravelCoordinatorToolkit = Toolkit.make(destinationResearchDelegation.tool);\n\nexport const TravelCoordinator = Agent.define(\"travel-coordinator\", {\n input: ResearchMission,\n output: DestinationShortlist,\n instructions: [\n \"You are the Effect Agent Travel Planner S1 delegation coordinator.\",\n `Coordinator-only context: ${coordinatorConfidentialMarker}.`,\n \"Call delegate_destination_research once per candidate in one Tool batch.\",\n \"Return only a JSON shortlist built from the delegated findings. This is read-only planning.\",\n ].join(\"\\n\"),\n toolkit: TravelCoordinatorToolkit,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 3,\n maxDuration: \"30 seconds\",\n toolConcurrency: 3,\n }),\n description:\n \"Coordinate bounded destination research through one declared attached delegation Tool.\",\n metadata: { deploymentClass: \"E\", phase: \"S1\" },\n});\n\nexport const researchMission = Schema.decodeSync(ResearchMission)({\n request: `Shortlist one September culture city; keep ${missionConfidentialMarker} inside the coordinator conversation.`,\n candidates: [\"LHR\", \"CDG\"],\n});\n\nexport const expectedDestinationShortlist = DestinationShortlist.make({\n recommendations: researchMission.candidates.map((destination) =>\n DestinationRecommendation.make({\n destination,\n summary: requireDestinationFacts(destination).advisory,\n }),\n ),\n nextAction: \"review\",\n});\n\n// ---------------------------------------------------------------------------\n// Scripted turns (scenarios.ts conventions).\n// ---------------------------------------------------------------------------\n\nconst scriptedUsage = { inputTokens: { total: 96 }, outputTokens: { total: 64 } };\n\nexport interface DestinationResearchCall {\n readonly id: string;\n readonly destination: string;\n readonly focus: string;\n}\n\n/** One coordinator Turn that declares the given delegation Tool Calls in order. */\nexport const coordinatorResearchTurn = (\n calls: ReadonlyArray<DestinationResearchCall>,\n): ScriptedTurnInput => ({\n _tag: \"Stream\",\n parts: [\n ...calls.map((call) => ({\n type: \"tool-call\" as const,\n id: call.id,\n name: \"delegate_destination_research\",\n params: { destination: call.destination, focus: call.focus },\n })),\n { type: \"finish\" as const, reason: \"tool-calls\" as const, usage: scriptedUsage },\n ],\n termination: { _tag: \"Complete\" },\n});\n\n/** The coordinator's final structured-output Turn. */\nexport const coordinatorShortlistTurn = (shortlist: DestinationShortlist): ScriptedTurnInput => ({\n _tag: \"Stream\",\n parts: [\n { type: \"text-start\", id: \"shortlist\" },\n {\n type: \"text-delta\",\n id: \"shortlist\",\n delta: JSON.stringify(Schema.encodeSync(DestinationShortlist)(shortlist)),\n },\n { type: \"text-end\", id: \"shortlist\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n ],\n termination: { _tag: \"Complete\" },\n});\n\n/** Static researcher script for single-child tests: one guide lookup, then the report. */\nexport const researcherHappyPathTurns = (\n destination: string,\n): readonly [ScriptedTurnInput, ScriptedTurnInput] => [\n {\n _tag: \"Stream\",\n parts: [\n {\n type: \"tool-call\",\n id: `lookup-${destination}`,\n name: \"lookup_destination\",\n params: { destination },\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n ],\n termination: { _tag: \"Complete\" },\n },\n {\n _tag: \"Stream\",\n parts: [\n { type: \"text-start\", id: \"destination-report\" },\n {\n type: \"text-delta\",\n id: \"destination-report\",\n delta: encodedDestinationReport(destination),\n },\n { type: \"text-end\", id: \"destination-report\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n ],\n termination: { _tag: \"Complete\" },\n },\n];\n\n// ---------------------------------------------------------------------------\n// Destination-keyed researcher model for parallel-children tests.\n// ---------------------------------------------------------------------------\n\n/**\n * Deterministic controls for parallel researcher children whose completions\n * are released in a caller-selected order (ReverseCompletionToolkitLayer\n * pattern). This is intentionally a test fixture: it uses no clock or sleep.\n */\nexport interface DestinationResearcherControls {\n /** Await the first model request of the child researching this destination. */\n readonly awaitStarted: (destination: string) => Effect.Effect<void>;\n /** Allow the child researching this destination to produce its final report. */\n readonly release: (destination: string) => Effect.Effect<void>;\n /** JSON-encoded first-Turn child prompts in arrival order (isolation evidence). */\n readonly prompts: Effect.Effect<ReadonlyArray<string>>;\n}\n\ninterface ResearcherGates {\n readonly started: Deferred.Deferred<void>;\n readonly release: Deferred.Deferred<void>;\n}\n\nconst researcherLookupParts = (destination: string): ReadonlyArray<Response.StreamPartEncoded> => [\n {\n type: \"tool-call\",\n id: `lookup-${destination}`,\n name: \"lookup_destination\",\n params: { destination },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst researcherReportParts = (destination: string): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"destination-report\" },\n { type: \"text-delta\", id: \"destination-report\", delta: encodedDestinationReport(destination) },\n { type: \"text-end\", id: \"destination-report\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\n/**\n * Build a deterministic researcher Model whose per-child behavior is keyed by\n * the destination named in the child's own prompt: Turn one records the\n * prompt, signals `started`, and calls the guide Tool; Turn two waits for the\n * caller's `release` before writing the report. Each child Run builds the\n * Model Layer inside its own scope, so one `CatalogLifecycle` acquisition and\n * finalization is observed per child — the same acquire/release counting the\n * catalog Layers use to prove interruption reaches every finalizer.\n */\nexport const makeDestinationResearcherModel = (destinations: ReadonlyArray<string>) =>\n Effect.gen(function* () {\n const lifecycle = yield* CatalogLifecycle;\n const prompts = yield* Ref.make<ReadonlyArray<string>>([]);\n const gates = new Map<string, ResearcherGates>();\n for (const destination of destinations) {\n gates.set(destination, {\n started: yield* Deferred.make<void>(),\n release: yield* Deferred.make<void>(),\n });\n }\n const gatesFor = (destination: string): Effect.Effect<ResearcherGates> =>\n Effect.suspend(() => {\n const entry = gates.get(destination);\n return entry === undefined\n ? Effect.die(new Error(`No researcher gates exist for destination ${destination}`))\n : Effect.succeed(entry);\n });\n const controls: DestinationResearcherControls = {\n awaitStarted: (destination) =>\n gatesFor(destination).pipe(Effect.flatMap((entry) => Deferred.await(entry.started))),\n release: (destination) =>\n gatesFor(destination).pipe(\n Effect.flatMap((entry) => Deferred.succeed(entry.release, undefined)),\n Effect.asVoid,\n ),\n prompts: Ref.get(prompts),\n };\n const model = Model.make(\n \"scripted\",\n \"destination-researcher-scripted\",\n Layer.effect(\n LanguageModel.LanguageModel,\n Effect.gen(function* () {\n yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);\n const turn = yield* Ref.make(0);\n return yield* LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (options) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const promptJson = JSON.stringify(options.prompt.content);\n const destination = destinations.find((candidate) =>\n promptJson.includes(candidate),\n );\n if (destination === undefined) {\n return yield* Effect.die(\n new Error(\"The researcher prompt names no scripted destination\"),\n );\n }\n const entry = yield* gatesFor(destination);\n const index = yield* Ref.getAndUpdate(turn, (value) => value + 1);\n if (index === 0) {\n yield* Ref.update(prompts, (previous) => [...previous, promptJson]);\n yield* Deferred.succeed(entry.started, undefined);\n return Stream.fromIterable(researcherLookupParts(destination));\n }\n yield* Deferred.await(entry.release);\n return Stream.fromIterable(researcherReportParts(destination));\n }),\n ),\n });\n }),\n ),\n );\n return { controls, model };\n });\n","import {\n delegationAllocationFromPolicy,\n SubagentReservationsMemoryLive,\n SubagentRuntime,\n} from \"@effect-agent/capabilities\";\nimport { Agent, type ConversationId } from \"@effect-agent/core\";\nimport type { RuntimeBinding } from \"@effect-agent/engine\";\nimport {\n DefinitionDigests,\n DeploymentId,\n Digest,\n DurableWorkerBinding,\n Principal,\n ProducerId,\n type DurableSubmitOptions,\n type IdempotencyKey,\n type ResolvedBinding,\n} from \"@effect-agent/session\";\nimport { Effect, Layer, Ref, Schema, Stream } from \"effect\";\nimport { LanguageModel, Model, type Response, type Toolkit } from \"effect/unstable/ai\";\n\nimport { DeterministicIdGeneratorLayer } from \"./deterministic-layers.ts\";\nimport {\n DestinationBrief,\n DestinationFacts,\n DestinationGuide,\n DestinationRecommendation,\n DestinationReport,\n DestinationResearcher,\n DestinationResearcherToolkit,\n DestinationResearcherToolkitLayer,\n destinationLookup,\n destinationReportFor,\n destinationResearchDelegation,\n destinationResearchPolicy,\n DestinationShortlist,\n encodedDestinationReport,\n mapResearchChildFailure,\n ResearchDispatchGate,\n TravelCoordinator,\n} from \"./subagents.ts\";\n\n// ---------------------------------------------------------------------------\n// S2 durability profile (spec/subagents.md §17): the S1 coordinator →\n// destination-researcher delegation re-run as ACCEPTED WORK on the Node/SQLite\n// runtime. The claim is `DN` durable attached Subagents only: establishment\n// and join are replay-safe by construction (SUB-016/SUB-019), a completed\n// child is never re-executed on a lost join acknowledgment, and NO claim of\n// exactly-once child external effects is made (rule 8; an unresolved ordinary\n// child Tool blocks as an Unknown Outcome instead, SUB-021). Cloudflare\n// equivalence is P6 scope and explicitly not claimed here.\n// ---------------------------------------------------------------------------\n\nexport class TravelPlannerSubagentDurabilityProfile extends Schema.Class<TravelPlannerSubagentDurabilityProfile>(\n \"@effect-agent/testing/travel-planner/TravelPlannerSubagentDurabilityProfile\",\n)({\n deploymentClass: Schema.Literal(\"DN\"),\n durableAttachedSubagents: Schema.Literal(true),\n canonicalSchemaVersion: Schema.Literal(1),\n /** Establishment/join replay converges on one child Receipt, Conversation, and join batch. */\n subagentReplaySafe: Schema.Literal(true),\n /** Never claimed (rule 8): child ordinary Tools stop at Unknown Outcomes, they do not replay. */\n childExternalEffectsExactlyOnce: Schema.Literal(false),\n /** The same conformance suite under DO eviction/alarms is P6 scope (spec §17 `DC`). */\n cloudflareEquivalence: Schema.Literal(false),\n}) {}\n\nexport const s2TravelPlannerProfile = TravelPlannerSubagentDurabilityProfile.make({\n deploymentClass: \"DN\",\n durableAttachedSubagents: true,\n canonicalSchemaVersion: 1,\n subagentReplaySafe: true,\n childExternalEffectsExactlyOnce: false,\n cloudflareEquivalence: false,\n});\n\nexport const s2TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-s2-deployment\",\n);\nexport const s2TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-s2-producer\",\n);\nexport const s2TravelPlannerPrincipal = Schema.decodeSync(Principal)(\"travel-planner-s2-principal\");\n\nconst digestOf = (character: string) => Schema.decodeSync(Digest)(character.repeat(64));\n\n/** Redacted, deterministic parent (coordinator) definition digests for this fixture version. */\nexport const s2CoordinatorDigests = DefinitionDigests.make({\n agent: digestOf(\"a\"),\n model: digestOf(\"b\"),\n tools: digestOf(\"c\"),\n});\n\n/**\n * The exact child Binding digest strings the application declares on\n * `SubagentRuntimeOptions.durable.targetDigests` AND the host registers with\n * the `AgentBindingResolver` for the researcher Binding. The coordinator\n * stores and verifies them byte-for-byte (SUB-023); a host registration under\n * different strings is a `ChildCompatibilityFailure`, never a substitution.\n */\nexport const s2ResearcherDigestStrings = {\n agent: \"d\".repeat(64),\n model: \"e\".repeat(64),\n tools: \"f\".repeat(64),\n} as const;\n\nexport const s2ResearcherDigests = DefinitionDigests.make({\n agent: Schema.decodeSync(Digest)(s2ResearcherDigestStrings.agent),\n model: Schema.decodeSync(Digest)(s2ResearcherDigestStrings.model),\n tools: Schema.decodeSync(Digest)(s2ResearcherDigestStrings.tools),\n});\n\n/** Durable admission options for one coordinator Submission on one mission lane. */\nexport const s2TravelPlannerSubmitOptions = (\n conversationId: ConversationId,\n idempotencyKey: IdempotencyKey,\n): DurableSubmitOptions => ({\n conversationId,\n principal: s2TravelPlannerPrincipal,\n idempotencyKey,\n definitions: s2CoordinatorDigests,\n});\n\n/** The structural submit slice of the coordinator Binding (`DurableAgentRuntime.submit`). */\nexport const s2CoordinatorSubmitAgent = {\n definition: { id: TravelCoordinator.id, input: TravelCoordinator.input },\n} as const;\n\n/**\n * The per-invocation reservation the durable handler computes from the S1\n * delegation policy (`delegationAllocationFromPolicy`): the conservation\n * evidence in the S2 tests checks the ledger reservation rows and the\n * canonical `SubagentJoined.finalAccounting` against exactly this value.\n */\nexport const durableResearchAllocation = delegationAllocationFromPolicy(destinationResearchPolicy);\n\n/** The one scripted delegation Tool Call id of the durable coordinator Run. */\nexport const durableResearchCallId = \"research-lhr-1\";\n\n/** The child's own scripted guide-lookup Tool Call id. */\nexport const durableChildLookupCallId = (destination: string): string => `lookup-${destination}`;\n\n/** The projected finding the parent joins (only the advisory crosses, SUB-015). */\nexport const durableResearchFinding = (destination: string) => ({\n destination: destinationReportFor(destination).destination,\n summary: destinationReportFor(destination).advisory,\n});\n\n/** The coordinator's expected final shortlist for one researched destination. */\nexport const durableResearchShortlist = (destination: string): DestinationShortlist =>\n DestinationShortlist.make({\n recommendations: [\n DestinationRecommendation.make({\n destination: destinationReportFor(destination).destination,\n summary: destinationReportFor(destination).advisory,\n }),\n ],\n nextAction: \"review\",\n });\n\n/**\n * The deterministic guide facts in encoded (wire) form: the \"supplier truth\"\n * an authorized operator records through `resolveUnknown` when a child guide\n * lookup stopped at an Unknown Outcome (DUR-017 — the framework never guesses\n * or replays it).\n */\nexport const encodedDestinationFacts = (destination: string): unknown => {\n const report = destinationReportFor(destination);\n return Schema.encodeSync(DestinationFacts)(\n DestinationFacts.make({\n destination: report.destination,\n highlights: report.highlights,\n advisory: report.advisory,\n }),\n );\n};\n\n// ---------------------------------------------------------------------------\n// Invocation-counting scripted models (the P5 SupplierBookingDesk counter\n// pattern): the call counter and captured prompts live OUTSIDE the Model\n// Layer, so they survive Layer rebuilds across Attempts and across separate\n// runtime handles over the same SQLite file — \"the child was never\n// re-executed\" is asserted, not assumed.\n// ---------------------------------------------------------------------------\n\nconst scriptedUsage = { inputTokens: { total: 96 }, outputTokens: { total: 64 } };\n\n/** One scripted model whose behavior is keyed by the global invocation index. */\nexport const makeInvocationCountingModel = (\n name: string,\n script: (call: number) => ReadonlyArray<Response.StreamPartEncoded>,\n) =>\n Effect.gen(function* () {\n const calls = yield* Ref.make(0);\n const prompts = yield* Ref.make<ReadonlyArray<string>>([]);\n const model = Model.make(\n \"scripted\",\n name,\n Layer.effect(\n LanguageModel.LanguageModel,\n LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (request) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const call = yield* Ref.getAndUpdate(calls, (value) => value + 1);\n yield* Ref.update(prompts, (previous) => [\n ...previous,\n JSON.stringify(request.prompt.content),\n ]);\n return Stream.fromIterable(script(call));\n }),\n ),\n }),\n ),\n );\n return { model, calls: Ref.get(calls), prompts: Ref.get(prompts) };\n });\n\nconst delegationTurnParts = (\n toolCallId: string,\n destination: string,\n focus: string,\n): ReadonlyArray<Response.StreamPartEncoded> => [\n {\n type: \"tool-call\",\n id: toolCallId,\n name: \"delegate_destination_research\",\n params: { destination, focus },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst shortlistParts = (\n shortlist: DestinationShortlist,\n): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"shortlist\" },\n {\n type: \"text-delta\",\n id: \"shortlist\",\n delta: JSON.stringify(Schema.encodeSync(DestinationShortlist)(shortlist)),\n },\n { type: \"text-end\", id: \"shortlist\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\nconst researcherLookupParts = (destination: string): ReadonlyArray<Response.StreamPartEncoded> => [\n {\n type: \"tool-call\",\n id: durableChildLookupCallId(destination),\n name: \"lookup_destination\",\n params: { destination },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst researcherReportParts = (destination: string): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"destination-report\" },\n { type: \"text-delta\", id: \"destination-report\", delta: encodedDestinationReport(destination) },\n { type: \"text-end\", id: \"destination-report\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\n// ---------------------------------------------------------------------------\n// Durable delegation wiring (S2): the SAME immutable S1 Delegation Definition\n// paired with one explicit child Binding, now carrying the construction-fixed\n// durable declaration. Under a durable coordinator the handler establishes an\n// accepted-work child instead of spawning an in-process fiber; without the\n// declaration a durable-mode invocation fails closed (WP5 contract).\n// ---------------------------------------------------------------------------\n\n/** Runtime wiring for the durable slice: the S1 delegation plus the S2 digest declaration. */\nexport const durableDestinationResearchHandlersLayer = <Provider, ModelProvides, ModelRequires>(\n childBinding: RuntimeBinding<\n typeof DestinationBrief,\n typeof DestinationReport,\n string,\n Toolkit.Tools<typeof DestinationResearcherToolkit>,\n Provider,\n ModelProvides,\n ModelRequires\n >,\n) =>\n SubagentRuntime.layer(destinationResearchDelegation, childBinding, {\n mapChildFailure: mapResearchChildFailure,\n durable: { targetDigests: s2ResearcherDigestStrings },\n });\n\n/** Optional overrides for one durable research harness. */\nexport interface DurableResearchHarnessOptions {\n /** Researched destination; defaults to \"LHR\". */\n readonly destination?: string | undefined;\n /** Delegation focus; defaults to \"museums\". */\n readonly focus?: string | undefined;\n /**\n * Digests the HOST registers the child Binding under; defaults to the exact\n * declared `s2ResearcherDigests`. Register different digests to force the\n * fail-closed `ChildCompatibilityFailure` path (SUB-023/SUB-032).\n */\n readonly childRegistrationDigests?: DefinitionDigests | undefined;\n}\n\n/** One durable coordinator/researcher pair with observable invocation counters. */\nexport interface DurableResearchHarness {\n /** Host registrations for `NodeDurableRuntimeOptions.bindings` (parent + child). */\n readonly bindings: ReadonlyArray<ResolvedBinding>;\n /** Total coordinator model invocations across every Attempt and runtime handle. */\n readonly parentModelCalls: Effect.Effect<number>;\n /** JSON-encoded coordinator prompts in request order. */\n readonly parentPrompts: Effect.Effect<ReadonlyArray<string>>;\n /** Total researcher model invocations across every Attempt and runtime handle. */\n readonly childModelCalls: Effect.Effect<number>;\n /** JSON-encoded researcher prompts in request order (context-isolation evidence). */\n readonly childPrompts: Effect.Effect<ReadonlyArray<string>>;\n /** Deterministic guide-lookup handler executions (ordinary child Tool side effects). */\n readonly guideInvocations: Effect.Effect<number>;\n}\n\n/**\n * Build the S2 Travel Planner harness: an invocation-counting scripted\n * coordinator (Turn 1 declares the one delegation call, Turn 2 writes the\n * shortlist), an invocation-counting scripted researcher (Turn 1 consults the\n * guide, Turn 2 writes the report), and both worker Bindings captured with\n * their requirement Contexts via `DurableWorkerBinding.make` under the exact\n * fixture digests. The returned `bindings` are plain values: they can be\n * registered with several `NodeDurableRuntime` stacks over the same SQLite\n * file while the counters keep counting across all of them.\n */\nexport const makeDurableResearchHarness = (options?: DurableResearchHarnessOptions) =>\n Effect.gen(function* () {\n const destination = options?.destination ?? \"LHR\";\n const focus = options?.focus ?? \"museums\";\n\n const guideInvocations = yield* Ref.make(0);\n const guideLayer = Layer.succeed(\n DestinationGuide,\n DestinationGuide.of({\n lookup: (query) =>\n Ref.update(guideInvocations, (count) => count + 1).pipe(\n Effect.andThen(destinationLookup(query)),\n ),\n }),\n );\n const childToolkitLayer = DestinationResearcherToolkitLayer.pipe(\n Layer.provideMerge(guideLayer),\n );\n\n const childModel = yield* makeInvocationCountingModel(\"destination-researcher-s2\", (call) =>\n call === 0 ? researcherLookupParts(destination) : researcherReportParts(destination),\n );\n const childBinding = Agent.withModel(DestinationResearcher, childModel.model);\n\n const parentModel = yield* makeInvocationCountingModel(\"travel-coordinator-s2\", (call) =>\n call === 0\n ? delegationTurnParts(durableResearchCallId, destination, focus)\n : shortlistParts(durableResearchShortlist(destination)),\n );\n const parentBinding = Agent.withModel(TravelCoordinator, parentModel.model);\n\n const delegationLayer = durableDestinationResearchHandlersLayer(childBinding).pipe(\n Layer.provide(\n Layer.mergeAll(\n childToolkitLayer,\n SubagentReservationsMemoryLive,\n DeterministicIdGeneratorLayer,\n ResearchDispatchGate.layerOpen,\n ),\n ),\n );\n\n const parentResolved: ResolvedBinding = yield* DurableWorkerBinding.make(\n parentBinding,\n s2CoordinatorDigests,\n ).pipe(Effect.provide(delegationLayer));\n const childResolved: ResolvedBinding = yield* DurableWorkerBinding.make(\n childBinding,\n options?.childRegistrationDigests ?? s2ResearcherDigests,\n ).pipe(Effect.provide(childToolkitLayer));\n\n const harness: DurableResearchHarness = {\n bindings: [parentResolved, childResolved],\n parentModelCalls: parentModel.calls,\n parentPrompts: parentModel.prompts,\n childModelCalls: childModel.calls,\n childPrompts: childModel.prompts,\n guideInvocations: Ref.get(guideInvocations),\n };\n return harness;\n });\n","import { SubagentReservationsMemoryLive } from \"@effect-agent/capabilities\";\nimport { Agent } from \"@effect-agent/core\";\nimport {\n DefinitionDigests,\n DeploymentId,\n Digest,\n DurableWorkerBinding,\n ProducerId,\n type CanonicalRecordEnvelope,\n type Receipt,\n type ResolvedBinding,\n type ToolReconciler,\n} from \"@effect-agent/session\";\nimport { Duration, Effect, Layer, Schema, Stream } from \"effect\";\nimport { LanguageModel, Model, type Response } from \"effect/unstable/ai\";\n\nimport { TravelPlan, TripRequest } from \"./definition.ts\";\nimport {\n DeterministicIdGeneratorLayer,\n SupplierBookingDesk,\n supplierBookingRefFor,\n} from \"./deterministic-layers.ts\";\nimport {\n TravelPlannerDurableEvidenceError,\n TravelPlannerPhase4,\n normalizeDurableTravelPlannerEvidence,\n phase4TravelPlannerDefinitionDigests,\n phase4TravelPlannerWorkerLayer,\n} from \"./phase4.ts\";\nimport {\n TravelPlannerPhase5,\n TravelSupplierReconcilerLayer,\n bookFlightIdempotencyKey,\n phase5TravelPlannerDefinitionDigests,\n phase5TravelPlannerWorkerLayer,\n} from \"./phase5.ts\";\nimport { expectedTravelPlan } from \"./scenarios.ts\";\nimport {\n durableDestinationResearchHandlersLayer,\n durableResearchCallId,\n durableResearchShortlist,\n s2CoordinatorDigests,\n s2ResearcherDigests,\n} from \"./subagents-durable.ts\";\nimport {\n DestinationGuide,\n DestinationResearcher,\n DestinationResearcherToolkitLayer,\n DestinationShortlist,\n ResearchDispatchGate,\n ResearchMission,\n TravelCoordinator,\n destinationLookup,\n encodedDestinationReport,\n} from \"./subagents.ts\";\n\n// ---------------------------------------------------------------------------\n// Phase 6 (P6): the SAME cumulative Travel Planner on the Cloudflare Durable\n// Object runtime, deployment class DC. This module is deliberately\n// platform-neutral (it imports no Cloudflare types): the worker Bindings it\n// builds are plain `ResolvedBinding` values a Conversation Object registers,\n// and the cross-platform evidence normal form is shared by the DN and DC\n// halves of the equivalence suite (plan §1.8, D-P6-6).\n// ---------------------------------------------------------------------------\n\n/**\n * The Phase 6 profile: the P4/P5/S2 Travel Planner claims re-earned on the Cloudflare Durable\n * Object runtime (deployment class `DC`), where eviction and alarm redelivery replace process\n * kill and restart as the exercised recovery path. `cloudflareEquivalence` is the claim the S2\n * fixture explicitly deferred to P6 (`TravelPlannerSubagentDurabilityProfile` pins it `false`\n * for `DN`): it flips to `true` here ONLY because the phase-6 suites assert byte-equal\n * cross-platform normalized canonical evidence against one committed golden. Exactly-once\n * EXTERNAL effects remain — deliberately — unclaimed on every platform (DUR-003).\n */\nexport class TravelPlannerCloudflareProfile extends Schema.Class<TravelPlannerCloudflareProfile>(\n \"@effect-agent/testing/travel-planner/TravelPlannerCloudflareProfile\",\n)({\n deploymentClass: Schema.Literal(\"DC\"),\n durableAcceptedWork: Schema.Literal(true),\n canonicalSchemaVersion: Schema.Literal(1),\n /** P5 semantics under DC recovery: prepared/settled records, Unknown Outcomes, approvals. */\n supplierBookingUncertaintyProtocol: Schema.Literal(true),\n /** S2 semantics under DC recovery: cross-Object establishment/join, completed child never re-runs. */\n durableAttachedSubagents: Schema.Literal(true),\n /** DN and DC produce byte-equal cross-platform normalized canonical evidence (one golden). */\n cloudflareEquivalence: Schema.Literal(true),\n /** Never claimed at any phase on any platform (DUR-003). */\n exactlyOnceExternalEffects: Schema.Literal(false),\n}) {}\n\nexport const phase6TravelPlannerProfile = TravelPlannerCloudflareProfile.make({\n deploymentClass: \"DC\",\n durableAcceptedWork: true,\n canonicalSchemaVersion: 1,\n supplierBookingUncertaintyProtocol: true,\n durableAttachedSubagents: true,\n cloudflareEquivalence: true,\n exactlyOnceExternalEffects: false,\n});\n\nexport const phase6TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-p6-deployment\",\n);\n/** Producer prefix of the DC host; each Object mints `{prefix}:{conversationId}`. */\nexport const phase6TravelPlannerProducerPrefix = \"travel-planner-p6-producer\";\n/** The full producer identity one DC Conversation Object mints for itself. */\nexport const phase6TravelPlannerProducerId = (conversationId: string): ProducerId =>\n Schema.decodeSync(ProducerId)(`${phase6TravelPlannerProducerPrefix}:${conversationId}`);\n\nconst digestOf = (character: string) => Schema.decodeSync(Digest)(character.repeat(64));\n\n/**\n * Registration digests of the GATED planner Binding: the same `TravelPlannerPhase4` definition\n * bound to a model whose first response waits on a test gate, addressable separately so the\n * admission-limits rows can hold a lane busy deterministically without touching the ordinary\n * planner registration.\n */\nexport const phase6GatedPlannerDefinitionDigests = DefinitionDigests.make({\n agent: digestOf(\"9\"),\n model: digestOf(\"8\"),\n tools: digestOf(\"7\"),\n});\n\n// ---------------------------------------------------------------------------\n// Cross-platform evidence normal form (plan §1.8, D-P6-6)\n// ---------------------------------------------------------------------------\n\n/** The run-specific identities the cross-platform normal form scrubs. */\nexport interface CrossPlatformEvidenceIdentity {\n /** The Conversation lane the evidence came from. */\n readonly conversationId: string;\n /** The host's deployment identity (`DeploymentId` on every record envelope). */\n readonly deploymentId: string;\n /** The full producer identity of the run (DN: configured; DC: `{prefix}:{conversationId}`). */\n readonly producerId: string;\n}\n\nconst decodeComparableJson = Schema.decodeUnknownEffect(Schema.Json);\n\n/** The base normal form's element shape, re-decoded so sequences can be renumbered. */\nconst ComparableEnvelope = Schema.Struct({\n batchId: Schema.String,\n sequence: Schema.Number,\n record: Schema.Json,\n});\nconst decodeComparableEnvelopes = Schema.decodeUnknownEffect(Schema.Array(ComparableEnvelope));\n\n/**\n * The CROSS-PLATFORM extension of `normalizeDurableTravelPlannerEvidence` (D-P6-6): after the\n * base normalization replaces the two ledger-minted identities (which also normalizes the\n * DC-format routable `{uuidv7}:{conversationId}` Submission identities and everything derived\n * from them), this form additionally scrubs everything that legitimately differs between a DN\n * process and a DC Durable Object over the same scenario:\n *\n * - `RepairAnnotated` audit records are dropped BEFORE normalization and the canonical\n * sequence is renumbered to the surviving order: repairs are DUR-013 evidence of recovery\n * itself, legally present in a recovered run and legally absent from an uninterrupted\n * control (on DC even a CLEAN run carries one, because every pass reconciles before it\n * claims, so the ready lane's input is applied through the recovery path). Canonical ORDER\n * is the durability §5 claim; sequence contiguity is a platform artifact of who appended;\n * - the Conversation identity (DC lanes mint unique names per test run);\n * - the deployment and producer identities (host configuration, not canonical semantics);\n * - `createdAt` commit timestamps (wall clock);\n * - 64-hex digests (they hash RAW content that legally embeds run-specific identity, so they\n * can never be byte-equal across runs; chain integrity is asserted separately by the\n * adapters and the convergence helpers).\n *\n * Two runs whose cross-platform normalized evidence is byte-equal took canonically equivalent\n * histories — the exact sense in which durability §5 permits storage differences while\n * requiring the same observable ordering. Both the DN and DC suites assert equality against\n * the one committed `phase6TravelPlannerGoldenEvidence`, so DN ≡ DC transitively.\n */\nexport const normalizeCrossPlatformTravelPlannerEvidence = Effect.fn(\n \"TravelPlannerPhase6.normalizeCrossPlatformTravelPlannerEvidence\",\n)(function* (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n receipt: Receipt,\n identity: CrossPlatformEvidenceIdentity,\n): Effect.fn.Return<Schema.Json, TravelPlannerDurableEvidenceError> {\n const canonical = records.filter(\n (envelope) => envelope.record.payload._tag !== \"RepairAnnotated\",\n );\n const base = yield* normalizeDurableTravelPlannerEvidence(canonical, receipt);\n const scrubbed: unknown = JSON.parse(\n JSON.stringify(base)\n .replaceAll(identity.producerId, \"{producerId}\")\n .replaceAll(identity.deploymentId, \"{deploymentId}\")\n .replaceAll(identity.conversationId, \"{conversationId}\")\n .replaceAll(/\\d{4}-\\d{2}-\\d{2}T[0-9:.]+Z/g, \"{timestamp}\")\n .replaceAll(/\"[0-9a-f]{64}\"/g, '\"{digest}\"'),\n );\n const comparable = yield* decodeComparableEnvelopes(scrubbed).pipe(\n Effect.mapError((error) =>\n TravelPlannerDurableEvidenceError.make({\n message: `Cross-platform normalized evidence lost the comparable shape: ${error.message}`,\n }),\n ),\n );\n const renumbered = comparable.map((entry, index) => ({\n batchId: entry.batchId,\n sequence: index + 1,\n record: entry.record,\n }));\n return yield* decodeComparableJson(renumbered).pipe(\n Effect.mapError((error) =>\n TravelPlannerDurableEvidenceError.make({\n message: `Cross-platform normalized evidence is not comparable JSON: ${error.message}`,\n }),\n ),\n );\n});\n\n// ---------------------------------------------------------------------------\n// Prompt-aware scripted models. A DC Attempt may resume on a FRESH Object\n// incarnation whose Layers (and any in-memory turn counter) were rebuilt, so\n// every phase-6 model derives its response purely from the committed history\n// in its prompt — the way a real model would — instead of from call order.\n// ---------------------------------------------------------------------------\n\nconst scriptedUsage = { inputTokens: { total: 128 }, outputTokens: { total: 96 } };\n\nconst promptAwareModel = (\n name: string,\n decide: (promptJson: string) => Stream.Stream<Response.StreamPartEncoded>,\n) =>\n Model.make(\n \"scripted\",\n name,\n Layer.effect(\n LanguageModel.LanguageModel,\n LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (options) =>\n Stream.unwrap(Effect.sync(() => decide(JSON.stringify(options.prompt)))),\n }),\n ),\n );\n\n/** The P1/P4 happy-path Tool Call identities (scenarios.ts, byte-stable since P1). */\nexport const phase6FlightCallId = \"flight-call-1\";\nexport const phase6LodgingCallId = \"lodging-call-1\";\nexport const phase6ActivityCallId = \"activity-call-1\";\n\n/** Turn 1 of the planner: the SAME three search declarations as `phase1HappyPathTurns`. */\nconst plannerSearchTurnParts: ReadonlyArray<Response.StreamPartEncoded> = [\n {\n type: \"tool-call\",\n id: phase6FlightCallId,\n name: \"search_flights\",\n params: { origin: \"SFO\", destination: \"LHR\", departOn: \"2026-09-14\", travelers: 2 },\n },\n {\n type: \"tool-call\",\n id: phase6LodgingCallId,\n name: \"search_lodging\",\n params: { destination: \"LHR\", departOn: \"2026-09-14\", nights: 4, travelers: 2 },\n },\n {\n type: \"tool-call\",\n id: phase6ActivityCallId,\n name: \"search_activities\",\n params: { destination: \"LHR\", departOn: \"2026-09-14\", nights: 4, travelers: 2 },\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\n/** Turn 2 of the planner: the SAME itinerary text as `phase1HappyPathTurns`. */\nconst plannerPlanTurnParts: ReadonlyArray<Response.StreamPartEncoded> = [\n { type: \"text-start\", id: \"itinerary-json\" },\n {\n type: \"text-delta\",\n id: \"itinerary-json\",\n delta: JSON.stringify(Schema.encodeSync(TravelPlan)(expectedTravelPlan)),\n },\n { type: \"text-end\", id: \"itinerary-json\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\nconst plannerDecide = (promptJson: string): Stream.Stream<Response.StreamPartEncoded> =>\n promptJson.includes(phase6FlightCallId)\n ? Stream.fromIterable(plannerPlanTurnParts)\n : Stream.fromIterable(plannerSearchTurnParts);\n\n/**\n * The P4 planner script (`phase1HappyPathTurns`) as a prompt-aware model: once the search\n * batch is committed history, every later request gets the plan — identical parts, so the DC\n * canonical evidence is byte-equivalent to the DN ScriptedModel run after normalization.\n */\nexport const phase6PlannerModel = promptAwareModel(\"travel-planner-phase-4\", plannerDecide);\n\n// ---------------------------------------------------------------------------\n// Deterministic test gate for the admission-limits rows. Module state is\n// intentionally NOT durable: it plays the external world's role (a slow\n// upstream model), never Conversation state.\n// ---------------------------------------------------------------------------\n\nconst releasedPlannerGates = new Set<string>();\n\n/** Release the gated planner model for one `[gate:...]` marker. */\nexport const releasePhase6PlannerGate = (marker: string): void => {\n releasedPlannerGates.add(marker);\n};\n\n/** Re-close one gate marker (fresh suites reuse markers safely). */\nexport const resetPhase6PlannerGate = (marker: string): void => {\n releasedPlannerGates.delete(marker);\n};\n\nconst awaitPlannerGate = (marker: string): Effect.Effect<void> =>\n Effect.gen(function* () {\n while (!releasedPlannerGates.has(marker)) {\n yield* Effect.sleep(Duration.millis(10));\n }\n });\n\nconst gateMarkerFromPrompt = (promptJson: string): string =>\n /\\[gate:([^\\]]+)\\]/.exec(promptJson)?.[1] ?? \"unknown-gate\";\n\n/** A trip whose request text carries the gate marker the gated model waits on. */\nexport const phase6GatedTrip = (marker: string): TripRequest =>\n Schema.decodeUnknownSync(TripRequest)({\n request: `Plan a review-only London trip, but wait for the concierge. [gate:${marker}]`,\n origin: \"SFO\",\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n nights: 4,\n travelers: 2,\n budgetCents: 350_000,\n currency: \"USD\",\n });\n\n/**\n * The SAME planner behavior with a hanging first response: the model waits on the released\n * gate before answering, keeping its lane durably busy so queue-depth admission limits can be\n * exercised deterministically.\n */\nexport const phase6GatedPlannerModel = Model.make(\n \"scripted\",\n \"travel-planner-phase-4-gated\",\n Layer.effect(\n LanguageModel.LanguageModel,\n LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (options) =>\n Stream.unwrap(\n Effect.sync(() => {\n const promptJson = JSON.stringify(options.prompt);\n return promptJson.includes(phase6FlightCallId)\n ? plannerDecide(promptJson)\n : Stream.fromEffectDrain(awaitPlannerGate(gateMarkerFromPrompt(promptJson))).pipe(\n Stream.concat(plannerDecide(promptJson)),\n );\n }),\n ),\n }),\n ),\n);\n\n// ---------------------------------------------------------------------------\n// P5 booking slice: the SAME phase-5 booking agent and supplier desk. The desk\n// is a module-level singleton because it IS the external supplier: like a real\n// supplier's ledger, its bookings and call counters survive `ctx.abort()` and\n// incarnation loss, which is exactly what the never-fabricate and\n// executed-once assertions measure.\n// ---------------------------------------------------------------------------\n\nconst sharedSupplierDesk = Effect.runSync(\n Effect.flatMap(SupplierBookingDesk, Effect.succeed).pipe(\n Effect.provide(SupplierBookingDesk.layer),\n ),\n);\n\n/** The shared external supplier desk instance (module-level external truth). */\nexport const phase6SupplierDesk = sharedSupplierDesk;\n\n/** Layer handing the shared desk to Bindings, reconcilers, and assertions. */\nexport const phase6SupplierDeskLayer: Layer.Layer<SupplierBookingDesk> = Layer.succeed(\n SupplierBookingDesk,\n sharedSupplierDesk,\n);\n\n/**\n * The REAL P5 supplier reconciliation policy over the shared desk, closed to no requirements\n * so a Conversation Object can install it directly: `book_flight` recovers only from supplier\n * truth (absence stays fail-closed `Uncertain` → durable Unknown Outcome), keyed Steps are\n * provably re-enterable.\n */\nexport const phase6SupplierReconcilerLayer: Layer.Layer<ToolReconciler> =\n TravelSupplierReconcilerLayer.pipe(Layer.provide(phase6SupplierDeskLayer));\n\nconst bookingMarkerFromPrompt = (promptJson: string): string =>\n /\\[case:([^\\]]+)\\]/.exec(promptJson)?.[1] ?? \"unknown-case\";\n\n/** The deterministic booking Tool Call identity for one `[case:...]` marker. */\nexport const phase6BookingToolCallId = (marker: string): string => `book-${marker}`;\n\n/** The bookingRef the supplier desk mints for one marker's approved booking. */\nexport const phase6BookingRef = (marker: string): string =>\n supplierBookingRefFor(bookFlightIdempotencyKey(phase6BookingToolCallId(marker)));\n\n/** A trip whose request text carries the per-lane booking case marker. */\nexport const phase6BookingTrip = (marker: string): TripRequest =>\n Schema.decodeUnknownSync(TripRequest)({\n request: `Book the approved London flight for the traveler. [case:${marker}]`,\n origin: \"SFO\",\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n nights: 4,\n travelers: 2,\n budgetCents: 350_000,\n currency: \"USD\",\n });\n\nconst bookingCallParts = (marker: string): ReadonlyArray<Response.StreamPartEncoded> => [\n {\n type: \"tool-call\",\n id: phase6BookingToolCallId(marker),\n name: \"book_flight\",\n params: {\n quoteId: \"quote-sfo-lhr-001\",\n travelerRef: `traveler-${marker}`,\n departOn: \"2026-09-14\",\n },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst bookingReportParts = (marker: string): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"booking-report\" },\n {\n type: \"text-delta\",\n id: \"booking-report\",\n delta: JSON.stringify({\n summary: \"trip booked\",\n bookingRefs: [phase6BookingRef(marker)],\n }),\n },\n { type: \"text-end\", id: \"booking-report\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\n/**\n * The P5 booking script as a prompt-aware model: request 1 declares the approval-gated\n * `book_flight` call (identity derived from the lane's `[case:...]` marker so supplier\n * idempotency keys never collide across lanes); once that call is committed history, the model\n * writes the booking report.\n */\nexport const phase6BookingModel = promptAwareModel(\"travel-planner-phase-5\", (promptJson) => {\n const marker = bookingMarkerFromPrompt(promptJson);\n return promptJson.includes(phase6BookingToolCallId(marker))\n ? Stream.fromIterable(bookingReportParts(marker))\n : Stream.fromIterable(bookingCallParts(marker));\n});\n\n// ---------------------------------------------------------------------------\n// S2 delegation slice: the SAME coordinator → destination-researcher pair.\n// The guide invocation counter is module state for the same reason as the\n// desk: it is the child's external side-effect record, and \"the completed\n// child never re-executes\" is asserted against it across evictions.\n// ---------------------------------------------------------------------------\n\nlet guideInvocations = 0;\n\n/** Deterministic guide-lookup handler executions across every incarnation. */\nexport const phase6GuideInvocationCount = (): number => guideInvocations;\n\nconst countingGuideLayer = Layer.succeed(\n DestinationGuide,\n DestinationGuide.of({\n lookup: (query) =>\n Effect.suspend(() => {\n guideInvocations += 1;\n return destinationLookup(query);\n }),\n }),\n);\n\n/** The one-candidate research mission of the DC delegation slice. */\nexport const phase6ResearchMission = Schema.decodeUnknownSync(ResearchMission)({\n request: \"Shortlist one September culture city for the DC delegation slice.\",\n candidates: [\"LHR\"],\n});\n\nexport const phase6ResearchDestination = \"LHR\";\n\n/** The child's scripted guide-lookup Tool Call identity. */\nexport const phase6ChildLookupCallId = `lookup-${phase6ResearchDestination}`;\n\nconst coordinatorDelegationParts: ReadonlyArray<Response.StreamPartEncoded> = [\n {\n type: \"tool-call\",\n id: durableResearchCallId,\n name: \"delegate_destination_research\",\n params: { destination: phase6ResearchDestination, focus: \"museums\" },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst coordinatorShortlistParts: ReadonlyArray<Response.StreamPartEncoded> = [\n { type: \"text-start\", id: \"shortlist\" },\n {\n type: \"text-delta\",\n id: \"shortlist\",\n delta: JSON.stringify(\n Schema.encodeSync(DestinationShortlist)(durableResearchShortlist(phase6ResearchDestination)),\n ),\n },\n { type: \"text-end\", id: \"shortlist\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\nconst researcherLookupParts: ReadonlyArray<Response.StreamPartEncoded> = [\n {\n type: \"tool-call\",\n id: phase6ChildLookupCallId,\n name: \"lookup_destination\",\n params: { destination: phase6ResearchDestination },\n providerExecuted: false,\n },\n { type: \"finish\", reason: \"tool-calls\", usage: scriptedUsage },\n];\n\nconst researcherReportParts: ReadonlyArray<Response.StreamPartEncoded> = [\n { type: \"text-start\", id: \"destination-report\" },\n {\n type: \"text-delta\",\n id: \"destination-report\",\n delta: encodedDestinationReport(phase6ResearchDestination),\n },\n { type: \"text-end\", id: \"destination-report\" },\n { type: \"finish\", reason: \"stop\", usage: scriptedUsage },\n];\n\n/** Prompt-aware S2 coordinator: delegation call first, shortlist once it is history. */\nexport const phase6CoordinatorModel = promptAwareModel(\"travel-coordinator-p6\", (promptJson) =>\n promptJson.includes(durableResearchCallId)\n ? Stream.fromIterable(coordinatorShortlistParts)\n : Stream.fromIterable(coordinatorDelegationParts),\n);\n\nlet researcherGateReleased = false;\n\n/** Allow the researcher's FIRST model response to proceed (sticky across incarnations). */\nexport const releasePhase6ResearcherGate = (): void => {\n researcherGateReleased = true;\n};\n\n/** Re-close the researcher gate (each delegation scenario starts gated). */\nexport const resetPhase6ResearcherGate = (): void => {\n researcherGateReleased = false;\n};\n\nconst awaitResearcherGate: Effect.Effect<void> = Effect.gen(function* () {\n while (!researcherGateReleased) {\n yield* Effect.sleep(Duration.millis(10));\n }\n});\n\n/**\n * Prompt-aware S2 researcher: guide lookup first, report once it is history. The FIRST\n * response waits on the researcher gate — a stand-in for real model latency. The child's own\n * Object may legally start its Attempt the moment its routed admission commits, while the\n * parent is still appending the lineage record into the child's log; a child whose first\n * batch commits during that window races the parent's append on one tail. Real models answer\n * in seconds, so establishment always wins that race in production; the gate reproduces that\n * timing deterministically instead of relying on scheduler luck.\n */\nexport const phase6ResearcherModel = promptAwareModel(\"destination-researcher-p6\", (promptJson) =>\n promptJson.includes(phase6ChildLookupCallId)\n ? Stream.fromIterable(researcherReportParts)\n : Stream.fromEffectDrain(awaitResearcherGate).pipe(\n Stream.concat(Stream.fromIterable(researcherLookupParts)),\n ),\n);\n\n// ---------------------------------------------------------------------------\n// Worker Binding registrations for the DC Conversation Object\n// ---------------------------------------------------------------------------\n\n/**\n * Every phase-6 Travel Planner worker Binding, captured with its requirement Contexts\n * (spec/subagents.md §11): the P4 planner and its gated twin, the P5 booking agent over the\n * shared supplier desk, and the S2 coordinator/researcher pair wired through the durable\n * delegation Layer. A Conversation Object registers these via its `bindings` option; the\n * capture runs once per incarnation, and everything stateful the assertions rely on (desk,\n * guide counter, gates) lives at module level so it survives incarnation loss.\n */\nexport const makePhase6TravelPlannerBindings: Effect.Effect<ReadonlyArray<ResolvedBinding>> =\n Effect.gen(function* () {\n const planner: ResolvedBinding = yield* DurableWorkerBinding.make(\n Agent.withModel(TravelPlannerPhase4, phase6PlannerModel),\n phase4TravelPlannerDefinitionDigests,\n ).pipe(Effect.provide(phase4TravelPlannerWorkerLayer));\n\n const gatedPlanner: ResolvedBinding = yield* DurableWorkerBinding.make(\n Agent.withModel(TravelPlannerPhase4, phase6GatedPlannerModel),\n phase6GatedPlannerDefinitionDigests,\n ).pipe(Effect.provide(phase4TravelPlannerWorkerLayer));\n\n const booking: ResolvedBinding = yield* DurableWorkerBinding.make(\n Agent.withModel(TravelPlannerPhase5, phase6BookingModel),\n phase5TravelPlannerDefinitionDigests,\n ).pipe(\n Effect.provide(\n phase5TravelPlannerWorkerLayer.pipe(Layer.provideMerge(phase6SupplierDeskLayer)),\n ),\n );\n\n const researcherBinding = Agent.withModel(DestinationResearcher, phase6ResearcherModel);\n const childToolkitLayer = DestinationResearcherToolkitLayer.pipe(\n Layer.provideMerge(countingGuideLayer),\n );\n\n const coordinator: ResolvedBinding = yield* DurableWorkerBinding.make(\n Agent.withModel(TravelCoordinator, phase6CoordinatorModel),\n s2CoordinatorDigests,\n ).pipe(\n Effect.provide(\n durableDestinationResearchHandlersLayer(researcherBinding).pipe(\n Layer.provide(\n Layer.mergeAll(\n childToolkitLayer,\n SubagentReservationsMemoryLive,\n DeterministicIdGeneratorLayer,\n ResearchDispatchGate.layerOpen,\n ),\n ),\n ),\n ),\n );\n\n const researcher: ResolvedBinding = yield* DurableWorkerBinding.make(\n researcherBinding,\n s2ResearcherDigests,\n ).pipe(Effect.provide(childToolkitLayer));\n\n return [planner, gatedPlanner, booking, coordinator, researcher];\n });\n\n// ---------------------------------------------------------------------------\n// The committed golden normalized-evidence fixture (D-P6-6)\n// ---------------------------------------------------------------------------\n\n/**\n * The committed cross-platform normalized canonical evidence of ONE uninterrupted Travel\n * Planner planning Submission (the P1/P4 happy path: canonical input, the search Turn, three\n * Tool settlements, the plan Turn, one Settlement). `travel-planner-phase6.test.ts` asserts\n * the DN run equals this value and `travel-planner-dc.test.ts` asserts the DC run equals this\n * value, so the two platforms' canonical outcomes are byte-equivalent transitively — the P6\n * exit gate \"Travel Planner produces equivalent canonical outcomes under DN and DC\".\n *\n * Regenerate ONLY when the Travel Planner scenario itself changes, by printing either suite's\n * normalized value; both suites must then agree on the new golden.\n */\nexport const phase6TravelPlannerGoldenEvidence: Schema.Json = [\n {\n batchId: \"conversation-created:{conversationId}\",\n sequence: 1,\n record: {\n recordId: \"conversation-created:{conversationId}\",\n family: \"conversation\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ConversationCreated\",\n agentId: \"travel-planner-phase-4\",\n definitions: {\n agent: \"{digest}\",\n model: \"{digest}\",\n tools: \"{digest}\",\n },\n },\n },\n },\n {\n batchId: \"submission-input:{submissionId}\",\n sequence: 2,\n record: {\n recordId: \"input:{submissionId}\",\n family: \"conversation\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"UserInputRecorded\",\n submissionId: \"{submissionId}\",\n kind: \"user\",\n runId: \"run:{submissionId}\",\n input: {\n request:\n \"Plan a review-only London trip using the deterministic flight, lodging, and activity searches.\",\n origin: \"SFO\",\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n nights: 4,\n travelers: 2,\n budgetCents: 350000,\n currency: \"USD\",\n },\n },\n },\n },\n {\n batchId: \"turn-response:run:{submissionId}:1\",\n sequence: 3,\n record: {\n recordId: \"model-response:run:{submissionId}:1\",\n family: \"conversation\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ModelResponseRecorded\",\n runId: \"run:{submissionId}\",\n turnId: \"turn:run:{submissionId}:1\",\n turn: 1,\n inputTokens: 128,\n outputTokens: 96,\n messages: {\n content: [\n {\n options: {},\n role: \"system\",\n content:\n 'You are the Effect Agent Travel Planner P1 interpreter fixture.\\nThe user asked: Plan a review-only London trip using the deterministic flight, lodging, and activity searches.\\nCall search_flights, search_lodging, and search_activities exactly once in one Tool batch.\\nThen return only a JSON object of exactly this shape, no prose:\\n{\"itineraries\": [{\"title\": \"<short itinerary name>\", \"route\": \"<origin-destination>\", \"dates\": \"<date range>\", \"flight\": \"<flight description from the Tool result>\", \"lodging\": \"<lodging description from the Tool result>\", \"activities\": [\"<activity>\", \"...\"], \"estimatedTotalCents\": <positive integer total in cents>, \"currency\": \"USD\", \"quoteId\": \"<quoteId from the flight Tool result>\", \"assumptions\": [\"<assumption>\", \"...\"], \"unresolvedConstraints\": [], \"nextAction\": \"review\"}]}\\nUse the Tool results verbatim; activity results may legitimately be an empty array.\\nThis is read-only planning. Require review before any mutation.',\n },\n {\n options: {},\n role: \"user\",\n content:\n '{\"request\":\"Plan a review-only London trip using the deterministic flight, lodging, and activity searches.\",\"origin\":\"SFO\",\"destination\":\"LHR\",\"departOn\":\"2026-09-14\",\"nights\":4,\"travelers\":2,\"budgetCents\":350000,\"currency\":\"USD\"}',\n },\n {\n options: {},\n role: \"assistant\",\n content: [\n {\n options: {},\n type: \"tool-call\",\n id: \"flight-call-1\",\n name: \"search_flights\",\n params: {\n origin: \"SFO\",\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n travelers: 2,\n },\n providerExecuted: false,\n },\n {\n options: {},\n type: \"tool-call\",\n id: \"lodging-call-1\",\n name: \"search_lodging\",\n params: {\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n nights: 4,\n travelers: 2,\n },\n providerExecuted: false,\n },\n {\n options: {},\n type: \"tool-call\",\n id: \"activity-call-1\",\n name: \"search_activities\",\n params: {\n destination: \"LHR\",\n departOn: \"2026-09-14\",\n nights: 4,\n travelers: 2,\n },\n providerExecuted: false,\n },\n ],\n },\n ],\n },\n messagesDigest: \"{digest}\",\n },\n },\n },\n {\n batchId: \"turn-results:run:{submissionId}:1\",\n sequence: 4,\n record: {\n recordId: \"tool-settled:run:{submissionId}:1:flight-call-1\",\n family: \"conversation\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ToolCallSettled\",\n runId: \"run:{submissionId}\",\n toolCallId: \"flight-call-1\",\n toolName: \"search_flights\",\n result: {\n quoteId: \"quote-sfo-lhr-001\",\n flight: \"EA 218 · nonstop · SFO 18:40 → LHR 13:05+1\",\n estimatedCents: 180000,\n currency: \"USD\",\n },\n isFailure: false,\n },\n },\n },\n {\n batchId: \"turn-results:run:{submissionId}:1\",\n sequence: 5,\n record: {\n recordId: \"tool-settled:run:{submissionId}:1:lodging-call-1\",\n family: \"conversation\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ToolCallSettled\",\n runId: \"run:{submissionId}\",\n toolCallId: \"lodging-call-1\",\n toolName: \"search_lodging\",\n result: {\n lodging: \"Bloomsbury House · refundable studio · 4 nights\",\n estimatedCents: 104000,\n currency: \"USD\",\n },\n isFailure: false,\n },\n },\n },\n {\n batchId: \"turn-results:run:{submissionId}:1\",\n sequence: 6,\n record: {\n recordId: \"tool-settled:run:{submissionId}:1:activity-call-1\",\n family: \"conversation\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ToolCallSettled\",\n runId: \"run:{submissionId}\",\n toolCallId: \"activity-call-1\",\n toolName: \"search_activities\",\n result: {\n activities: [\"British Museum timed entry\", \"Thames evening walk\"],\n },\n isFailure: false,\n },\n },\n },\n {\n batchId: \"turn:run:{submissionId}:2\",\n sequence: 7,\n record: {\n recordId: \"model-response:run:{submissionId}:2\",\n family: \"conversation\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ModelResponseRecorded\",\n runId: \"run:{submissionId}\",\n turnId: \"turn:run:{submissionId}:2\",\n turn: 2,\n inputTokens: 128,\n outputTokens: 96,\n messages: {\n content: [\n {\n options: {},\n role: \"assistant\",\n content:\n '{\"itineraries\":[{\"title\":\"Westward light, eastbound overnight\",\"route\":\"San Francisco → London\",\"dates\":\"14–19 September 2026\",\"flight\":\"EA 218 · nonstop · SFO 18:40 → LHR 13:05+1\",\"lodging\":\"Bloomsbury House · refundable studio · 4 nights\",\"activities\":[\"British Museum timed entry\",\"Thames evening walk\"],\"estimatedTotalCents\":284000,\"currency\":\"USD\",\"quoteId\":\"quote-sfo-lhr-001\",\"assumptions\":[\"Two travelers sharing one studio\",\"Quote is read-only availability, not a reservation\"],\"unresolvedConstraints\":[\"Traveler names and accessibility requests are intentionally omitted\"],\"nextAction\":\"review\"}]}',\n },\n ],\n },\n messagesDigest: \"{digest}\",\n },\n },\n },\n {\n batchId: \"submission-settlement:{submissionId}\",\n sequence: 8,\n record: {\n recordId: \"settlement:{submissionId}\",\n family: \"conversation\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"SubmissionSettled\",\n submissionId: \"{submissionId}\",\n settlementId: \"settlement:{submissionId}\",\n receiptId: \"{receiptId}\",\n outcome: \"completed\",\n runId: \"run:{submissionId}\",\n result: {\n itineraries: [\n {\n title: \"Westward light, eastbound overnight\",\n route: \"San Francisco → London\",\n dates: \"14–19 September 2026\",\n flight: \"EA 218 · nonstop · SFO 18:40 → LHR 13:05+1\",\n lodging: \"Bloomsbury House · refundable studio · 4 nights\",\n activities: [\"British Museum timed entry\", \"Thames evening walk\"],\n estimatedTotalCents: 284000,\n currency: \"USD\",\n quoteId: \"quote-sfo-lhr-001\",\n assumptions: [\n \"Two travelers sharing one studio\",\n \"Quote is read-only availability, not a reservation\",\n ],\n unresolvedConstraints: [\n \"Traveler names and accessibility requests are intentionally omitted\",\n ],\n nextAction: \"review\",\n },\n ],\n },\n },\n },\n },\n];\n","import { Schema } from \"effect\";\n\n// ---------------------------------------------------------------------------\n// Phase 7 (P7): the Travel Planner as an INTERNAL agent with two explicit\n// profiles (ROADMAP P7 exit gate: \"Travel Planner ... retains a deterministic\n// offline conformance profile alongside its live integration profiles\").\n//\n// - The OFFLINE profile is the cumulative P1–P6/S1/S2 suite set that already\n// exists: scripted `LanguageModel`, deterministic supplier Layers,\n// controllable time and IDs, no network, no credentials. Nothing in P7\n// weakens it; this module only pins the claim as a Schema value so evidence\n// can cite one committed fact instead of prose.\n// - The LIVE profile is opt-in and test-side: a suite gates itself with\n// `describe.skipIf(...)` on the environment predicate below, so ordinary\n// `bun run test` never makes a network request and never needs a credential.\n// Live profiles bind live MODEL Layers only. No real travel supplier exists\n// to integrate, so the deterministic supplier desk is retained deliberately\n// and `liveSupplierLayers` is pinned `false` — the roadmap's \"selected\n// supplier Layers\" is honestly scoped to live-model-only (P7 plan decision\n// 9), recorded here rather than silently claimed.\n// ---------------------------------------------------------------------------\n\n/**\n * The P7 dual-profile claim, schema-first so the exact scope of \"live\n * integration profiles\" is a committed, decodable value:\n *\n * - `offlineConformanceDeterministic` / `offlineRequiresCredentials`: the\n * cumulative conformance suites stay deterministic and credential-free.\n * - `liveProfileOptIn`: live suites are excluded from ordinary gates by the\n * environment predicate (`phase7LiveProfileEnabled`), never by test-runner\n * configuration that could silently drift.\n * - `liveModelLayers` / `liveSupplierLayers`: live profiles exercise real\n * model Layers over the SAME deterministic supplier desk — no claim of a\n * live supplier integration is made anywhere (decision 9).\n * - `structurallyRedactedTranscripts`: transcript evidence a live profile\n * emits passes through the structural `Redactor` first (SEC-008,\n * testing.md §12: \"live model and supplier profiles are opt-in smoke or\n * release tests, rate-limited and structurally redacted\").\n * - `exactlyOnceExternalEffects`: never claimed at any phase (DUR-003).\n */\nexport class TravelPlannerPhase7Profile extends Schema.Class<TravelPlannerPhase7Profile>(\n \"@effect-agent/testing/travel-planner/TravelPlannerPhase7Profile\",\n)({\n phase: Schema.Literal(\"P7\"),\n offlineConformanceDeterministic: Schema.Literal(true),\n offlineRequiresCredentials: Schema.Literal(false),\n liveProfileOptIn: Schema.Literal(true),\n liveModelLayers: Schema.Literal(true),\n liveSupplierLayers: Schema.Literal(false),\n structurallyRedactedTranscripts: Schema.Literal(true),\n exactlyOnceExternalEffects: Schema.Literal(false),\n}) {}\n\nexport const phase7TravelPlannerProfile = TravelPlannerPhase7Profile.make({\n phase: \"P7\",\n offlineConformanceDeterministic: true,\n offlineRequiresCredentials: false,\n liveProfileOptIn: true,\n liveModelLayers: true,\n liveSupplierLayers: false,\n structurallyRedactedTranscripts: true,\n exactlyOnceExternalEffects: false,\n});\n\n/**\n * The one opt-in switch for EVERY live profile in this repository. `\"1\"` is\n * the only enabling value: an unset, empty, or differently-truthy value keeps\n * the suite skipped, so CI and ordinary developer runs stay offline.\n */\nexport const PHASE7_LIVE_GATE_ENV = \"EFFECT_AGENT_LIVE\";\n\n/** The credential a Travel Planner live-model profile additionally requires. */\nexport const PHASE7_LIVE_CREDENTIAL_ENV = \"OPENAI_API_KEY\";\n\n/** Structural shape of `process.env` without importing Node types here. */\nexport interface Phase7LiveGateEnvironment {\n readonly [name: string]: string | undefined;\n}\n\n/**\n * The test-side live gate (P7 plan §6: no test-side live-gating pattern\n * existed before this — the demo gates at serve time via\n * `Config.redacted(\"OPENAI_API_KEY\")`). Suites use it as\n * `describe.skipIf(!phase7LiveProfileEnabled(process.env))`, which keeps the\n * live block out of ordinary gates while the SAME file's ungated tests keep\n * pinning the profile schema on every run.\n */\nexport const phase7LiveProfileEnabled = (env: Phase7LiveGateEnvironment): boolean =>\n env[PHASE7_LIVE_GATE_ENV] === \"1\" && (env[PHASE7_LIVE_CREDENTIAL_ENV] ?? \"\") !== \"\";\n\n// ---------------------------------------------------------------------------\n// Authoring friction note (WP7 input; real observations from wiring the P7\n// live profile onto the existing Travel Planner):\n//\n// 1. There was no framework-owned place to put a test-side live gate: every\n// earlier profile was either always-deterministic or gated at serve time\n// inside an application. The predicate had to be invented here as a plain\n// exported function because `packages/testing/src` must stay\n// platform-neutral and cannot read `process.env` itself — fine, but the\n// split (fixture exports the predicate, the example test applies it to\n// `process.env`) is a convention a future author has to discover by\n// reading this file rather than a typed seam.\n// 2. Capturing a structurally redacted transcript from a live Run takes\n// manual assembly: collect `RunEvent`s, `Schema.encode` each one, pass the\n// encoded value through `Redactor.redact`. Nothing composes those three\n// steps, and nothing type-level stops a test from logging the RAW event by\n// accident. A `redactedTranscript(events)` helper in capabilities (or an\n// engine stream combinator) would make the safe path the short path.\n// 3. Binding a live model to the existing definition was pleasantly trivial\n// (`Agent.withModel` + the upstream client Layer): no friction to report\n// on the authoring surface itself for plain ephemeral runs.\n// ---------------------------------------------------------------------------\n"],"mappings":";;;;;;;;;;;AAmJA,MAAa,0BAAgE;CAC3E;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;AAYA,MAAa,4BAA4E;CACvF;CAKA;CACA;CACA;AACF;;AAGA,MAAa,4BACX,UACmD;CACnD,MAAM,wBAAQ,IAAI,IAAqC;CACvD,KAAK,MAAM,OAAO,OAChB,IAAI,IAAI,gBAAgB,MAAM,IAAI,IAAI,QAAQ;CAEhD,OAAO,gCAAgC,SAAS,QAAQ,aAAa,CAAC,MAAM,IAAI,QAAQ,CAAC,CAAC,CAAC,KAAK;AAClG;AAMA,MAAM,QAAQ,OAAO,WAAW,MAAM,CAAC,CAAC,IAAI,OAAO,EAAE,CAAC;AACtD,MAAM,UAAU,kBAAkB,KAAK;CAAE,OAAO;CAAO,OAAO;CAAO,OAAO;AAAM,CAAC;AACnF,MAAM,uBAAuB;CAC3B,OAAO,IAAI,OAAO,EAAE;CACpB,OAAO,IAAI,OAAO,EAAE;CACpB,OAAO,IAAI,OAAO,EAAE;AACtB;AACA,MAAM,gBAAgB,kBAAkB,KAAK;CAC3C,OAAO,OAAO,WAAW,MAAM,CAAC,CAAC,qBAAqB,KAAK;CAC3D,OAAO,OAAO,WAAW,MAAM,CAAC,CAAC,qBAAqB,KAAK;CAC3D,OAAO,OAAO,WAAW,MAAM,CAAC,CAAC,qBAAqB,KAAK;AAC7D,CAAC;AACD,MAAM,YAAY,OAAO,WAAW,SAAS,CAAC,CAAC,yBAAyB;AACx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KACP,OAAO;IACT;GACF;EACF;CACF;CACA;EACE,SAAS;EACT,UAAU;EACV,QAAQ;GACN,UAAU;GACV,QAAQ;GACR,eAAe;GACf,WAAW;GACX,cAAc;GACd,SAAS;IACP,MAAM;IACN,cAAc;IACd,MAAM;IACN,OAAO;IACP,OAAO;KACL,SACE;KACF,QAAQ;KACR,aAAa;KACb,UAAU;KACV,QAAQ;KACR,WAAW;KACX,aAAa;KACb,UAAU;IACZ;GACF;EACF;CACF;CACA;EACE,SAAS;EACT,UAAU;EACV,QAAQ;GACN,UAAU;GACV,QAAQ;GACR,eAAe;GACf,WAAW;GACX,cAAc;GACd,SAAS;IACP,MAAM;IACN,OAAO;IACP,QAAQ;IACR,MAAM;IACN,aAAa;IACb,cAAc;IACd,UAAU,EACR,SAAS;KACP;MACE,SAAS,CAAC;MACV,MAAM;MACN,SACE;KACJ;KACA;MACE,SAAS,CAAC;MACV,MAAM;MACN,SACE;KACJ;KACA;MACE,SAAS,CAAC;MACV,MAAM;MACN,SAAS;OACP;QACE,SAAS,CAAC;QACV,MAAM;QACN,IAAI;QACJ,MAAM;QACN,QAAQ;SACN,QAAQ;SACR,aAAa;SACb,UAAU;SACV,WAAW;QACb;QACA,kBAAkB;OACpB;OACA;QACE,SAAS,CAAC;QACV,MAAM;QACN,IAAI;QACJ,MAAM;QACN,QAAQ;SACN,aAAa;SACb,UAAU;SACV,QAAQ;SACR,WAAW;QACb;QACA,kBAAkB;OACpB;OACA;QACE,SAAS,CAAC;QACV,MAAM;QACN,IAAI;QACJ,MAAM;QACN,QAAQ;SACN,aAAa;SACb,UAAU;SACV,QAAQ;SACR,WAAW;QACb;QACA,kBAAkB;OACpB;MACF;KACF;IACF,EACF;IACA,gBAAgB;GAClB;EACF;CACF;CACA;EACE,SAAS;EACT,UAAU;EACV,QAAQ;GACN,UAAU;GACV,QAAQ;GACR,eAAe;GACf,WAAW;GACX,cAAc;GACd,SAAS;IACP,MAAM;IACN,OAAO;IACP,YAAY;IACZ,UAAU;IACV,QAAQ;KACN,SAAS;KACT,QAAQ;KACR,gBAAgB;KAChB,UAAU;IACZ;IACA,WAAW;GACb;EACF;CACF;CACA;EACE,SAAS;EACT,UAAU;EACV,QAAQ;GACN,UAAU;GACV,QAAQ;GACR,eAAe;GACf,WAAW;GACX,cAAc;GACd,SAAS;IACP,MAAM;IACN,OAAO;IACP,YAAY;IACZ,UAAU;IACV,QAAQ;KACN,SAAS;KACT,gBAAgB;KAChB,UAAU;IACZ;IACA,WAAW;GACb;EACF;CACF;CACA;EACE,SAAS;EACT,UAAU;EACV,QAAQ;GACN,UAAU;GACV,QAAQ;GACR,eAAe;GACf,WAAW;GACX,cAAc;GACd,SAAS;IACP,MAAM;IACN,OAAO;IACP,YAAY;IACZ,UAAU;IACV,QAAQ,EACN,YAAY,CAAC,8BAA8B,qBAAqB,EAClE;IACA,WAAW;GACb;EACF;CACF;CACA;EACE,SAAS;EACT,UAAU;EACV,QAAQ;GACN,UAAU;GACV,QAAQ;GACR,eAAe;GACf,WAAW;GACX,cAAc;GACd,SAAS;IACP,MAAM;IACN,OAAO;IACP,QAAQ;IACR,MAAM;IACN,aAAa;IACb,cAAc;IACd,UAAU,EACR,SAAS,CACP;KACE,SAAS,CAAC;KACV,MAAM;KACN,SACE;IACJ,CACF,EACF;IACA,gBAAgB;GAClB;EACF;CACF;CACA;EACE,SAAS;EACT,UAAU;EACV,QAAQ;GACN,UAAU;GACV,QAAQ;GACR,eAAe;GACf,WAAW;GACX,cAAc;GACd,SAAS;IACP,MAAM;IACN,cAAc;IACd,cAAc;IACd,WAAW;IACX,SAAS;IACT,OAAO;IACP,QAAQ,EACN,aAAa,CACX;KACE,OAAO;KACP,OAAO;KACP,OAAO;KACP,QAAQ;KACR,SAAS;KACT,YAAY,CAAC,8BAA8B,qBAAqB;KAChE,qBAAqB;KACrB,UAAU;KACV,SAAS;KACT,aAAa,CACX,oCACA,oDACF;KACA,uBAAuB,CACrB,qEACF;KACA,YAAY;IACd,CACF,EACF;GAC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