@effect-agent/testing 0.1.0-beta.63 → 0.1.0-beta.65

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.
@@ -71,8 +71,8 @@ interface CertifyDurableAdaptersOptions<LedgerE = never, StoreE = never> {
71
71
  declare const CERTIFICATION_SCENARIOS: ReadonlyArray<CertificationScenario>;
72
72
  /**
73
73
  * Coordinator failpoint locations that none of the six scenario shapes can reach, recorded
74
- * honestly instead of silently claimed: all three sit on operator/abort paths the shapes do
75
- * not take. They are pinned in-process by the P5/S2 suites
74
+ * honestly instead of silently claimed. These require operator, compaction, reservation, or
75
+ * background-worker paths the shapes do not take. They are pinned in-process by the P5/S2 suites
76
76
  * (`packages/testing/test/durable-tools.test.ts` "resolveUnknown is idempotent across the
77
77
  * intent failpoint", `durable-runtime.test.ts` abort rows,
78
78
  * `durable-subagents.test.ts` abort propagation) and by the process-kill/eviction crash
@@ -34,8 +34,8 @@ const CERTIFICATION_SCENARIOS = [
34
34
  ];
35
35
  /**
36
36
  * Coordinator failpoint locations that none of the six scenario shapes can reach, recorded
37
- * honestly instead of silently claimed: all three sit on operator/abort paths the shapes do
38
- * not take. They are pinned in-process by the P5/S2 suites
37
+ * honestly instead of silently claimed. These require operator, compaction, reservation, or
38
+ * background-worker paths the shapes do not take. They are pinned in-process by the P5/S2 suites
39
39
  * (`packages/testing/test/durable-tools.test.ts` "resolveUnknown is idempotent across the
40
40
  * intent failpoint", `durable-runtime.test.ts` abort rows,
41
41
  * `durable-subagents.test.ts` abort propagation) and by the process-kill/eviction crash
@@ -43,6 +43,8 @@ const CERTIFICATION_SCENARIOS = [
43
43
  * protocol change that silently stops exercising a location fails the certification.
44
44
  */
45
45
  const TIER2_UNREACHED_LOCATIONS = [
46
+ "checkpoint:before-save",
47
+ "checkpoint:after-save",
46
48
  "abort:after-intent",
47
49
  "compaction:before-canonical-append",
48
50
  "compaction:after-canonical-append",
@@ -1 +1 @@
1
- {"version":3,"file":"Certification.mjs","names":[],"sources":["../src/Certification.ts"],"sourcesContent":["import * as Subagent from \"@effect-agent/capabilities/Subagent\";\nimport { SubagentPolicy, SubagentRuntime } from \"@effect-agent/capabilities/Subagent\";\nimport { SubagentReservationsMemoryLive } from \"@effect-agent/capabilities/SubagentReservations\";\nimport * as Agent from \"@effect-agent/core/Agent\";\nimport { AgentPolicy } from \"@effect-agent/core/AgentPolicy\";\nimport {\n ThreadId,\n RunId,\n ToolCallId,\n TurnId,\n type AgentId,\n type SubmissionId,\n} from \"@effect-agent/core/Identifiers\";\nimport { IdGenerator } from \"@effect-agent/core/IdGenerator\";\nimport { DurableStep, DurableStepError } from \"@effect-agent/engine/DurableStep\";\nimport { RunToolAuthorization } from \"@effect-agent/engine/RunOptions\";\nimport { DurableWorkerBinding, type ResolvedBinding } from \"@effect-agent/thread/AgentRegistration\";\nimport {\n DurableAgentRuntime,\n DurableRuntimeConfig,\n type DurableSubmitFailure,\n type DurableSubmitOptions,\n type Receipt,\n} from \"@effect-agent/thread/DurableAgentRuntime\";\nimport {\n DurableRuntimeFailpointError,\n DurableRuntimeFailpointLocation,\n} from \"@effect-agent/thread/DurableFailpoint\";\nimport {\n DefinitionDigests,\n DeploymentId,\n Digest,\n ProducerId,\n type BatchId,\n} from \"@effect-agent/thread/Records\";\nimport { childThreadIdFor } from \"@effect-agent/thread/RunJournal\";\nimport {\n ApprovalDecisionCommand,\n IdempotencyKey,\n Principal,\n ResolutionSafeToRetry,\n SubmissionLedger,\n SubmissionLookupById,\n UnknownResolutionCommand,\n DEFAULT_OWNERSHIP_LEASE_DURATION,\n type SubmissionSnapshot,\n} from \"@effect-agent/thread/SubmissionLedger\";\nimport {\n type CertificationCaseResult,\n CertificationReport,\n CertificationSweepResult,\n CertificationTierThreeReport,\n CertifiedAdapterIdentity,\n certifyPorts,\n type CertificationScenario,\n} from \"@effect-agent/thread/testing/Certification\";\nimport { DurableRuntimeFailpointTestControl } from \"@effect-agent/thread/testing/DurableFailpointTestControl\";\nimport { verifyThreadInvariants } from \"@effect-agent/thread/ThreadInvariants\";\nimport {\n ThreadExportRequest,\n ThreadStore,\n LoadCheckpointRequest,\n} from \"@effect-agent/thread/ThreadStore\";\nimport { ToolReconciler } from \"@effect-agent/thread/ToolReconciler\";\nimport { WakeScheduler } from \"@effect-agent/thread/WakeScheduler\";\nimport type { Crypto } from \"effect\";\nimport {\n Cause,\n Clock,\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 `verifyThreadInvariants` 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 threadStore: Layer.Layer<ThreadStore, 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:before-canonical-append\",\n \"compaction:after-canonical-append\",\n // These shapes use neither programmatic Tools nor grace finalization. Their reservations\n // are exercised before/after append in the public durable-runtime regression suite.\n \"policy:before-reservation-append\",\n \"policy:after-reservation-append\",\n \"resolve:after-intent\",\n \"subagent:after-child-abort-intent\",\n // Background workers use retained delivery, source capacity, and child-origin paths absent\n // from these six attached/ordinary scenarios. The before/after creation and completion\n // boundaries are exercised by packages/thread/test/worker-host.test.ts.\n \"worker:before-source-append\",\n \"worker:after-source-append\",\n \"worker:before-origin-append\",\n \"worker:after-origin-append\",\n \"worker:before-completion-append\",\n \"worker:after-completion-append\",\n // Root attached declarations keep their independent pool; nested shared subtree mutations\n // are covered by the same focused worker-host failpoint suite.\n \"worker:before-subtree-append\",\n \"worker:after-subtree-append\",\n // Automatic report decisions and retained delivery insertion have dedicated worker crash tests.\n \"worker:before-report-append\",\n \"worker:after-report-append\",\n \"worker:before-report-delivery\",\n \"worker:after-report-delivery\",\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\n for (const row of tier2) {\n if (row.failpointFired) fired.add(row.location);\n }\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 });\n\nconst CHILD_DIGEST_STRINGS = {\n agent: \"b\".repeat(64),\n model: \"c\".repeat(64),\n tools: \"d\".repeat(64),\n} as const;\n\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});\n\nconst PRINCIPAL = Schema.decodeSync(Principal)(\"principal-certification\");\nconst decodeThreadId = Schema.decodeSync(ThreadId);\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\n const parts =\n toolParts === undefined || hasToolResult ? finalParts(finalText) : toolParts;\n\n return Stream.fromIterable(parts);\n },\n }),\n ),\n );\n\n// Tier-2 intentionally advances virtual time past a 30-second ownership lease on every\n// re-drive round. Keep its business-policy duration above the full eight-round sweep so this\n// fixture certifies crash convergence rather than accidentally relying on a fresh duration\n// allowance per replacement Attempt. RUN-030 owns the dedicated duration-expiry coverage.\nconst CERTIFICATION_MAX_DURATION = \"10 minutes\" as const;\n\nconst policy = AgentPolicy.make({\n maxTurns: 4,\n maxToolCalls: 4,\n maxDuration: CERTIFICATION_MAX_DURATION,\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.make(\"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});\n\nconst bookToolkit = Toolkit.make(Book);\n\nconst uncertainDefinition = Agent.make(\"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});\n\nconst itineraryToolkit = Toolkit.make(Itinerary);\n\nconst stepsDefinition = Agent.make(\"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});\n\nconst approvalToolkit = Toolkit.make(BookApproval);\n\nconst approvalDefinition = Agent.make(\"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.make(\"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: CERTIFICATION_MAX_DURATION,\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: CERTIFICATION_MAX_DURATION,\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.make(\"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: CERTIFICATION_MAX_DURATION,\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\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\n return {\n nextThreadId: next(decodeThreadId, \"certify-fixture-thread\"),\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 bindings: ReadonlyArray<ResolvedBinding>;\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<ThreadId>;\n}\n\nconst submitOptionsFor = (slug: string, threadId: ThreadId): DurableSubmitOptions => ({\n threadId,\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 threadId = decodeThreadId(`certify-${slug}`);\n\n const submit = Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n\n const receipt = yield* runtime.submit(\n { definition: { id: definition.id, input: definition.input } },\n { question: `certify ${slug}` },\n submitOptionsFor(slug, threadId),\n );\n\n return [receipt];\n });\n\n return {\n bindings: [resolved],\n submit,\n lanes: () => [threadId],\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\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS);\n\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\n const toolLayer = bookToolkit.toLayer({\n book: ({ ref }) => Effect.succeed({ confirmation: `confirmed-${ref}` }),\n });\n\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(\n Effect.provide(toolLayer),\n );\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\n const toolLayer = itineraryToolkit.toLayer({\n itinerary: ({ ref }) =>\n Effect.gen(function* () {\n const step = yield* DurableStep;\n\n const flight = yield* step.do(\n \"reserve-flight\",\n Schema.String,\n Effect.succeed(`flight-${ref}`),\n );\n\n const lodging = yield* step.do(\n \"reserve-lodging\",\n Schema.String,\n Effect.succeed(`lodging-${ref}`),\n );\n\n return { state: `${flight}+${lodging}` };\n }),\n });\n\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(\n Effect.provide(toolLayer),\n );\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\n const toolLayer = approvalToolkit.toLayer({\n book: ({ ref }) => Effect.succeed({ confirmation: `confirmed-${ref}` }),\n });\n\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(\n Effect.provide(toolLayer),\n );\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\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS);\n const threadId = decodeThreadId(`certify-${slug}`);\n\n const submitOne = Effect.fn(\"Certification.submitOne\")(function* (\n key: string,\n question: string,\n ) {\n const runtime = yield* DurableAgentRuntime;\n\n return yield* runtime.submit(\n { definition: { id: plainDefinition.id, input: plainDefinition.input } },\n { question },\n {\n threadId,\n principal: PRINCIPAL,\n idempotencyKey: decodeIdempotencyKey(key),\n definitions: DIGESTS,\n },\n );\n });\n\n const cell: CertificationCell = {\n bindings: [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\n return [host, queued];\n }),\n lanes: () => [threadId],\n };\n\n return cell;\n }\n case \"delegation\": {\n const childBinding = Agent.withModel(\n childDefinition,\n promptShapeModel(\"certify-child\", '{\"answer\":\"child-answer\"}'),\n );\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\n const delegationLayer = SubagentRuntime.layer(researchDelegation, childBinding, {\n mapChildFailure,\n durable: { targetDigests: CHILD_DIGEST_STRINGS },\n }).pipe(Layer.provide(delegationSupport));\n\n const lookupLayer = Toolkit.make(Lookup).toLayer({\n lookup: ({ key }) => Effect.succeed({ value: `found-${key}` }),\n });\n\n const parentResolved = yield* DurableWorkerBinding.make(parentBinding, DIGESTS).pipe(\n Effect.provide(Layer.mergeAll(delegationLayer, lookupLayer)),\n );\n\n const childResolved = yield* DurableWorkerBinding.make(childBinding, CHILD_DIGESTS);\n const threadId = decodeThreadId(`certify-${slug}`);\n\n const cell: CertificationCell = {\n bindings: [parentResolved, childResolved],\n submit: Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n\n const receipt = yield* runtime.submit(\n { definition: { id: coordinatorDefinition.id, input: coordinatorDefinition.input } },\n { mission: \"plan\" },\n submitOptionsFor(slug, threadId),\n );\n\n return [receipt];\n }),\n lanes: (receipts) => {\n const parent = receipts.at(0);\n\n return parent === undefined\n ? [threadId]\n : [threadId, childThreadIdFor(parent.submissionId, DELEGATE_CALL)];\n },\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: ThreadId,\n batchProducers: ReadonlyMap<BatchId, ProducerId>,\n) {\n const store = yield* ThreadStore;\n const ledger = yield* SubmissionLedger;\n const exported = yield* store.export(ThreadExportRequest.make({ threadId: lane }));\n const rows = new Map<SubmissionId, SubmissionSnapshot>();\n const nonterminal = yield* Stream.runCollect(ledger.scanNonterminal);\n\n for (const submission of nonterminal) {\n if (submission.threadId === lane) rows.set(submission.submissionId, submission);\n }\n const named = new Set<SubmissionId>();\n\n for (const envelope of exported.records) {\n const payload = envelope.record.payload;\n\n if (\n payload._tag === \"UserInputRecorded\" ||\n payload._tag === \"SubmissionSettled\" ||\n payload._tag === \"AbortRequested\"\n ) {\n if (payload.submissionId !== undefined) 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\n if (Option.isSome(found) && found.value.threadId === lane) {\n rows.set(submissionId, found.value);\n }\n }\n\n const checkpoint =\n store.checkpoints === undefined\n ? Option.none()\n : yield* store.checkpoints.load(LoadCheckpointRequest.make({ threadId: lane }));\n\n return yield* verifyThreadInvariants({\n export: exported,\n submissions: [...rows.values()],\n batchProducers,\n checkpoint: Option.getOrUndefined(checkpoint),\n checkpointsSupported: store.checkpoints !== undefined,\n requireAllSettled: true,\n });\n});\n\nconst failureTagOf = <E>(cause: Cause.Cause<E>): string => {\n const failure = Cause.findErrorOption(cause);\n\n if (Option.isSome(failure)) {\n const error: unknown = failure.value;\n\n if (typeof error === \"object\" && error !== null && \"_tag\" in error) {\n return String(error._tag);\n }\n\n return String(error).slice(0, 256);\n }\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 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 const runtime = yield* DurableAgentRuntime.pipe(\n Effect.provide(\n DurableAgentRuntime.layerWithBindings(cell.bindings).pipe(\n Layer.provide(RunToolAuthorization.allowAll),\n ),\n ),\n );\n\n const submit = cell.submit.pipe(Effect.provideService(DurableAgentRuntime, runtime));\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\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(submit);\n\n if (Exit.isSuccess(firstSubmit)) {\n receipts = firstSubmit.value;\n } else {\n const secondSubmit = yield* Effect.exit(submit);\n\n if (Exit.isFailure(secondSubmit)) {\n yield* control.clear;\n\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: ThreadId) => runtime.processThreadResolved(lane);\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\n if (Option.isNone(snapshot) || snapshot.value.state !== \"settled\") return false;\n }\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 `explainThread`.\n let converged = false;\n\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.explainThread(lane));\n\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\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\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\n for (const lane of lanes) {\n const verdict = yield* Effect.exit(verifyLane(lane, batchProducers));\n\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\n return CertificationTierThreeReport.make({\n status: cases.length === 0 ? \"not-exercised\" : \"exercised\",\n evidence: options.tierThreeEvidence ?? [],\n cases,\n ...(cases.length === 0\n ? { detail: \"the supplied crash lever executed no real-loss cases\" }\n : {}),\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\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\n // Interpose the candidate store with an append-time capture of each batch's producer\n // identity — the one value the ThreadStore 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(ThreadStore)(\n Effect.gen(function* () {\n const inner = yield* ThreadStore;\n\n return ThreadStore.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.threadStore));\n\n // RUN-036: certification uses the default-none Tool failure observer. Trusted application\n // reporting adds no durable transition and is verified separately from adapter certification.\n const environment = Layer.mergeAll(\n options.submissionLedger,\n capturingStore,\n options.wakeScheduler ?? WakeScheduler.layerNoop,\n DurableRuntimeFailpointTestControl.layer,\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\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\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\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@2\",\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 fullyCertified:\n ok &&\n capabilities.durability !== \"non-durable\" &&\n tier3.status === \"exercised\" &&\n tier3.cases.length > 0 &&\n tier3.cases.every((result) => result.suite === \"real-loss\"),\n });\n });\n\n return program.pipe(Effect.provide(environment));\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAwJA,MAAa,0BAAgE;CAC3E;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;AAYA,MAAa,4BAA4E;CACvF;CAKA;CACA;CAGA;CACA;CACA;CACA;CAIA;CACA;CACA;CACA;CACA;CACA;CAGA;CACA;CAEA;CACA;CACA;CACA;AACF;;AAGA,MAAa,4BACX,UACmD;CACnD,MAAM,wBAAQ,IAAI,IAAqC;CAEvD,KAAK,MAAM,OAAO,OAChB,IAAI,IAAI,gBAAgB,MAAM,IAAI,IAAI,QAAQ;CAGhD,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;AAEnF,MAAM,uBAAuB;CAC3B,OAAO,IAAI,OAAO,EAAE;CACpB,OAAO,IAAI,OAAO,EAAE;CACpB,OAAO,IAAI,OAAO,EAAE;AACtB;AAEA,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;AAED,MAAM,YAAY,OAAO,WAAW,SAAS,CAAC,CAAC,yBAAyB;AACxE,MAAM,iBAAiB,OAAO,WAAW,QAAQ;AACjD,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AO;EAE3B,MAAM,KACJ,MAAM,OAAO,WAAW,OAAO,WAAW,QAAQ,KAClD,MAAM,OAAO,WAAW,OAAO,WAAW,QAAQ,KAClD,MAAM,MAAM,OAAO,WAAW,OAAO,WAAW,QAAQ;EAE1D,OAAO,oBAAoB,KAAK;GAC9B,QAAQ;GACR,SAAS,yBAAyB,KAAK;IACrC,MAAM,QAAQ,QAAQ;IACtB,GAAI,QAAQ,QAAQ,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,QAAQ,QAAQ,QAAQ;IACpF,YAAY,aAAa;GAC3B,CAAC;GACD;GACA;GACA;GACA;GACA;GACA,gBACE,MACA,aAAa,eAAe,iBAC5B,MAAM,WAAW,eACjB,MAAM,MAAM,SAAS,KACrB,MAAM,MAAM,OAAO,WAAW,OAAO,UAAU,WAAW;EAC9D,CAAC;CACH,CAEa,CAAC,CAAC,KAAK,OAAO,QAAQ,WAAW,CAAC;AACjD"}
1
+ {"version":3,"file":"Certification.mjs","names":[],"sources":["../src/Certification.ts"],"sourcesContent":["import * as Subagent from \"@effect-agent/capabilities/Subagent\";\nimport { SubagentPolicy, SubagentRuntime } from \"@effect-agent/capabilities/Subagent\";\nimport { SubagentReservationsMemoryLive } from \"@effect-agent/capabilities/SubagentReservations\";\nimport * as Agent from \"@effect-agent/core/Agent\";\nimport { AgentPolicy } from \"@effect-agent/core/AgentPolicy\";\nimport {\n ThreadId,\n RunId,\n ToolCallId,\n TurnId,\n type AgentId,\n type SubmissionId,\n} from \"@effect-agent/core/Identifiers\";\nimport { IdGenerator } from \"@effect-agent/core/IdGenerator\";\nimport { DurableStep, DurableStepError } from \"@effect-agent/engine/DurableStep\";\nimport { RunToolAuthorization } from \"@effect-agent/engine/RunOptions\";\nimport { DurableWorkerBinding, type ResolvedBinding } from \"@effect-agent/thread/AgentRegistration\";\nimport {\n DurableAgentRuntime,\n DurableRuntimeConfig,\n type DurableSubmitFailure,\n type DurableSubmitOptions,\n type Receipt,\n} from \"@effect-agent/thread/DurableAgentRuntime\";\nimport {\n DurableRuntimeFailpointError,\n DurableRuntimeFailpointLocation,\n} from \"@effect-agent/thread/DurableFailpoint\";\nimport {\n DefinitionDigests,\n DeploymentId,\n Digest,\n ProducerId,\n type BatchId,\n} from \"@effect-agent/thread/Records\";\nimport { childThreadIdFor } from \"@effect-agent/thread/RunJournal\";\nimport {\n ApprovalDecisionCommand,\n IdempotencyKey,\n Principal,\n ResolutionSafeToRetry,\n SubmissionLedger,\n SubmissionLookupById,\n UnknownResolutionCommand,\n DEFAULT_OWNERSHIP_LEASE_DURATION,\n type SubmissionSnapshot,\n} from \"@effect-agent/thread/SubmissionLedger\";\nimport {\n type CertificationCaseResult,\n CertificationReport,\n CertificationSweepResult,\n CertificationTierThreeReport,\n CertifiedAdapterIdentity,\n certifyPorts,\n type CertificationScenario,\n} from \"@effect-agent/thread/testing/Certification\";\nimport { DurableRuntimeFailpointTestControl } from \"@effect-agent/thread/testing/DurableFailpointTestControl\";\nimport { verifyThreadInvariants } from \"@effect-agent/thread/ThreadInvariants\";\nimport {\n ThreadExportRequest,\n ThreadStore,\n LoadCheckpointRequest,\n} from \"@effect-agent/thread/ThreadStore\";\nimport { ToolReconciler } from \"@effect-agent/thread/ToolReconciler\";\nimport { WakeScheduler } from \"@effect-agent/thread/WakeScheduler\";\nimport type { Crypto } from \"effect\";\nimport {\n Cause,\n Clock,\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 `verifyThreadInvariants` 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 threadStore: Layer.Layer<ThreadStore, 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. These require operator, compaction, reservation, or\n * background-worker paths the shapes do 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 // Tier 2 has no native compaction; dedicated checkpoint process-loss tests cover these.\n \"checkpoint:before-save\",\n \"checkpoint:after-save\",\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:before-canonical-append\",\n \"compaction:after-canonical-append\",\n // These shapes use neither programmatic Tools nor grace finalization. Their reservations\n // are exercised before/after append in the public durable-runtime regression suite.\n \"policy:before-reservation-append\",\n \"policy:after-reservation-append\",\n \"resolve:after-intent\",\n \"subagent:after-child-abort-intent\",\n // Background workers use retained delivery, source capacity, and child-origin paths absent\n // from these six attached/ordinary scenarios. The before/after creation and completion\n // boundaries are exercised by packages/thread/test/worker-host.test.ts.\n \"worker:before-source-append\",\n \"worker:after-source-append\",\n \"worker:before-origin-append\",\n \"worker:after-origin-append\",\n \"worker:before-completion-append\",\n \"worker:after-completion-append\",\n // Root attached declarations keep their independent pool; nested shared subtree mutations\n // are covered by the same focused worker-host failpoint suite.\n \"worker:before-subtree-append\",\n \"worker:after-subtree-append\",\n // Automatic report decisions and retained delivery insertion have dedicated worker crash tests.\n \"worker:before-report-append\",\n \"worker:after-report-append\",\n \"worker:before-report-delivery\",\n \"worker:after-report-delivery\",\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\n for (const row of tier2) {\n if (row.failpointFired) fired.add(row.location);\n }\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 });\n\nconst CHILD_DIGEST_STRINGS = {\n agent: \"b\".repeat(64),\n model: \"c\".repeat(64),\n tools: \"d\".repeat(64),\n} as const;\n\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});\n\nconst PRINCIPAL = Schema.decodeSync(Principal)(\"principal-certification\");\nconst decodeThreadId = Schema.decodeSync(ThreadId);\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\n const parts =\n toolParts === undefined || hasToolResult ? finalParts(finalText) : toolParts;\n\n return Stream.fromIterable(parts);\n },\n }),\n ),\n );\n\n// Tier-2 intentionally advances virtual time past a 30-second ownership lease on every\n// re-drive round. Keep its business-policy duration above the full eight-round sweep so this\n// fixture certifies crash convergence rather than accidentally relying on a fresh duration\n// allowance per replacement Attempt. RUN-030 owns the dedicated duration-expiry coverage.\nconst CERTIFICATION_MAX_DURATION = \"10 minutes\" as const;\n\nconst policy = AgentPolicy.make({\n maxTurns: 4,\n maxToolCalls: 4,\n maxDuration: CERTIFICATION_MAX_DURATION,\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.make(\"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});\n\nconst bookToolkit = Toolkit.make(Book);\n\nconst uncertainDefinition = Agent.make(\"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});\n\nconst itineraryToolkit = Toolkit.make(Itinerary);\n\nconst stepsDefinition = Agent.make(\"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});\n\nconst approvalToolkit = Toolkit.make(BookApproval);\n\nconst approvalDefinition = Agent.make(\"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.make(\"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: CERTIFICATION_MAX_DURATION,\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: CERTIFICATION_MAX_DURATION,\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.make(\"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: CERTIFICATION_MAX_DURATION,\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\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\n return {\n nextThreadId: next(decodeThreadId, \"certify-fixture-thread\"),\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 bindings: ReadonlyArray<ResolvedBinding>;\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<ThreadId>;\n}\n\nconst submitOptionsFor = (slug: string, threadId: ThreadId): DurableSubmitOptions => ({\n threadId,\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 threadId = decodeThreadId(`certify-${slug}`);\n\n const submit = Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n\n const receipt = yield* runtime.submit(\n { definition: { id: definition.id, input: definition.input } },\n { question: `certify ${slug}` },\n submitOptionsFor(slug, threadId),\n );\n\n return [receipt];\n });\n\n return {\n bindings: [resolved],\n submit,\n lanes: () => [threadId],\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\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS);\n\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\n const toolLayer = bookToolkit.toLayer({\n book: ({ ref }) => Effect.succeed({ confirmation: `confirmed-${ref}` }),\n });\n\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(\n Effect.provide(toolLayer),\n );\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\n const toolLayer = itineraryToolkit.toLayer({\n itinerary: ({ ref }) =>\n Effect.gen(function* () {\n const step = yield* DurableStep;\n\n const flight = yield* step.do(\n \"reserve-flight\",\n Schema.String,\n Effect.succeed(`flight-${ref}`),\n );\n\n const lodging = yield* step.do(\n \"reserve-lodging\",\n Schema.String,\n Effect.succeed(`lodging-${ref}`),\n );\n\n return { state: `${flight}+${lodging}` };\n }),\n });\n\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(\n Effect.provide(toolLayer),\n );\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\n const toolLayer = approvalToolkit.toLayer({\n book: ({ ref }) => Effect.succeed({ confirmation: `confirmed-${ref}` }),\n });\n\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(\n Effect.provide(toolLayer),\n );\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\n const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS);\n const threadId = decodeThreadId(`certify-${slug}`);\n\n const submitOne = Effect.fn(\"Certification.submitOne\")(function* (\n key: string,\n question: string,\n ) {\n const runtime = yield* DurableAgentRuntime;\n\n return yield* runtime.submit(\n { definition: { id: plainDefinition.id, input: plainDefinition.input } },\n { question },\n {\n threadId,\n principal: PRINCIPAL,\n idempotencyKey: decodeIdempotencyKey(key),\n definitions: DIGESTS,\n },\n );\n });\n\n const cell: CertificationCell = {\n bindings: [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\n return [host, queued];\n }),\n lanes: () => [threadId],\n };\n\n return cell;\n }\n case \"delegation\": {\n const childBinding = Agent.withModel(\n childDefinition,\n promptShapeModel(\"certify-child\", '{\"answer\":\"child-answer\"}'),\n );\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\n const delegationLayer = SubagentRuntime.layer(researchDelegation, childBinding, {\n mapChildFailure,\n durable: { targetDigests: CHILD_DIGEST_STRINGS },\n }).pipe(Layer.provide(delegationSupport));\n\n const lookupLayer = Toolkit.make(Lookup).toLayer({\n lookup: ({ key }) => Effect.succeed({ value: `found-${key}` }),\n });\n\n const parentResolved = yield* DurableWorkerBinding.make(parentBinding, DIGESTS).pipe(\n Effect.provide(Layer.mergeAll(delegationLayer, lookupLayer)),\n );\n\n const childResolved = yield* DurableWorkerBinding.make(childBinding, CHILD_DIGESTS);\n const threadId = decodeThreadId(`certify-${slug}`);\n\n const cell: CertificationCell = {\n bindings: [parentResolved, childResolved],\n submit: Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n\n const receipt = yield* runtime.submit(\n { definition: { id: coordinatorDefinition.id, input: coordinatorDefinition.input } },\n { mission: \"plan\" },\n submitOptionsFor(slug, threadId),\n );\n\n return [receipt];\n }),\n lanes: (receipts) => {\n const parent = receipts.at(0);\n\n return parent === undefined\n ? [threadId]\n : [threadId, childThreadIdFor(parent.submissionId, DELEGATE_CALL)];\n },\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: ThreadId,\n batchProducers: ReadonlyMap<BatchId, ProducerId>,\n) {\n const store = yield* ThreadStore;\n const ledger = yield* SubmissionLedger;\n const exported = yield* store.export(ThreadExportRequest.make({ threadId: lane }));\n const rows = new Map<SubmissionId, SubmissionSnapshot>();\n const nonterminal = yield* Stream.runCollect(ledger.scanNonterminal);\n\n for (const submission of nonterminal) {\n if (submission.threadId === lane) rows.set(submission.submissionId, submission);\n }\n const named = new Set<SubmissionId>();\n\n for (const envelope of exported.records) {\n const payload = envelope.record.payload;\n\n if (\n payload._tag === \"UserInputRecorded\" ||\n payload._tag === \"SubmissionSettled\" ||\n payload._tag === \"AbortRequested\"\n ) {\n if (payload.submissionId !== undefined) 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\n if (Option.isSome(found) && found.value.threadId === lane) {\n rows.set(submissionId, found.value);\n }\n }\n\n const checkpoint =\n store.checkpoints === undefined\n ? Option.none()\n : yield* store.checkpoints.load(LoadCheckpointRequest.make({ threadId: lane }));\n\n return yield* verifyThreadInvariants({\n export: exported,\n submissions: [...rows.values()],\n batchProducers,\n checkpoint: Option.getOrUndefined(checkpoint),\n checkpointsSupported: store.checkpoints !== undefined,\n requireAllSettled: true,\n });\n});\n\nconst failureTagOf = <E>(cause: Cause.Cause<E>): string => {\n const failure = Cause.findErrorOption(cause);\n\n if (Option.isSome(failure)) {\n const error: unknown = failure.value;\n\n if (typeof error === \"object\" && error !== null && \"_tag\" in error) {\n return String(error._tag);\n }\n\n return String(error).slice(0, 256);\n }\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 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 const runtime = yield* DurableAgentRuntime.pipe(\n Effect.provide(\n DurableAgentRuntime.layerWithBindings(cell.bindings).pipe(\n Layer.provide(RunToolAuthorization.allowAll),\n ),\n ),\n );\n\n const submit = cell.submit.pipe(Effect.provideService(DurableAgentRuntime, runtime));\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\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(submit);\n\n if (Exit.isSuccess(firstSubmit)) {\n receipts = firstSubmit.value;\n } else {\n const secondSubmit = yield* Effect.exit(submit);\n\n if (Exit.isFailure(secondSubmit)) {\n yield* control.clear;\n\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: ThreadId) => runtime.processThreadResolved(lane);\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\n if (Option.isNone(snapshot) || snapshot.value.state !== \"settled\") return false;\n }\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 `explainThread`.\n let converged = false;\n\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.explainThread(lane));\n\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\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\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\n for (const lane of lanes) {\n const verdict = yield* Effect.exit(verifyLane(lane, batchProducers));\n\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\n return CertificationTierThreeReport.make({\n status: cases.length === 0 ? \"not-exercised\" : \"exercised\",\n evidence: options.tierThreeEvidence ?? [],\n cases,\n ...(cases.length === 0\n ? { detail: \"the supplied crash lever executed no real-loss cases\" }\n : {}),\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\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\n // Interpose the candidate store with an append-time capture of each batch's producer\n // identity — the one value the ThreadStore 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(ThreadStore)(\n Effect.gen(function* () {\n const inner = yield* ThreadStore;\n\n return ThreadStore.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.threadStore));\n\n // RUN-036: certification uses the default-none Tool failure observer. Trusted application\n // reporting adds no durable transition and is verified separately from adapter certification.\n const environment = Layer.mergeAll(\n options.submissionLedger,\n capturingStore,\n options.wakeScheduler ?? WakeScheduler.layerNoop,\n DurableRuntimeFailpointTestControl.layer,\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\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\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\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@2\",\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 fullyCertified:\n ok &&\n capabilities.durability !== \"non-durable\" &&\n tier3.status === \"exercised\" &&\n tier3.cases.length > 0 &&\n tier3.cases.every((result) => result.suite === \"real-loss\"),\n });\n });\n\n return program.pipe(Effect.provide(environment));\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAwJA,MAAa,0BAAgE;CAC3E;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;AAYA,MAAa,4BAA4E;CAEvF;CACA;CACA;CAKA;CACA;CAGA;CACA;CACA;CACA;CAIA;CACA;CACA;CACA;CACA;CACA;CAGA;CACA;CAEA;CACA;CACA;CACA;AACF;;AAGA,MAAa,4BACX,UACmD;CACnD,MAAM,wBAAQ,IAAI,IAAqC;CAEvD,KAAK,MAAM,OAAO,OAChB,IAAI,IAAI,gBAAgB,MAAM,IAAI,IAA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CAEa,CAAC,CAAC,KAAK,OAAO,QAAQ,WAAW,CAAC;AACjD"}
package/dist/Chaos.d.mts CHANGED
@@ -42,7 +42,7 @@ declare const ChaosPlan_base: Schema.Class<ChaosPlan, Schema.Struct<{
42
42
  readonly lanes: Schema.Int;
43
43
  readonly submissions: Schema.NonEmptyArray<typeof ChaosSubmissionSpec>;
44
44
  /** Coordinator failpoint arms, consumed one per round (each fails every hit that round). */
45
- readonly failpointArms: Schema.$Array<Schema.Literals<readonly ["submit:after-admit", "submit:after-materialize", "claim:after-claim", "input:after-canonical-append", "run:before-start-append", "run:after-start-append", "turn:after-canonical-append", "turn:after-response-append", "turn:after-results-append", "compaction:before-canonical-append", "compaction:after-canonical-append", "tools:after-prepared-append", "tools:before-prepared-append", "policy:before-reservation-append", "policy:after-reservation-append", "step:after-step-append", "approval:after-request-append", "approval:after-suspend", "join:after-claim", "join:after-canonical-append", "resolve:after-intent", "terminalize:after-reserve", "terminalize:after-canonical-append", "abort:after-intent", "subagent:after-reserve", "subagent:after-request-append", "subagent:after-admit", "subagent:after-child-ready", "subagent:after-start-append", "subagent:after-sibling-settle", "subagent:after-suspend", "subagent:after-child-abort-intent", "subagent:after-join-append", "subagent:after-release-pending", "subagent:after-release", "worker:before-source-append", "worker:after-source-append", "worker:before-origin-append", "worker:after-origin-append", "worker:before-completion-append", "worker:after-completion-append", "worker:before-subtree-append", "worker:after-subtree-append", "worker:before-report-append", "worker:after-report-append", "worker:before-report-delivery", "worker:after-report-delivery"]>>;
45
+ readonly failpointArms: Schema.$Array<Schema.Literals<readonly ["submit:after-admit", "submit:after-materialize", "claim:after-claim", "input:after-canonical-append", "run:before-start-append", "run:after-start-append", "turn:after-canonical-append", "turn:after-response-append", "turn:after-results-append", "compaction:before-canonical-append", "compaction:after-canonical-append", "checkpoint:before-save", "checkpoint:after-save", "tools:after-prepared-append", "tools:before-prepared-append", "policy:before-reservation-append", "policy:after-reservation-append", "step:after-step-append", "approval:after-request-append", "approval:after-suspend", "join:after-claim", "join:after-canonical-append", "resolve:after-intent", "terminalize:after-reserve", "terminalize:after-canonical-append", "abort:after-intent", "subagent:after-reserve", "subagent:after-request-append", "subagent:after-admit", "subagent:after-child-ready", "subagent:after-start-append", "subagent:after-sibling-settle", "subagent:after-suspend", "subagent:after-child-abort-intent", "subagent:after-join-append", "subagent:after-release-pending", "subagent:after-release", "worker:before-source-append", "worker:after-source-append", "worker:before-origin-append", "worker:after-origin-append", "worker:before-completion-append", "worker:after-completion-append", "worker:before-subtree-append", "worker:after-subtree-append", "worker:before-report-append", "worker:after-report-append", "worker:before-report-delivery", "worker:after-report-delivery"]>>;
46
46
  /** Adapter-owned failpoint arms (e.g. SQLite `ledger:*`/`append:*` locations). */
47
47
  readonly adapterArms: Schema.$Array<Schema.String>;
48
48
  /** Flattened submission indices to abort mid-plan (modulo the submission count). */
@@ -240,10 +240,6 @@ const makePhase3TravelPlannerCheckpoint = (projection) => Schema.decodeSync(Thre
240
240
  threadId: projection.threadId,
241
241
  throughSequence: projection.throughSequence,
242
242
  tailDigest: projection.tailDigest,
243
- engineVersion: "phase-3-test-runtime",
244
- agentDefinitionDigest: phase3TravelPlannerDefinitionDigests.agent,
245
- modelDigest: phase3TravelPlannerDefinitionDigests.model,
246
- toolDigest: phase3TravelPlannerDefinitionDigests.tools,
247
243
  state: Schema.encodeSync(ThreadProjection)(projection),
248
244
  createdAt: "2026-09-01T00:00:04.000Z"
249
245
  });
@@ -1 +1 @@
1
- {"version":3,"file":"TravelPlanner.mjs","names":["digest","digest","decodeComparableJson","scriptedUsage","researcherLookupParts","researcherReportParts","digestOf","scriptedUsage","researcherLookupParts","researcherReportParts"],"sources":["../src/fixtures/travel-planner/phase2.ts","../src/fixtures/travel-planner/scenarios.ts","../src/fixtures/travel-planner/phase3.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 * as Agent from \"@effect-agent/core/Agent\";\nimport { AgentPolicy } from \"@effect-agent/core/AgentPolicy\";\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.make(\"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: 4_096,\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 \"../../ScriptedModel.ts\";\nimport { TravelPlan, TripRequest, type TravelPlan as TravelPlanValue } from \"./definition.ts\";\n\nconst usage = { inputTokens: { total: 128 }, outputTokens: { total: 96 } };\n\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\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];\n","import { AgentId, ThreadId, RunId, SubmissionId } from \"@effect-agent/core/Identifiers\";\nimport {\n BatchId,\n CanonicalBatch,\n DefinitionDigests,\n DeploymentId,\n Digest,\n ProducerId,\n RecordEnvelope,\n RecordId,\n} from \"@effect-agent/thread/Records\";\nimport { ThreadProjection } from \"@effect-agent/thread/ThreadProjection\";\nimport { ThreadCheckpoint } from \"@effect-agent/thread/ThreadStore\";\nimport { Effect, Schema } from \"effect\";\n\nimport { TravelPlan, TripRequest } from \"./definition.ts\";\nimport { expectedTravelPlan, phase1Trip } from \"./scenarios.ts\";\n\nexport const phase3TravelPlannerThreadId = Schema.decodeSync(ThreadId)(\"travel-planner-p3-thread\");\n\nexport const phase3TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-p3-producer\",\n);\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: \"thread\",\n schemaVersion: 1,\n createdAt,\n deploymentId,\n payload,\n });\n\n/**\n * The first atomic append establishes the Thread 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: \"ThreadCreated\",\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: ReadonlyArray<typeof CanonicalBatch.Encoded> =\n Schema.encodeSync(Schema.Array(CanonicalBatch))(phase3TravelPlannerBatches);\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: ThreadProjection,\n): Effect.Effect<TravelPlan, TravelPlannerProjectionError> => {\n const output = projection.modelOutputs.at(-1);\n\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\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 = (projection: ThreadProjection): ThreadCheckpoint =>\n Schema.decodeSync(ThreadCheckpoint)({\n schemaVersion: 1,\n threadId: projection.threadId,\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(ThreadProjection)(projection),\n createdAt: \"2026-09-01T00:00:04.000Z\",\n });\n","import * as Agent from \"@effect-agent/core/Agent\";\nimport { AgentPolicy } from \"@effect-agent/core/AgentPolicy\";\nimport { type ThreadId } from \"@effect-agent/core/Identifiers\";\nimport { ToolExecutionClass } from \"@effect-agent/engine/DurableStep\";\nimport { type DurableSubmitOptions, type Receipt } from \"@effect-agent/thread/DurableAgentRuntime\";\nimport {\n CanonicalRecordEnvelope,\n DefinitionDigests,\n DeploymentId,\n Digest,\n ProducerId,\n} from \"@effect-agent/thread/Records\";\nimport { Principal, type IdempotencyKey } from \"@effect-agent/thread/SubmissionLedger\";\nimport { Effect, Layer, Schema } from \"effect\";\nimport { Model, Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport { ScriptedModel, type ScriptedTurnInput } from \"../../ScriptedModel.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\nexport const phase4TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-p4-deployment\",\n);\n\nexport const phase4TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-p4-producer\",\n);\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 threadId: ThreadId,\n idempotencyKey: IdempotencyKey,\n): DurableSubmitOptions => ({\n threadId,\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\");\n\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\");\n\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.make(\"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\n const settled = settlements.at(0);\n\n if (settled === undefined) {\n return yield* TravelPlannerDurableEvidenceError.make({\n message: \"The canonical Thread 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\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 Threads 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\n const comparable = encoded.map((envelope) => ({\n batchId: envelope.batchId,\n sequence: envelope.sequence,\n record: envelope.record,\n }));\n\n const substituted: unknown = JSON.parse(\n JSON.stringify(comparable)\n .replaceAll(receipt.submissionId, \"{submissionId}\")\n .replaceAll(receipt.receiptId, \"{receiptId}\"),\n );\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 * as Agent from \"@effect-agent/core/Agent\";\nimport { AgentPolicy } from \"@effect-agent/core/AgentPolicy\";\nimport { type ThreadId } from \"@effect-agent/core/Identifiers\";\nimport {\n DurableStep,\n DurableStepError,\n ToolExecutionClass,\n} from \"@effect-agent/engine/DurableStep\";\nimport { type DurableSubmitOptions } from \"@effect-agent/thread/DurableAgentRuntime\";\nimport {\n DefinitionDigests,\n DeploymentId,\n Digest,\n PersistedJson,\n ProducerId,\n type CanonicalRecordEnvelope,\n} from \"@effect-agent/thread/Records\";\nimport { Principal, type IdempotencyKey } from \"@effect-agent/thread/SubmissionLedger\";\nimport {\n ReconciliationCompleted,\n ReconciliationSafeToRetry,\n ReconciliationUncertain,\n ToolReconciler,\n ToolReconcilerError,\n} from \"@effect-agent/thread/ToolReconciler\";\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\nexport const phase5TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-p5-deployment\",\n);\n\nexport const phase5TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-p5-producer\",\n);\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 threadId: ThreadId,\n idempotencyKey: IdempotencyKey,\n): DurableSubmitOptions => ({\n threadId,\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);\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}`;\n\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 * (GLOSSARY.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\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\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\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\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\n const flight = yield* bookStep(\n \"reserve-flight\",\n `flight ${request.quoteId} for ${request.travelerRef}`,\n );\n\n const lodging = yield* bookStep(\n \"reserve-lodging\",\n `lodging ${request.destination} for ${request.nights} nights (${request.travelerRef})`,\n );\n\n const confirmation = yield* bookStep(\n \"issue-confirmation\",\n `itinerary confirmation for ${request.travelerRef}`,\n );\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\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\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\n return ReconciliationCompleted.make({ result: confirmation, isFailure: false });\n }\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.make(\"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\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\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\n for (const envelope of records) {\n const payload = envelope.record.payload;\n\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 * as Subagent from \"@effect-agent/capabilities/Subagent\";\nimport { SubagentPolicy, SubagentRuntime } from \"@effect-agent/capabilities/Subagent\";\nimport * as Agent from \"@effect-agent/core/Agent\";\nimport { AgentPolicy } from \"@effect-agent/core/AgentPolicy\";\nimport { type RuntimeBinding } from \"@effect-agent/engine/AgentRuntime\";\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 \"../../ScriptedModel.ts\";\nimport { AirportCode } from \"./definition.ts\";\nimport { CatalogLifecycle } from \"./deterministic-layers.ts\";\n\n// ---------------------------------------------------------------------------\n// Destination Researcher: the S1 specialist child Agent.\n// 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);\n\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.make(\"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\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\n if (facts === undefined) {\n throw new Error(`No deterministic guide entry exists for destination ${destination}`);\n }\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\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\n yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);\n\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: 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`. 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\n yield* gate.awaitDispatch(request.destination);\n\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 Thread.\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.make(\"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 thread.`,\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\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\n const gatesFor = (destination: string): Effect.Effect<ResearcherGates> =>\n Effect.suspend(() => {\n const entry = gates.get(destination);\n\n return entry === undefined\n ? Effect.die(new Error(`No researcher gates exist for destination ${destination}`))\n : Effect.succeed(entry);\n });\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\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\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\n const destination = destinations.find((candidate) =>\n promptJson.includes(candidate),\n );\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\n if (index === 0) {\n yield* Ref.update(prompts, (previous) => [...previous, promptJson]);\n yield* Deferred.succeed(entry.started, undefined);\n\n return Stream.fromIterable(researcherLookupParts(destination));\n }\n yield* Deferred.await(entry.release);\n\n return Stream.fromIterable(researcherReportParts(destination));\n }),\n ),\n });\n }),\n ),\n );\n\n return { controls, model };\n });\n","import {\n delegationAllocationFromPolicy,\n SubagentRuntime,\n} from \"@effect-agent/capabilities/Subagent\";\nimport { SubagentReservationsMemoryLive } from \"@effect-agent/capabilities/SubagentReservations\";\nimport * as Agent from \"@effect-agent/core/Agent\";\nimport { type ThreadId } from \"@effect-agent/core/Identifiers\";\nimport { type RuntimeBinding } from \"@effect-agent/engine/AgentRuntime\";\nimport { DurableWorkerBinding, type ResolvedBinding } from \"@effect-agent/thread/AgentRegistration\";\nimport { type DurableSubmitOptions } from \"@effect-agent/thread/DurableAgentRuntime\";\nimport { DefinitionDigests, DeploymentId, Digest, ProducerId } from \"@effect-agent/thread/Records\";\nimport { Principal, type IdempotencyKey } from \"@effect-agent/thread/SubmissionLedger\";\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 type {\n DestinationBrief,\n DestinationReport,\n DestinationResearcherToolkit,\n} from \"./subagents.ts\";\nimport {\n DestinationFacts,\n DestinationGuide,\n DestinationRecommendation,\n DestinationResearcher,\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/** Registered coordinator and researcher bindings for durable delegation tests. */\nexport const s2TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-s2-deployment\",\n);\n\nexport const s2TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-s2-producer\",\n);\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 host's binding array 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 threadId: ThreadId,\n idempotencyKey: IdempotencyKey,\n): DurableSubmitOptions => ({\n threadId,\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\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\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\n yield* Ref.update(prompts, (previous) => [\n ...previous,\n JSON.stringify(request.prompt.content),\n ]);\n\n return Stream.fromIterable(script(call));\n }),\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 `NodeDurableAgentRuntimeOptions.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 `NodeDurableAgentRuntime` 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\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\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\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\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\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\n return harness;\n });\n","import { SubagentReservationsMemoryLive } from \"@effect-agent/capabilities/SubagentReservations\";\nimport * as Agent from \"@effect-agent/core/Agent\";\nimport { DurableWorkerBinding, type ResolvedBinding } from \"@effect-agent/thread/AgentRegistration\";\nimport { type Receipt } from \"@effect-agent/thread/DurableAgentRuntime\";\nimport {\n DefinitionDigests,\n DeploymentId,\n Digest,\n ProducerId,\n type CanonicalRecordEnvelope,\n} from \"@effect-agent/thread/Records\";\nimport { type ToolReconciler } from \"@effect-agent/thread/ToolReconciler\";\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/** Platform-neutral bindings and canonical evidence shared by Node and Cloudflare tests. */\nexport const phase6TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-p6-deployment\",\n);\n\n/** Producer prefix of the DC host; each Object mints `{prefix}:{threadId}`. */\nexport const phase6TravelPlannerProducerPrefix = \"travel-planner-p6-producer\";\n\n/** The full producer identity one DC Thread Object mints for itself. */\nexport const phase6TravelPlannerProducerId = (threadId: string): ProducerId =>\n Schema.decodeSync(ProducerId)(`${phase6TravelPlannerProducerPrefix}:${threadId}`);\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 Thread lane the evidence came from. */\n readonly threadId: 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}:{threadId}`). */\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});\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}:{threadId}` 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 Thread 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\n const base = yield* normalizeDurableTravelPlannerEvidence(canonical, receipt);\n\n const scrubbed: unknown = JSON.parse(\n JSON.stringify(base)\n .replaceAll(identity.producerId, \"{producerId}\")\n .replaceAll(identity.deploymentId, \"{deploymentId}\")\n .replaceAll(identity.threadId, \"{threadId}\")\n .replaceAll(/\\d{4}-\\d{2}-\\d{2}T[0-9:.]+Z/g, \"{timestamp}\")\n .replaceAll(/\"[0-9a-f]{64}\"/g, '\"{digest}\"'),\n );\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\n const renumbered = comparable.map((entry, index) => ({\n batchId: entry.batchId,\n sequence: index + 1,\n record: entry.record,\n }));\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 Thread 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\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 Thread 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\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\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 Thread Object\n// ---------------------------------------------------------------------------\n\n/**\n * Every phase-6 Travel Planner worker Binding, captured with its requirement Contexts:\n * 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 Thread 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\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: \"thread-created:{threadId}\",\n sequence: 1,\n record: {\n recordId: \"thread-created:{threadId}\",\n family: \"thread\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ThreadCreated\",\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: \"thread\",\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: \"run-start:run:{submissionId}\",\n sequence: 3,\n record: {\n recordId: \"run-start:run:{submissionId}\",\n family: \"thread\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"RunStarted\",\n runId: \"run:{submissionId}\",\n policyAccountingVersion: 1,\n maxDurationMillis: 30_000,\n },\n },\n },\n {\n batchId: \"turn-response:run:{submissionId}:1\",\n sequence: 4,\n record: {\n recordId: \"model-response:run:{submissionId}:1\",\n family: \"thread\",\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 runScopedPrefixLength: 2,\n modelUsage: [\n {\n provider: \"scripted\",\n model: \"travel-planner-phase-4\",\n purpose: \"turn\",\n usageStatus: \"partial\",\n pricingStatus: \"unknown\",\n inputTokens: {\n total: 128,\n uncached: 128,\n cacheRead: 0,\n cacheWrite: 0,\n },\n outputTokens: {\n total: 96,\n text: 96,\n reasoning: 0,\n },\n costMicrousd: 0,\n },\n ],\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: 5,\n record: {\n recordId: \"tool-settled:run:{submissionId}:1:flight-call-1\",\n family: \"thread\",\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: 6,\n record: {\n recordId: \"tool-settled:run:{submissionId}:1:lodging-call-1\",\n family: \"thread\",\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: 7,\n record: {\n recordId: \"tool-settled:run:{submissionId}:1:activity-call-1\",\n family: \"thread\",\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: 8,\n record: {\n recordId: \"model-response:run:{submissionId}:2\",\n family: \"thread\",\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 modelUsage: [\n {\n provider: \"scripted\",\n model: \"travel-planner-phase-4\",\n purpose: \"turn\",\n usageStatus: \"partial\",\n pricingStatus: \"unknown\",\n inputTokens: {\n total: 128,\n uncached: 128,\n cacheRead: 0,\n cacheWrite: 0,\n },\n outputTokens: {\n total: 96,\n text: 96,\n reasoning: 0,\n },\n costMicrousd: 0,\n },\n ],\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: \"turn:run:{submissionId}:2\",\n sequence: 9,\n record: {\n recordId: \"run-completed:run:{submissionId}\",\n family: \"thread\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"RunCompleted\",\n runId: \"run:{submissionId}\",\n output: {\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 batchId: \"submission-settlement:{submissionId}\",\n sequence: 10,\n record: {\n recordId: \"settlement:{submissionId}\",\n family: \"thread\",\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 uncommittedModelUsage: [],\n usageSummary: {\n usageStatus: \"partial\",\n pricingStatus: \"unknown\",\n unobservedModelCalls: 0,\n modelCalls: 2,\n inputTokens: {\n total: 256,\n uncached: 256,\n cacheRead: 0,\n cacheWrite: 0,\n },\n outputTokens: {\n total: 192,\n text: 192,\n reasoning: 0,\n },\n costMicrousd: 0,\n byModel: [\n {\n provider: \"scripted\",\n model: \"travel-planner-phase-4\",\n modelCalls: 2,\n inputTokens: {\n total: 256,\n uncached: 256,\n cacheRead: 0,\n cacheWrite: 0,\n },\n outputTokens: {\n total: 192,\n text: 192,\n reasoning: 0,\n },\n costMicrousd: 0,\n },\n ],\n },\n },\n },\n },\n];\n","/** Explicit opt-in switch for live integration tests. */\nexport const PHASE7_LIVE_GATE_ENV = \"EFFECT_AGENT_LIVE\";\n\n/** The credential required by the Travel Planner live-model tests. */\nexport const PHASE7_LIVE_CREDENTIAL_ENV = \"OPENAI_API_KEY\";\n\n/** Structural shape of an environment without importing Node types. */\nexport interface Phase7LiveGateEnvironment {\n readonly [name: string]: string | undefined;\n}\n\n/** Enable live tests only when both the opt-in flag and credential are present. */\nexport const phase7LiveProfileEnabled = (env: Phase7LiveGateEnvironment): boolean =>\n env[PHASE7_LIVE_GATE_ENV] === \"1\" && (env[PHASE7_LIVE_CREDENTIAL_ENV]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EACE,SAAS;EACT,UAAU;EACV,QAAQ;GACN,UAAU;GACV,QAAQ;GACR,eAAe;GACf,WAAW;GACX,cAAc;GACd,SAAS;IACP,MAAM;IACN,SAAS;IACT,aAAa;KACX,OAAO;KACP,OAAO;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,yBAAyB;IACzB,mBAAmB;GACrB;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,uBAAuB;IACvB,YAAY,CACV;KACE,UAAU;KACV,OAAO;KACP,SAAS;KACT,aAAa;KACb,eAAe;KACf,aAAa;MACX,OAAO;MACP,UAAU;MACV,WAAW;MACX,YAAY;KACd;KACA,cAAc;MACZ,OAAO;MACP,MAAM;MACN,WAAW;KACb;KACA,cAAc;IAChB,CACF;IACA,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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AM;IACN,aAAa;IACb,cAAc;IACd,YAAY,CACV;KACE,UAAU;KACV,OAAO;KACP,SAAS;KACT,aAAa;KACb,eAAe;KACf,aAAa;MACX,OAAO;MACP,UAAU;MACV,WAAW;MACX,YAAY;KACd;KACA,cAAc;MACZ,OAAO;MACP,MAAM;MACN,WAAW;KACb;KACA,cAAc;IAChB,CACF;IACA,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,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;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;IACA,uBAAuB,CAAC;IACxB,cAAc;KACZ,aAAa;KACb,eAAe;KACf,sBAAsB;KACtB,YAAY;KACZ,aAAa;MACX,OAAO;MACP,UAAU;MACV,WAAW;MACX,YAAY;KACd;KACA,cAAc;MACZ,OAAO;MACP,MAAM;MACN,WAAW;KACb;KACA,cAAc;KACd,SAAS,CACP;MACE,UAAU;MACV,OAAO;MACP,YAAY;MACZ,aAAa;OACX,OAAO;OACP,UAAU;OACV,WAAW;OACX,YAAY;MACd;MACA,cAAc;OACZ,OAAO;OACP,MAAM;OACN,WAAW;MACb;MACA,cAAc;KAChB,CACF;IACF;GACF;EACF;CACF;AACF;;;;ACrgCA,MAAa,uBAAuB;;AAGpC,MAAa,6BAA6B;;AAQ1C,MAAa,4BAA4B,QACvC,IAAA,yBAA8B,QAAQ,IAAA,qBAAmC,QAAQ"}
1
+ {"version":3,"file":"TravelPlanner.mjs","names":["digest","digest","decodeComparableJson","scriptedUsage","researcherLookupParts","researcherReportParts","digestOf","scriptedUsage","researcherLookupParts","researcherReportParts"],"sources":["../src/fixtures/travel-planner/phase2.ts","../src/fixtures/travel-planner/scenarios.ts","../src/fixtures/travel-planner/phase3.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 * as Agent from \"@effect-agent/core/Agent\";\nimport { AgentPolicy } from \"@effect-agent/core/AgentPolicy\";\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.make(\"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: 4_096,\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 \"../../ScriptedModel.ts\";\nimport { TravelPlan, TripRequest, type TravelPlan as TravelPlanValue } from \"./definition.ts\";\n\nconst usage = { inputTokens: { total: 128 }, outputTokens: { total: 96 } };\n\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\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];\n","import { AgentId, ThreadId, RunId, SubmissionId } from \"@effect-agent/core/Identifiers\";\nimport {\n BatchId,\n CanonicalBatch,\n DefinitionDigests,\n DeploymentId,\n Digest,\n ProducerId,\n RecordEnvelope,\n RecordId,\n} from \"@effect-agent/thread/Records\";\nimport { ThreadProjection } from \"@effect-agent/thread/ThreadProjection\";\nimport { ThreadCheckpoint } from \"@effect-agent/thread/ThreadStore\";\nimport { Effect, Schema } from \"effect\";\n\nimport { TravelPlan, TripRequest } from \"./definition.ts\";\nimport { expectedTravelPlan, phase1Trip } from \"./scenarios.ts\";\n\nexport const phase3TravelPlannerThreadId = Schema.decodeSync(ThreadId)(\"travel-planner-p3-thread\");\n\nexport const phase3TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-p3-producer\",\n);\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: \"thread\",\n schemaVersion: 1,\n createdAt,\n deploymentId,\n payload,\n });\n\n/**\n * The first atomic append establishes the Thread 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: \"ThreadCreated\",\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: ReadonlyArray<typeof CanonicalBatch.Encoded> =\n Schema.encodeSync(Schema.Array(CanonicalBatch))(phase3TravelPlannerBatches);\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: ThreadProjection,\n): Effect.Effect<TravelPlan, TravelPlannerProjectionError> => {\n const output = projection.modelOutputs.at(-1);\n\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\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 = (projection: ThreadProjection): ThreadCheckpoint =>\n Schema.decodeSync(ThreadCheckpoint)({\n schemaVersion: 1,\n threadId: projection.threadId,\n throughSequence: projection.throughSequence,\n tailDigest: projection.tailDigest,\n state: Schema.encodeSync(ThreadProjection)(projection),\n createdAt: \"2026-09-01T00:00:04.000Z\",\n });\n","import * as Agent from \"@effect-agent/core/Agent\";\nimport { AgentPolicy } from \"@effect-agent/core/AgentPolicy\";\nimport { type ThreadId } from \"@effect-agent/core/Identifiers\";\nimport { ToolExecutionClass } from \"@effect-agent/engine/DurableStep\";\nimport { type DurableSubmitOptions, type Receipt } from \"@effect-agent/thread/DurableAgentRuntime\";\nimport {\n CanonicalRecordEnvelope,\n DefinitionDigests,\n DeploymentId,\n Digest,\n ProducerId,\n} from \"@effect-agent/thread/Records\";\nimport { Principal, type IdempotencyKey } from \"@effect-agent/thread/SubmissionLedger\";\nimport { Effect, Layer, Schema } from \"effect\";\nimport { Model, Tool, Toolkit } from \"effect/unstable/ai\";\n\nimport { ScriptedModel, type ScriptedTurnInput } from \"../../ScriptedModel.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\nexport const phase4TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-p4-deployment\",\n);\n\nexport const phase4TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-p4-producer\",\n);\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 threadId: ThreadId,\n idempotencyKey: IdempotencyKey,\n): DurableSubmitOptions => ({\n threadId,\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\");\n\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\");\n\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.make(\"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\n const settled = settlements.at(0);\n\n if (settled === undefined) {\n return yield* TravelPlannerDurableEvidenceError.make({\n message: \"The canonical Thread 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\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 Threads 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\n const comparable = encoded.map((envelope) => ({\n batchId: envelope.batchId,\n sequence: envelope.sequence,\n record: envelope.record,\n }));\n\n const substituted: unknown = JSON.parse(\n JSON.stringify(comparable)\n .replaceAll(receipt.submissionId, \"{submissionId}\")\n .replaceAll(receipt.receiptId, \"{receiptId}\"),\n );\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 * as Agent from \"@effect-agent/core/Agent\";\nimport { AgentPolicy } from \"@effect-agent/core/AgentPolicy\";\nimport { type ThreadId } from \"@effect-agent/core/Identifiers\";\nimport {\n DurableStep,\n DurableStepError,\n ToolExecutionClass,\n} from \"@effect-agent/engine/DurableStep\";\nimport { type DurableSubmitOptions } from \"@effect-agent/thread/DurableAgentRuntime\";\nimport {\n DefinitionDigests,\n DeploymentId,\n Digest,\n PersistedJson,\n ProducerId,\n type CanonicalRecordEnvelope,\n} from \"@effect-agent/thread/Records\";\nimport { Principal, type IdempotencyKey } from \"@effect-agent/thread/SubmissionLedger\";\nimport {\n ReconciliationCompleted,\n ReconciliationSafeToRetry,\n ReconciliationUncertain,\n ToolReconciler,\n ToolReconcilerError,\n} from \"@effect-agent/thread/ToolReconciler\";\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\nexport const phase5TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-p5-deployment\",\n);\n\nexport const phase5TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-p5-producer\",\n);\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 threadId: ThreadId,\n idempotencyKey: IdempotencyKey,\n): DurableSubmitOptions => ({\n threadId,\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);\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}`;\n\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 * (GLOSSARY.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\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\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\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\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\n const flight = yield* bookStep(\n \"reserve-flight\",\n `flight ${request.quoteId} for ${request.travelerRef}`,\n );\n\n const lodging = yield* bookStep(\n \"reserve-lodging\",\n `lodging ${request.destination} for ${request.nights} nights (${request.travelerRef})`,\n );\n\n const confirmation = yield* bookStep(\n \"issue-confirmation\",\n `itinerary confirmation for ${request.travelerRef}`,\n );\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\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\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\n return ReconciliationCompleted.make({ result: confirmation, isFailure: false });\n }\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.make(\"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\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\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\n for (const envelope of records) {\n const payload = envelope.record.payload;\n\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 * as Subagent from \"@effect-agent/capabilities/Subagent\";\nimport { SubagentPolicy, SubagentRuntime } from \"@effect-agent/capabilities/Subagent\";\nimport * as Agent from \"@effect-agent/core/Agent\";\nimport { AgentPolicy } from \"@effect-agent/core/AgentPolicy\";\nimport { type RuntimeBinding } from \"@effect-agent/engine/AgentRuntime\";\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 \"../../ScriptedModel.ts\";\nimport { AirportCode } from \"./definition.ts\";\nimport { CatalogLifecycle } from \"./deterministic-layers.ts\";\n\n// ---------------------------------------------------------------------------\n// Destination Researcher: the S1 specialist child Agent.\n// 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);\n\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.make(\"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\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\n if (facts === undefined) {\n throw new Error(`No deterministic guide entry exists for destination ${destination}`);\n }\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\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\n yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);\n\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: 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`. 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\n yield* gate.awaitDispatch(request.destination);\n\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 Thread.\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.make(\"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 thread.`,\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\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\n const gatesFor = (destination: string): Effect.Effect<ResearcherGates> =>\n Effect.suspend(() => {\n const entry = gates.get(destination);\n\n return entry === undefined\n ? Effect.die(new Error(`No researcher gates exist for destination ${destination}`))\n : Effect.succeed(entry);\n });\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\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\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\n const destination = destinations.find((candidate) =>\n promptJson.includes(candidate),\n );\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\n if (index === 0) {\n yield* Ref.update(prompts, (previous) => [...previous, promptJson]);\n yield* Deferred.succeed(entry.started, undefined);\n\n return Stream.fromIterable(researcherLookupParts(destination));\n }\n yield* Deferred.await(entry.release);\n\n return Stream.fromIterable(researcherReportParts(destination));\n }),\n ),\n });\n }),\n ),\n );\n\n return { controls, model };\n });\n","import {\n delegationAllocationFromPolicy,\n SubagentRuntime,\n} from \"@effect-agent/capabilities/Subagent\";\nimport { SubagentReservationsMemoryLive } from \"@effect-agent/capabilities/SubagentReservations\";\nimport * as Agent from \"@effect-agent/core/Agent\";\nimport { type ThreadId } from \"@effect-agent/core/Identifiers\";\nimport { type RuntimeBinding } from \"@effect-agent/engine/AgentRuntime\";\nimport { DurableWorkerBinding, type ResolvedBinding } from \"@effect-agent/thread/AgentRegistration\";\nimport { type DurableSubmitOptions } from \"@effect-agent/thread/DurableAgentRuntime\";\nimport { DefinitionDigests, DeploymentId, Digest, ProducerId } from \"@effect-agent/thread/Records\";\nimport { Principal, type IdempotencyKey } from \"@effect-agent/thread/SubmissionLedger\";\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 type {\n DestinationBrief,\n DestinationReport,\n DestinationResearcherToolkit,\n} from \"./subagents.ts\";\nimport {\n DestinationFacts,\n DestinationGuide,\n DestinationRecommendation,\n DestinationResearcher,\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/** Registered coordinator and researcher bindings for durable delegation tests. */\nexport const s2TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-s2-deployment\",\n);\n\nexport const s2TravelPlannerProducerId = Schema.decodeSync(ProducerId)(\n \"travel-planner-s2-producer\",\n);\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 host's binding array 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 threadId: ThreadId,\n idempotencyKey: IdempotencyKey,\n): DurableSubmitOptions => ({\n threadId,\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\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\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\n yield* Ref.update(prompts, (previous) => [\n ...previous,\n JSON.stringify(request.prompt.content),\n ]);\n\n return Stream.fromIterable(script(call));\n }),\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 `NodeDurableAgentRuntimeOptions.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 `NodeDurableAgentRuntime` 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\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\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\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\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\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\n return harness;\n });\n","import { SubagentReservationsMemoryLive } from \"@effect-agent/capabilities/SubagentReservations\";\nimport * as Agent from \"@effect-agent/core/Agent\";\nimport { DurableWorkerBinding, type ResolvedBinding } from \"@effect-agent/thread/AgentRegistration\";\nimport { type Receipt } from \"@effect-agent/thread/DurableAgentRuntime\";\nimport {\n DefinitionDigests,\n DeploymentId,\n Digest,\n ProducerId,\n type CanonicalRecordEnvelope,\n} from \"@effect-agent/thread/Records\";\nimport { type ToolReconciler } from \"@effect-agent/thread/ToolReconciler\";\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/** Platform-neutral bindings and canonical evidence shared by Node and Cloudflare tests. */\nexport const phase6TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)(\n \"travel-planner-p6-deployment\",\n);\n\n/** Producer prefix of the DC host; each Object mints `{prefix}:{threadId}`. */\nexport const phase6TravelPlannerProducerPrefix = \"travel-planner-p6-producer\";\n\n/** The full producer identity one DC Thread Object mints for itself. */\nexport const phase6TravelPlannerProducerId = (threadId: string): ProducerId =>\n Schema.decodeSync(ProducerId)(`${phase6TravelPlannerProducerPrefix}:${threadId}`);\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 Thread lane the evidence came from. */\n readonly threadId: 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}:{threadId}`). */\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});\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}:{threadId}` 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 Thread 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\n const base = yield* normalizeDurableTravelPlannerEvidence(canonical, receipt);\n\n const scrubbed: unknown = JSON.parse(\n JSON.stringify(base)\n .replaceAll(identity.producerId, \"{producerId}\")\n .replaceAll(identity.deploymentId, \"{deploymentId}\")\n .replaceAll(identity.threadId, \"{threadId}\")\n .replaceAll(/\\d{4}-\\d{2}-\\d{2}T[0-9:.]+Z/g, \"{timestamp}\")\n .replaceAll(/\"[0-9a-f]{64}\"/g, '\"{digest}\"'),\n );\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\n const renumbered = comparable.map((entry, index) => ({\n batchId: entry.batchId,\n sequence: index + 1,\n record: entry.record,\n }));\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 Thread 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\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 Thread 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\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\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 Thread Object\n// ---------------------------------------------------------------------------\n\n/**\n * Every phase-6 Travel Planner worker Binding, captured with its requirement Contexts:\n * 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 Thread 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\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: \"thread-created:{threadId}\",\n sequence: 1,\n record: {\n recordId: \"thread-created:{threadId}\",\n family: \"thread\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"ThreadCreated\",\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: \"thread\",\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: \"run-start:run:{submissionId}\",\n sequence: 3,\n record: {\n recordId: \"run-start:run:{submissionId}\",\n family: \"thread\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"RunStarted\",\n runId: \"run:{submissionId}\",\n policyAccountingVersion: 1,\n maxDurationMillis: 30_000,\n },\n },\n },\n {\n batchId: \"turn-response:run:{submissionId}:1\",\n sequence: 4,\n record: {\n recordId: \"model-response:run:{submissionId}:1\",\n family: \"thread\",\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 runScopedPrefixLength: 2,\n modelUsage: [\n {\n provider: \"scripted\",\n model: \"travel-planner-phase-4\",\n purpose: \"turn\",\n usageStatus: \"partial\",\n pricingStatus: \"unknown\",\n inputTokens: {\n total: 128,\n uncached: 128,\n cacheRead: 0,\n cacheWrite: 0,\n },\n outputTokens: {\n total: 96,\n text: 96,\n reasoning: 0,\n },\n costMicrousd: 0,\n },\n ],\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: 5,\n record: {\n recordId: \"tool-settled:run:{submissionId}:1:flight-call-1\",\n family: \"thread\",\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: 6,\n record: {\n recordId: \"tool-settled:run:{submissionId}:1:lodging-call-1\",\n family: \"thread\",\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: 7,\n record: {\n recordId: \"tool-settled:run:{submissionId}:1:activity-call-1\",\n family: \"thread\",\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: 8,\n record: {\n recordId: \"model-response:run:{submissionId}:2\",\n family: \"thread\",\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 modelUsage: [\n {\n provider: \"scripted\",\n model: \"travel-planner-phase-4\",\n purpose: \"turn\",\n usageStatus: \"partial\",\n pricingStatus: \"unknown\",\n inputTokens: {\n total: 128,\n uncached: 128,\n cacheRead: 0,\n cacheWrite: 0,\n },\n outputTokens: {\n total: 96,\n text: 96,\n reasoning: 0,\n },\n costMicrousd: 0,\n },\n ],\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: \"turn:run:{submissionId}:2\",\n sequence: 9,\n record: {\n recordId: \"run-completed:run:{submissionId}\",\n family: \"thread\",\n schemaVersion: 1,\n createdAt: \"{timestamp}\",\n deploymentId: \"{deploymentId}\",\n payload: {\n _tag: \"RunCompleted\",\n runId: \"run:{submissionId}\",\n output: {\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 batchId: \"submission-settlement:{submissionId}\",\n sequence: 10,\n record: {\n recordId: \"settlement:{submissionId}\",\n family: \"thread\",\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 uncommittedModelUsage: [],\n usageSummary: {\n usageStatus: \"partial\",\n pricingStatus: \"unknown\",\n unobservedModelCalls: 0,\n modelCalls: 2,\n inputTokens: {\n total: 256,\n uncached: 256,\n cacheRead: 0,\n cacheWrite: 0,\n },\n outputTokens: {\n total: 192,\n text: 192,\n reasoning: 0,\n },\n costMicrousd: 0,\n byModel: [\n {\n provider: \"scripted\",\n model: \"travel-planner-phase-4\",\n modelCalls: 2,\n inputTokens: {\n total: 256,\n uncached: 256,\n cacheRead: 0,\n cacheWrite: 0,\n },\n outputTokens: {\n total: 192,\n text: 192,\n reasoning: 0,\n },\n costMicrousd: 0,\n },\n ],\n },\n },\n },\n },\n];\n","/** Explicit opt-in switch for live integration tests. */\nexport const PHASE7_LIVE_GATE_ENV = \"EFFECT_AGENT_LIVE\";\n\n/** The credential required by the Travel Planner live-model tests. */\nexport const PHASE7_LIVE_CREDENTIAL_ENV = \"OPENAI_API_KEY\";\n\n/** Structural shape of an environment without importing Node types. */\nexport interface Phase7LiveGateEnvironment {\n readonly [name: string]: string | undefined;\n}\n\n/** Enable live tests only when both the opt-in flag and credential are present. */\nexport const phase7LiveProfileEnabled = (env: Phase7LiveGateEnvironment): boolean =>\n env[PHASE7_LIVE_GATE_ENV] === \"1\" && (env[PHASE7_LIVE_CREDENTIAL_ENV] ?? \"\") !== \"\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAkBA,IAAa,uBAAb,cAA0C,OAAO,MAC/C,2DACF,CAAC,CAAC;CACA,SAAS;CACT,kBAAkB,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,GAAG,OAAO,oBAAoB,EAAE,CAAC;AAC5F,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,gBAAb,cAAmC,OAAO,MACxC,oDACF,CAAC,CAAC;CACA,QAAQ,OAAO;CACf,SAAS;CACT,QAAQ,OAAO,QAAQ,MAAM;AAC/B,CAAC,CAAC,CAAC,CAAC;AAEJ,IAAa,2BAAb,cAA8C,OAAO,YAAsC,CAAC,CAC1F,4BACA;CACE,SAAS;CACT,SAAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;AAEH,IAAa,uBAAb,cAA0C,QAAQ,QAOhD,CAAC,CAAC,2DAA2D,CAAC,CAAC,CAAC;;;;;AAMlE,MAAa,gBAAgB,KAAK,KAAK,kBAAkB;CACvD,YAAY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Ac;GACd,SAAS;IACP,MAAM;IACN,OAAO;IACP,QAAQ;IACR,MAAM;IACN,aAAa;IACb,cAAc;IACd,uBAAuB;IACvB,YAAY,CACV;KACE,UAAU;KACV,OAAO;KACP,SAAS;KACT,aAAa;KACb,eAAe;KACf,aAAa;MACX,OAAO;MACP,UAAU;MACV,WAAW;MACX,YAAY;KACd;KACA,cAAc;MACZ,OAAO;MACP,MAAM;MACN,WAAW;KACb;KACA,cAAc;IAChB,CACF;IACA,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,YAAY,CACV;KACE,UAAU;KACV,OAAO;KACP,SAAS;KACT,aAAa;KACb,eAAe;KACf,aAAa;MACX,OAAO;MACP,UAAU;MACV,WAAW;MACX,YAAY;KACd;KACA,cAAc;MACZ,OAAO;MACP,MAAM;MACN,WAAW;KACb;KACA,cAAc;IAChB,CACF;IACA,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,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;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;IACA,uBAAuB,CAAC;IACxB,cAAc;KACZ,aAAa;KACb,eAAe;KACf,sBAAsB;KACtB,YAAY;KACZ,aAAa;MACX,OAAO;MACP,UAAU;MACV,WAAW;MACX,YAAY;KACd;KACA,cAAc;MACZ,OAAO;MACP,MAAM;MACN,WAAW;KACb;KACA,cAAc;KACd,SAAS,CACP;MACE,UAAU;MACV,OAAO;MACP,YAAY;MACZ,aAAa;OACX,OAAO;OACP,UAAU;OACV,WAAW;OACX,YAAY;MACd;MACA,cAAc;OACZ,OAAO;OACP,MAAM;OACN,WAAW;MACb;MACA,cAAc;KAChB,CACF;IACF;GACF;EACF;CACF;AACF;;;;ACrgCA,MAAa,uBAAuB;;AAGpC,MAAa,6BAA6B;;AAQ1C,MAAa,4BAA4B,QACvC,IAAA,yBAA8B,QAAQ,IAAA,qBAAmC,QAAQ"}
package/package.json CHANGED
@@ -1 +1 @@
1
- {"name":"@effect-agent/testing","version":"0.1.0-beta.63","dependencies":{"@effect-agent/capabilities":"0.1.0-beta.63","@effect-agent/core":"0.1.0-beta.63","@effect-agent/engine":"0.1.0-beta.63","@effect-agent/sandbox":"0.1.0-beta.63","@effect-agent/thread":"0.1.0-beta.63"},"devDependencies":{"@effect-agent/platform-node":"0.1.0-beta.63","@effect-agent/storage-memory":"0.1.0-beta.63","@effect-agent/storage-sqlite":"0.1.0-beta.63","@effect/platform-node":"4.0.0-rc.112","@effect/sql-sqlite-node":"4.0.0-rc.112","@effect/vitest":"4.0.0-rc.112","effect":"4.0.0-rc.112","typescript":"7.0.2","vite-plus":"0.3.0"},"peerDependencies":{"effect":"^4.0.0-rc.112"},"exports":{".":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"./Certification":{"types":"./dist/Certification.d.mts","default":"./dist/Certification.mjs"},"./Chaos":{"types":"./dist/Chaos.d.mts","default":"./dist/Chaos.mjs"},"./CodeExecutorConformance":{"types":"./dist/CodeExecutorConformance.d.mts","default":"./dist/CodeExecutorConformance.mjs"},"./CodeExecutorSubstitute":{"types":"./dist/CodeExecutorSubstitute.d.mts","default":"./dist/CodeExecutorSubstitute.mjs"},"./DocsResearcher":{"types":"./dist/DocsResearcher.d.mts","default":"./dist/DocsResearcher.mjs"},"./ScriptedModel":{"types":"./dist/ScriptedModel.d.mts","default":"./dist/ScriptedModel.mjs"},"./TravelPlanner":{"types":"./dist/TravelPlanner.d.mts","default":"./dist/TravelPlanner.mjs"}},"description":"Scripted models, deterministic fixtures, and adapter conformance kits for testing Effect Agent applications.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/danieljvdm/effect-agent.git","directory":"packages/testing"},"files":["dist","src"],"type":"module","sideEffects":[],"publishConfig":{"access":"public"},"scripts":{"build":"vp pack","check":"tsc --noEmit -p tsconfig.json","test":"vp test --passWithNoTests"}}
1
+ {"name":"@effect-agent/testing","version":"0.1.0-beta.65","dependencies":{"@effect-agent/capabilities":"0.1.0-beta.65","@effect-agent/core":"0.1.0-beta.65","@effect-agent/engine":"0.1.0-beta.65","@effect-agent/sandbox":"0.1.0-beta.65","@effect-agent/thread":"0.1.0-beta.65"},"devDependencies":{"@effect-agent/platform-node":"0.1.0-beta.65","@effect-agent/storage-memory":"0.1.0-beta.65","@effect-agent/storage-sqlite":"0.1.0-beta.65","@effect/platform-node":"4.0.0-rc.112","@effect/sql-sqlite-node":"4.0.0-rc.112","@effect/vitest":"4.0.0-rc.112","effect":"4.0.0-rc.112","typescript":"7.0.2","vite-plus":"0.3.0"},"peerDependencies":{"effect":"^4.0.0-rc.112"},"exports":{".":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"./Certification":{"types":"./dist/Certification.d.mts","default":"./dist/Certification.mjs"},"./Chaos":{"types":"./dist/Chaos.d.mts","default":"./dist/Chaos.mjs"},"./CodeExecutorConformance":{"types":"./dist/CodeExecutorConformance.d.mts","default":"./dist/CodeExecutorConformance.mjs"},"./CodeExecutorSubstitute":{"types":"./dist/CodeExecutorSubstitute.d.mts","default":"./dist/CodeExecutorSubstitute.mjs"},"./DocsResearcher":{"types":"./dist/DocsResearcher.d.mts","default":"./dist/DocsResearcher.mjs"},"./ScriptedModel":{"types":"./dist/ScriptedModel.d.mts","default":"./dist/ScriptedModel.mjs"},"./TravelPlanner":{"types":"./dist/TravelPlanner.d.mts","default":"./dist/TravelPlanner.mjs"}},"description":"Scripted models, deterministic fixtures, and adapter conformance kits for testing Effect Agent applications.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/danieljvdm/effect-agent.git","directory":"packages/testing"},"files":["dist","src"],"type":"module","sideEffects":[],"publishConfig":{"access":"public"},"scripts":{"build":"vp pack","check":"tsc --noEmit -p tsconfig.json","test":"vp test --passWithNoTests"}}
@@ -161,8 +161,8 @@ export const CERTIFICATION_SCENARIOS: ReadonlyArray<CertificationScenario> = [
161
161
 
162
162
  /**
163
163
  * Coordinator failpoint locations that none of the six scenario shapes can reach, recorded
164
- * honestly instead of silently claimed: all three sit on operator/abort paths the shapes do
165
- * not take. They are pinned in-process by the P5/S2 suites
164
+ * honestly instead of silently claimed. These require operator, compaction, reservation, or
165
+ * background-worker paths the shapes do not take. They are pinned in-process by the P5/S2 suites
166
166
  * (`packages/testing/test/durable-tools.test.ts` "resolveUnknown is idempotent across the
167
167
  * intent failpoint", `durable-runtime.test.ts` abort rows,
168
168
  * `durable-subagents.test.ts` abort propagation) and by the process-kill/eviction crash
@@ -170,6 +170,9 @@ export const CERTIFICATION_SCENARIOS: ReadonlyArray<CertificationScenario> = [
170
170
  * protocol change that silently stops exercising a location fails the certification.
171
171
  */
172
172
  export const TIER2_UNREACHED_LOCATIONS: ReadonlyArray<DurableRuntimeFailpointLocation> = [
173
+ // Tier 2 has no native compaction; dedicated checkpoint process-loss tests cover these.
174
+ "checkpoint:before-save",
175
+ "checkpoint:after-save",
173
176
  "abort:after-intent",
174
177
  // Compaction requires a `contextTokenLimit` policy plus prior-Run history
175
178
  // none of the six scenario shapes carries; pinned in-process by the
@@ -131,10 +131,6 @@ export const makePhase3TravelPlannerCheckpoint = (projection: ThreadProjection):
131
131
  threadId: projection.threadId,
132
132
  throughSequence: projection.throughSequence,
133
133
  tailDigest: projection.tailDigest,
134
- engineVersion: "phase-3-test-runtime",
135
- agentDefinitionDigest: phase3TravelPlannerDefinitionDigests.agent,
136
- modelDigest: phase3TravelPlannerDefinitionDigests.model,
137
- toolDigest: phase3TravelPlannerDefinitionDigests.tools,
138
134
  state: Schema.encodeSync(ThreadProjection)(projection),
139
135
  createdAt: "2026-09-01T00:00:04.000Z",
140
136
  });