@effect-agent/testing 0.0.1-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,4205 @@
1
+ import { McpConnectionRequest, McpConnector, McpServerIdentity, McpToolkitMismatch, Redactor, Subagent, SubagentPolicy, SubagentReservationsMemoryLive, SubagentRuntime, connectMcp, delegationAllocationFromPolicy } from "@effect-agent/capabilities";
2
+ import { Agent, AgentId, AgentPolicy, ConversationId, IdGenerator, RunId, SubmissionId, ToolCallId, TurnId } from "@effect-agent/core";
3
+ import { DurableStep, DurableStepError, ToolExecutionClass } from "@effect-agent/engine";
4
+ import { AbortCommand, AgentBindingResolver, ApprovalDecisionCommand, BatchId, CanonicalBatch, CanonicalRecordEnvelope, CertificationReport, CertificationSweepResult, CertificationTierThreeReport, CertifiedAdapterIdentity, ConversationCheckpoint, ConversationExportRequest, ConversationProjection, ConversationStore, DEFAULT_OWNERSHIP_LEASE_DURATION, DefinitionDigests, DeploymentId, Digest, DurableAgentRuntime, DurableRuntimeConfig, DurableRuntimeFailpoint, DurableRuntimeFailpointError, DurableRuntimeFailpointLocation, DurableRuntimeFailpointTestControl, DurableWorkerBinding, IdempotencyKey, LoadCheckpointRequest, ObligationThresholds, PersistedJson, Principal, ProducerId, ReconciliationCompleted, ReconciliationSafeToRetry, ReconciliationUncertain, RecordEnvelope, RecordId, ResolutionAbortSubmission, ResolutionCompletedWithResult, ResolutionNeverHappened, ResolutionSafeToRetry, SubmissionLedger, SubmissionLookupById, ToolReconciler, ToolReconcilerError, UnknownResolutionCommand, WakeScheduler, certifyPorts, childConversationIdFor, verifyConversationInvariants } from "@effect-agent/session";
5
+ import { Cause, Clock, Context, DateTime, Deferred, Duration, Effect, Exit, Layer, Option, Ref, Schema, Stream } from "effect";
6
+ import { FastCheck, TestClock } from "effect/testing";
7
+ import { AiError, LanguageModel, Model, Response, Tool, Toolkit } from "effect/unstable/ai";
8
+ import * as McpSchema from "effect/unstable/ai/McpSchema";
9
+ //#region src/certification.ts
10
+ /** The six Tier-2 scenario shapes in sweep order. */
11
+ const CERTIFICATION_SCENARIOS = [
12
+ "plain",
13
+ "uncertain-tool",
14
+ "durable-steps",
15
+ "approval",
16
+ "join",
17
+ "delegation"
18
+ ];
19
+ /**
20
+ * Coordinator failpoint locations that none of the six scenario shapes can reach, recorded
21
+ * honestly instead of silently claimed: all three sit on operator/abort paths the shapes do
22
+ * not take. They are pinned in-process by the P5/S2 suites
23
+ * (`packages/testing/test/durable-tools.test.ts` "resolveUnknown is idempotent across the
24
+ * intent failpoint", `durable-runtime.test.ts` abort rows,
25
+ * `durable-subagents.test.ts` abort propagation) and by the process-kill/eviction crash
26
+ * matrices. Runner tests assert the observed never-fired set equals EXACTLY this list, so a
27
+ * protocol change that silently stops exercising a location fails the certification.
28
+ */
29
+ const TIER2_UNREACHED_LOCATIONS = [
30
+ "abort:after-intent",
31
+ "resolve:after-intent",
32
+ "subagent:after-child-abort-intent"
33
+ ];
34
+ /** Locations of `tier2` rows whose armed fault never fired in ANY scenario, sorted. */
35
+ const tier2NeverFiredLocations = (tier2) => {
36
+ const fired = /* @__PURE__ */ new Set();
37
+ for (const row of tier2) if (row.failpointFired) fired.add(row.location);
38
+ return DurableRuntimeFailpointLocation.literals.filter((location) => !fired.has(location)).sort();
39
+ };
40
+ const SHA_A = Schema.decodeSync(Digest)("a".repeat(64));
41
+ const DIGESTS = DefinitionDigests.make({
42
+ agent: SHA_A,
43
+ model: SHA_A,
44
+ tools: SHA_A
45
+ });
46
+ const CHILD_DIGEST_STRINGS = {
47
+ agent: "b".repeat(64),
48
+ model: "c".repeat(64),
49
+ tools: "d".repeat(64)
50
+ };
51
+ const CHILD_DIGESTS = DefinitionDigests.make({
52
+ agent: Schema.decodeSync(Digest)(CHILD_DIGEST_STRINGS.agent),
53
+ model: Schema.decodeSync(Digest)(CHILD_DIGEST_STRINGS.model),
54
+ tools: Schema.decodeSync(Digest)(CHILD_DIGEST_STRINGS.tools)
55
+ });
56
+ const PRINCIPAL = Schema.decodeSync(Principal)("principal-certification");
57
+ const decodeConversationId$1 = Schema.decodeSync(ConversationId);
58
+ const decodeIdempotencyKey$1 = Schema.decodeSync(IdempotencyKey);
59
+ const decodeToolCallId$1 = Schema.decodeSync(ToolCallId);
60
+ const usage$2 = {
61
+ inputTokens: {},
62
+ outputTokens: {}
63
+ };
64
+ const finalParts$1 = (text) => [
65
+ {
66
+ type: "text-start",
67
+ id: "answer"
68
+ },
69
+ {
70
+ type: "text-delta",
71
+ id: "answer",
72
+ delta: text
73
+ },
74
+ {
75
+ type: "text-end",
76
+ id: "answer"
77
+ },
78
+ {
79
+ type: "finish",
80
+ reason: "stop",
81
+ usage: usage$2
82
+ }
83
+ ];
84
+ const toolCallPart$1 = (id, name, params) => ({
85
+ type: "tool-call",
86
+ id,
87
+ name,
88
+ params,
89
+ providerExecuted: false
90
+ });
91
+ const toolTurn$1 = (...calls) => [...calls, {
92
+ type: "finish",
93
+ reason: "tool-calls",
94
+ usage: usage$2
95
+ }];
96
+ /**
97
+ * Stateless scripted model that decides by PROMPT SHAPE instead of call count: while the
98
+ * prompt carries no committed tool result the model declares `toolParts` (when given),
99
+ * otherwise it answers with the final text. Deciding on the canonical prompt keeps every cell
100
+ * deterministic regardless of where the injected fault fell — a re-invoked Turn re-declares
101
+ * the same batch and a resumed batch flows into the final answer, so every scenario always
102
+ * exercises its tool path and always converges.
103
+ */
104
+ const promptShapeModel = (name, finalText, toolParts) => Model.make("scripted", name, Layer.effect(LanguageModel.LanguageModel, LanguageModel.make({
105
+ generateText: () => Effect.succeed([]),
106
+ streamText: (request) => {
107
+ const hasToolResult = request.prompt.content.some((message) => message.role === "tool");
108
+ const parts = toolParts === void 0 || hasToolResult ? finalParts$1(finalText) : toolParts;
109
+ return Stream.fromIterable(parts);
110
+ }
111
+ })));
112
+ const policy$1 = AgentPolicy.make({
113
+ maxTurns: 4,
114
+ maxToolCalls: 4,
115
+ maxDuration: "30 seconds",
116
+ toolConcurrency: 2
117
+ });
118
+ const QuestionInput = Schema.Struct({ question: Schema.String });
119
+ const AnswerOutput = Schema.Struct({ answer: Schema.String });
120
+ /** plain / join: no tools — the pure Turn/submission/join seams. */
121
+ const plainDefinition$1 = Agent.define("certify-plain", {
122
+ input: QuestionInput,
123
+ output: AnswerOutput,
124
+ instructions: "Answer as JSON.",
125
+ toolkit: Toolkit.empty,
126
+ policy: policy$1
127
+ });
128
+ /** uncertain-tool: unannotated → fail-closed `uncertain`, enters the prepared/settled protocol. */
129
+ const Book = Tool.make("book", {
130
+ parameters: Schema.Struct({ ref: Schema.String }),
131
+ success: Schema.Struct({ confirmation: Schema.String })
132
+ });
133
+ const bookToolkit = Toolkit.make(Book);
134
+ const uncertainDefinition = Agent.define("certify-uncertain", {
135
+ input: QuestionInput,
136
+ output: AnswerOutput,
137
+ instructions: "Book it.",
138
+ toolkit: bookToolkit,
139
+ policy: policy$1
140
+ });
141
+ /** durable-steps: declaring `DurableStep` as a dependency is what makes the Tool durable. */
142
+ const Itinerary$2 = Tool.make("itinerary", {
143
+ parameters: Schema.Struct({ ref: Schema.String }),
144
+ success: Schema.Struct({ state: Schema.String }),
145
+ failure: DurableStepError,
146
+ dependencies: [DurableStep]
147
+ });
148
+ const itineraryToolkit = Toolkit.make(Itinerary$2);
149
+ const stepsDefinition = Agent.define("certify-steps", {
150
+ input: QuestionInput,
151
+ output: AnswerOutput,
152
+ instructions: "Reserve the itinerary.",
153
+ toolkit: itineraryToolkit,
154
+ policy: policy$1
155
+ });
156
+ /** approval: fail-closed — no `DurableApprovalResolver` Layer, so undecided approvals suspend. */
157
+ const BookApproval$1 = Tool.make("book", {
158
+ parameters: Schema.Struct({ ref: Schema.String }),
159
+ success: Schema.Struct({ confirmation: Schema.String }),
160
+ needsApproval: true
161
+ });
162
+ const approvalToolkit = Toolkit.make(BookApproval$1);
163
+ const approvalDefinition$1 = Agent.define("certify-approval", {
164
+ input: QuestionInput,
165
+ output: AnswerOutput,
166
+ instructions: "Book after approval.",
167
+ toolkit: approvalToolkit,
168
+ policy: policy$1
169
+ });
170
+ /** delegation: durable attached child plus an ordinary uncertain sibling in ONE batch. */
171
+ const childDefinition$1 = Agent.define("certify-child", {
172
+ input: QuestionInput,
173
+ output: AnswerOutput,
174
+ instructions: "Answer as JSON.",
175
+ toolkit: Toolkit.empty,
176
+ policy: AgentPolicy.make({
177
+ maxTurns: 2,
178
+ maxToolCalls: 1,
179
+ maxDuration: "30 seconds",
180
+ toolConcurrency: 1
181
+ })
182
+ });
183
+ var CertifyDelegationFailed = class extends Schema.TaggedErrorClass()("CertifyDelegationFailed", { childErrorTag: Schema.String }) {};
184
+ const researchDelegation = Subagent.define("delegate_research", {
185
+ description: "Research one bounded question and return findings.",
186
+ target: childDefinition$1,
187
+ parameters: Schema.Struct({ topic: Schema.String }),
188
+ success: Schema.Struct({ summary: Schema.String }),
189
+ failure: CertifyDelegationFailed,
190
+ prepareInput: ({ topic }) => Effect.succeed({ question: `research:${topic}` }),
191
+ projectResult: (output) => Effect.succeed({ summary: `finding:${output.answer}` }),
192
+ policy: SubagentPolicy.make({
193
+ maxChildren: 2,
194
+ maxConcurrency: 2,
195
+ maxTurns: 4,
196
+ maxToolCalls: 4,
197
+ maxDuration: "10 seconds"
198
+ })
199
+ });
200
+ const Lookup = Tool.make("lookup", {
201
+ parameters: Schema.Struct({ key: Schema.String }),
202
+ success: Schema.Struct({ value: Schema.String })
203
+ });
204
+ const coordinatorDefinition$1 = Agent.define("certify-coordinator", {
205
+ input: Schema.Struct({ mission: Schema.String }),
206
+ output: Schema.Struct({ report: Schema.String }),
207
+ instructions: "Delegate and look up, then answer as JSON.",
208
+ toolkit: Toolkit.make(researchDelegation.tool, Lookup),
209
+ policy: AgentPolicy.make({
210
+ maxTurns: 4,
211
+ maxToolCalls: 3,
212
+ maxDuration: "30 seconds",
213
+ toolConcurrency: 2
214
+ })
215
+ });
216
+ const mapChildFailure = (failure) => CertifyDelegationFailed.make({ childErrorTag: failure._tag });
217
+ const DELEGATE_CALL = decodeToolCallId$1("delegate-1");
218
+ /** Fixture-only identity source consumed by the delegation Layer's ephemeral capture. */
219
+ const identifiers = Layer.effect(IdGenerator, Effect.gen(function* () {
220
+ const counter = yield* Ref.make(0);
221
+ const next = (decode, prefix) => Ref.getAndUpdate(counter, (value) => value + 1).pipe(Effect.map((value) => decode(`${prefix}-${value}`)));
222
+ return {
223
+ nextConversationId: next(decodeConversationId$1, "certify-fixture-conversation"),
224
+ nextRunId: next(Schema.decodeSync(RunId), "certify-fixture-run"),
225
+ nextTurnId: next(Schema.decodeSync(TurnId), "certify-fixture-turn")
226
+ };
227
+ }));
228
+ const delegationSupport$1 = Layer.mergeAll(SubagentReservationsMemoryLive, identifiers);
229
+ const submitOptionsFor = (slug, conversationId) => ({
230
+ conversationId,
231
+ principal: PRINCIPAL,
232
+ idempotencyKey: decodeIdempotencyKey$1(`certify-key-${slug}`),
233
+ definitions: DIGESTS
234
+ });
235
+ /** One single-agent cell: one lane, one Submission, one registered exact-digest binding. */
236
+ const makeSingleAgentCell = (definition, resolved, slug) => {
237
+ const conversationId = decodeConversationId$1(`certify-${slug}`);
238
+ const submit = Effect.gen(function* () {
239
+ return [yield* (yield* DurableAgentRuntime).submit({ definition: {
240
+ id: definition.id,
241
+ input: definition.input
242
+ } }, { question: `certify ${slug}` }, submitOptionsFor(slug, conversationId))];
243
+ });
244
+ return {
245
+ resolver: AgentBindingResolver.fromBindings([resolved]),
246
+ submit,
247
+ lanes: () => [conversationId]
248
+ };
249
+ };
250
+ const makeCell = Effect.fn("Certification.makeCell")(function* (scenario, slug) {
251
+ switch (scenario) {
252
+ case "plain": {
253
+ const binding = Agent.withModel(plainDefinition$1, promptShapeModel("certify-plain", "{\"answer\":\"done\"}"));
254
+ const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS);
255
+ return makeSingleAgentCell(plainDefinition$1, resolved, slug);
256
+ }
257
+ case "uncertain-tool": {
258
+ const binding = Agent.withModel(uncertainDefinition, promptShapeModel("certify-uncertain", "{\"answer\":\"booked\"}", toolTurn$1(toolCallPart$1("book-1", "book", { ref: `r-${slug}` }))));
259
+ const toolLayer = bookToolkit.toLayer({ book: ({ ref }) => Effect.succeed({ confirmation: `confirmed-${ref}` }) });
260
+ const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(Effect.provide(toolLayer));
261
+ return makeSingleAgentCell(uncertainDefinition, resolved, slug);
262
+ }
263
+ case "durable-steps": {
264
+ const binding = Agent.withModel(stepsDefinition, promptShapeModel("certify-steps", "{\"answer\":\"reserved\"}", toolTurn$1(toolCallPart$1("itinerary-1", "itinerary", { ref: `trip-${slug}` }))));
265
+ const toolLayer = itineraryToolkit.toLayer({ itinerary: ({ ref }) => Effect.gen(function* () {
266
+ const step = yield* DurableStep;
267
+ return { state: `${yield* step.do("reserve-flight", Schema.String, Effect.succeed(`flight-${ref}`))}+${yield* step.do("reserve-lodging", Schema.String, Effect.succeed(`lodging-${ref}`))}` };
268
+ }) });
269
+ const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(Effect.provide(toolLayer));
270
+ return makeSingleAgentCell(stepsDefinition, resolved, slug);
271
+ }
272
+ case "approval": {
273
+ const binding = Agent.withModel(approvalDefinition$1, promptShapeModel("certify-approval", "{\"answer\":\"approved\"}", toolTurn$1(toolCallPart$1("book-1", "book", { ref: `r-${slug}` }))));
274
+ const toolLayer = approvalToolkit.toLayer({ book: ({ ref }) => Effect.succeed({ confirmation: `confirmed-${ref}` }) });
275
+ const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(Effect.provide(toolLayer));
276
+ return makeSingleAgentCell(approvalDefinition$1, resolved, slug);
277
+ }
278
+ case "join": {
279
+ const binding = Agent.withModel(plainDefinition$1, promptShapeModel("certify-join", "{\"answer\":\"host answer\"}"));
280
+ const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS);
281
+ const conversationId = decodeConversationId$1(`certify-${slug}`);
282
+ const submitOne = (key, question) => Effect.gen(function* () {
283
+ return yield* (yield* DurableAgentRuntime).submit({ definition: {
284
+ id: plainDefinition$1.id,
285
+ input: plainDefinition$1.input
286
+ } }, { question }, {
287
+ conversationId,
288
+ principal: PRINCIPAL,
289
+ idempotencyKey: decodeIdempotencyKey$1(key),
290
+ definitions: DIGESTS
291
+ });
292
+ });
293
+ return {
294
+ resolver: AgentBindingResolver.fromBindings([resolved]),
295
+ submit: Effect.gen(function* () {
296
+ return [yield* submitOne(`certify-key-${slug}-host`, "host question"), yield* submitOne(`certify-key-${slug}-queued`, "queued question")];
297
+ }),
298
+ lanes: () => [conversationId]
299
+ };
300
+ }
301
+ case "delegation": {
302
+ const childBinding = Agent.withModel(childDefinition$1, promptShapeModel("certify-child", "{\"answer\":\"child-answer\"}"));
303
+ const parentBinding = Agent.withModel(coordinatorDefinition$1, promptShapeModel("certify-parent", "{\"report\":\"done\"}", toolTurn$1(toolCallPart$1("delegate-1", "delegate_research", { topic: "paris" }), toolCallPart$1("lookup-1", "lookup", { key: "hotels" }))));
304
+ const delegationLayer = SubagentRuntime.layer(researchDelegation, childBinding, {
305
+ mapChildFailure,
306
+ durable: { targetDigests: CHILD_DIGEST_STRINGS }
307
+ }).pipe(Layer.provide(delegationSupport$1));
308
+ const lookupLayer = Toolkit.make(Lookup).toLayer({ lookup: ({ key }) => Effect.succeed({ value: `found-${key}` }) });
309
+ const parentResolved = yield* DurableWorkerBinding.make(parentBinding, DIGESTS).pipe(Effect.provide(Layer.mergeAll(delegationLayer, lookupLayer)));
310
+ const childResolved = yield* DurableWorkerBinding.make(childBinding, CHILD_DIGESTS);
311
+ const conversationId = decodeConversationId$1(`certify-${slug}`);
312
+ return {
313
+ resolver: AgentBindingResolver.fromBindings([parentResolved, childResolved]),
314
+ submit: Effect.gen(function* () {
315
+ return [yield* (yield* DurableAgentRuntime).submit({ definition: {
316
+ id: coordinatorDefinition$1.id,
317
+ input: coordinatorDefinition$1.input
318
+ } }, { mission: "plan" }, submitOptionsFor(slug, conversationId))];
319
+ }),
320
+ lanes: (receipts) => {
321
+ const parent = receipts.at(0);
322
+ return parent === void 0 ? [conversationId] : [conversationId, childConversationIdFor(parent.submissionId, DELEGATE_CALL)];
323
+ }
324
+ };
325
+ }
326
+ }
327
+ });
328
+ /** Maximum recovery/drive/unblock rounds before a cell is reported non-convergent. */
329
+ const MAX_REDRIVE_ROUNDS = 8;
330
+ /**
331
+ * Verify one lane after convergence: canonical export + every lane Submission the ledger or
332
+ * the log names (the same collection rule as the admin `verify` member), fed to the shared
333
+ * invariant checker in convergence mode WITH the captured per-batch producer directory, so
334
+ * the digest chain is fully recomputed instead of skipped.
335
+ */
336
+ const verifyLane = Effect.fn("Certification.verifyLane")(function* (lane, batchProducers) {
337
+ const store = yield* ConversationStore;
338
+ const ledger = yield* SubmissionLedger;
339
+ const exported = yield* store.export(ConversationExportRequest.make({ conversationId: lane }));
340
+ const rows = /* @__PURE__ */ new Map();
341
+ const nonterminal = yield* Stream.runCollect(ledger.scanNonterminal);
342
+ for (const submission of nonterminal) if (submission.conversationId === lane) rows.set(submission.submissionId, submission);
343
+ const named = /* @__PURE__ */ new Set();
344
+ for (const envelope of exported.records) {
345
+ const payload = envelope.record.payload;
346
+ if (payload._tag === "UserInputRecorded" || payload._tag === "SubmissionSettled" || payload._tag === "AbortRequested") named.add(payload.submissionId);
347
+ }
348
+ for (const submissionId of named) {
349
+ if (rows.has(submissionId)) continue;
350
+ const found = yield* ledger.lookup(SubmissionLookupById.make({ submissionId }));
351
+ if (Option.isSome(found) && found.value.conversationId === lane) rows.set(submissionId, found.value);
352
+ }
353
+ const checkpoint = yield* store.loadCheckpoint(LoadCheckpointRequest.make({ conversationId: lane }));
354
+ return yield* verifyConversationInvariants({
355
+ export: exported,
356
+ submissions: [...rows.values()],
357
+ batchProducers,
358
+ checkpoint: Option.getOrUndefined(checkpoint),
359
+ requireAllSettled: true
360
+ });
361
+ });
362
+ const failureTagOf = (cause) => {
363
+ const failure = Cause.findErrorOption(cause);
364
+ if (Option.isSome(failure)) {
365
+ const error = failure.value;
366
+ if (typeof error === "object" && error !== null && "_tag" in error) return String(error._tag);
367
+ return String(error).slice(0, 256);
368
+ }
369
+ return "defect";
370
+ };
371
+ /** One Tier-2 sweep cell: arm `location` one-shot, drive `scenario`, converge, verify. */
372
+ const runSweepCell = Effect.fn("Certification.runSweepCell")(function* (scenario, location, batchProducers, leaseAdvance) {
373
+ const runtime = yield* DurableAgentRuntime;
374
+ const ledger = yield* SubmissionLedger;
375
+ const control = yield* DurableRuntimeFailpointTestControl;
376
+ const slug = `${scenario}-${location.replaceAll(":", "-")}`;
377
+ const failed = (detail, fired) => CertificationSweepResult.make({
378
+ scenario,
379
+ location,
380
+ failpointFired: fired,
381
+ status: "failed",
382
+ digestChainVerified: false,
383
+ detail: detail.slice(0, 4096)
384
+ });
385
+ const cell = yield* makeCell(scenario, slug);
386
+ const fired = yield* Ref.make(false);
387
+ yield* control.setHandler((hit) => hit !== location ? Effect.void : Ref.getAndSet(fired, true).pipe(Effect.flatMap((already) => already ? Effect.void : Effect.fail(DurableRuntimeFailpointError.make({ location: hit })))));
388
+ let receipts;
389
+ const firstSubmit = yield* Effect.exit(cell.submit);
390
+ if (Exit.isSuccess(firstSubmit)) receipts = firstSubmit.value;
391
+ else {
392
+ const secondSubmit = yield* Effect.exit(cell.submit);
393
+ if (Exit.isFailure(secondSubmit)) {
394
+ yield* control.clear;
395
+ return failed(`submission replay did not recover: ${failureTagOf(secondSubmit.cause)}`, yield* Ref.get(fired));
396
+ }
397
+ receipts = secondSubmit.value;
398
+ }
399
+ const lanes = cell.lanes(receipts);
400
+ const driveLane = (lane) => runtime.processConversationResolved(lane).pipe(Effect.provideService(AgentBindingResolver, cell.resolver));
401
+ const allSettled = Effect.gen(function* () {
402
+ for (const receipt of receipts) {
403
+ const snapshot = yield* ledger.lookup(SubmissionLookupById.make({ submissionId: receipt.submissionId }));
404
+ if (Option.isNone(snapshot) || snapshot.value.state !== "settled") return false;
405
+ }
406
+ return true;
407
+ });
408
+ let converged = false;
409
+ for (let round = 0; round < MAX_REDRIVE_ROUNDS && !converged; round++) {
410
+ yield* TestClock.adjust(leaseAdvance);
411
+ yield* Effect.exit(runtime.runRecovery);
412
+ for (const lane of lanes) yield* Effect.exit(driveLane(lane));
413
+ for (const lane of lanes) {
414
+ const explains = yield* Effect.exit(runtime.explainConversation(lane));
415
+ if (Exit.isFailure(explains)) continue;
416
+ for (const explanation of explains.value) {
417
+ for (const unknown of explanation.evidence.unknownCalls) {
418
+ if (unknown.resolved) continue;
419
+ yield* Effect.exit(runtime.resolveUnknown(UnknownResolutionCommand.make({
420
+ submissionId: explanation.submission.submissionId,
421
+ toolCallId: unknown.toolCallId,
422
+ author: "certification-runner",
423
+ reason: `re-drive after injected fault at ${location}`,
424
+ resolution: ResolutionSafeToRetry.make()
425
+ })));
426
+ }
427
+ for (const pending of explanation.evidence.approvalsPending) {
428
+ if (explanation.evidence.approvalDecisions.some((decision) => decision.toolCallId === pending.toolCallId)) continue;
429
+ yield* Effect.exit(runtime.resolveApproval(ApprovalDecisionCommand.make({
430
+ submissionId: explanation.submission.submissionId,
431
+ toolCallId: pending.toolCallId,
432
+ decision: "approved",
433
+ resolver: "certification-runner",
434
+ reason: `re-drive after injected fault at ${location}`
435
+ })));
436
+ }
437
+ }
438
+ }
439
+ const settled = yield* Effect.exit(allSettled);
440
+ converged = Exit.isSuccess(settled) && settled.value;
441
+ }
442
+ yield* control.clear;
443
+ const wasFired = yield* Ref.get(fired);
444
+ if (!converged) return failed(`did not converge within ${MAX_REDRIVE_ROUNDS} re-drive rounds`, wasFired);
445
+ let digestChainVerified = true;
446
+ const failedChecks = [];
447
+ for (const lane of lanes) {
448
+ const verdict = yield* Effect.exit(verifyLane(lane, batchProducers));
449
+ if (Exit.isFailure(verdict)) return failed(`lane ${lane} could not be verified: ${failureTagOf(verdict.cause)}`, wasFired);
450
+ for (const check of verdict.value.checks) {
451
+ if (check.status === "failed") failedChecks.push(`${lane}:${check.name}${check.detail === void 0 ? "" : ` (${check.detail})`}`);
452
+ if (check.name === "digest-chain" && check.status !== "passed") digestChainVerified = false;
453
+ }
454
+ }
455
+ if (failedChecks.length > 0 || !digestChainVerified) return failed(failedChecks.length > 0 ? `invariant checks failed: ${failedChecks.join("; ")}` : "the digest chain was not fully recomputed", wasFired);
456
+ return CertificationSweepResult.make({
457
+ scenario,
458
+ location,
459
+ failpointFired: wasFired,
460
+ status: wasFired ? "converged" : "not-triggered",
461
+ digestChainVerified
462
+ });
463
+ });
464
+ /**
465
+ * Resolve the Tier-3 record honestly (plan §1): a non-durable reference adapter has no real
466
+ * loss to exercise (`not-applicable`); a supplied lever runs NOW (`exercised`); committed
467
+ * real-loss citations are recorded (`recorded-evidence`); otherwise the certificate says
468
+ * `not-exercised` — a scoped statement, never a silent claim.
469
+ */
470
+ const resolveTierThree = Effect.fn("Certification.resolveTierThree")(function* (durability, options) {
471
+ if (durability === "non-durable") return CertificationTierThreeReport.make({
472
+ status: "not-applicable",
473
+ evidence: [],
474
+ cases: [],
475
+ detail: "the adapter declares non-durable state (reference/conformance adapter); there is no real loss to exercise"
476
+ });
477
+ if (options.crashLever !== void 0) {
478
+ const cases = yield* options.crashLever;
479
+ return CertificationTierThreeReport.make({
480
+ status: "exercised",
481
+ evidence: options.tierThreeEvidence ?? [],
482
+ cases
483
+ });
484
+ }
485
+ if (options.tierThreeEvidence !== void 0 && options.tierThreeEvidence.length > 0) return CertificationTierThreeReport.make({
486
+ status: "recorded-evidence",
487
+ evidence: options.tierThreeEvidence,
488
+ cases: []
489
+ });
490
+ return CertificationTierThreeReport.make({
491
+ status: "not-exercised",
492
+ evidence: [],
493
+ cases: [],
494
+ detail: "no crash lever was supplied and no committed real-loss evidence was cited; Tier 3 is NOT discharged for this adapter"
495
+ });
496
+ });
497
+ const nowUtc = Effect.map(Clock.currentTimeMillis, (millis) => DateTime.toUtc(DateTime.makeUnsafe(millis)));
498
+ /**
499
+ * Certify one durable adapter pair (plan §1, §8 WP2). Runs Tier 2 FIRST over pristine
500
+ * storage (each cell converges to all-settled before the next starts, so the recovery scan
501
+ * never sees foreign leftovers), then Tier 1's port contract cases (whose lanes deliberately
502
+ * end in every nonterminal shape), then records Tier 3. Requires `Crypto.Crypto` and a
503
+ * TestClock-backed environment; the candidate Layers are built exactly once.
504
+ */
505
+ const certifyDurableAdapters = (options) => {
506
+ const batchProducers = /* @__PURE__ */ new Map();
507
+ const capturingStore = Layer.effect(ConversationStore)(Effect.gen(function* () {
508
+ const inner = yield* ConversationStore;
509
+ return ConversationStore.of({
510
+ ...inner,
511
+ append: (request) => Effect.sync(() => {
512
+ batchProducers.set(request.batch.batchId, request.batch.producerId);
513
+ }).pipe(Effect.andThen(inner.append(request)))
514
+ });
515
+ })).pipe(Layer.provide(options.conversationStore));
516
+ const support = Layer.mergeAll(options.submissionLedger, capturingStore, options.wakeScheduler ?? WakeScheduler.layerNoop, DurableRuntimeFailpoint.layerTest, ToolReconciler.uncertain, DurableRuntimeConfig.layer({
517
+ deploymentId: Schema.decodeSync(DeploymentId)("deployment-certification"),
518
+ producerId: Schema.decodeSync(ProducerId)("producer-certification"),
519
+ settlementPollInterval: Duration.millis(50),
520
+ leaseRenewalInterval: Duration.seconds(5),
521
+ abortPollInterval: Duration.millis(50)
522
+ }));
523
+ const environment = DurableAgentRuntime.layer.pipe(Layer.provideMerge(support));
524
+ const leaseAdvance = Duration.millis(Duration.toMillis(options.ownershipLeaseDuration ?? DEFAULT_OWNERSHIP_LEASE_DURATION) + 1e3);
525
+ return Effect.gen(function* () {
526
+ const ledger = yield* SubmissionLedger;
527
+ const tier2 = [];
528
+ for (const scenario of CERTIFICATION_SCENARIOS) for (const location of DurableRuntimeFailpointLocation.literals) tier2.push(yield* runSweepCell(scenario, location, batchProducers, leaseAdvance));
529
+ const tier1 = yield* certifyPorts();
530
+ const capabilities = yield* ledger.capabilities;
531
+ const tier3 = yield* resolveTierThree(capabilities.durability, options);
532
+ const generatedAt = yield* nowUtc;
533
+ const ok = tier1.every((result) => result.status === "passed") && tier2.every((result) => result.status !== "failed") && tier3.cases.every((result) => result.status === "passed");
534
+ return CertificationReport.make({
535
+ format: "effect-agent/certification@1",
536
+ adapter: CertifiedAdapterIdentity.make({
537
+ name: options.adapter.name,
538
+ ...options.adapter.version === void 0 ? {} : { version: options.adapter.version },
539
+ durability: capabilities.durability
540
+ }),
541
+ generatedAt,
542
+ tier1,
543
+ tier2,
544
+ tier3,
545
+ ok
546
+ });
547
+ }).pipe(Effect.provide(environment));
548
+ };
549
+ //#endregion
550
+ //#region src/chaos.ts
551
+ /**
552
+ * P7 WP4 chaos machinery (plan §5): a Schema-first `ChaosPlan`, a seeded generator over
553
+ * `effect/testing/FastCheck` (already inside the pinned Effect — no new dependency), and a
554
+ * deterministic runner that drives the durable coordinator over whatever adapter pair the test
555
+ * provides. Every plan ends in the SAME claims the crash matrices make:
556
+ *
557
+ * 1. `verifyConversationInvariants` in convergence mode over every touched Conversation (the
558
+ * shared WP1 checker — one set of claims for admin verify, certification, chaos, and soak);
559
+ * 2. `scanObligations` returning ZERO entries (everything settled; nothing invisibly stuck);
560
+ * 3. supplier non-fabrication wherever the deterministic desk was in play (durability §10: no
561
+ * canonical Tool success exists that the external store did not actually produce).
562
+ *
563
+ * Replay contract: the memory/SQLite chaos tests derive every plan from one root seed
564
+ * (`CHAOS_SEED` env override; see `chaosSeedFromEnv`) and print that seed plus the failing
565
+ * plan's own seed in the failure output, so any red run is replayable byte-for-byte.
566
+ */
567
+ /** The six durable scenario flavors a chaos lane can exercise (plan §5). */
568
+ const ChaosScenarioKind = Schema.Literals([
569
+ "plain",
570
+ "uncertain-tool",
571
+ "durable-steps",
572
+ "approval",
573
+ "join",
574
+ "delegation"
575
+ ]);
576
+ const LaneIndex = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(7));
577
+ /** One Submission of a plan: which lane it queues into and that lane's scenario flavor. */
578
+ var ChaosSubmissionSpec = class extends Schema.Class("@effect-agent/testing/ChaosSubmissionSpec")({
579
+ lane: LaneIndex,
580
+ /** The lane's flavor; the FIRST spec of a lane fixes the lane's agent. */
581
+ kind: ChaosScenarioKind
582
+ }) {};
583
+ /** How the runner resolves a durable Unknown Outcome it encounters (DUR-017 driver). */
584
+ const ChaosResolutionKind = Schema.Literals([
585
+ "never-happened",
586
+ "completed-from-supplier",
587
+ "abort-submission"
588
+ ]);
589
+ const ChaosApprovalDecision = Schema.Literals(["approved", "denied"]);
590
+ const BoundedAdapterArm = Schema.String.check(Schema.isMaxLength(128));
591
+ /**
592
+ * One seeded chaos plan (plan §5): the full fault schedule is data, so a failing run replays
593
+ * from the plan alone. `failpointArms` are coordinator locations; `adapterArms` are
594
+ * adapter-owned location names the adapter test validates (the memory runner has none).
595
+ */
596
+ var ChaosPlan = class extends Schema.Class("@effect-agent/testing/ChaosPlan")({
597
+ /** Identifies this plan in failure output; derived from the root seed plus the plan index. */
598
+ seed: Schema.Int,
599
+ /** Lane count; submissions address lanes `0..lanes-1`. */
600
+ lanes: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(8)),
601
+ submissions: Schema.NonEmptyArray(ChaosSubmissionSpec),
602
+ /** Coordinator failpoint arms, consumed one per round (each fails every hit that round). */
603
+ failpointArms: Schema.Array(DurableRuntimeFailpointLocation),
604
+ /** Adapter-owned failpoint arms (e.g. SQLite `ledger:*`/`append:*` locations). */
605
+ adapterArms: Schema.Array(BoundedAdapterArm),
606
+ /** Flattened submission indices to abort mid-plan (modulo the submission count). */
607
+ abortInjections: Schema.Array(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
608
+ /** Resolution choices for Unknown Outcomes, indexed deterministically per open call. */
609
+ resolutionInjections: Schema.Array(ChaosResolutionKind),
610
+ /** Approval decisions for suspended approval lanes, indexed deterministically per call. */
611
+ approvalDecisions: Schema.Array(ChaosApprovalDecision)
612
+ }) {};
613
+ /** Per-lane verification result inside a plan report. */
614
+ var ChaosLaneReport = class extends Schema.Class("@effect-agent/testing/ChaosLaneReport")({
615
+ conversationId: ConversationId,
616
+ kind: ChaosScenarioKind,
617
+ submissionCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
618
+ /** Verdict of `verifyConversationInvariants` in convergence mode. */
619
+ verified: Schema.Boolean
620
+ }) {};
621
+ /** The Schema-first outcome of one executed chaos plan. */
622
+ var ChaosPlanReport = class extends Schema.Class("@effect-agent/testing/ChaosPlanReport")({
623
+ seed: Schema.Int,
624
+ rounds: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
625
+ lanes: Schema.Array(ChaosLaneReport),
626
+ /** `scanObligations` entries after convergence — MUST be zero. */
627
+ openObligations: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))
628
+ }) {};
629
+ /** Typed convergence/verification failure of one chaos plan (never a bare defect). */
630
+ var ChaosConvergenceFailure = class extends Schema.TaggedErrorClass()("ChaosConvergenceFailure", {
631
+ seed: Schema.Int,
632
+ message: Schema.String.check(Schema.isMaxLength(16384))
633
+ }) {};
634
+ /** Default root seed for chaos suites; override with the `CHAOS_SEED` environment variable. */
635
+ const DEFAULT_CHAOS_SEED = 20260813;
636
+ /** The root seed for this run: `CHAOS_SEED` when set to an integer, the default otherwise. */
637
+ const chaosSeedFromEnv = (env) => {
638
+ const raw = env["CHAOS_SEED"];
639
+ if (raw === void 0 || raw === "") return DEFAULT_CHAOS_SEED;
640
+ const parsed = Number.parseInt(raw, 10);
641
+ return Number.isSafeInteger(parsed) ? parsed : DEFAULT_CHAOS_SEED;
642
+ };
643
+ const laneArbitrary = FastCheck.constantFrom("plain", "uncertain-tool", "durable-steps", "approval", "join", "delegation").chain((kind) => kind === "join" ? FastCheck.integer({
644
+ min: 2,
645
+ max: 3
646
+ }).map((depth) => ({
647
+ kind,
648
+ depth
649
+ })) : kind === "plain" ? FastCheck.integer({
650
+ min: 1,
651
+ max: 2
652
+ }).map((depth) => ({
653
+ kind,
654
+ depth
655
+ })) : FastCheck.constant({
656
+ kind,
657
+ depth: 1
658
+ }));
659
+ const planShapeArbitrary = (adapterArms) => FastCheck.record({
660
+ lanes: FastCheck.array(laneArbitrary, {
661
+ minLength: 1,
662
+ maxLength: 3
663
+ }),
664
+ failpointArms: FastCheck.uniqueArray(FastCheck.constantFrom(...DurableRuntimeFailpointLocation.literals), { maxLength: 3 }),
665
+ adapterArms: adapterArms.length === 0 ? FastCheck.constant([]) : FastCheck.uniqueArray(FastCheck.constantFrom(...adapterArms), { maxLength: 2 }),
666
+ abortInjections: FastCheck.uniqueArray(FastCheck.integer({
667
+ min: 0,
668
+ max: 15
669
+ }), { maxLength: 2 }),
670
+ resolutionInjections: FastCheck.array(FastCheck.constantFrom("never-happened", "completed-from-supplier", "abort-submission"), { maxLength: 4 }),
671
+ approvalDecisions: FastCheck.array(FastCheck.constantFrom("approved", "denied"), { maxLength: 2 })
672
+ }).map((shape) => {
673
+ const [first, ...rest] = shape.lanes.flatMap((lane, index) => Array.from({ length: lane.depth }, () => ChaosSubmissionSpec.make({
674
+ lane: index,
675
+ kind: lane.kind
676
+ })));
677
+ if (first === void 0) throw new Error("chaos generator produced an empty plan");
678
+ return {
679
+ lanes: shape.lanes.length,
680
+ submissions: [first, ...rest],
681
+ failpointArms: shape.failpointArms,
682
+ adapterArms: shape.adapterArms,
683
+ abortInjections: shape.abortInjections,
684
+ resolutionInjections: shape.resolutionInjections,
685
+ approvalDecisions: shape.approvalDecisions
686
+ };
687
+ });
688
+ /**
689
+ * Derive `count` chaos plans deterministically from one root seed. The same
690
+ * `{seed, count, adapterArms}` triple always yields byte-identical plans, so a failure line
691
+ * `CHAOS_SEED=<seed>` replays the exact schedule.
692
+ */
693
+ const generateChaosPlans = (options) => {
694
+ return FastCheck.sample(planShapeArbitrary(options.adapterArms ?? []), {
695
+ seed: options.seed,
696
+ numRuns: options.count
697
+ }).map((shape, index) => ChaosPlan.make({
698
+ ...shape,
699
+ seed: Math.imul(options.seed, 31) + index | 0
700
+ }));
701
+ };
702
+ /** Deterministic PRNG for the runner's small ordering choices (lane drive order). */
703
+ const mulberry32 = (seed) => {
704
+ let state = seed | 0;
705
+ return () => {
706
+ state = state + 1831565813 | 0;
707
+ let t = Math.imul(state ^ state >>> 15, 1 | state);
708
+ t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
709
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
710
+ };
711
+ };
712
+ const usage$1 = {
713
+ inputTokens: {},
714
+ outputTokens: {}
715
+ };
716
+ const finalParts = (text) => [
717
+ {
718
+ type: "text-start",
719
+ id: "answer"
720
+ },
721
+ {
722
+ type: "text-delta",
723
+ id: "answer",
724
+ delta: text
725
+ },
726
+ {
727
+ type: "text-end",
728
+ id: "answer"
729
+ },
730
+ {
731
+ type: "finish",
732
+ reason: "stop",
733
+ usage: usage$1
734
+ }
735
+ ];
736
+ const toolTurn = (...calls) => [...calls, {
737
+ type: "finish",
738
+ reason: "tool-calls",
739
+ usage: usage$1
740
+ }];
741
+ const toolCallPart = (id, name, params) => ({
742
+ type: "tool-call",
743
+ id,
744
+ name,
745
+ params,
746
+ providerExecuted: false
747
+ });
748
+ /**
749
+ * Prompt-shaped scripted model: the response depends ONLY on the request prompt, so it stays
750
+ * deterministic across Attempt re-invocations, batch resumes, and joined steering — no counter
751
+ * to drift when chaos re-enters a Turn.
752
+ */
753
+ const promptScriptedModel = (label, script) => Model.make("scripted", label, Layer.effect(LanguageModel.LanguageModel, LanguageModel.make({
754
+ generateText: () => Effect.succeed([]),
755
+ streamText: (request) => Stream.fromIterable(script(request.prompt))
756
+ })));
757
+ const lastRole = (prompt) => prompt.content.at(-1)?.role;
758
+ const policy = AgentPolicy.make({
759
+ maxTurns: 3,
760
+ maxToolCalls: 4,
761
+ maxDuration: "30 seconds",
762
+ toolConcurrency: 2
763
+ });
764
+ const PlainInput = Schema.Struct({ question: Schema.String });
765
+ const PlainOutput = Schema.Struct({ answer: Schema.String });
766
+ const plainDefinition = Agent.define("chaos-plain", {
767
+ input: PlainInput,
768
+ output: PlainOutput,
769
+ instructions: "Answer as JSON.",
770
+ toolkit: Toolkit.empty,
771
+ policy
772
+ });
773
+ /** Unannotated → fail-closed `uncertain`: enters the prepared/settled protocol (DUR-009). */
774
+ const BookUncertain = Tool.make("book", {
775
+ parameters: Schema.Struct({ ref: Schema.String }),
776
+ success: Schema.Struct({ confirmation: Schema.String })
777
+ });
778
+ const bookTools = Toolkit.make(BookUncertain);
779
+ const bookDefinition = Agent.define("chaos-book", {
780
+ input: PlainInput,
781
+ output: PlainOutput,
782
+ instructions: "Book it.",
783
+ toolkit: bookTools,
784
+ policy
785
+ });
786
+ const BookApproval = Tool.make("book", {
787
+ parameters: Schema.Struct({ ref: Schema.String }),
788
+ success: Schema.Struct({ confirmation: Schema.String }),
789
+ needsApproval: true
790
+ });
791
+ const approvalTools = Toolkit.make(BookApproval);
792
+ const approvalDefinition = Agent.define("chaos-approval", {
793
+ input: PlainInput,
794
+ output: PlainOutput,
795
+ instructions: "Book after approval.",
796
+ toolkit: approvalTools,
797
+ policy
798
+ });
799
+ const Itinerary$1 = Tool.make("itinerary", {
800
+ parameters: Schema.Struct({ ref: Schema.String }),
801
+ success: Schema.Struct({ state: Schema.String }),
802
+ failure: DurableStepError,
803
+ dependencies: [DurableStep]
804
+ }).annotate(ToolExecutionClass, "uncertain");
805
+ const itineraryTools = Toolkit.make(Itinerary$1);
806
+ const itineraryDefinition = Agent.define("chaos-itinerary", {
807
+ input: PlainInput,
808
+ output: PlainOutput,
809
+ instructions: "Reserve the itinerary.",
810
+ toolkit: itineraryTools,
811
+ policy
812
+ });
813
+ const childDefinition = Agent.define("chaos-child", {
814
+ input: PlainInput,
815
+ output: PlainOutput,
816
+ instructions: "Answer as JSON.",
817
+ toolkit: Toolkit.empty,
818
+ policy: AgentPolicy.make({
819
+ maxTurns: 2,
820
+ maxToolCalls: 1,
821
+ maxDuration: "30 seconds",
822
+ toolConcurrency: 1
823
+ })
824
+ });
825
+ var ChaosDelegationFailed = class extends Schema.TaggedErrorClass()("ChaosDelegationFailed", { childErrorTag: Schema.String }) {};
826
+ const chaosDelegation = Subagent.define("delegate_chaos", {
827
+ description: "Delegate one bounded chaos question.",
828
+ target: childDefinition,
829
+ parameters: Schema.Struct({ topic: Schema.String }),
830
+ success: Schema.Struct({ summary: Schema.String }),
831
+ failure: ChaosDelegationFailed,
832
+ prepareInput: ({ topic }) => Effect.succeed({ question: `chaos:${topic}` }),
833
+ projectResult: (output) => Effect.succeed({ summary: `finding:${output.answer}` }),
834
+ policy: SubagentPolicy.make({
835
+ maxChildren: 2,
836
+ maxConcurrency: 2,
837
+ maxTurns: 4,
838
+ maxToolCalls: 4,
839
+ maxDuration: "30 seconds"
840
+ })
841
+ });
842
+ const coordinatorDefinition = Agent.define("chaos-coordinator", {
843
+ input: Schema.Struct({ mission: Schema.String }),
844
+ output: Schema.Struct({ report: Schema.String }),
845
+ instructions: "Delegate, then report as JSON.",
846
+ toolkit: Toolkit.make(chaosDelegation.tool),
847
+ policy
848
+ });
849
+ const DELEGATE_CALL_ID = "chaos-delegate-1";
850
+ const HEX = "0123456789abcdef";
851
+ const decodeDigest = Schema.decodeSync(Digest);
852
+ const laneDigests = (lane) => {
853
+ const digest = decodeDigest(HEX[lane % 8].repeat(64));
854
+ return DefinitionDigests.make({
855
+ agent: digest,
856
+ model: digest,
857
+ tools: digest
858
+ });
859
+ };
860
+ const childDigestStrings = (lane) => {
861
+ const char = HEX[8 + lane % 8];
862
+ return {
863
+ agent: char.repeat(64),
864
+ model: char.repeat(64),
865
+ tools: char.repeat(64)
866
+ };
867
+ };
868
+ const childLaneDigests = (lane) => {
869
+ const strings = childDigestStrings(lane);
870
+ return DefinitionDigests.make({
871
+ agent: decodeDigest(strings.agent),
872
+ model: decodeDigest(strings.model),
873
+ tools: decodeDigest(strings.tools)
874
+ });
875
+ };
876
+ const CHAOS_PRINCIPAL = Schema.decodeSync(Principal)("principal-chaos");
877
+ const decodeConversationId = Schema.decodeSync(ConversationId);
878
+ const decodeIdempotencyKey = Schema.decodeSync(IdempotencyKey);
879
+ const decodeToolCallId = Schema.decodeSync(ToolCallId);
880
+ const decodeRunId = Schema.decodeSync(RunId);
881
+ const decodeTurnId = Schema.decodeSync(TurnId);
882
+ /** Fixture-only identity source consumed by the delegation Layer's ephemeral capture. */
883
+ const chaosIdentifiers = Layer.effect(IdGenerator, Effect.gen(function* () {
884
+ const counter = yield* Ref.make(0);
885
+ const next = (decode, prefix) => Ref.getAndUpdate(counter, (value) => value + 1).pipe(Effect.map((value) => decode(`${prefix}-${value}`)));
886
+ return {
887
+ nextConversationId: next(decodeConversationId, "chaos-fixture-conversation"),
888
+ nextRunId: next(decodeRunId, "chaos-fixture-run"),
889
+ nextTurnId: next(decodeTurnId, "chaos-fixture-turn")
890
+ };
891
+ }));
892
+ const delegationSupport = Layer.mergeAll(SubagentReservationsMemoryLive, chaosIdentifiers);
893
+ const makeChaosDesk = Effect.gen(function* () {
894
+ const produced = yield* Ref.make(/* @__PURE__ */ new Set());
895
+ return {
896
+ produced: Ref.get(produced),
897
+ record: (value) => Ref.update(produced, (current) => new Set(current).add(value))
898
+ };
899
+ });
900
+ const bookConfirmation = (ref) => `confirmed-${ref}`;
901
+ const flightValue = (ref) => `flight-${ref}`;
902
+ const lodgingValue = (ref) => `lodging-${ref}`;
903
+ /** Success → Some; typed failure → None (chaos tolerates it); defect → rethrown loudly. */
904
+ const tolerateTyped = (effect) => effect.pipe(Effect.exit, Effect.flatMap((exit) => {
905
+ if (Exit.isSuccess(exit)) return Effect.succeed(Option.some(exit.value));
906
+ if (Option.isSome(Cause.findErrorOption(exit.cause))) return Effect.succeed(Option.none());
907
+ return Effect.die(/* @__PURE__ */ new Error(`chaos step died: ${Cause.pretty(exit.cause)}`));
908
+ }));
909
+ const scriptFor = (kind, ref) => {
910
+ switch (kind) {
911
+ case "plain":
912
+ case "join": return () => finalParts("{\"answer\":\"chaos\"}");
913
+ case "uncertain-tool":
914
+ case "approval": return (prompt) => lastRole(prompt) === "tool" ? finalParts("{\"answer\":\"booked\"}") : toolTurn(toolCallPart(`book-${ref}`, "book", { ref }));
915
+ case "durable-steps": return (prompt) => lastRole(prompt) === "tool" ? finalParts("{\"answer\":\"reserved\"}") : toolTurn(toolCallPart(`itinerary-${ref}`, "itinerary", { ref }));
916
+ case "delegation": return (prompt) => lastRole(prompt) === "tool" ? finalParts("{\"report\":\"done\"}") : toolTurn(toolCallPart(DELEGATE_CALL_ID, "delegate_chaos", { topic: ref }));
917
+ }
918
+ };
919
+ const makeLaneFixture = Effect.fn("Chaos.makeLaneFixture")(function* (plan, laneIndex, kind, submissionIndexes, desk) {
920
+ const runtime = yield* DurableAgentRuntime;
921
+ const conversationId = decodeConversationId(`chaos-${plan.seed}-lane-${laneIndex}`);
922
+ const ref = `ref-l${laneIndex}`;
923
+ const script = scriptFor(kind, ref);
924
+ const model = promptScriptedModel(`chaos-${kind}-${laneIndex}`, script);
925
+ const digests = laneDigests(laneIndex);
926
+ const submitOptionsFor = (flatIndex) => ({
927
+ conversationId,
928
+ principal: CHAOS_PRINCIPAL,
929
+ idempotencyKey: decodeIdempotencyKey(`chaos-${plan.seed}-s${flatIndex}`),
930
+ definitions: digests
931
+ });
932
+ const bookToolLayerFor = (tools) => tools.toLayer({ book: ({ ref: called }) => desk.record(bookConfirmation(called)).pipe(Effect.as({ confirmation: bookConfirmation(called) })) });
933
+ const plainLaneFixture = (deskInPlay, drive, submitOne) => ({
934
+ index: laneIndex,
935
+ kind,
936
+ conversationId,
937
+ ref,
938
+ deskInPlay,
939
+ submissionIndexes,
940
+ submitOne,
941
+ drives: () => [drive],
942
+ childConversationOf: () => void 0
943
+ });
944
+ switch (kind) {
945
+ case "plain":
946
+ case "join": {
947
+ const agent = Agent.withModel(plainDefinition, model);
948
+ return plainLaneFixture(false, runtime.processConversation(agent, conversationId), (flatIndex) => runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)));
949
+ }
950
+ case "uncertain-tool": {
951
+ const agent = Agent.withModel(bookDefinition, model);
952
+ return plainLaneFixture(true, runtime.processConversation(agent, conversationId).pipe(Effect.provide(bookToolLayerFor(bookTools))), (flatIndex) => runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)));
953
+ }
954
+ case "approval": {
955
+ const agent = Agent.withModel(approvalDefinition, model);
956
+ return plainLaneFixture(true, runtime.processConversation(agent, conversationId).pipe(Effect.provide(bookToolLayerFor(approvalTools))), (flatIndex) => runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)));
957
+ }
958
+ case "durable-steps": {
959
+ const agent = Agent.withModel(itineraryDefinition, model);
960
+ const toolLayer = itineraryTools.toLayer({ itinerary: ({ ref: called }) => Effect.gen(function* () {
961
+ const step = yield* DurableStep;
962
+ return { state: `${yield* step.do("reserve-flight", Schema.String, desk.record(flightValue(called)).pipe(Effect.as(flightValue(called))))}+${yield* step.do("reserve-lodging", Schema.String, desk.record(lodgingValue(called)).pipe(Effect.as(lodgingValue(called))))}` };
963
+ }) });
964
+ return plainLaneFixture(true, runtime.processConversation(agent, conversationId).pipe(Effect.provide(toolLayer)), (flatIndex) => runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)));
965
+ }
966
+ case "delegation": {
967
+ const parentBinding = Agent.withModel(coordinatorDefinition, model);
968
+ const childModel = promptScriptedModel(`chaos-child-${laneIndex}`, () => finalParts("{\"answer\":\"child\"}"));
969
+ const childBinding = Agent.withModel(childDefinition, childModel);
970
+ const delegationLayer = SubagentRuntime.layer(chaosDelegation, childBinding, {
971
+ mapChildFailure: (failure) => ChaosDelegationFailed.make({ childErrorTag: failure._tag }),
972
+ durable: { targetDigests: childDigestStrings(laneIndex) }
973
+ }).pipe(Layer.provide(delegationSupport));
974
+ const parentResolved = yield* DurableWorkerBinding.make(parentBinding, digests).pipe(Effect.provide(delegationLayer));
975
+ const childResolved = yield* DurableWorkerBinding.make(childBinding, childLaneDigests(laneIndex));
976
+ const resolver = AgentBindingResolver.fromBindings([parentResolved, childResolved]);
977
+ const driveResolved = (conversation) => runtime.processConversationResolved(conversation).pipe(Effect.provideService(AgentBindingResolver, resolver));
978
+ return {
979
+ index: laneIndex,
980
+ kind,
981
+ conversationId,
982
+ ref,
983
+ deskInPlay: false,
984
+ submissionIndexes,
985
+ submitOne: (flatIndex) => runtime.submit({ definition: {
986
+ id: coordinatorDefinition.id,
987
+ input: coordinatorDefinition.input
988
+ } }, { mission: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)),
989
+ drives: (firstReceipt) => {
990
+ const drives = [driveResolved(conversationId)];
991
+ if (firstReceipt !== void 0) drives.push(driveResolved(childConversationIdFor(firstReceipt.submissionId, decodeToolCallId(DELEGATE_CALL_ID))));
992
+ return drives;
993
+ },
994
+ childConversationOf: (firstReceipt) => childConversationIdFor(firstReceipt.submissionId, decodeToolCallId(DELEGATE_CALL_ID))
995
+ };
996
+ }
997
+ }
998
+ });
999
+ /** Stable per-call index into an injection list (identical across resolution passes). */
1000
+ const injectionIndex = (submissionFlatIndex, callId, length) => {
1001
+ let hash = submissionFlatIndex + 1;
1002
+ for (const char of callId) hash = Math.imul(hash, 31) + char.charCodeAt(0) | 0;
1003
+ return (hash % length + length) % length;
1004
+ };
1005
+ const resolutionFor = (kind, toolName, ref, produced) => {
1006
+ switch (kind) {
1007
+ case "abort-submission": return ResolutionAbortSubmission.make();
1008
+ case "completed-from-supplier":
1009
+ if (toolName === "book" && produced.has(bookConfirmation(ref))) return ResolutionCompletedWithResult.make({
1010
+ result: { confirmation: bookConfirmation(ref) },
1011
+ isFailure: false
1012
+ });
1013
+ if (toolName === "itinerary" && produced.has(flightValue(ref)) && produced.has(lodgingValue(ref))) return ResolutionCompletedWithResult.make({
1014
+ result: { state: `${flightValue(ref)}+${lodgingValue(ref)}` },
1015
+ isFailure: false
1016
+ });
1017
+ return ResolutionNeverHappened.make();
1018
+ case "never-happened": return ResolutionNeverHappened.make();
1019
+ }
1020
+ };
1021
+ /** Drive one DUR-017 pass: resolve Unknown Outcomes and pending approvals from the plan. */
1022
+ const resolutionPass = Effect.fn("Chaos.resolutionPass")(function* (plan, states, desk) {
1023
+ const runtime = yield* DurableAgentRuntime;
1024
+ const ledger = yield* SubmissionLedger;
1025
+ const produced = yield* desk.produced;
1026
+ const nonterminal = yield* tolerateTyped(Stream.runCollect(ledger.scanNonterminal));
1027
+ if (Option.isNone(nonterminal)) return;
1028
+ const byId = /* @__PURE__ */ new Map();
1029
+ for (const state of states) if (state.receipt !== void 0) byId.set(state.receipt.submissionId, state);
1030
+ for (const row of nonterminal.value) {
1031
+ if (row.state !== "unknown" && row.state !== "suspended") continue;
1032
+ const state = byId.get(row.submissionId);
1033
+ const explanation = yield* tolerateTyped(runtime.explain(row.submissionId));
1034
+ if (Option.isNone(explanation)) continue;
1035
+ const flatIndex = state?.flatIndex ?? 0;
1036
+ const ref = state?.lane.ref ?? "ref-child";
1037
+ if (row.state === "unknown") for (const call of explanation.value.evidence.unknownCalls) {
1038
+ if (call.resolved) continue;
1039
+ const kind = plan.resolutionInjections.length === 0 ? "never-happened" : plan.resolutionInjections[injectionIndex(flatIndex, call.toolCallId, plan.resolutionInjections.length)];
1040
+ yield* tolerateTyped(runtime.resolveUnknown(UnknownResolutionCommand.make({
1041
+ submissionId: row.submissionId,
1042
+ toolCallId: call.toolCallId,
1043
+ author: "chaos-runner",
1044
+ reason: `chaos plan ${plan.seed} resolution (${kind})`,
1045
+ resolution: resolutionFor(kind, call.toolName, ref, produced)
1046
+ })));
1047
+ }
1048
+ else for (const pending of explanation.value.evidence.approvalsPending) {
1049
+ const decision = plan.approvalDecisions.length === 0 ? "approved" : plan.approvalDecisions[injectionIndex(flatIndex, pending.toolCallId, plan.approvalDecisions.length)];
1050
+ yield* tolerateTyped(runtime.resolveApproval(ApprovalDecisionCommand.make({
1051
+ submissionId: row.submissionId,
1052
+ toolCallId: pending.toolCallId,
1053
+ decision,
1054
+ resolver: "chaos-runner",
1055
+ reason: `chaos plan ${plan.seed} approval (${decision})`
1056
+ })));
1057
+ }
1058
+ }
1059
+ });
1060
+ const submissionIdsNamedBy = (records) => {
1061
+ const named = /* @__PURE__ */ new Set();
1062
+ for (const envelope of records) {
1063
+ const payload = envelope.record.payload;
1064
+ if (payload._tag === "UserInputRecorded" || payload._tag === "SubmissionSettled" || payload._tag === "AbortRequested") named.add(payload.submissionId);
1065
+ }
1066
+ return named;
1067
+ };
1068
+ /**
1069
+ * The final non-fabrication sweep (durability §10): every canonical Tool success recorded on a
1070
+ * desk-backed lane must be a value the desk actually produced.
1071
+ */
1072
+ const BookResult = Schema.Struct({ confirmation: Schema.String });
1073
+ const ItineraryResult = Schema.Struct({ state: Schema.String });
1074
+ const decodeBookResult = Schema.decodeUnknownOption(BookResult);
1075
+ const decodeItineraryResult = Schema.decodeUnknownOption(ItineraryResult);
1076
+ const decodeStepOutput = Schema.decodeUnknownOption(Schema.String);
1077
+ const assertNoFabrication = (plan, records, produced) => {
1078
+ const fabricated = [];
1079
+ const requireProduced = (value, label) => {
1080
+ if (!produced.has(value)) fabricated.push(`${label} "${value}"`);
1081
+ };
1082
+ for (const envelope of records) {
1083
+ const payload = envelope.record.payload;
1084
+ if (payload._tag === "ToolCallSettled" && !payload.isFailure) {
1085
+ if (payload.toolName === "book") {
1086
+ const result = decodeBookResult(payload.result);
1087
+ if (Option.isSome(result)) requireProduced(result.value.confirmation, "book result");
1088
+ }
1089
+ if (payload.toolName === "itinerary") {
1090
+ const result = decodeItineraryResult(payload.result);
1091
+ if (Option.isSome(result)) for (const part of result.value.state.split("+")) requireProduced(part, "itinerary step result");
1092
+ }
1093
+ }
1094
+ if (payload._tag === "ToolStepSettled") {
1095
+ const output = decodeStepOutput(payload.output);
1096
+ if (Option.isSome(output)) requireProduced(output.value, "step output");
1097
+ }
1098
+ }
1099
+ return fabricated.length === 0 ? Effect.void : Effect.fail(ChaosConvergenceFailure.make({
1100
+ seed: plan.seed,
1101
+ message: `fabricated Tool results absent from the desk: ${fabricated.join(", ")}`
1102
+ }));
1103
+ };
1104
+ /**
1105
+ * Execute one chaos plan against whatever adapters the ambient Layer provides and end in the
1106
+ * shared invariant claims. Deterministic: same plan + same adapters → same schedule.
1107
+ */
1108
+ const runChaosPlan = Effect.fn("Chaos.runChaosPlan")(function* (plan, options) {
1109
+ const runtime = yield* DurableAgentRuntime;
1110
+ const ledger = yield* SubmissionLedger;
1111
+ const store = yield* ConversationStore;
1112
+ const config = yield* DurableRuntimeConfig;
1113
+ const failpoints = yield* DurableRuntimeFailpointTestControl;
1114
+ const random = mulberry32(plan.seed);
1115
+ const desk = yield* makeChaosDesk;
1116
+ const laneKinds = /* @__PURE__ */ new Map();
1117
+ const laneSubmissions = /* @__PURE__ */ new Map();
1118
+ plan.submissions.forEach((spec, flatIndex) => {
1119
+ const lane = spec.lane % plan.lanes;
1120
+ if (!laneKinds.has(lane)) laneKinds.set(lane, spec.kind);
1121
+ const list = laneSubmissions.get(lane) ?? [];
1122
+ list.push(flatIndex);
1123
+ laneSubmissions.set(lane, list);
1124
+ });
1125
+ const lanes = [];
1126
+ for (const [lane, kind] of laneKinds) lanes.push(yield* makeLaneFixture(plan, lane, kind, laneSubmissions.get(lane) ?? [], desk));
1127
+ const states = plan.submissions.map((spec, flatIndex) => ({
1128
+ flatIndex,
1129
+ lane: lanes.find((fixture) => fixture.index === spec.lane % plan.lanes),
1130
+ receipt: void 0
1131
+ }));
1132
+ const appliedAborts = /* @__PURE__ */ new Set();
1133
+ const armQueue = [...plan.failpointArms.map((location) => ({
1134
+ family: "coordinator",
1135
+ location
1136
+ })), ...plan.adapterArms.map((location) => ({
1137
+ family: "adapter",
1138
+ location
1139
+ }))];
1140
+ const allSettled = Effect.gen(function* () {
1141
+ if (states.some((state) => state.receipt === void 0)) return false;
1142
+ const nonterminal = yield* tolerateTyped(Stream.runCollect(ledger.scanNonterminal));
1143
+ return Option.isSome(nonterminal) && Array.from(nonterminal.value).length === 0;
1144
+ });
1145
+ const maxRounds = armQueue.length + states.length * 2 + 12;
1146
+ let rounds = 0;
1147
+ let converged = false;
1148
+ for (let round = 0; round < maxRounds; round++) {
1149
+ rounds = round + 1;
1150
+ const arm = armQueue[round];
1151
+ if (arm?.family === "coordinator") {
1152
+ const location = arm.location;
1153
+ yield* failpoints.setHandler((hit) => hit === location ? Effect.fail(DurableRuntimeFailpointError.make({ location: hit })) : Effect.void);
1154
+ } else if (arm?.family === "adapter" && options?.adapterFailpoints !== void 0) yield* options.adapterFailpoints.arm(arm.location);
1155
+ for (const state of states) {
1156
+ if (state.receipt !== void 0) continue;
1157
+ const receipt = yield* tolerateTyped(state.lane.submitOne(state.flatIndex));
1158
+ if (Option.isSome(receipt)) state.receipt = receipt.value;
1159
+ }
1160
+ const order = [...lanes].sort(() => random() - .5);
1161
+ for (const lane of order) {
1162
+ const firstFlat = lane.submissionIndexes[0];
1163
+ const firstReceipt = firstFlat === void 0 ? void 0 : states[firstFlat]?.receipt;
1164
+ for (const drive of lane.drives(firstReceipt)) yield* tolerateTyped(drive);
1165
+ }
1166
+ if (round >= 1) for (const rawIndex of plan.abortInjections) {
1167
+ const index = rawIndex % states.length;
1168
+ if (appliedAborts.has(index)) continue;
1169
+ const receipt = states[index]?.receipt;
1170
+ if (receipt === void 0) continue;
1171
+ appliedAborts.add(index);
1172
+ yield* tolerateTyped(runtime.abort(AbortCommand.make({
1173
+ submissionId: receipt.submissionId,
1174
+ author: "chaos-runner",
1175
+ reason: `chaos plan ${plan.seed} abort injection`
1176
+ })));
1177
+ }
1178
+ yield* resolutionPass(plan, states, desk);
1179
+ yield* failpoints.clear;
1180
+ if (options?.adapterFailpoints !== void 0) yield* options.adapterFailpoints.clear;
1181
+ yield* tolerateTyped(runtime.runRecovery);
1182
+ yield* resolutionPass(plan, states, desk);
1183
+ if (yield* allSettled) {
1184
+ converged = true;
1185
+ break;
1186
+ }
1187
+ if (options?.betweenRounds !== void 0) yield* options.betweenRounds;
1188
+ }
1189
+ if (!converged) {
1190
+ const nonterminal = yield* tolerateTyped(Stream.runCollect(ledger.scanNonterminal));
1191
+ const detail = Option.isSome(nonterminal) ? Array.from(nonterminal.value).map((row) => `${row.submissionId}(${row.state})`).join(", ") : "ledger scan failed";
1192
+ return yield* ChaosConvergenceFailure.make({
1193
+ seed: plan.seed,
1194
+ message: `plan did not converge within ${maxRounds} rounds; nonterminal: [${detail}]; pending receipts: ${states.filter((state) => state.receipt === void 0).length}`
1195
+ });
1196
+ }
1197
+ const produced = yield* desk.produced;
1198
+ const laneReports = [];
1199
+ const verifyConversation = Effect.fn("Chaos.verifyConversation")(function* (conversationId, kind, deskInPlay) {
1200
+ const exported = yield* store.export(ConversationExportRequest.make({ conversationId })).pipe(Effect.mapError((error) => ChaosConvergenceFailure.make({
1201
+ seed: plan.seed,
1202
+ message: `export of ${conversationId} failed: ${String(error)}`
1203
+ })));
1204
+ const rows = [];
1205
+ for (const submissionId of submissionIdsNamedBy(exported.records)) {
1206
+ const found = yield* ledger.lookup(SubmissionLookupById.make({ submissionId })).pipe(Effect.mapError((error) => ChaosConvergenceFailure.make({
1207
+ seed: plan.seed,
1208
+ message: `lookup of ${submissionId} failed: ${String(error)}`
1209
+ })));
1210
+ if (Option.isSome(found)) rows.push(found.value);
1211
+ }
1212
+ const report = yield* verifyConversationInvariants({
1213
+ export: exported,
1214
+ submissions: rows,
1215
+ batchProducers: new Map(exported.records.map((envelope) => [envelope.batchId, config.producerId])),
1216
+ requireAllSettled: true
1217
+ });
1218
+ if (!report.ok) {
1219
+ const failed = report.checks.filter((check) => check.status === "failed").map((check) => `${check.name}: ${check.detail ?? "failed"}`).join("; ");
1220
+ return yield* ChaosConvergenceFailure.make({
1221
+ seed: plan.seed,
1222
+ message: `invariants failed for ${conversationId} (${kind}): ${failed}`
1223
+ });
1224
+ }
1225
+ if (deskInPlay) yield* assertNoFabrication(plan, exported.records, produced);
1226
+ laneReports.push(ChaosLaneReport.make({
1227
+ conversationId,
1228
+ kind,
1229
+ submissionCount: rows.length,
1230
+ verified: report.ok
1231
+ }));
1232
+ });
1233
+ for (const lane of lanes) {
1234
+ yield* verifyConversation(lane.conversationId, lane.kind, lane.deskInPlay);
1235
+ for (const flatIndex of lane.submissionIndexes) {
1236
+ const receipt = states[flatIndex]?.receipt;
1237
+ if (receipt === void 0) continue;
1238
+ const child = lane.childConversationOf(receipt);
1239
+ if (child === void 0) continue;
1240
+ const childExport = yield* Effect.exit(store.export(ConversationExportRequest.make({ conversationId: child })));
1241
+ if (Exit.isSuccess(childExport) && childExport.value.records.length > 0) yield* verifyConversation(child, "plain", false);
1242
+ }
1243
+ }
1244
+ const obligations = yield* runtime.scanObligations(ObligationThresholds.make({
1245
+ agingSeconds: 0,
1246
+ overdueSeconds: 0
1247
+ })).pipe(Effect.mapError((error) => ChaosConvergenceFailure.make({
1248
+ seed: plan.seed,
1249
+ message: `scanObligations failed: ${String(error)}`
1250
+ })));
1251
+ if (obligations.entries.length > 0) return yield* ChaosConvergenceFailure.make({
1252
+ seed: plan.seed,
1253
+ message: `open obligations after convergence: ${obligations.entries.map((entry) => `${entry.submissionId}(${entry.blockedOn})`).join(", ")}`
1254
+ });
1255
+ return ChaosPlanReport.make({
1256
+ seed: plan.seed,
1257
+ rounds,
1258
+ lanes: laneReports,
1259
+ openObligations: obligations.entries.length
1260
+ });
1261
+ });
1262
+ //#endregion
1263
+ //#region src/fixtures/docs-researcher/definition.ts
1264
+ const ResearchDocumentId = Schema.NonEmptyString.check(Schema.isMaxLength(64)).pipe(Schema.brand("@effect-agent/testing/docs-researcher/ResearchDocumentId"));
1265
+ const BoundedTitle = Schema.NonEmptyString.check(Schema.isMaxLength(120));
1266
+ const BoundedBody = Schema.NonEmptyString.check(Schema.isMaxLength(16 * 1024));
1267
+ /** Bounded summary text: the ONLY child-derived text that may cross to the parent. */
1268
+ const BoundedSummary = Schema.NonEmptyString.check(Schema.isMaxLength(240));
1269
+ var DocumentQuery = class extends Schema.Class("DocumentQuery")({ documentId: ResearchDocumentId }) {};
1270
+ /** One bounded research document as the MCP content server exposes it. */
1271
+ var ResearchDocument = class extends Schema.Class("ResearchDocument")({
1272
+ documentId: ResearchDocumentId,
1273
+ title: BoundedTitle,
1274
+ body: BoundedBody
1275
+ }) {};
1276
+ var DocumentUnavailable = class extends Schema.TaggedErrorClass()("DocumentUnavailable", {
1277
+ documentId: ResearchDocumentId,
1278
+ message: Schema.String
1279
+ }) {};
1280
+ /** The content store behind the scripted MCP server. */
1281
+ var DocumentLibrary = class extends Context.Service()("@effect-agent/testing/docs-researcher/DocumentLibrary") {};
1282
+ /**
1283
+ * The one content tool the doc-summarizer child uses. Its authored JSON
1284
+ * schema is what MCP discovery must serve byte-for-byte: the scripted MCP
1285
+ * fixture derives its discovery entry from `Tool.getJsonSchema(FetchDocument)`
1286
+ * and `validateMcpDiscovery` re-derives and digests both sides (CAP-009).
1287
+ */
1288
+ const FetchDocument = Tool.make("fetch_document", {
1289
+ description: "Fetch one bounded research document by its identifier.",
1290
+ parameters: DocumentQuery,
1291
+ success: ResearchDocument,
1292
+ failure: DocumentUnavailable,
1293
+ failureMode: "error",
1294
+ dependencies: [DocumentLibrary]
1295
+ });
1296
+ const DocContentToolkit = Toolkit.make(FetchDocument);
1297
+ const docContentToolkitLayer = DocContentToolkit.toLayer({ fetch_document: (query) => Effect.flatMap(DocumentLibrary, (library) => library.fetch(query)) });
1298
+ /** Never allowed outside a child Conversation or an unredacted fixture value. */
1299
+ const docsDocumentBodySecret = "docs-vault-secret-771";
1300
+ const decodeDocumentId = Schema.decodeSync(ResearchDocumentId);
1301
+ const corpusEntries = new Map([{
1302
+ documentId: "durability-notes",
1303
+ title: "Durability protocol notes",
1304
+ bodyPhrase: "amber-ledger-passage",
1305
+ summary: "Settlement results are recorded exactly once while external side effects stay at-least-once."
1306
+ }, {
1307
+ documentId: "subagent-notes",
1308
+ title: "Subagent join notes",
1309
+ bodyPhrase: "cobalt-join-corridor",
1310
+ summary: "A parent joins only the verified settlement of its own established child."
1311
+ }].map((entry) => [entry.documentId, {
1312
+ document: ResearchDocument.make({
1313
+ documentId: decodeDocumentId(entry.documentId),
1314
+ title: entry.title,
1315
+ body: `${entry.bodyPhrase}: internal working notes. ${docsDocumentBodySecret}. ${entry.summary} Raw notes stay inside the child Conversation.`
1316
+ }),
1317
+ bodyPhrase: entry.bodyPhrase,
1318
+ summary: entry.summary
1319
+ }]));
1320
+ /** The corpus document ids in canonical fixture order. */
1321
+ const researchCorpusDocumentIds = [decodeDocumentId("durability-notes"), decodeDocumentId("subagent-notes")];
1322
+ const requireCorpusEntry = (documentId) => {
1323
+ const entry = corpusEntries.get(documentId);
1324
+ if (entry === void 0) throw new Error(`No deterministic corpus entry exists for document ${documentId}`);
1325
+ return entry;
1326
+ };
1327
+ /** Deterministic library lookup shared by the scripted MCP content handlers. */
1328
+ const researchDocumentLookup = (query) => {
1329
+ const entry = corpusEntries.get(query.documentId);
1330
+ return entry === void 0 ? Effect.fail(DocumentUnavailable.make({
1331
+ documentId: query.documentId,
1332
+ message: "No deterministic corpus entry exists for this document."
1333
+ })) : Effect.succeed(entry.document);
1334
+ };
1335
+ /** The full fixture document (body includes the secret marker — child-side only). */
1336
+ const researchDocumentFor = (documentId) => requireCorpusEntry(documentId).document;
1337
+ /** The distinctive body phrase used by context-isolation assertions. */
1338
+ const documentBodyPhrase = (documentId) => requireCorpusEntry(documentId).bodyPhrase;
1339
+ var SummaryBrief = class extends Schema.Class("SummaryBrief")({
1340
+ documentId: ResearchDocumentId,
1341
+ focus: Schema.NonEmptyString
1342
+ }) {};
1343
+ var DocumentSummary = class extends Schema.Class("DocumentSummary")({
1344
+ documentId: ResearchDocumentId,
1345
+ summary: BoundedSummary
1346
+ }) {};
1347
+ /** The summary the scripted child writes after fetching the document. */
1348
+ const documentSummaryFor = (documentId) => DocumentSummary.make({
1349
+ documentId: requireCorpusEntry(documentId).document.documentId,
1350
+ summary: requireCorpusEntry(documentId).summary
1351
+ });
1352
+ const encodedDocumentSummary = (documentId) => JSON.stringify(Schema.encodeSync(DocumentSummary)(documentSummaryFor(documentId)));
1353
+ const DocSummarizer = Agent.define("doc-summarizer", {
1354
+ input: SummaryBrief,
1355
+ output: DocumentSummary,
1356
+ instructions: "Fetch the briefed document with fetch_document exactly once, then return only a JSON document summary. Never copy raw notes or secrets into the summary.",
1357
+ toolkit: DocContentToolkit,
1358
+ policy: AgentPolicy.make({
1359
+ maxTurns: 2,
1360
+ maxToolCalls: 1,
1361
+ maxDuration: "30 seconds",
1362
+ toolConcurrency: 1
1363
+ }),
1364
+ description: "Summarize one bounded research document fetched through MCP content tools.",
1365
+ metadata: {
1366
+ deploymentClass: "DN",
1367
+ phase: "P7"
1368
+ }
1369
+ });
1370
+ var SummaryRequest = class extends Schema.Class("SummaryRequest")({ documentId: ResearchDocumentId }) {};
1371
+ var SummaryFinding = class extends Schema.Class("SummaryFinding")({
1372
+ documentId: ResearchDocumentId,
1373
+ summary: BoundedSummary
1374
+ }) {};
1375
+ var DocumentSummaryFailed = class extends Schema.TaggedErrorClass()("DocumentSummaryFailed", { childErrorTag: Schema.NonEmptyString }) {};
1376
+ /** Finite per-invocation bounds (SUB-009): one fetch per child, two children per Run. */
1377
+ const documentSummaryPolicy = SubagentPolicy.make({
1378
+ maxChildren: 2,
1379
+ maxConcurrency: 2,
1380
+ maxTurns: 2,
1381
+ maxToolCalls: 1,
1382
+ maxDuration: "10 seconds"
1383
+ });
1384
+ const delegateDocumentSummary = Subagent.define("delegate_document_summary", {
1385
+ description: "Summarize one research document through the doc-summarizer child and return a bounded finding.",
1386
+ target: DocSummarizer,
1387
+ parameters: SummaryRequest,
1388
+ success: SummaryFinding,
1389
+ failure: DocumentSummaryFailed,
1390
+ prepareInput: (request) => Effect.succeed(SummaryBrief.make({
1391
+ documentId: request.documentId,
1392
+ focus: "summarize:durability-claims"
1393
+ })),
1394
+ projectResult: (summary) => Effect.succeed(SummaryFinding.make({
1395
+ documentId: summary.documentId,
1396
+ summary: summary.summary
1397
+ })),
1398
+ policy: documentSummaryPolicy
1399
+ });
1400
+ /** Total mapping from every expected child Run failure to the declared Tool failure (SUB-028). */
1401
+ const mapSummaryChildFailure = (failure) => DocumentSummaryFailed.make({ childErrorTag: failure._tag });
1402
+ /** The exact digest strings the durable declaration AND host registration must share (SUB-023). */
1403
+ const docsSummarizerDigestStrings = {
1404
+ agent: "50".repeat(32),
1405
+ model: "51".repeat(32),
1406
+ tools: "52".repeat(32)
1407
+ };
1408
+ /** Runtime wiring: the immutable delegation plus one explicit child Binding (S2 declaration). */
1409
+ const docsSummaryHandlersLayer = (childBinding) => SubagentRuntime.layer(delegateDocumentSummary, childBinding, {
1410
+ mapChildFailure: mapSummaryChildFailure,
1411
+ durable: { targetDigests: docsSummarizerDigestStrings }
1412
+ });
1413
+ var ResearchRequest = class extends Schema.Class("ResearchRequest")({
1414
+ question: Schema.NonEmptyString,
1415
+ documentIds: Schema.Array(ResearchDocumentId).check(Schema.isMinLength(1))
1416
+ }) {};
1417
+ var ResearchDigest = class extends Schema.Class("ResearchDigest")({
1418
+ findings: Schema.Array(SummaryFinding),
1419
+ nextAction: Schema.Literal("review")
1420
+ }) {};
1421
+ /** Parent-only transcript markers proving child context isolation (SUB-006/SUB-015). */
1422
+ const docsCoordinatorConfidentialMarker = "docs-coordinator-vault-19x";
1423
+ const docsMissionConfidentialMarker = "docs-mission-dossier-42f";
1424
+ const DocsResearcherToolkit = Toolkit.make(delegateDocumentSummary.tool);
1425
+ const DocsResearcher = Agent.define("docs-researcher", {
1426
+ input: ResearchRequest,
1427
+ output: ResearchDigest,
1428
+ instructions: [
1429
+ "You are the Effect Agent P7 docs-researcher coordinator.",
1430
+ `Coordinator-only context: ${docsCoordinatorConfidentialMarker}.`,
1431
+ "Call delegate_document_summary once per requested document in one Tool batch.",
1432
+ "Return only a JSON digest built from the delegated findings. This is read-only research."
1433
+ ].join("\n"),
1434
+ toolkit: DocsResearcherToolkit,
1435
+ policy: AgentPolicy.make({
1436
+ maxTurns: 2,
1437
+ maxToolCalls: 2,
1438
+ maxDuration: "30 seconds",
1439
+ toolConcurrency: 2
1440
+ }),
1441
+ description: "Coordinate per-document summarization through one declared delegation Tool.",
1442
+ metadata: {
1443
+ deploymentClass: "DN",
1444
+ phase: "P7"
1445
+ }
1446
+ });
1447
+ /** The default two-document research mission. */
1448
+ const researchMissionRequest = ResearchRequest.make({
1449
+ question: `Summarize the durability and subagent notes; keep ${docsMissionConfidentialMarker} inside the coordinator conversation.`,
1450
+ documentIds: researchCorpusDocumentIds
1451
+ });
1452
+ /** The coordinator's expected final digest for the given documents. */
1453
+ const expectedResearchDigest = (documentIds = researchCorpusDocumentIds) => ResearchDigest.make({
1454
+ findings: documentIds.map((documentId) => {
1455
+ const summary = documentSummaryFor(documentId);
1456
+ return SummaryFinding.make({
1457
+ documentId: summary.documentId,
1458
+ summary: summary.summary
1459
+ });
1460
+ }),
1461
+ nextAction: "review"
1462
+ });
1463
+ //#endregion
1464
+ //#region src/fixtures/travel-planner/definition.ts
1465
+ const AirportCode = Schema.NonEmptyString.pipe(Schema.brand("@effect-agent/testing/travel-planner/AirportCode"));
1466
+ const QuoteId = Schema.NonEmptyString.pipe(Schema.brand("@effect-agent/testing/travel-planner/QuoteId"));
1467
+ var TripRequest = class extends Schema.Class("TripRequest")({
1468
+ request: Schema.NonEmptyString,
1469
+ origin: AirportCode,
1470
+ destination: AirportCode,
1471
+ departOn: Schema.String,
1472
+ nights: Schema.Int.check(Schema.isGreaterThan(0)),
1473
+ travelers: Schema.Int.check(Schema.isGreaterThan(0)),
1474
+ budgetCents: Schema.Int.check(Schema.isGreaterThan(0)),
1475
+ currency: Schema.Literal("USD")
1476
+ }) {};
1477
+ var FlightQuery = class extends Schema.Class("FlightQuery")({
1478
+ origin: AirportCode,
1479
+ destination: AirportCode,
1480
+ departOn: Schema.String,
1481
+ travelers: Schema.Int.check(Schema.isGreaterThan(0))
1482
+ }) {};
1483
+ var LodgingQuery = class extends Schema.Class("LodgingQuery")({
1484
+ destination: AirportCode,
1485
+ departOn: Schema.String,
1486
+ nights: Schema.Int.check(Schema.isGreaterThan(0)),
1487
+ travelers: Schema.Int.check(Schema.isGreaterThan(0))
1488
+ }) {};
1489
+ var ActivityQuery = class extends Schema.Class("ActivityQuery")({
1490
+ destination: AirportCode,
1491
+ departOn: Schema.String,
1492
+ nights: Schema.Int.check(Schema.isGreaterThan(0)),
1493
+ travelers: Schema.Int.check(Schema.isGreaterThan(0))
1494
+ }) {};
1495
+ var FlightOption = class extends Schema.Class("FlightOption")({
1496
+ quoteId: QuoteId,
1497
+ flight: Schema.String,
1498
+ estimatedCents: Schema.Int.check(Schema.isGreaterThan(0)),
1499
+ currency: Schema.Literal("USD")
1500
+ }) {};
1501
+ var LodgingOption = class extends Schema.Class("LodgingOption")({
1502
+ lodging: Schema.String,
1503
+ estimatedCents: Schema.Int.check(Schema.isGreaterThan(0)),
1504
+ currency: Schema.Literal("USD")
1505
+ }) {};
1506
+ /** A successful empty activity search is distinct from supplier unavailability. */
1507
+ var ActivitySearchResult = class extends Schema.Class("ActivitySearchResult")({ activities: Schema.Array(Schema.String) }) {};
1508
+ var Itinerary = class extends Schema.Class("Itinerary")({
1509
+ title: Schema.String,
1510
+ route: Schema.String,
1511
+ dates: Schema.String,
1512
+ flight: Schema.String,
1513
+ lodging: Schema.String,
1514
+ activities: Schema.Array(Schema.String),
1515
+ estimatedTotalCents: Schema.Int.check(Schema.isGreaterThan(0)),
1516
+ currency: Schema.Literal("USD"),
1517
+ quoteId: QuoteId,
1518
+ assumptions: Schema.Array(Schema.String),
1519
+ unresolvedConstraints: Schema.Array(Schema.String),
1520
+ nextAction: Schema.Literal("review")
1521
+ }) {};
1522
+ var TravelPlan = class extends Schema.Class("TravelPlan")({ itineraries: Schema.Array(Itinerary) }) {};
1523
+ const unavailableFields = {
1524
+ query: Schema.String,
1525
+ message: Schema.String
1526
+ };
1527
+ var FlightUnavailable = class extends Schema.TaggedErrorClass()("FlightUnavailable", unavailableFields) {};
1528
+ var LodgingUnavailable = class extends Schema.TaggedErrorClass()("LodgingUnavailable", unavailableFields) {};
1529
+ var ActivityUnavailable = class extends Schema.TaggedErrorClass()("ActivityUnavailable", unavailableFields) {};
1530
+ var GuidanceFailure = class extends Schema.TaggedErrorClass()("GuidanceFailure", { message: Schema.String }) {};
1531
+ var FlightCatalog = class extends Context.Service()("@effect-agent/testing/travel-planner/FlightCatalog") {};
1532
+ var LodgingCatalog = class extends Context.Service()("@effect-agent/testing/travel-planner/LodgingCatalog") {};
1533
+ var ActivityCatalog = class extends Context.Service()("@effect-agent/testing/travel-planner/ActivityCatalog") {};
1534
+ var TravelGuidance = class extends Context.Service()("@effect-agent/testing/travel-planner/TravelGuidance") {};
1535
+ const SearchFlights = Tool.make("search_flights", {
1536
+ parameters: FlightQuery,
1537
+ success: FlightOption,
1538
+ failure: FlightUnavailable,
1539
+ failureMode: "error",
1540
+ dependencies: [FlightCatalog]
1541
+ });
1542
+ const SearchLodging = Tool.make("search_lodging", {
1543
+ parameters: LodgingQuery,
1544
+ success: LodgingOption,
1545
+ failure: LodgingUnavailable,
1546
+ failureMode: "error",
1547
+ dependencies: [LodgingCatalog]
1548
+ });
1549
+ const SearchActivities = Tool.make("search_activities", {
1550
+ parameters: ActivityQuery,
1551
+ success: ActivitySearchResult,
1552
+ failure: ActivityUnavailable,
1553
+ failureMode: "error",
1554
+ dependencies: [ActivityCatalog]
1555
+ });
1556
+ const TravelPlannerToolkit = Toolkit.make(SearchFlights, SearchLodging, SearchActivities);
1557
+ const TravelPlannerToolkitLayer = TravelPlannerToolkit.toLayer({
1558
+ search_flights: (query) => Effect.flatMap(FlightCatalog, (catalog) => catalog.search(query)),
1559
+ search_lodging: (query) => Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(query)),
1560
+ search_activities: (query) => Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(query))
1561
+ });
1562
+ const TravelPlanner = Agent.define("travel-planner", {
1563
+ input: TripRequest,
1564
+ output: TravelPlan,
1565
+ instructions: (input) => Effect.flatMap(TravelGuidance, (guidance) => guidance.instructions(input)),
1566
+ toolkit: TravelPlannerToolkit,
1567
+ policy: AgentPolicy.make({
1568
+ maxTurns: 2,
1569
+ maxToolCalls: 3,
1570
+ maxDuration: "30 seconds",
1571
+ toolConcurrency: 3
1572
+ }),
1573
+ description: "Build one review-only itinerary from bounded parallel deterministic searches.",
1574
+ metadata: {
1575
+ deploymentClass: "E",
1576
+ phase: "P1"
1577
+ }
1578
+ });
1579
+ //#endregion
1580
+ //#region src/fixtures/travel-planner/deterministic-layers.ts
1581
+ var CatalogLifecycleCounts = class extends Schema.Class("CatalogLifecycleCounts")({
1582
+ acquired: Schema.Natural,
1583
+ finalized: Schema.Natural
1584
+ }) {};
1585
+ var CatalogLifecycle = class CatalogLifecycle extends Context.Service()("@effect-agent/testing/travel-planner/CatalogLifecycle") {
1586
+ static layerNoDeps = Layer.effect(this, Effect.gen(function* () {
1587
+ const acquired = yield* Ref.make(0);
1588
+ const finalized = yield* Ref.make(0);
1589
+ return CatalogLifecycle.of({
1590
+ markAcquired: Ref.update(acquired, (n) => n + 1),
1591
+ markFinalized: Ref.update(finalized, (n) => n + 1),
1592
+ counts: Effect.all({
1593
+ acquired: Ref.get(acquired),
1594
+ finalized: Ref.get(finalized)
1595
+ }).pipe(Effect.map((counts) => CatalogLifecycleCounts.make(counts)))
1596
+ });
1597
+ }));
1598
+ };
1599
+ const flight = FlightOption.make({
1600
+ quoteId: Schema.decodeSync(QuoteId)("quote-sfo-lhr-001"),
1601
+ flight: "EA 218 · nonstop · SFO 18:40 → LHR 13:05+1",
1602
+ estimatedCents: 18e4,
1603
+ currency: "USD"
1604
+ });
1605
+ const lodging = LodgingOption.make({
1606
+ lodging: "Bloomsbury House · refundable studio · 4 nights",
1607
+ estimatedCents: 104e3,
1608
+ currency: "USD"
1609
+ });
1610
+ const activities = ActivitySearchResult.make({ activities: ["British Museum timed entry", "Thames evening walk"] });
1611
+ const ReverseCompletionToolkitLayer = Effect.gen(function* () {
1612
+ const flightStarted = yield* Deferred.make();
1613
+ const lodgingStarted = yield* Deferred.make();
1614
+ const activityStarted = yield* Deferred.make();
1615
+ const releaseFlight = yield* Deferred.make();
1616
+ const releaseLodging = yield* Deferred.make();
1617
+ const releaseActivity = yield* Deferred.make();
1618
+ const awaitRelease = (started, release, value) => Deferred.succeed(started, void 0).pipe(Effect.andThen(Deferred.await(release)), Effect.as(value));
1619
+ return {
1620
+ controls: {
1621
+ flightStarted: Deferred.await(flightStarted),
1622
+ lodgingStarted: Deferred.await(lodgingStarted),
1623
+ activityStarted: Deferred.await(activityStarted),
1624
+ releaseFlight: Deferred.succeed(releaseFlight, void 0).pipe(Effect.asVoid),
1625
+ releaseLodging: Deferred.succeed(releaseLodging, void 0).pipe(Effect.asVoid),
1626
+ releaseActivity: Deferred.succeed(releaseActivity, void 0).pipe(Effect.asVoid)
1627
+ },
1628
+ layer: TravelPlannerToolkit.toLayer({
1629
+ search_flights: () => awaitRelease(flightStarted, releaseFlight, flight),
1630
+ search_lodging: () => awaitRelease(lodgingStarted, releaseLodging, lodging),
1631
+ search_activities: () => awaitRelease(activityStarted, releaseActivity, activities)
1632
+ })
1633
+ };
1634
+ });
1635
+ const FlightCatalogLayer = Layer.effect(FlightCatalog, Effect.gen(function* () {
1636
+ const lifecycle = yield* CatalogLifecycle;
1637
+ yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);
1638
+ return FlightCatalog.of({ search: (query) => query.origin === query.destination ? Effect.fail(FlightUnavailable.make({
1639
+ query: `${query.origin}-${query.destination}`,
1640
+ message: "Origin and destination must differ."
1641
+ })) : Effect.succeed(flight) });
1642
+ }));
1643
+ const LodgingCatalogLayer = Layer.effect(LodgingCatalog, Effect.gen(function* () {
1644
+ const lifecycle = yield* CatalogLifecycle;
1645
+ yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);
1646
+ return LodgingCatalog.of({ search: (query) => query.nights < 1 ? Effect.fail(LodgingUnavailable.make({
1647
+ query: query.destination,
1648
+ message: "At least one night is required."
1649
+ })) : Effect.succeed(lodging) });
1650
+ }));
1651
+ const ActivityCatalogLayer = Layer.effect(ActivityCatalog, Effect.gen(function* () {
1652
+ const lifecycle = yield* CatalogLifecycle;
1653
+ yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);
1654
+ return ActivityCatalog.of({ search: (query) => query.destination === "" ? Effect.fail(ActivityUnavailable.make({
1655
+ query: query.destination,
1656
+ message: "Destination is required."
1657
+ })) : Effect.succeed(activities) });
1658
+ }));
1659
+ /** Stable supplier-side booking identity, minted deterministically from the idempotency key. */
1660
+ const BookingRef = Schema.NonEmptyString.pipe(Schema.brand("@effect-agent/testing/travel-planner/BookingRef"));
1661
+ /** The supplier desk operations the P5 booking Tools and Steps invoke. */
1662
+ const SupplierOperation = Schema.Literals([
1663
+ "book-flight",
1664
+ "cancel-booking",
1665
+ "reserve-flight",
1666
+ "reserve-lodging",
1667
+ "issue-confirmation"
1668
+ ]);
1669
+ /**
1670
+ * One row of external supplier truth. The desk deduplicates by `idempotencyKey` — replaying a
1671
+ * call with the same key returns this exact record without creating a second booking — which is
1672
+ * precisely the honesty model of DUR-010: the framework never makes an external call
1673
+ * exactly-once; the supplier's idempotency key does.
1674
+ */
1675
+ var SupplierBookingRecord = class extends Schema.Class("@effect-agent/testing/travel-planner/SupplierBookingRecord")({
1676
+ bookingRef: BookingRef,
1677
+ idempotencyKey: Schema.NonEmptyString,
1678
+ operation: SupplierOperation,
1679
+ detail: Schema.NonEmptyString,
1680
+ status: Schema.Literals(["confirmed", "cancelled"])
1681
+ }) {};
1682
+ var SupplierUnavailable = class extends Schema.TaggedErrorClass()("SupplierUnavailable", { message: Schema.String }) {};
1683
+ /** The desk-internal idempotency key of one cancellation: cancel is idempotent by bookingRef. */
1684
+ const cancelBookingIdempotencyKey = (bookingRef) => `cancel-booking:${bookingRef}`;
1685
+ /** The deterministic bookingRef the desk mints for one idempotency key. */
1686
+ const supplierBookingRefFor = (idempotencyKey) => Schema.decodeSync(BookingRef)(`ref:${idempotencyKey}`);
1687
+ /**
1688
+ * The deterministic in-memory supplier: an idempotency-keyed booking store with per-key call
1689
+ * counters and injectable crash windows.
1690
+ *
1691
+ * - `book`/`cancel` always count the call (at-least-once execution stays observable), then
1692
+ * dedupe the external effect by idempotency key — the supplier-side contract the P5 Tools and
1693
+ * Steps rely on.
1694
+ * - `holdAfterWrite` arms a one-shot crash window: the next call with that key performs its
1695
+ * supplier write, signals `held`, and never returns. Interrupting the Attempt at that point
1696
+ * models "the external effect happened but no outcome was recorded" without any wall clock.
1697
+ * - `bookings`/`lookup` expose external truth for the reconciler and for never-fabricate
1698
+ * assertions.
1699
+ */
1700
+ var SupplierBookingDesk = class SupplierBookingDesk extends Context.Service()("@effect-agent/testing/travel-planner/SupplierBookingDesk") {
1701
+ static layer = Layer.effect(this, Effect.gen(function* () {
1702
+ const state = yield* Ref.make({
1703
+ bookings: /* @__PURE__ */ new Map(),
1704
+ counts: /* @__PURE__ */ new Map(),
1705
+ holds: /* @__PURE__ */ new Map()
1706
+ });
1707
+ const enterHold = (hold) => Option.isSome(hold) ? Deferred.succeed(hold.value.held, void 0).pipe(Effect.andThen(Deferred.await(hold.value.release))) : Effect.void;
1708
+ const book = (request) => Ref.modify(state, (current) => {
1709
+ const counts = new Map(current.counts).set(request.idempotencyKey, (current.counts.get(request.idempotencyKey) ?? 0) + 1);
1710
+ const existing = current.bookings.get(request.idempotencyKey);
1711
+ const record = existing ?? SupplierBookingRecord.make({
1712
+ bookingRef: supplierBookingRefFor(request.idempotencyKey),
1713
+ idempotencyKey: request.idempotencyKey,
1714
+ operation: request.operation,
1715
+ detail: request.detail,
1716
+ status: "confirmed"
1717
+ });
1718
+ const bookings = existing === void 0 ? new Map(current.bookings).set(request.idempotencyKey, record) : current.bookings;
1719
+ const hold = Option.fromNullishOr(current.holds.get(request.idempotencyKey));
1720
+ const holds = Option.isSome(hold) ? (() => {
1721
+ const next = new Map(current.holds);
1722
+ next.delete(request.idempotencyKey);
1723
+ return next;
1724
+ })() : current.holds;
1725
+ return [{
1726
+ record,
1727
+ hold
1728
+ }, {
1729
+ bookings,
1730
+ counts,
1731
+ holds
1732
+ }];
1733
+ }).pipe(Effect.flatMap(({ hold, record }) => enterHold(hold).pipe(Effect.as(record))));
1734
+ const cancel = (bookingRef) => Ref.modify(state, (current) => {
1735
+ const key = cancelBookingIdempotencyKey(bookingRef);
1736
+ const counts = new Map(current.counts).set(key, (current.counts.get(key) ?? 0) + 1);
1737
+ const existingEntry = [...current.bookings.entries()].find(([, record]) => record.bookingRef === bookingRef);
1738
+ if (existingEntry === void 0) return [{
1739
+ record: Option.none(),
1740
+ hold: Option.none()
1741
+ }, {
1742
+ ...current,
1743
+ counts
1744
+ }];
1745
+ const [storeKey, existing] = existingEntry;
1746
+ const cancelled = existing.status === "cancelled" ? existing : SupplierBookingRecord.make({
1747
+ ...existing,
1748
+ status: "cancelled"
1749
+ });
1750
+ const bookings = new Map(current.bookings).set(storeKey, cancelled);
1751
+ const hold = Option.fromNullishOr(current.holds.get(key));
1752
+ const holds = Option.isSome(hold) ? (() => {
1753
+ const next = new Map(current.holds);
1754
+ next.delete(key);
1755
+ return next;
1756
+ })() : current.holds;
1757
+ return [{
1758
+ record: Option.some(cancelled),
1759
+ hold
1760
+ }, {
1761
+ bookings,
1762
+ counts,
1763
+ holds
1764
+ }];
1765
+ }).pipe(Effect.flatMap(({ hold, record }) => Option.isNone(record) ? Effect.fail(SupplierUnavailable.make({ message: `The supplier desk has no booking under ${bookingRef}.` })) : enterHold(hold).pipe(Effect.as(record.value))));
1766
+ return SupplierBookingDesk.of({
1767
+ book,
1768
+ cancel,
1769
+ lookup: (idempotencyKey) => Ref.get(state).pipe(Effect.map((current) => Option.fromNullishOr(current.bookings.get(idempotencyKey)))),
1770
+ bookings: Ref.get(state).pipe(Effect.map((current) => [...current.bookings.values()])),
1771
+ callCount: (idempotencyKey) => Ref.get(state).pipe(Effect.map((current) => current.counts.get(idempotencyKey) ?? 0)),
1772
+ holdAfterWrite: (idempotencyKey) => Effect.gen(function* () {
1773
+ const held = yield* Deferred.make();
1774
+ const release = yield* Deferred.make();
1775
+ yield* Ref.update(state, (current) => ({
1776
+ ...current,
1777
+ holds: new Map(current.holds).set(idempotencyKey, {
1778
+ held,
1779
+ release
1780
+ })
1781
+ }));
1782
+ return {
1783
+ held: Deferred.await(held),
1784
+ release: Deferred.succeed(release, void 0).pipe(Effect.asVoid)
1785
+ };
1786
+ })
1787
+ });
1788
+ }));
1789
+ };
1790
+ const TravelGuidanceLayer = Layer.succeed(TravelGuidance, TravelGuidance.of({ instructions: (input) => Effect.succeed([
1791
+ "You are the Effect Agent Travel Planner P1 interpreter fixture.",
1792
+ `The user asked: ${input.request}`,
1793
+ "Call search_flights, search_lodging, and search_activities exactly once in one Tool batch.",
1794
+ "Then return only a JSON object of exactly this shape, no prose:",
1795
+ "{\"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\"}]}",
1796
+ "Use the Tool results verbatim; activity results may legitimately be an empty array.",
1797
+ "This is read-only planning. Require review before any mutation."
1798
+ ].join("\n")) }));
1799
+ const DeterministicIdGeneratorLayer = Layer.effect(IdGenerator, Effect.gen(function* () {
1800
+ const conversation = yield* Ref.make(0);
1801
+ const run = yield* Ref.make(0);
1802
+ const turn = yield* Ref.make(0);
1803
+ return IdGenerator.of({
1804
+ nextConversationId: Ref.updateAndGet(conversation, (n) => n + 1).pipe(Effect.map((n) => Schema.decodeSync(ConversationId)(`conversation-${n}`))),
1805
+ nextRunId: Ref.updateAndGet(run, (n) => n + 1).pipe(Effect.map((n) => Schema.decodeSync(RunId)(`run-${n}`))),
1806
+ nextTurnId: Ref.updateAndGet(turn, (n) => n + 1).pipe(Effect.map((n) => Schema.decodeSync(TurnId)(`turn-${n}`)))
1807
+ });
1808
+ }));
1809
+ const TravelPlannerRuntimeLayer = Layer.mergeAll(TravelPlannerToolkitLayer, FlightCatalogLayer, LodgingCatalogLayer, ActivityCatalogLayer, TravelGuidanceLayer, DeterministicIdGeneratorLayer).pipe(Layer.provide(CatalogLifecycle.layerNoDeps));
1810
+ //#endregion
1811
+ //#region src/fixtures/docs-researcher/mcp.ts
1812
+ /** Framework-side hard bounds one docs-researcher assembly requests. */
1813
+ const docsMcpRequest = McpConnectionRequest.make({
1814
+ serverId: "docs-content-mcp",
1815
+ maxToolCount: 4,
1816
+ maxToolDescriptionBytes: 256,
1817
+ maxDiscoveryBytes: 16384,
1818
+ connectTimeoutMillis: 1e3
1819
+ });
1820
+ const docsMcpIdentity = McpServerIdentity.make({
1821
+ serverId: docsMcpRequest.serverId,
1822
+ implementation: McpSchema.Implementation.make({
1823
+ name: "docs-researcher-content-fixture",
1824
+ version: "1.0.0"
1825
+ })
1826
+ });
1827
+ const discoveredFetchDocument = McpSchema.Tool.make({
1828
+ name: FetchDocument.name,
1829
+ description: "Fetch one bounded research document by its identifier.",
1830
+ inputSchema: Tool.getJsonSchema(FetchDocument)
1831
+ });
1832
+ const scriptedConnector = (tools) => Layer.succeed(McpConnector)({ connect: () => Effect.acquireRelease(Effect.succeed({
1833
+ identity: docsMcpIdentity,
1834
+ capabilities: McpSchema.ServerCapabilities.make({}),
1835
+ tools,
1836
+ toolkit: DocContentToolkit
1837
+ }), () => Effect.void) });
1838
+ /** The well-behaved scripted content server. */
1839
+ const docsMcpConnectorLayer = scriptedConnector([discoveredFetchDocument]);
1840
+ /** Serves a tool description exceeding `maxToolDescriptionBytes` (SEC-013 bound). */
1841
+ const docsMcpOversizedConnectorLayer = scriptedConnector([McpSchema.Tool.make({
1842
+ name: discoveredFetchDocument.name,
1843
+ description: "x".repeat(1024),
1844
+ inputSchema: discoveredFetchDocument.inputSchema
1845
+ })]);
1846
+ /** Serves a discovery schema that disagrees with the authored toolkit (drift fails closed). */
1847
+ const docsMcpMismatchedConnectorLayer = scriptedConnector([McpSchema.Tool.make({
1848
+ name: discoveredFetchDocument.name,
1849
+ description: discoveredFetchDocument.description,
1850
+ inputSchema: {
1851
+ type: "object",
1852
+ properties: { url: { type: "string" } }
1853
+ }
1854
+ })]);
1855
+ const isJsonEqual = (left, right) => JSON.stringify(left) === JSON.stringify(right);
1856
+ /**
1857
+ * Bind DISCOVERY to AUTHORING: `validateMcpDiscovery` (inside `connectMcp`)
1858
+ * already proved the served discovery matches the connection's own Toolkit;
1859
+ * this check additionally proves that Toolkit is the exact toolkit the
1860
+ * doc-summarizer was AUTHORED against — same tool names, same derived JSON
1861
+ * schemas — so a connector cannot substitute a look-alike toolkit. The
1862
+ * docs-researcher harness runs it before any worker Binding registration and
1863
+ * fails closed on any drift.
1864
+ */
1865
+ const assertDiscoveryMatchesAuthoredToolkit = Effect.fn("DocsResearcher.assertDiscoveryMatchesAuthoredToolkit")(function* (connection) {
1866
+ const authored = Object.values(DocContentToolkit.tools).map((tool) => ({
1867
+ name: tool.name,
1868
+ inputSchema: Tool.getJsonSchema(tool)
1869
+ })).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
1870
+ const discovered = Object.values(connection.toolkit.tools).map((tool) => ({
1871
+ name: tool.name,
1872
+ inputSchema: Tool.getJsonSchema(tool)
1873
+ })).sort((left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0);
1874
+ if (!(authored.length === discovered.length && authored.every((tool, index) => tool.name === discovered[index]?.name && isJsonEqual(tool.inputSchema, discovered[index]?.inputSchema)))) return yield* McpToolkitMismatch.make({
1875
+ serverId: connection.discovery.identity.serverId,
1876
+ message: "The MCP-discovered toolkit does not match the doc-summarizer's authored content toolkit"
1877
+ });
1878
+ });
1879
+ /** Round-trip guard for encoded discovery values persisted as fixture evidence. */
1880
+ const DocsMcpDiscoveryEvidence = Schema.Struct({
1881
+ serverId: Schema.NonEmptyString,
1882
+ toolCount: Schema.Natural,
1883
+ encodedBytes: Schema.Natural,
1884
+ toolkitSchemaDigest: Schema.String
1885
+ });
1886
+ //#endregion
1887
+ //#region src/fixtures/docs-researcher/harness.ts
1888
+ const docsResearcherDeploymentId = Schema.decodeSync(DeploymentId)("docs-researcher-p7-deployment");
1889
+ const docsResearcherProducerId = Schema.decodeSync(ProducerId)("docs-researcher-p7-producer");
1890
+ const docsResearcherPrincipal = Schema.decodeSync(Principal)("docs-researcher-p7-principal");
1891
+ const digestOf$2 = (pair) => Schema.decodeSync(Digest)(pair.repeat(32));
1892
+ /** Redacted, deterministic coordinator definition digests for this fixture version. */
1893
+ const docsCoordinatorDigests = DefinitionDigests.make({
1894
+ agent: digestOf$2("40"),
1895
+ model: digestOf$2("41"),
1896
+ tools: digestOf$2("42")
1897
+ });
1898
+ /** The child registration digests — byte-equal to `docsSummarizerDigestStrings` (SUB-023). */
1899
+ const docsSummarizerDigests = DefinitionDigests.make({
1900
+ agent: digestOf$2("50"),
1901
+ model: digestOf$2("51"),
1902
+ tools: digestOf$2("52")
1903
+ });
1904
+ /** Durable admission options for one docs-researcher Submission on one mission lane. */
1905
+ const docsResearcherSubmitOptions = (conversationId, idempotencyKey) => ({
1906
+ conversationId,
1907
+ principal: docsResearcherPrincipal,
1908
+ idempotencyKey,
1909
+ definitions: docsCoordinatorDigests
1910
+ });
1911
+ /** The structural submit slice of the coordinator Binding (`DurableAgentRuntime.submit`). */
1912
+ const docsResearcherSubmitAgent = { definition: {
1913
+ id: DocsResearcher.id,
1914
+ input: DocsResearcher.input
1915
+ } };
1916
+ /** The deterministic delegation Tool Call identity for one document. */
1917
+ const summarizeCallId = (documentId) => `summarize-${documentId}`;
1918
+ /** The child's own scripted fetch Tool Call identity for one document. */
1919
+ const fetchCallId = (documentId) => `fetch-${documentId}`;
1920
+ const scriptedUsage$3 = {
1921
+ inputTokens: { total: 96 },
1922
+ outputTokens: { total: 64 }
1923
+ };
1924
+ const summaryDelegationParts = (documentIds) => [...documentIds.map((documentId) => ({
1925
+ type: "tool-call",
1926
+ id: summarizeCallId(documentId),
1927
+ name: "delegate_document_summary",
1928
+ params: { documentId },
1929
+ providerExecuted: false
1930
+ })), {
1931
+ type: "finish",
1932
+ reason: "tool-calls",
1933
+ usage: scriptedUsage$3
1934
+ }];
1935
+ const digestParts = (documentIds) => [
1936
+ {
1937
+ type: "text-start",
1938
+ id: "digest"
1939
+ },
1940
+ {
1941
+ type: "text-delta",
1942
+ id: "digest",
1943
+ delta: JSON.stringify(Schema.encodeSync(ResearchDigest)(expectedResearchDigest(documentIds)))
1944
+ },
1945
+ {
1946
+ type: "text-end",
1947
+ id: "digest"
1948
+ },
1949
+ {
1950
+ type: "finish",
1951
+ reason: "stop",
1952
+ usage: scriptedUsage$3
1953
+ }
1954
+ ];
1955
+ const fetchParts = (documentId) => [{
1956
+ type: "tool-call",
1957
+ id: fetchCallId(documentId),
1958
+ name: "fetch_document",
1959
+ params: { documentId },
1960
+ providerExecuted: false
1961
+ }, {
1962
+ type: "finish",
1963
+ reason: "tool-calls",
1964
+ usage: scriptedUsage$3
1965
+ }];
1966
+ const summaryParts = (documentId) => [
1967
+ {
1968
+ type: "text-start",
1969
+ id: "document-summary"
1970
+ },
1971
+ {
1972
+ type: "text-delta",
1973
+ id: "document-summary",
1974
+ delta: encodedDocumentSummary(documentId)
1975
+ },
1976
+ {
1977
+ type: "text-end",
1978
+ id: "document-summary"
1979
+ },
1980
+ {
1981
+ type: "finish",
1982
+ reason: "stop",
1983
+ usage: scriptedUsage$3
1984
+ }
1985
+ ];
1986
+ /**
1987
+ * One prompt-aware scripted model with externally observable counters. A DN
1988
+ * Attempt may resume on a fresh Layer build, so responses derive from the
1989
+ * committed history in the prompt — never from an in-Layer turn counter.
1990
+ */
1991
+ const makeCountingModel = (name, decide) => Effect.gen(function* () {
1992
+ const calls = yield* Ref.make(0);
1993
+ const prompts = yield* Ref.make([]);
1994
+ return {
1995
+ model: Model.make("scripted", name, Layer.effect(LanguageModel.LanguageModel, LanguageModel.make({
1996
+ generateText: () => Effect.succeed([]),
1997
+ streamText: (request) => Stream.unwrap(Effect.gen(function* () {
1998
+ yield* Ref.update(calls, (value) => value + 1);
1999
+ const promptJson = JSON.stringify(request.prompt);
2000
+ yield* Ref.update(prompts, (previous) => [...previous, promptJson]);
2001
+ return Stream.fromIterable(yield* decide(promptJson));
2002
+ }))
2003
+ }))),
2004
+ calls: Ref.get(calls),
2005
+ prompts: Ref.get(prompts)
2006
+ };
2007
+ });
2008
+ /**
2009
+ * Build the docs-researcher harness. Order matters and is the point: the
2010
+ * child's content toolkit is only registered as a worker Binding AFTER the
2011
+ * MCP connector's bounded discovery validated the authored toolkit
2012
+ * byte-for-byte (`connectMcp` + `assertDiscoveryMatchesAuthoredToolkit`), so
2013
+ * "the tools the summarizer runs are the tools discovery served" is enforced
2014
+ * at assembly, not assumed. Content-tool execution then flows through the
2015
+ * counting `DocumentLibrary` — the scripted MCP server's content store.
2016
+ */
2017
+ const makeDocsResearcherHarness = (options) => Effect.gen(function* () {
2018
+ const documentIds = options?.documentIds ?? researchCorpusDocumentIds;
2019
+ const discovery = yield* Effect.scoped(Effect.gen(function* () {
2020
+ const connection = yield* connectMcp(docsMcpRequest);
2021
+ yield* assertDiscoveryMatchesAuthoredToolkit(connection);
2022
+ return connection.discovery;
2023
+ })).pipe(Effect.provide(docsMcpConnectorLayer));
2024
+ const fetchCounts = yield* Ref.make(/* @__PURE__ */ new Map());
2025
+ const libraryLayer = Layer.succeed(DocumentLibrary, DocumentLibrary.of({ fetch: (query) => Ref.update(fetchCounts, (current) => new Map(current).set(query.documentId, (current.get(query.documentId) ?? 0) + 1)).pipe(Effect.andThen(researchDocumentLookup(query))) }));
2026
+ const childToolkitLayer = docContentToolkitLayer.pipe(Layer.provideMerge(libraryLayer));
2027
+ const childModel = yield* makeCountingModel("doc-summarizer-p7", (promptJson) => Effect.suspend(() => {
2028
+ const documentId = documentIds.find((candidate) => promptJson.includes(candidate));
2029
+ if (documentId === void 0) return Effect.die(/* @__PURE__ */ new Error("The summarizer prompt names no corpus document"));
2030
+ return Effect.succeed(promptJson.includes(fetchCallId(documentId)) ? summaryParts(documentId) : fetchParts(documentId));
2031
+ }));
2032
+ const childBinding = Agent.withModel(DocSummarizer, childModel.model);
2033
+ const firstCallId = summarizeCallId(documentIds[0] ?? "durability-notes");
2034
+ const parentModel = yield* makeCountingModel("docs-researcher-p7", (promptJson) => Effect.succeed(promptJson.includes(firstCallId) ? digestParts(documentIds) : summaryDelegationParts(documentIds)));
2035
+ const parentBinding = Agent.withModel(DocsResearcher, parentModel.model);
2036
+ const delegationLayer = docsSummaryHandlersLayer(childBinding).pipe(Layer.provide(Layer.mergeAll(childToolkitLayer, SubagentReservationsMemoryLive, DeterministicIdGeneratorLayer)));
2037
+ return {
2038
+ bindings: [yield* DurableWorkerBinding.make(parentBinding, docsCoordinatorDigests).pipe(Effect.provide(delegationLayer)), yield* DurableWorkerBinding.make(childBinding, docsSummarizerDigests).pipe(Effect.provide(childToolkitLayer))],
2039
+ discovery,
2040
+ parentModelCalls: parentModel.calls,
2041
+ parentPrompts: parentModel.prompts,
2042
+ childModelCalls: childModel.calls,
2043
+ childPrompts: childModel.prompts,
2044
+ fetchInvocations: (documentId) => Ref.get(fetchCounts).pipe(Effect.map((current) => current.get(documentId) ?? 0))
2045
+ };
2046
+ });
2047
+ const encodeResearchDocument = Schema.encodeEffect(ResearchDocument);
2048
+ /**
2049
+ * The audit-surface preview of one fetched document: the raw document —
2050
+ * secret marker and all — passes through the configured structural `Redactor`
2051
+ * before anything may quote it outside the child Conversation (SEC-008,
2052
+ * CAP-013). Tests assert the preview keeps shape but no scalar content.
2053
+ */
2054
+ const redactedDocumentPreview = Effect.fn("DocsResearcher.redactedDocumentPreview")(function* (documentId) {
2055
+ const redactor = yield* Redactor;
2056
+ const encoded = yield* encodeResearchDocument(researchDocumentFor(documentId)).pipe(Effect.orDie);
2057
+ return yield* redactor.redact(encoded);
2058
+ });
2059
+ //#endregion
2060
+ //#region src/fixtures/travel-planner/phase2.ts
2061
+ var ItineraryHoldRequest = class extends Schema.Class("@effect-agent/testing/travel-planner/ItineraryHoldRequest")({
2062
+ quoteId: QuoteId,
2063
+ expiresInMinutes: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(60))
2064
+ }) {};
2065
+ var ItineraryHold = class extends Schema.Class("@effect-agent/testing/travel-planner/ItineraryHold")({
2066
+ holdId: Schema.NonEmptyString,
2067
+ quoteId: QuoteId,
2068
+ status: Schema.Literal("held")
2069
+ }) {};
2070
+ var ItineraryHoldUnavailable = class extends Schema.TaggedErrorClass()("ItineraryHoldUnavailable", {
2071
+ quoteId: QuoteId,
2072
+ message: Schema.String
2073
+ }) {};
2074
+ var ItineraryHoldGateway = class extends Context.Service()("@effect-agent/testing/travel-planner/ItineraryHoldGateway") {};
2075
+ /**
2076
+ * The first mutating Travel Planner Tool. Effect AI marks it as approval-gated
2077
+ * so the engine must settle approval before acquiring a handler permit.
2078
+ */
2079
+ const HoldItinerary = Tool.make("hold_itinerary", {
2080
+ parameters: ItineraryHoldRequest,
2081
+ success: ItineraryHold,
2082
+ failure: ItineraryHoldUnavailable,
2083
+ failureMode: "error",
2084
+ dependencies: [ItineraryHoldGateway],
2085
+ needsApproval: true
2086
+ });
2087
+ const TravelPlannerPhase2Toolkit = Toolkit.make(SearchFlights, SearchLodging, SearchActivities, HoldItinerary);
2088
+ const TravelPlannerPhase2ToolkitLayer = TravelPlannerPhase2Toolkit.toLayer({
2089
+ search_flights: (query) => Effect.flatMap(FlightCatalog, (catalog) => catalog.search(query)),
2090
+ search_lodging: (query) => Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(query)),
2091
+ search_activities: (query) => Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(query)),
2092
+ hold_itinerary: (request) => Effect.flatMap(ItineraryHoldGateway, (gateway) => gateway.hold(request))
2093
+ });
2094
+ const TravelPlannerPhase2 = Agent.define("travel-planner-phase-2", {
2095
+ input: TripRequest,
2096
+ output: TravelPlan,
2097
+ instructions: (input) => Effect.flatMap(TravelGuidance, (guidance) => guidance.instructions(input)),
2098
+ toolkit: TravelPlannerPhase2Toolkit,
2099
+ policy: AgentPolicy.make({
2100
+ maxTurns: 3,
2101
+ maxToolCalls: 4,
2102
+ maxDuration: "30 seconds",
2103
+ toolConcurrency: 3,
2104
+ tokenBudget: 2048
2105
+ }),
2106
+ description: "Build a review-only itinerary and require approval before creating a temporary hold.",
2107
+ metadata: {
2108
+ deploymentClass: "E",
2109
+ phase: "P2"
2110
+ }
2111
+ });
2112
+ //#endregion
2113
+ //#region src/fixtures/travel-planner/scenarios.ts
2114
+ const usage = {
2115
+ inputTokens: { total: 128 },
2116
+ outputTokens: { total: 96 }
2117
+ };
2118
+ const phase1Trip = Schema.decodeSync(TripRequest)({
2119
+ request: "Plan a review-only London trip using the deterministic flight, lodging, and activity searches.",
2120
+ origin: "SFO",
2121
+ destination: "LHR",
2122
+ departOn: "2026-09-14",
2123
+ nights: 4,
2124
+ travelers: 2,
2125
+ budgetCents: 35e4,
2126
+ currency: "USD"
2127
+ });
2128
+ /** Backward-compatible fixture alias while consumers transition to the P1 name. */
2129
+ const phase0Trip = phase1Trip;
2130
+ const expectedTravelPlan = Schema.decodeSync(TravelPlan)({ itineraries: [{
2131
+ title: "Westward light, eastbound overnight",
2132
+ route: "San Francisco → London",
2133
+ dates: "14–19 September 2026",
2134
+ flight: "EA 218 · nonstop · SFO 18:40 → LHR 13:05+1",
2135
+ lodging: "Bloomsbury House · refundable studio · 4 nights",
2136
+ activities: ["British Museum timed entry", "Thames evening walk"],
2137
+ estimatedTotalCents: 284e3,
2138
+ currency: "USD",
2139
+ quoteId: "quote-sfo-lhr-001",
2140
+ assumptions: ["Two travelers sharing one studio", "Quote is read-only availability, not a reservation"],
2141
+ unresolvedConstraints: ["Traveler names and accessibility requests are intentionally omitted"],
2142
+ nextAction: "review"
2143
+ }] });
2144
+ const phase1HappyPathTurns = [{
2145
+ _tag: "Stream",
2146
+ parts: [
2147
+ {
2148
+ type: "tool-call",
2149
+ id: "flight-call-1",
2150
+ name: "search_flights",
2151
+ params: {
2152
+ origin: "SFO",
2153
+ destination: "LHR",
2154
+ departOn: "2026-09-14",
2155
+ travelers: 2
2156
+ }
2157
+ },
2158
+ {
2159
+ type: "tool-call",
2160
+ id: "lodging-call-1",
2161
+ name: "search_lodging",
2162
+ params: {
2163
+ destination: "LHR",
2164
+ departOn: "2026-09-14",
2165
+ nights: 4,
2166
+ travelers: 2
2167
+ }
2168
+ },
2169
+ {
2170
+ type: "tool-call",
2171
+ id: "activity-call-1",
2172
+ name: "search_activities",
2173
+ params: {
2174
+ destination: "LHR",
2175
+ departOn: "2026-09-14",
2176
+ nights: 4,
2177
+ travelers: 2
2178
+ }
2179
+ },
2180
+ {
2181
+ type: "finish",
2182
+ reason: "tool-calls",
2183
+ usage
2184
+ }
2185
+ ],
2186
+ termination: { _tag: "Complete" }
2187
+ }, {
2188
+ _tag: "Stream",
2189
+ parts: [
2190
+ {
2191
+ type: "text-start",
2192
+ id: "itinerary-json"
2193
+ },
2194
+ {
2195
+ type: "text-delta",
2196
+ id: "itinerary-json",
2197
+ delta: JSON.stringify(Schema.encodeSync(TravelPlan)(expectedTravelPlan))
2198
+ },
2199
+ {
2200
+ type: "text-end",
2201
+ id: "itinerary-json"
2202
+ },
2203
+ {
2204
+ type: "finish",
2205
+ reason: "stop",
2206
+ usage
2207
+ }
2208
+ ],
2209
+ termination: { _tag: "Complete" }
2210
+ }];
2211
+ const phase0HappyPathTurns = phase1HappyPathTurns;
2212
+ //#endregion
2213
+ //#region src/fixtures/travel-planner/phase3.ts
2214
+ /**
2215
+ * The Phase 3 profile persists Conversation history but deliberately does not
2216
+ * claim durable admission or recovery of accepted work.
2217
+ */
2218
+ var TravelPlannerPersistenceProfile = class extends Schema.Class("@effect-agent/testing/travel-planner/TravelPlannerPersistenceProfile")({
2219
+ deploymentClass: Schema.Literal("P"),
2220
+ durableAcceptedWork: Schema.Literal(false),
2221
+ canonicalSchemaVersion: Schema.Literal(1)
2222
+ }) {};
2223
+ const phase3TravelPlannerProfile = TravelPlannerPersistenceProfile.make({
2224
+ deploymentClass: "P",
2225
+ durableAcceptedWork: false,
2226
+ canonicalSchemaVersion: 1
2227
+ });
2228
+ const phase3TravelPlannerConversationId = Schema.decodeSync(ConversationId)("travel-planner-p3-conversation");
2229
+ const phase3TravelPlannerProducerId = Schema.decodeSync(ProducerId)("travel-planner-p3-producer");
2230
+ const phase3TravelPlannerRunId = Schema.decodeSync(RunId)("travel-planner-p3-run");
2231
+ const deploymentId = Schema.decodeSync(DeploymentId)("travel-planner-p3-scripted");
2232
+ const agentId = Schema.decodeSync(AgentId)("travel-planner");
2233
+ const submissionId = Schema.decodeSync(SubmissionId)("travel-planner-p3-submission");
2234
+ const digest$2 = (character) => Schema.decodeSync(Digest)(character.repeat(64));
2235
+ /** Redacted, deterministic definition identities for the current fixture version. */
2236
+ const phase3TravelPlannerDefinitionDigests = DefinitionDigests.make({
2237
+ agent: digest$2("a"),
2238
+ model: digest$2("b"),
2239
+ tools: digest$2("c")
2240
+ });
2241
+ const tripInput = Schema.encodeSync(TripRequest)(phase1Trip);
2242
+ const travelPlanOutput = Schema.encodeSync(TravelPlan)(expectedTravelPlan);
2243
+ const record = (recordId, createdAt, payload) => Schema.decodeUnknownSync(RecordEnvelope)({
2244
+ recordId: Schema.decodeSync(RecordId)(recordId),
2245
+ family: "conversation",
2246
+ schemaVersion: 1,
2247
+ createdAt,
2248
+ deploymentId,
2249
+ payload
2250
+ });
2251
+ /**
2252
+ * The first atomic append establishes the Conversation and records its input.
2253
+ * Its encoded value is the redacted current-version persistence fixture.
2254
+ */
2255
+ const phase3TravelPlannerInitialBatch = CanonicalBatch.make({
2256
+ batchId: Schema.decodeSync(BatchId)("travel-planner-p3-initial"),
2257
+ producerId: phase3TravelPlannerProducerId,
2258
+ records: [record("travel-planner-p3-created", "2026-09-01T00:00:00.000Z", {
2259
+ _tag: "ConversationCreated",
2260
+ agentId,
2261
+ definitions: phase3TravelPlannerDefinitionDigests
2262
+ }), record("travel-planner-p3-input", "2026-09-01T00:00:01.000Z", {
2263
+ _tag: "UserInputRecorded",
2264
+ submissionId,
2265
+ kind: "user",
2266
+ runId: phase3TravelPlannerRunId,
2267
+ input: tripInput
2268
+ })]
2269
+ });
2270
+ /** The second append records the Schema-decoded itinerary and terminal Run result. */
2271
+ const phase3TravelPlannerCompletionBatch = CanonicalBatch.make({
2272
+ batchId: Schema.decodeSync(BatchId)("travel-planner-p3-completion"),
2273
+ producerId: phase3TravelPlannerProducerId,
2274
+ records: [record("travel-planner-p3-model", "2026-09-01T00:00:02.000Z", {
2275
+ _tag: "ModelCompleted",
2276
+ runId: phase3TravelPlannerRunId,
2277
+ output: travelPlanOutput
2278
+ }), record("travel-planner-p3-completed", "2026-09-01T00:00:03.000Z", {
2279
+ _tag: "RunCompleted",
2280
+ runId: phase3TravelPlannerRunId,
2281
+ output: travelPlanOutput
2282
+ })]
2283
+ });
2284
+ const phase3TravelPlannerBatches = [phase3TravelPlannerInitialBatch, phase3TravelPlannerCompletionBatch];
2285
+ /** Portable current-version fixture; it contains no passenger identity or credentials. */
2286
+ const phase3TravelPlannerEncodedFixture = Schema.encodeSync(Schema.Array(CanonicalBatch))(phase3TravelPlannerBatches);
2287
+ var TravelPlannerProjectionError = class extends Schema.TaggedErrorClass()("TravelPlannerProjectionError", { message: Schema.String }) {};
2288
+ /** Decode the itinerary projection rebuilt from canonical model-completion records. */
2289
+ const travelPlanFromProjection = (projection) => {
2290
+ const output = projection.modelOutputs.at(-1);
2291
+ if (output === void 0) return Effect.fail(TravelPlannerProjectionError.make({ message: "The canonical projection has no completed Travel Planner model output." }));
2292
+ return Schema.decodeUnknownEffect(TravelPlan)(output).pipe(Effect.mapError((error) => TravelPlannerProjectionError.make({ message: error.message })));
2293
+ };
2294
+ /** Build a disposable checkpoint bound to a validated canonical prefix. */
2295
+ const makePhase3TravelPlannerCheckpoint = (projection) => Schema.decodeSync(ConversationCheckpoint)({
2296
+ schemaVersion: 1,
2297
+ conversationId: projection.conversationId,
2298
+ throughSequence: projection.throughSequence,
2299
+ tailDigest: projection.tailDigest,
2300
+ engineVersion: "phase-3-test-runtime",
2301
+ agentDefinitionDigest: phase3TravelPlannerDefinitionDigests.agent,
2302
+ modelDigest: phase3TravelPlannerDefinitionDigests.model,
2303
+ toolDigest: phase3TravelPlannerDefinitionDigests.tools,
2304
+ state: Schema.encodeSync(ConversationProjection)(projection),
2305
+ createdAt: "2026-09-01T00:00:04.000Z"
2306
+ });
2307
+ //#endregion
2308
+ //#region src/scripted-model.ts
2309
+ const ScriptedPartMetadata = Schema.Record(Schema.String, Schema.NullOr(Schema.Json));
2310
+ const ScriptedPartBase = { metadata: Schema.optionalKey(ScriptedPartMetadata) };
2311
+ const ScriptedToolCallPart = Schema.Struct({
2312
+ ...ScriptedPartBase,
2313
+ type: Schema.Literal("tool-call"),
2314
+ id: Schema.String,
2315
+ name: Schema.String,
2316
+ params: Schema.Unknown,
2317
+ providerExecuted: Schema.optionalKey(Schema.Boolean)
2318
+ });
2319
+ const ScriptedToolResultPart = Schema.Struct({
2320
+ ...ScriptedPartBase,
2321
+ type: Schema.Literal("tool-result"),
2322
+ id: Schema.String,
2323
+ name: Schema.String,
2324
+ result: Schema.Unknown,
2325
+ isFailure: Schema.Boolean,
2326
+ providerExecuted: Schema.optionalKey(Schema.Boolean),
2327
+ preliminary: Schema.optionalKey(Schema.Boolean)
2328
+ });
2329
+ /**
2330
+ * Schema for encoded, non-streaming Effect AI response parts.
2331
+ *
2332
+ * Generic Tool payloads remain explicitly unknown here. `LanguageModel.make`
2333
+ * performs the toolkit-specific decode when the scripted response is consumed.
2334
+ */
2335
+ const ScriptedGeneratePart = Schema.Union([
2336
+ Schema.toEncoded(Response.TextPart),
2337
+ Schema.toEncoded(Response.ReasoningPart),
2338
+ Schema.toEncoded(Response.ReasoningDeltaPart),
2339
+ Schema.toEncoded(Response.ReasoningEndPart),
2340
+ ScriptedToolCallPart,
2341
+ ScriptedToolResultPart,
2342
+ Schema.toEncoded(Response.ToolApprovalRequestPart),
2343
+ Schema.toEncoded(Response.FilePart),
2344
+ Schema.toEncoded(Response.DocumentSourcePart),
2345
+ Schema.toEncoded(Response.UrlSourcePart),
2346
+ Schema.toEncoded(Response.ResponseMetadataPart),
2347
+ Schema.toEncoded(Response.FinishPart)
2348
+ ]).annotate({ identifier: "ScriptedGeneratePart" });
2349
+ /**
2350
+ * Schema for encoded Effect AI streaming response parts.
2351
+ */
2352
+ const ScriptedStreamPart = Schema.Union([
2353
+ Schema.toEncoded(Response.TextStartPart),
2354
+ Schema.toEncoded(Response.TextDeltaPart),
2355
+ Schema.toEncoded(Response.TextEndPart),
2356
+ Schema.toEncoded(Response.ReasoningStartPart),
2357
+ Schema.toEncoded(Response.ReasoningDeltaPart),
2358
+ Schema.toEncoded(Response.ReasoningEndPart),
2359
+ Schema.toEncoded(Response.ToolParamsStartPart),
2360
+ Schema.toEncoded(Response.ToolParamsDeltaPart),
2361
+ Schema.toEncoded(Response.ToolParamsEndPart),
2362
+ ScriptedToolCallPart,
2363
+ ScriptedToolResultPart,
2364
+ Schema.toEncoded(Response.ToolApprovalRequestPart),
2365
+ Schema.toEncoded(Response.FilePart),
2366
+ Schema.toEncoded(Response.DocumentSourcePart),
2367
+ Schema.toEncoded(Response.UrlSourcePart),
2368
+ Schema.toEncoded(Response.ResponseMetadataPart),
2369
+ Schema.toEncoded(Response.FinishPart),
2370
+ Schema.toEncoded(Response.ErrorPart)
2371
+ ]).annotate({ identifier: "ScriptedStreamPart" });
2372
+ /** Controls whether a scripted stream completes, fails, or waits for interruption. */
2373
+ const ScriptedStreamTermination = Schema.Union([
2374
+ Schema.TaggedStruct("Complete", {}),
2375
+ Schema.TaggedStruct("Fail", { description: Schema.String }),
2376
+ Schema.TaggedStruct("Hang", {})
2377
+ ]);
2378
+ /** One non-streaming invocation and the encoded response parts it returns. */
2379
+ const ScriptedGenerateTurn = Schema.TaggedStruct("Generate", { parts: Schema.Array(ScriptedGeneratePart) });
2380
+ /** One streaming invocation with its encoded parts and terminal behavior. */
2381
+ const ScriptedStreamTurn = Schema.TaggedStruct("Stream", {
2382
+ parts: Schema.Array(ScriptedStreamPart),
2383
+ termination: ScriptedStreamTermination
2384
+ });
2385
+ /**
2386
+ * Serializable grammar for one finite scripted provider invocation.
2387
+ */
2388
+ const ScriptedTurn = Schema.Union([ScriptedGenerateTurn, ScriptedStreamTurn]);
2389
+ const scriptedError = (method, description) => AiError.AiError.make({
2390
+ module: "@effect-agent/testing/ScriptedModel",
2391
+ method,
2392
+ reason: AiError.UnknownError.make({ description })
2393
+ });
2394
+ const runAssertion = Effect.fn("ScriptedModel.runAssertion")((assertion, request) => {
2395
+ if (assertion === void 0) return Effect.void;
2396
+ return Effect.suspend(() => {
2397
+ const result = assertion(request);
2398
+ return Effect.isEffect(result) ? result : Effect.void;
2399
+ });
2400
+ });
2401
+ const takeTurn = Effect.fn("ScriptedModel.takeTurn")((state, kind, options) => Ref.modify(state, (current) => {
2402
+ const turn = current.remaining[0];
2403
+ if (turn === void 0) return [void 0, {
2404
+ ...current,
2405
+ requests: [...current.requests, {
2406
+ kind,
2407
+ options
2408
+ }]
2409
+ }];
2410
+ return [turn, {
2411
+ remaining: current.remaining.slice(1),
2412
+ requests: [...current.requests, {
2413
+ kind,
2414
+ options
2415
+ }]
2416
+ }];
2417
+ }).pipe(Effect.flatMap((turn) => turn === void 0 ? Effect.fail(scriptedError(kind, `Script exhausted before the ${kind} request`)) : Effect.succeed(turn))));
2418
+ const requireGenerateTurn = (turn) => turn._tag === "Generate" ? Effect.succeed(turn) : Effect.fail(scriptedError("generate", `Expected a Generate turn but found ${turn._tag}`));
2419
+ const requireStreamTurn = (turn) => turn._tag === "Stream" ? Effect.succeed(turn) : Effect.fail(scriptedError("stream", `Expected a Stream turn but found ${turn._tag}`));
2420
+ const streamForTurn = (turn) => {
2421
+ let stream = Stream.fromIterable(turn.parts);
2422
+ switch (turn.termination._tag) {
2423
+ case "Complete": break;
2424
+ case "Fail":
2425
+ stream = stream.pipe(Stream.concat(Stream.fail(scriptedError("stream", turn.termination.description))));
2426
+ break;
2427
+ case "Hang":
2428
+ stream = stream.pipe(Stream.concat(Stream.never));
2429
+ break;
2430
+ }
2431
+ if (turn.onStreamStart !== void 0) stream = Stream.fromEffectDrain(turn.onStreamStart).pipe(Stream.concat(stream));
2432
+ if (turn.onStreamFinalize !== void 0) stream = stream.pipe(Stream.ensuring(turn.onStreamFinalize));
2433
+ return stream;
2434
+ };
2435
+ /** Inspection service for a deterministic LanguageModel backed by finite scripted turns. */
2436
+ var ScriptedModel = class ScriptedModel extends Context.Service()("@effect-agent/testing/ScriptedModel") {
2437
+ /**
2438
+ * Provides the native Effect AI `LanguageModel` and this inspection service.
2439
+ * Supplying the extra inspection service does not add it to model-call
2440
+ * requirements. Each model invocation consumes one turn before assertion and
2441
+ * turn-kind validation.
2442
+ */
2443
+ static layer(turns) {
2444
+ return Layer.effectContext(Effect.gen(function* () {
2445
+ const state = yield* Ref.make({
2446
+ remaining: [...turns],
2447
+ requests: []
2448
+ });
2449
+ const languageModel = yield* LanguageModel.make({
2450
+ generateText: (options) => Effect.gen(function* () {
2451
+ const turn = yield* takeTurn(state, "generate", options);
2452
+ yield* runAssertion(turn.assertRequest, options);
2453
+ return [...(yield* requireGenerateTurn(turn)).parts];
2454
+ }),
2455
+ streamText: (options) => Stream.unwrap(Effect.gen(function* () {
2456
+ const turn = yield* takeTurn(state, "stream", options);
2457
+ yield* runAssertion(turn.assertRequest, options);
2458
+ const streamTurn = yield* requireStreamTurn(turn);
2459
+ return streamForTurn(streamTurn);
2460
+ }))
2461
+ });
2462
+ const inspection = ScriptedModel.of({
2463
+ requests: Ref.get(state).pipe(Effect.map((current) => current.requests)),
2464
+ remaining: Ref.get(state).pipe(Effect.map((current) => current.remaining.length)),
2465
+ assertExhausted: Ref.get(state).pipe(Effect.flatMap((current) => current.remaining.length === 0 ? Effect.void : Effect.fail(scriptedError("assertExhausted", `${current.remaining.length} scripted turn(s) remain`))))
2466
+ });
2467
+ return Context.make(LanguageModel.LanguageModel, languageModel).pipe(Context.add(ScriptedModel, inspection));
2468
+ }));
2469
+ }
2470
+ };
2471
+ //#endregion
2472
+ //#region src/fixtures/travel-planner/phase4.ts
2473
+ /**
2474
+ * The Phase 4 profile claims durable accepted work on the Node/SQLite runtime (deployment class
2475
+ * DN): once `submit` returns a Receipt, the Submission settles exactly once even across process
2476
+ * loss. The claim is limited to safe-to-repeat toolkits (D6): supplier booking is explicitly NOT
2477
+ * claimed safely replayable — replay-safe external mutation is P5 (Durable Tools) scope.
2478
+ */
2479
+ var TravelPlannerDurabilityProfile = class extends Schema.Class("@effect-agent/testing/travel-planner/TravelPlannerDurabilityProfile")({
2480
+ deploymentClass: Schema.Literal("DN"),
2481
+ durableAcceptedWork: Schema.Literal(true),
2482
+ canonicalSchemaVersion: Schema.Literal(1),
2483
+ /** Supplier booking replay safety is P5 (Durable Tools) scope; DN does not claim it. */
2484
+ supplierBookingReplaySafe: Schema.Literal(false)
2485
+ }) {};
2486
+ const phase4TravelPlannerProfile = TravelPlannerDurabilityProfile.make({
2487
+ deploymentClass: "DN",
2488
+ durableAcceptedWork: true,
2489
+ canonicalSchemaVersion: 1,
2490
+ supplierBookingReplaySafe: false
2491
+ });
2492
+ const phase4TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)("travel-planner-p4-deployment");
2493
+ const phase4TravelPlannerProducerId = Schema.decodeSync(ProducerId)("travel-planner-p4-producer");
2494
+ const phase4TravelPlannerPrincipal = Schema.decodeSync(Principal)("travel-planner-p4-principal");
2495
+ const digest$1 = (character) => Schema.decodeSync(Digest)(character.repeat(64));
2496
+ /** Redacted, deterministic definition identities for the current fixture version. */
2497
+ const phase4TravelPlannerDefinitionDigests = DefinitionDigests.make({
2498
+ agent: digest$1("d"),
2499
+ model: digest$1("e"),
2500
+ tools: digest$1("f")
2501
+ });
2502
+ /** Durable admission options for one Travel Planner Submission on one trip lane. */
2503
+ const phase4TravelPlannerSubmitOptions = (conversationId, idempotencyKey) => ({
2504
+ conversationId,
2505
+ principal: phase4TravelPlannerPrincipal,
2506
+ idempotencyKey,
2507
+ definitions: phase4TravelPlannerDefinitionDigests
2508
+ });
2509
+ /**
2510
+ * The P4 read-only search Tools, calling the same deterministic catalogs as the P1 toolkit.
2511
+ *
2512
+ * The plain-Struct parameter shape is a historical remnant of the P4 carry-in workaround: since
2513
+ * the P5 engine fix, official history carries Schema-ENCODED Tool-call parameters, so class-typed
2514
+ * parameter codecs persist canonically too — the Structs simply need no change here. The
2515
+ * `ToolExecutionClass` `readonly` annotation is the deliberate P5 migration (plan §4.3): these
2516
+ * Tools perform no external mutation, so a crash between start and settlement is a free re-run
2517
+ * and they never enter the prepared/settled uncertainty protocol — keeping the P4 canonical
2518
+ * history byte-stable (an unannotated Tool fails closed to `uncertain`).
2519
+ */
2520
+ const DurableSearchFlights = Tool.make("search_flights", {
2521
+ parameters: Schema.Struct(FlightQuery.fields),
2522
+ success: FlightOption,
2523
+ failure: FlightUnavailable,
2524
+ failureMode: "error",
2525
+ dependencies: [FlightCatalog]
2526
+ }).annotate(ToolExecutionClass, "readonly");
2527
+ const DurableSearchLodging = Tool.make("search_lodging", {
2528
+ parameters: Schema.Struct(LodgingQuery.fields),
2529
+ success: LodgingOption,
2530
+ failure: LodgingUnavailable,
2531
+ failureMode: "error",
2532
+ dependencies: [LodgingCatalog]
2533
+ }).annotate(ToolExecutionClass, "readonly");
2534
+ const DurableSearchActivities = Tool.make("search_activities", {
2535
+ parameters: Schema.Struct(ActivityQuery.fields),
2536
+ success: ActivitySearchResult,
2537
+ failure: ActivityUnavailable,
2538
+ failureMode: "error",
2539
+ dependencies: [ActivityCatalog]
2540
+ }).annotate(ToolExecutionClass, "readonly");
2541
+ const TravelPlannerPhase4Toolkit = Toolkit.make(DurableSearchFlights, DurableSearchLodging, DurableSearchActivities);
2542
+ const TravelPlannerPhase4ToolkitLayer = TravelPlannerPhase4Toolkit.toLayer({
2543
+ search_flights: (query) => Effect.flatMap(FlightCatalog, (catalog) => catalog.search(FlightQuery.make(query))),
2544
+ search_lodging: (query) => Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(LodgingQuery.make(query))),
2545
+ search_activities: (query) => Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(ActivityQuery.make(query)))
2546
+ });
2547
+ /**
2548
+ * The cumulative Travel Planner, Phase 4: the P1 planning behavior on the durable Node/SQLite
2549
+ * runtime. The searches are read-only and safe to repeat across Attempts (D6); supplier booking
2550
+ * is deliberately absent because DN does NOT claim replay-safe external mutation (P5 scope).
2551
+ */
2552
+ const TravelPlannerPhase4 = Agent.define("travel-planner-phase-4", {
2553
+ input: TripRequest,
2554
+ output: TravelPlan,
2555
+ instructions: (input) => Effect.flatMap(TravelGuidance, (guidance) => guidance.instructions(input)),
2556
+ toolkit: TravelPlannerPhase4Toolkit,
2557
+ policy: AgentPolicy.make({
2558
+ maxTurns: 2,
2559
+ maxToolCalls: 3,
2560
+ maxDuration: "30 seconds",
2561
+ toolConcurrency: 3
2562
+ }),
2563
+ description: "Durably plan one review-only itinerary from safe-to-repeat deterministic searches; supplier booking is not claimed safely replayable.",
2564
+ metadata: {
2565
+ deploymentClass: "DN",
2566
+ phase: "P4"
2567
+ }
2568
+ });
2569
+ /**
2570
+ * The P4 Agent Binding: the durable Travel Planner definition bound to a finite scripted model.
2571
+ * The scripted Layer is rebuilt per Run, so every Run of one Binding replays the same
2572
+ * deterministic script.
2573
+ */
2574
+ const makePhase4TravelPlannerAgent = (turns = phase1HappyPathTurns) => Agent.withModel(TravelPlannerPhase4, Model.make("scripted", "travel-planner-phase-4", ScriptedModel.layer(turns)));
2575
+ /**
2576
+ * Everything a durable worker needs beyond the runtime stack, reusing the deterministic P1
2577
+ * travel-service Layers. The durable coordinator supplies its own deterministic `IdGenerator`,
2578
+ * so this Layer deliberately provides none.
2579
+ */
2580
+ const phase4TravelPlannerWorkerLayer = Layer.mergeAll(TravelPlannerPhase4ToolkitLayer, FlightCatalogLayer, LodgingCatalogLayer, ActivityCatalogLayer, TravelGuidanceLayer).pipe(Layer.provide(CatalogLifecycle.layerNoDeps));
2581
+ var TravelPlannerDurableEvidenceError = class extends Schema.TaggedErrorClass()("TravelPlannerDurableEvidenceError", { message: Schema.String }) {};
2582
+ /**
2583
+ * Decode the completed itinerary from the canonical `SubmissionSettled` record. Canonical history
2584
+ * is the outcome authority (DUR-015): the settled result — not any ledger cache — must decode
2585
+ * through the trip output schema.
2586
+ */
2587
+ const travelPlanFromDurableSettlement = Effect.fn("TravelPlannerPhase4.travelPlanFromDurableSettlement")(function* (records) {
2588
+ const settled = records.flatMap((envelope) => envelope.record.payload._tag === "SubmissionSettled" ? [envelope.record.payload] : []).at(0);
2589
+ if (settled === void 0) return yield* TravelPlannerDurableEvidenceError.make({ message: "The canonical Conversation Log has no SubmissionSettled record." });
2590
+ if (settled.outcome !== "completed" || settled.result === void 0) return yield* TravelPlannerDurableEvidenceError.make({ message: `The Submission settled ${settled.outcome} without a completed itinerary result.` });
2591
+ return yield* Schema.decodeUnknownEffect(TravelPlan)(settled.result).pipe(Effect.mapError((error) => TravelPlannerDurableEvidenceError.make({ message: `The settled result does not decode through the TravelPlan schema: ${error.message}` })));
2592
+ });
2593
+ const encodeEvidence = Schema.encodeEffect(Schema.Array(CanonicalRecordEnvelope));
2594
+ const decodeComparableJson$1 = Schema.decodeUnknownEffect(Schema.Json);
2595
+ /**
2596
+ * Project canonical evidence into a Submission-identity-independent comparable form: batch
2597
+ * identity, canonical sequence, and the full encoded record, with the ledger-minted
2598
+ * `submissionId`/`receiptId` (and every identity derived from them: run, turn, batch, record,
2599
+ * and settlement ids) replaced by stable placeholders. Two Conversations whose normalized
2600
+ * evidence is equal took byte-equivalent canonical histories, so restart-equivalence can compare
2601
+ * a recovered run against an uninterrupted control run on a separate database.
2602
+ */
2603
+ const normalizeDurableTravelPlannerEvidence = Effect.fn("TravelPlannerPhase4.normalizeDurableTravelPlannerEvidence")(function* (records, receipt) {
2604
+ const comparable = (yield* encodeEvidence(records).pipe(Effect.mapError((error) => TravelPlannerDurableEvidenceError.make({ message: `Canonical evidence failed to encode: ${error.message}` })))).map((envelope) => ({
2605
+ batchId: envelope.batchId,
2606
+ sequence: envelope.sequence,
2607
+ record: envelope.record
2608
+ }));
2609
+ const substituted = JSON.parse(JSON.stringify(comparable).replaceAll(receipt.submissionId, "{submissionId}").replaceAll(receipt.receiptId, "{receiptId}"));
2610
+ return yield* decodeComparableJson$1(substituted).pipe(Effect.mapError((error) => TravelPlannerDurableEvidenceError.make({ message: `Normalized evidence is not comparable JSON: ${error.message}` })));
2611
+ });
2612
+ //#endregion
2613
+ //#region src/fixtures/travel-planner/phase5.ts
2614
+ /**
2615
+ * The Phase 5 profile extends the P4 `DN` claim to consequential supplier mutation: booking
2616
+ * Tools enter the prepared/settled uncertainty protocol, unresolved external effects stop at
2617
+ * Unknown Outcomes instead of replaying, Durable Steps replay recorded results, and queued
2618
+ * traveler input joins the active Run. Exactly-once EXTERNAL execution is still — deliberately —
2619
+ * not claimed (DUR-003): the supplier's own idempotency keys are what dedupe repeats.
2620
+ */
2621
+ var TravelPlannerBookingProfile = class extends Schema.Class("@effect-agent/testing/travel-planner/TravelPlannerBookingProfile")({
2622
+ deploymentClass: Schema.Literal("DN"),
2623
+ durableAcceptedWork: Schema.Literal(true),
2624
+ canonicalSchemaVersion: Schema.Literal(1),
2625
+ /** P5: supplier mutations get prepared/settled records, Unknown Outcomes, and reconciliation. */
2626
+ supplierBookingUncertaintyProtocol: Schema.Literal(true),
2627
+ /** P5: Durable Steps are exactly-once-RECORDED; their side effects stay at-least-once. */
2628
+ durableStepsRecorded: Schema.Literal(true),
2629
+ /** Never claimed at any phase (DUR-003). */
2630
+ exactlyOnceExternalEffects: Schema.Literal(false)
2631
+ }) {};
2632
+ const phase5TravelPlannerProfile = TravelPlannerBookingProfile.make({
2633
+ deploymentClass: "DN",
2634
+ durableAcceptedWork: true,
2635
+ canonicalSchemaVersion: 1,
2636
+ supplierBookingUncertaintyProtocol: true,
2637
+ durableStepsRecorded: true,
2638
+ exactlyOnceExternalEffects: false
2639
+ });
2640
+ const phase5TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)("travel-planner-p5-deployment");
2641
+ const phase5TravelPlannerProducerId = Schema.decodeSync(ProducerId)("travel-planner-p5-producer");
2642
+ const phase5TravelPlannerPrincipal = Schema.decodeSync(Principal)("travel-planner-p5-principal");
2643
+ const digest = (character) => Schema.decodeSync(Digest)(character.repeat(64));
2644
+ /** Redacted, deterministic definition identities for the current fixture version. */
2645
+ const phase5TravelPlannerDefinitionDigests = DefinitionDigests.make({
2646
+ agent: digest("1"),
2647
+ model: digest("2"),
2648
+ tools: digest("3")
2649
+ });
2650
+ /** Durable admission options for one Travel Planner Submission on one trip lane. */
2651
+ const phase5TravelPlannerSubmitOptions = (conversationId, idempotencyKey) => ({
2652
+ conversationId,
2653
+ principal: phase5TravelPlannerPrincipal,
2654
+ idempotencyKey,
2655
+ definitions: phase5TravelPlannerDefinitionDigests
2656
+ });
2657
+ const TravelerRef = Schema.NonEmptyString.pipe(Schema.brand("@effect-agent/testing/travel-planner/TravelerRef"));
2658
+ /**
2659
+ * Class-shaped booking parameters with branded fields: since the P5 engine fix, official history
2660
+ * carries Schema-ENCODED Tool-call parameters, so class-typed parameter codecs persist
2661
+ * canonically end-to-end (the P4 Struct workaround is gone for new Tools).
2662
+ */
2663
+ var FlightBookingRequest = class extends Schema.Class("FlightBookingRequest")({
2664
+ quoteId: QuoteId,
2665
+ travelerRef: TravelerRef,
2666
+ departOn: Schema.String
2667
+ }) {};
2668
+ var SupplierBookingConfirmation = class extends Schema.Class("SupplierBookingConfirmation")({
2669
+ bookingRef: BookingRef,
2670
+ status: Schema.Literal("confirmed"),
2671
+ detail: Schema.String
2672
+ }) {};
2673
+ var CancelBookingRequest = class extends Schema.Class("CancelBookingRequest")({
2674
+ bookingRef: BookingRef,
2675
+ travelerRef: TravelerRef
2676
+ }) {};
2677
+ var CancellationConfirmation = class extends Schema.Class("CancellationConfirmation")({
2678
+ bookingRef: BookingRef,
2679
+ status: Schema.Literal("cancelled")
2680
+ }) {};
2681
+ var ItineraryBookingRequest = class extends Schema.Class("ItineraryBookingRequest")({
2682
+ quoteId: QuoteId,
2683
+ destination: AirportCode,
2684
+ nights: Schema.Int.check(Schema.isGreaterThan(0)),
2685
+ travelerRef: TravelerRef
2686
+ }) {};
2687
+ var ItineraryConfirmation = class extends Schema.Class("ItineraryConfirmation")({
2688
+ flightBookingRef: BookingRef,
2689
+ lodgingBookingRef: BookingRef,
2690
+ confirmationCode: Schema.String
2691
+ }) {};
2692
+ /** The P5 Run output: a booked (or explicitly not-booked) trip report. */
2693
+ var TravelBookingReport = class extends Schema.Class("TravelBookingReport")({
2694
+ summary: Schema.String,
2695
+ bookingRefs: Schema.Array(BookingRef)
2696
+ }) {};
2697
+ /**
2698
+ * Supplier idempotency-key derivations. The handler owns key derivation (the `idempotent` and
2699
+ * `uncertain` execution classes carry no key), and the reconciler MUST use the same derivations
2700
+ * to query external truth — both sides are exported so they cannot drift.
2701
+ */
2702
+ const bookFlightIdempotencyKey = (toolCallId) => `book-flight:${toolCallId}`;
2703
+ const itineraryStepIdempotencyKey = (toolCallId, stepName) => `${toolCallId}:${stepName}`;
2704
+ /**
2705
+ * Approval-gated supplier booking, explicitly `uncertain`: a crash after the call may have
2706
+ * mutated supplier state without a recorded outcome, so recovery must reconcile or stop at an
2707
+ * Unknown Outcome — never replay automatically (DUR-009, ADR-0004).
2708
+ */
2709
+ const BookFlight = Tool.make("book_flight", {
2710
+ parameters: FlightBookingRequest,
2711
+ success: SupplierBookingConfirmation,
2712
+ failure: SupplierUnavailable,
2713
+ failureMode: "error",
2714
+ needsApproval: true,
2715
+ dependencies: [SupplierBookingDesk]
2716
+ }).annotate(ToolExecutionClass, "uncertain");
2717
+ /**
2718
+ * Approval-gated cancellation, annotated `idempotent`: the DECLARED external contract is that
2719
+ * cancellation is idempotent by `bookingRef` (the supplier desk enforces it), so recovery may
2720
+ * re-execute a prepared-but-unsettled cancel without reconciliation proof. Repeats stay
2721
+ * observable in the supplier call counters — the annotation never claims exactly-once execution.
2722
+ */
2723
+ const CancelBooking = Tool.make("cancel_booking", {
2724
+ parameters: CancelBookingRequest,
2725
+ success: CancellationConfirmation,
2726
+ failure: SupplierUnavailable,
2727
+ failureMode: "error",
2728
+ needsApproval: true,
2729
+ dependencies: [SupplierBookingDesk]
2730
+ }).annotate(ToolExecutionClass, "idempotent");
2731
+ /**
2732
+ * The Durable Tool: declaring `DurableStep` in `dependencies` is what makes it durable
2733
+ * (CONTEXT.md). Its handler divides supplier mutation into three named Steps — `reserve-flight`,
2734
+ * `reserve-lodging`, `issue-confirmation` — each deriving its supplier idempotency key from
2735
+ * `(toolCallId, stepName)`, so re-entry after interruption replays recorded Step results and the
2736
+ * supplier dedupes any honestly-repeated call. The Tool itself carries no execution-class
2737
+ * annotation: it stays fail-closed `uncertain`, and `TravelSupplierReconcilerLayer` proves
2738
+ * re-entry safe from the keyed-Step construction instead.
2739
+ */
2740
+ const BookItinerary = Tool.make("book_itinerary", {
2741
+ parameters: ItineraryBookingRequest,
2742
+ success: ItineraryConfirmation,
2743
+ failure: Schema.Union([SupplierUnavailable, DurableStepError]),
2744
+ failureMode: "error",
2745
+ dependencies: [DurableStep, SupplierBookingDesk]
2746
+ });
2747
+ const TravelPlannerPhase5Toolkit = Toolkit.make(DurableSearchFlights, DurableSearchLodging, DurableSearchActivities, BookFlight, CancelBooking, BookItinerary);
2748
+ const requireToolCallId = (toolName, toolCallId) => toolCallId === void 0 ? Effect.fail(SupplierUnavailable.make({ message: `${toolName} needs its stable Tool Call ID to derive the supplier idempotency key.` })) : Effect.succeed(toolCallId);
2749
+ const TravelPlannerPhase5ToolkitLayer = TravelPlannerPhase5Toolkit.toLayer({
2750
+ search_flights: (query) => Effect.flatMap(FlightCatalog, (catalog) => catalog.search(FlightQuery.make(query))),
2751
+ search_lodging: (query) => Effect.flatMap(LodgingCatalog, (catalog) => catalog.search(LodgingQuery.make(query))),
2752
+ search_activities: (query) => Effect.flatMap(ActivityCatalog, (catalog) => catalog.search(ActivityQuery.make(query))),
2753
+ book_flight: (request, context) => Effect.gen(function* () {
2754
+ const desk = yield* SupplierBookingDesk;
2755
+ const toolCallId = yield* requireToolCallId("book_flight", context.toolCallId);
2756
+ const record = yield* desk.book({
2757
+ operation: "book-flight",
2758
+ idempotencyKey: bookFlightIdempotencyKey(toolCallId),
2759
+ detail: `flight ${request.quoteId} for ${request.travelerRef} on ${request.departOn}`
2760
+ });
2761
+ return SupplierBookingConfirmation.make({
2762
+ bookingRef: record.bookingRef,
2763
+ status: "confirmed",
2764
+ detail: record.detail
2765
+ });
2766
+ }),
2767
+ cancel_booking: (request) => Effect.gen(function* () {
2768
+ const record = yield* (yield* SupplierBookingDesk).cancel(request.bookingRef);
2769
+ return CancellationConfirmation.make({
2770
+ bookingRef: record.bookingRef,
2771
+ status: "cancelled"
2772
+ });
2773
+ }),
2774
+ book_itinerary: (request, context) => Effect.gen(function* () {
2775
+ const desk = yield* SupplierBookingDesk;
2776
+ const step = yield* DurableStep;
2777
+ const toolCallId = yield* requireToolCallId("book_itinerary", context.toolCallId);
2778
+ const bookStep = (stepName, detail) => step.do(stepName, SupplierBookingRecord, desk.book({
2779
+ operation: stepName,
2780
+ idempotencyKey: itineraryStepIdempotencyKey(toolCallId, stepName),
2781
+ detail
2782
+ }));
2783
+ const flight = yield* bookStep("reserve-flight", `flight ${request.quoteId} for ${request.travelerRef}`);
2784
+ const lodging = yield* bookStep("reserve-lodging", `lodging ${request.destination} for ${request.nights} nights (${request.travelerRef})`);
2785
+ const confirmation = yield* bookStep("issue-confirmation", `itinerary confirmation for ${request.travelerRef}`);
2786
+ return ItineraryConfirmation.make({
2787
+ flightBookingRef: flight.bookingRef,
2788
+ lodgingBookingRef: lodging.bookingRef,
2789
+ confirmationCode: confirmation.bookingRef
2790
+ });
2791
+ })
2792
+ });
2793
+ const decodePersistedJson = Schema.decodeUnknownEffect(PersistedJson);
2794
+ const encodeConfirmation = Schema.encodeEffect(SupplierBookingConfirmation);
2795
+ /**
2796
+ * The application reconciliation policy (durability §10): a claim about EXTERNAL truth, queried
2797
+ * from the supplier desk by the same idempotency-key derivations the handlers use.
2798
+ *
2799
+ * - `book_flight`: a confirmed booking under `book-flight:{toolCallId}` is recovered supplier
2800
+ * truth — `CompletedWithResult` settles it canonically without executing anything. Absence is
2801
+ * NOT proof the call never started (a real supplier write could be in flight), so the desk
2802
+ * answer stays fail-closed `Uncertain`.
2803
+ * - `book_itinerary`: every external mutation inside is a named Step whose supplier idempotency
2804
+ * key derives from `(toolCallId, stepName)`, so re-entry is provably safe by construction —
2805
+ * `SafeToRetry`. Committed Steps replay from their records; repeated calls dedupe at the desk.
2806
+ * - `cancel_booking`: declared `idempotent`, so the coordinator re-executes without consulting
2807
+ * this policy; if ever asked, the bookingRef contract makes `SafeToRetry` honest.
2808
+ * - anything else: fail-closed `Uncertain` (AGENTS rule 11).
2809
+ */
2810
+ const TravelSupplierReconcilerLayer = Layer.effect(ToolReconciler, Effect.gen(function* () {
2811
+ const desk = yield* SupplierBookingDesk;
2812
+ return ToolReconciler.of({ reconcile: (evidence) => Effect.gen(function* () {
2813
+ switch (evidence.toolName) {
2814
+ case "book_flight": {
2815
+ const key = bookFlightIdempotencyKey(evidence.toolCallId);
2816
+ const booking = yield* desk.lookup(key);
2817
+ if (Option.isSome(booking) && booking.value.status === "confirmed") {
2818
+ const confirmation = yield* encodeConfirmation(SupplierBookingConfirmation.make({
2819
+ bookingRef: booking.value.bookingRef,
2820
+ status: "confirmed",
2821
+ detail: booking.value.detail
2822
+ })).pipe(Effect.flatMap(decodePersistedJson));
2823
+ return ReconciliationCompleted.make({
2824
+ result: confirmation,
2825
+ isFailure: false
2826
+ });
2827
+ }
2828
+ return ReconciliationUncertain.make({ reason: `The supplier desk shows no confirmed booking under ${key}; a write may still be in flight.` });
2829
+ }
2830
+ case "book_itinerary": return ReconciliationSafeToRetry.make();
2831
+ case "cancel_booking": return ReconciliationSafeToRetry.make();
2832
+ default: return ReconciliationUncertain.make({ reason: `No supplier reconciliation exists for ${evidence.toolName}.` });
2833
+ }
2834
+ }).pipe(Effect.mapError((error) => ToolReconcilerError.make({
2835
+ toolCallId: evidence.toolCallId,
2836
+ message: `Supplier reconciliation failed: ${error.message}`
2837
+ }))) });
2838
+ }));
2839
+ /**
2840
+ * The cumulative Travel Planner, Phase 5: the durable planner now performs consequential
2841
+ * supplier mutation under the full uncertainty protocol — approval-gated uncertain booking,
2842
+ * idempotent-by-contract cancellation, and one Durable Tool whose Steps carry supplier
2843
+ * idempotency keys.
2844
+ */
2845
+ const TravelPlannerPhase5 = Agent.define("travel-planner-phase-5", {
2846
+ input: TripRequest,
2847
+ output: TravelBookingReport,
2848
+ instructions: [
2849
+ "You are the Effect Agent Travel Planner P5 booking fixture.",
2850
+ "Search with the read-only tools, then book with book_flight, book_itinerary, or",
2851
+ "cancel_booking exactly as scripted. Every consequential mutation is approval-gated",
2852
+ "or Step-structured. Return only a JSON object with summary and bookingRefs."
2853
+ ].join(" "),
2854
+ toolkit: TravelPlannerPhase5Toolkit,
2855
+ policy: AgentPolicy.make({
2856
+ maxTurns: 4,
2857
+ maxToolCalls: 6,
2858
+ maxDuration: "30 seconds",
2859
+ toolConcurrency: 2
2860
+ }),
2861
+ description: "Durably book one itinerary with prepared/settled supplier records, Unknown Outcomes, named Steps, and joined traveler input.",
2862
+ metadata: {
2863
+ deploymentClass: "DN",
2864
+ phase: "P5"
2865
+ }
2866
+ });
2867
+ var TravelPlannerBookingEvidenceError = class extends Schema.TaggedErrorClass()("TravelPlannerBookingEvidenceError", { message: Schema.String }) {};
2868
+ const bookingResultRefs = (result) => {
2869
+ if (typeof result !== "object" || result === null) return [];
2870
+ const refs = [];
2871
+ for (const [field, value] of Object.entries(result)) if (typeof value === "string" && (field === "bookingRef" || field === "flightBookingRef" || field === "lodgingBookingRef" || field === "confirmationCode")) refs.push(value);
2872
+ return refs;
2873
+ };
2874
+ const bookingToolNames = /* @__PURE__ */ new Set([
2875
+ "book_flight",
2876
+ "cancel_booking",
2877
+ "book_itinerary"
2878
+ ]);
2879
+ /**
2880
+ * Never-fabricate assertion (ROADMAP P5 exit gate): every successfully settled booking result in
2881
+ * canonical history must reference a booking that actually exists in the supplier store. A
2882
+ * `ToolCallSettled` whose bookingRef the supplier cannot produce would be a fabricated result —
2883
+ * the exact lie the uncertainty protocol exists to prevent.
2884
+ */
2885
+ const assertSettledBookingsExistAtSupplier = Effect.fn("TravelPlannerPhase5.assertSettledBookingsExistAtSupplier")(function* (records) {
2886
+ const bookings = yield* (yield* SupplierBookingDesk).bookings;
2887
+ const knownRefs = new Set(bookings.map((booking) => booking.bookingRef));
2888
+ for (const envelope of records) {
2889
+ const payload = envelope.record.payload;
2890
+ if (payload._tag !== "ToolCallSettled" || payload.isFailure || !bookingToolNames.has(payload.toolName)) continue;
2891
+ for (const ref of bookingResultRefs(payload.result)) if (!knownRefs.has(ref)) return yield* TravelPlannerBookingEvidenceError.make({ message: `Canonical record ${envelope.record.recordId} settled bookingRef ${ref}, which the supplier store cannot produce — a fabricated result.` });
2892
+ }
2893
+ });
2894
+ /**
2895
+ * Everything a durable P5 worker needs beyond the runtime stack and the supplier desk: the
2896
+ * booking toolkit plus the deterministic P1 travel-service Layers. `SupplierBookingDesk` is
2897
+ * deliberately NOT provided here — tests own the desk's lifetime so its counters, bookings, and
2898
+ * crash windows survive Tool-Layer rebuilds across Attempts.
2899
+ */
2900
+ const phase5TravelPlannerWorkerLayer = Layer.mergeAll(TravelPlannerPhase5ToolkitLayer, FlightCatalogLayer, LodgingCatalogLayer, ActivityCatalogLayer).pipe(Layer.provide(CatalogLifecycle.layerNoDeps));
2901
+ //#endregion
2902
+ //#region src/fixtures/travel-planner/subagents.ts
2903
+ var DestinationQuery = class extends Schema.Class("DestinationQuery")({ destination: AirportCode }) {};
2904
+ var DestinationFacts = class extends Schema.Class("DestinationFacts")({
2905
+ destination: AirportCode,
2906
+ highlights: Schema.Array(Schema.String),
2907
+ advisory: Schema.NonEmptyString
2908
+ }) {};
2909
+ var DestinationGuideUnavailable = class extends Schema.TaggedErrorClass()("DestinationGuideUnavailable", {
2910
+ destination: AirportCode,
2911
+ message: Schema.String
2912
+ }) {};
2913
+ var DestinationGuide = class extends Context.Service()("@effect-agent/testing/travel-planner/DestinationGuide") {};
2914
+ const LookupDestination = Tool.make("lookup_destination", {
2915
+ parameters: DestinationQuery,
2916
+ success: DestinationFacts,
2917
+ failure: DestinationGuideUnavailable,
2918
+ failureMode: "error",
2919
+ dependencies: [DestinationGuide]
2920
+ });
2921
+ const DestinationResearcherToolkit = Toolkit.make(LookupDestination);
2922
+ const DestinationResearcherToolkitLayer = DestinationResearcherToolkit.toLayer({ lookup_destination: (query) => Effect.flatMap(DestinationGuide, (guide) => guide.lookup(query)) });
2923
+ var DestinationBrief = class extends Schema.Class("DestinationBrief")({
2924
+ destination: AirportCode,
2925
+ focus: Schema.NonEmptyString
2926
+ }) {};
2927
+ var DestinationReport = class extends Schema.Class("DestinationReport")({
2928
+ destination: AirportCode,
2929
+ highlights: Schema.Array(Schema.String),
2930
+ advisory: Schema.NonEmptyString
2931
+ }) {};
2932
+ const DestinationResearcher = Agent.define("destination-researcher", {
2933
+ input: DestinationBrief,
2934
+ output: DestinationReport,
2935
+ instructions: "Consult lookup_destination exactly once for the briefed airport, then return only a JSON destination report.",
2936
+ toolkit: DestinationResearcherToolkit,
2937
+ policy: AgentPolicy.make({
2938
+ maxTurns: 2,
2939
+ maxToolCalls: 1,
2940
+ maxDuration: "30 seconds",
2941
+ toolConcurrency: 1
2942
+ }),
2943
+ description: "Research one candidate destination with the deterministic travel guide.",
2944
+ metadata: {
2945
+ deploymentClass: "E",
2946
+ phase: "S1"
2947
+ }
2948
+ });
2949
+ const decodeAirportCode = Schema.decodeSync(AirportCode);
2950
+ const guideFacts = /* @__PURE__ */ new Map([["LHR", DestinationFacts.make({
2951
+ destination: decodeAirportCode("LHR"),
2952
+ highlights: ["Barbican brutalism walk", "Kew glasshouse survey"],
2953
+ advisory: "London favors museum mornings and riverside evenings."
2954
+ })], ["CDG", DestinationFacts.make({
2955
+ destination: decodeAirportCode("CDG"),
2956
+ highlights: ["Marais passage crawl", "Seine bookstall loop"],
2957
+ advisory: "Paris rewards early galleries and late cafes."
2958
+ })]]);
2959
+ /** Deterministic guide lookup shared by the default and test-local guide Layers. */
2960
+ const destinationLookup = (query) => {
2961
+ const facts = guideFacts.get(query.destination);
2962
+ return facts === void 0 ? Effect.fail(DestinationGuideUnavailable.make({
2963
+ destination: query.destination,
2964
+ message: "No deterministic guide entry exists for this destination."
2965
+ })) : Effect.succeed(facts);
2966
+ };
2967
+ const requireDestinationFacts = (destination) => {
2968
+ const facts = guideFacts.get(destination);
2969
+ if (facts === void 0) throw new Error(`No deterministic guide entry exists for destination ${destination}`);
2970
+ return facts;
2971
+ };
2972
+ /** The report the scripted researcher writes after consulting the guide. */
2973
+ const destinationReportFor = (destination) => {
2974
+ const facts = requireDestinationFacts(destination);
2975
+ return DestinationReport.make({
2976
+ destination: facts.destination,
2977
+ highlights: facts.highlights,
2978
+ advisory: facts.advisory
2979
+ });
2980
+ };
2981
+ const encodedDestinationReport = (destination) => JSON.stringify(Schema.encodeSync(DestinationReport)(destinationReportFor(destination)));
2982
+ const DestinationGuideLayer = Layer.effect(DestinationGuide, Effect.gen(function* () {
2983
+ const lifecycle = yield* CatalogLifecycle;
2984
+ yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);
2985
+ return DestinationGuide.of({ lookup: destinationLookup });
2986
+ }));
2987
+ /** Child-side construction requirements of the delegation handler Layer. */
2988
+ const DestinationResearchSupportLayer = Layer.mergeAll(DestinationResearcherToolkitLayer, DestinationGuideLayer);
2989
+ var DestinationResearchRequest = class extends Schema.Class("DestinationResearchRequest")({
2990
+ destination: AirportCode,
2991
+ focus: Schema.NonEmptyString
2992
+ }) {};
2993
+ var DestinationResearchFindings = class extends Schema.Class("DestinationResearchFindings")({
2994
+ destination: AirportCode,
2995
+ summary: Schema.NonEmptyString
2996
+ }) {};
2997
+ var DestinationResearchFailed = class extends Schema.TaggedErrorClass()("DestinationResearchFailed", { childErrorTag: Schema.NonEmptyString }) {};
2998
+ /**
2999
+ * Deterministic delegation-admission choreography seam. `prepareInput` awaits
3000
+ * this gate before the handler reserves budget or spawns, so tests can order
3001
+ * concurrent delegation preflights without sleeps. It also keeps the
3002
+ * projection's construction requirements honestly visible in the handler
3003
+ * Layer's `R` (spec/subagents.md §4.1). The open Layer never waits.
3004
+ */
3005
+ var ResearchDispatchGate = class ResearchDispatchGate extends Context.Service()("@effect-agent/testing/travel-planner/ResearchDispatchGate") {
3006
+ static layerOpen = Layer.succeed(this, ResearchDispatchGate.of({ awaitDispatch: () => Effect.void }));
3007
+ };
3008
+ /**
3009
+ * Finite per-invocation bounds (SUB-009): each child may use two Turns and
3010
+ * one Tool Call; the parent Run may establish at most two children with at
3011
+ * most two running concurrently.
3012
+ */
3013
+ const destinationResearchPolicy = SubagentPolicy.make({
3014
+ maxChildren: 2,
3015
+ maxConcurrency: 2,
3016
+ maxTurns: 2,
3017
+ maxToolCalls: 1,
3018
+ maxDuration: "10 seconds"
3019
+ });
3020
+ const destinationResearchDelegation = Subagent.define("delegate_destination_research", {
3021
+ description: "Research one candidate destination with the deterministic travel guide and return a bounded finding.",
3022
+ target: DestinationResearcher,
3023
+ parameters: DestinationResearchRequest,
3024
+ success: DestinationResearchFindings,
3025
+ failure: DestinationResearchFailed,
3026
+ prepareInput: (request) => Effect.gen(function* () {
3027
+ yield* (yield* ResearchDispatchGate).awaitDispatch(request.destination);
3028
+ return DestinationBrief.make({
3029
+ destination: request.destination,
3030
+ focus: `research:${request.focus}`
3031
+ });
3032
+ }),
3033
+ projectResult: (report) => Effect.succeed(DestinationResearchFindings.make({
3034
+ destination: report.destination,
3035
+ summary: report.advisory
3036
+ })),
3037
+ policy: destinationResearchPolicy
3038
+ });
3039
+ /** Total mapping from every expected child Run failure to the declared Tool failure (SUB-028). */
3040
+ const mapResearchChildFailure = (failure) => DestinationResearchFailed.make({ childErrorTag: failure._tag });
3041
+ /** Runtime wiring: pair the immutable delegation with one explicit child Binding. */
3042
+ const destinationResearchHandlersLayer = (childBinding) => SubagentRuntime.layer(destinationResearchDelegation, childBinding, { mapChildFailure: mapResearchChildFailure });
3043
+ var ResearchMission = class extends Schema.Class("ResearchMission")({
3044
+ request: Schema.NonEmptyString,
3045
+ candidates: Schema.Array(AirportCode).check(Schema.isMinLength(1))
3046
+ }) {};
3047
+ var DestinationRecommendation = class extends Schema.Class("DestinationRecommendation")({
3048
+ destination: AirportCode,
3049
+ summary: Schema.NonEmptyString
3050
+ }) {};
3051
+ var DestinationShortlist = class extends Schema.Class("DestinationShortlist")({
3052
+ recommendations: Schema.Array(DestinationRecommendation),
3053
+ nextAction: Schema.Literal("review")
3054
+ }) {};
3055
+ /** Parent-only transcript markers used to prove child context isolation (SUB-006/015). */
3056
+ const coordinatorConfidentialMarker = "coordinator-vault-7q42";
3057
+ const missionConfidentialMarker = "traveler-dossier-19f";
3058
+ const TravelCoordinatorToolkit = Toolkit.make(destinationResearchDelegation.tool);
3059
+ const TravelCoordinator = Agent.define("travel-coordinator", {
3060
+ input: ResearchMission,
3061
+ output: DestinationShortlist,
3062
+ instructions: [
3063
+ "You are the Effect Agent Travel Planner S1 delegation coordinator.",
3064
+ `Coordinator-only context: ${coordinatorConfidentialMarker}.`,
3065
+ "Call delegate_destination_research once per candidate in one Tool batch.",
3066
+ "Return only a JSON shortlist built from the delegated findings. This is read-only planning."
3067
+ ].join("\n"),
3068
+ toolkit: TravelCoordinatorToolkit,
3069
+ policy: AgentPolicy.make({
3070
+ maxTurns: 2,
3071
+ maxToolCalls: 3,
3072
+ maxDuration: "30 seconds",
3073
+ toolConcurrency: 3
3074
+ }),
3075
+ description: "Coordinate bounded destination research through one declared attached delegation Tool.",
3076
+ metadata: {
3077
+ deploymentClass: "E",
3078
+ phase: "S1"
3079
+ }
3080
+ });
3081
+ const researchMission = Schema.decodeSync(ResearchMission)({
3082
+ request: `Shortlist one September culture city; keep ${missionConfidentialMarker} inside the coordinator conversation.`,
3083
+ candidates: ["LHR", "CDG"]
3084
+ });
3085
+ const expectedDestinationShortlist = DestinationShortlist.make({
3086
+ recommendations: researchMission.candidates.map((destination) => DestinationRecommendation.make({
3087
+ destination,
3088
+ summary: requireDestinationFacts(destination).advisory
3089
+ })),
3090
+ nextAction: "review"
3091
+ });
3092
+ const scriptedUsage$2 = {
3093
+ inputTokens: { total: 96 },
3094
+ outputTokens: { total: 64 }
3095
+ };
3096
+ /** One coordinator Turn that declares the given delegation Tool Calls in order. */
3097
+ const coordinatorResearchTurn = (calls) => ({
3098
+ _tag: "Stream",
3099
+ parts: [...calls.map((call) => ({
3100
+ type: "tool-call",
3101
+ id: call.id,
3102
+ name: "delegate_destination_research",
3103
+ params: {
3104
+ destination: call.destination,
3105
+ focus: call.focus
3106
+ }
3107
+ })), {
3108
+ type: "finish",
3109
+ reason: "tool-calls",
3110
+ usage: scriptedUsage$2
3111
+ }],
3112
+ termination: { _tag: "Complete" }
3113
+ });
3114
+ /** The coordinator's final structured-output Turn. */
3115
+ const coordinatorShortlistTurn = (shortlist) => ({
3116
+ _tag: "Stream",
3117
+ parts: [
3118
+ {
3119
+ type: "text-start",
3120
+ id: "shortlist"
3121
+ },
3122
+ {
3123
+ type: "text-delta",
3124
+ id: "shortlist",
3125
+ delta: JSON.stringify(Schema.encodeSync(DestinationShortlist)(shortlist))
3126
+ },
3127
+ {
3128
+ type: "text-end",
3129
+ id: "shortlist"
3130
+ },
3131
+ {
3132
+ type: "finish",
3133
+ reason: "stop",
3134
+ usage: scriptedUsage$2
3135
+ }
3136
+ ],
3137
+ termination: { _tag: "Complete" }
3138
+ });
3139
+ /** Static researcher script for single-child tests: one guide lookup, then the report. */
3140
+ const researcherHappyPathTurns = (destination) => [{
3141
+ _tag: "Stream",
3142
+ parts: [{
3143
+ type: "tool-call",
3144
+ id: `lookup-${destination}`,
3145
+ name: "lookup_destination",
3146
+ params: { destination }
3147
+ }, {
3148
+ type: "finish",
3149
+ reason: "tool-calls",
3150
+ usage: scriptedUsage$2
3151
+ }],
3152
+ termination: { _tag: "Complete" }
3153
+ }, {
3154
+ _tag: "Stream",
3155
+ parts: [
3156
+ {
3157
+ type: "text-start",
3158
+ id: "destination-report"
3159
+ },
3160
+ {
3161
+ type: "text-delta",
3162
+ id: "destination-report",
3163
+ delta: encodedDestinationReport(destination)
3164
+ },
3165
+ {
3166
+ type: "text-end",
3167
+ id: "destination-report"
3168
+ },
3169
+ {
3170
+ type: "finish",
3171
+ reason: "stop",
3172
+ usage: scriptedUsage$2
3173
+ }
3174
+ ],
3175
+ termination: { _tag: "Complete" }
3176
+ }];
3177
+ const researcherLookupParts$2 = (destination) => [{
3178
+ type: "tool-call",
3179
+ id: `lookup-${destination}`,
3180
+ name: "lookup_destination",
3181
+ params: { destination },
3182
+ providerExecuted: false
3183
+ }, {
3184
+ type: "finish",
3185
+ reason: "tool-calls",
3186
+ usage: scriptedUsage$2
3187
+ }];
3188
+ const researcherReportParts$2 = (destination) => [
3189
+ {
3190
+ type: "text-start",
3191
+ id: "destination-report"
3192
+ },
3193
+ {
3194
+ type: "text-delta",
3195
+ id: "destination-report",
3196
+ delta: encodedDestinationReport(destination)
3197
+ },
3198
+ {
3199
+ type: "text-end",
3200
+ id: "destination-report"
3201
+ },
3202
+ {
3203
+ type: "finish",
3204
+ reason: "stop",
3205
+ usage: scriptedUsage$2
3206
+ }
3207
+ ];
3208
+ /**
3209
+ * Build a deterministic researcher Model whose per-child behavior is keyed by
3210
+ * the destination named in the child's own prompt: Turn one records the
3211
+ * prompt, signals `started`, and calls the guide Tool; Turn two waits for the
3212
+ * caller's `release` before writing the report. Each child Run builds the
3213
+ * Model Layer inside its own scope, so one `CatalogLifecycle` acquisition and
3214
+ * finalization is observed per child — the same acquire/release counting the
3215
+ * catalog Layers use to prove interruption reaches every finalizer.
3216
+ */
3217
+ const makeDestinationResearcherModel = (destinations) => Effect.gen(function* () {
3218
+ const lifecycle = yield* CatalogLifecycle;
3219
+ const prompts = yield* Ref.make([]);
3220
+ const gates = /* @__PURE__ */ new Map();
3221
+ for (const destination of destinations) gates.set(destination, {
3222
+ started: yield* Deferred.make(),
3223
+ release: yield* Deferred.make()
3224
+ });
3225
+ const gatesFor = (destination) => Effect.suspend(() => {
3226
+ const entry = gates.get(destination);
3227
+ return entry === void 0 ? Effect.die(/* @__PURE__ */ new Error(`No researcher gates exist for destination ${destination}`)) : Effect.succeed(entry);
3228
+ });
3229
+ return {
3230
+ controls: {
3231
+ awaitStarted: (destination) => gatesFor(destination).pipe(Effect.flatMap((entry) => Deferred.await(entry.started))),
3232
+ release: (destination) => gatesFor(destination).pipe(Effect.flatMap((entry) => Deferred.succeed(entry.release, void 0)), Effect.asVoid),
3233
+ prompts: Ref.get(prompts)
3234
+ },
3235
+ model: Model.make("scripted", "destination-researcher-scripted", Layer.effect(LanguageModel.LanguageModel, Effect.gen(function* () {
3236
+ yield* Effect.acquireRelease(lifecycle.markAcquired, () => lifecycle.markFinalized);
3237
+ const turn = yield* Ref.make(0);
3238
+ return yield* LanguageModel.make({
3239
+ generateText: () => Effect.succeed([]),
3240
+ streamText: (options) => Stream.unwrap(Effect.gen(function* () {
3241
+ const promptJson = JSON.stringify(options.prompt.content);
3242
+ const destination = destinations.find((candidate) => promptJson.includes(candidate));
3243
+ if (destination === void 0) return yield* Effect.die(/* @__PURE__ */ new Error("The researcher prompt names no scripted destination"));
3244
+ const entry = yield* gatesFor(destination);
3245
+ if ((yield* Ref.getAndUpdate(turn, (value) => value + 1)) === 0) {
3246
+ yield* Ref.update(prompts, (previous) => [...previous, promptJson]);
3247
+ yield* Deferred.succeed(entry.started, void 0);
3248
+ return Stream.fromIterable(researcherLookupParts$2(destination));
3249
+ }
3250
+ yield* Deferred.await(entry.release);
3251
+ return Stream.fromIterable(researcherReportParts$2(destination));
3252
+ }))
3253
+ });
3254
+ })))
3255
+ };
3256
+ });
3257
+ //#endregion
3258
+ //#region src/fixtures/travel-planner/subagents-durable.ts
3259
+ var TravelPlannerSubagentDurabilityProfile = class extends Schema.Class("@effect-agent/testing/travel-planner/TravelPlannerSubagentDurabilityProfile")({
3260
+ deploymentClass: Schema.Literal("DN"),
3261
+ durableAttachedSubagents: Schema.Literal(true),
3262
+ canonicalSchemaVersion: Schema.Literal(1),
3263
+ /** Establishment/join replay converges on one child Receipt, Conversation, and join batch. */
3264
+ subagentReplaySafe: Schema.Literal(true),
3265
+ /** Never claimed (rule 8): child ordinary Tools stop at Unknown Outcomes, they do not replay. */
3266
+ childExternalEffectsExactlyOnce: Schema.Literal(false),
3267
+ /** The same conformance suite under DO eviction/alarms is P6 scope (spec §17 `DC`). */
3268
+ cloudflareEquivalence: Schema.Literal(false)
3269
+ }) {};
3270
+ const s2TravelPlannerProfile = TravelPlannerSubagentDurabilityProfile.make({
3271
+ deploymentClass: "DN",
3272
+ durableAttachedSubagents: true,
3273
+ canonicalSchemaVersion: 1,
3274
+ subagentReplaySafe: true,
3275
+ childExternalEffectsExactlyOnce: false,
3276
+ cloudflareEquivalence: false
3277
+ });
3278
+ const s2TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)("travel-planner-s2-deployment");
3279
+ const s2TravelPlannerProducerId = Schema.decodeSync(ProducerId)("travel-planner-s2-producer");
3280
+ const s2TravelPlannerPrincipal = Schema.decodeSync(Principal)("travel-planner-s2-principal");
3281
+ const digestOf$1 = (character) => Schema.decodeSync(Digest)(character.repeat(64));
3282
+ /** Redacted, deterministic parent (coordinator) definition digests for this fixture version. */
3283
+ const s2CoordinatorDigests = DefinitionDigests.make({
3284
+ agent: digestOf$1("a"),
3285
+ model: digestOf$1("b"),
3286
+ tools: digestOf$1("c")
3287
+ });
3288
+ /**
3289
+ * The exact child Binding digest strings the application declares on
3290
+ * `SubagentRuntimeOptions.durable.targetDigests` AND the host registers with
3291
+ * the `AgentBindingResolver` for the researcher Binding. The coordinator
3292
+ * stores and verifies them byte-for-byte (SUB-023); a host registration under
3293
+ * different strings is a `ChildCompatibilityFailure`, never a substitution.
3294
+ */
3295
+ const s2ResearcherDigestStrings = {
3296
+ agent: "d".repeat(64),
3297
+ model: "e".repeat(64),
3298
+ tools: "f".repeat(64)
3299
+ };
3300
+ const s2ResearcherDigests = DefinitionDigests.make({
3301
+ agent: Schema.decodeSync(Digest)(s2ResearcherDigestStrings.agent),
3302
+ model: Schema.decodeSync(Digest)(s2ResearcherDigestStrings.model),
3303
+ tools: Schema.decodeSync(Digest)(s2ResearcherDigestStrings.tools)
3304
+ });
3305
+ /** Durable admission options for one coordinator Submission on one mission lane. */
3306
+ const s2TravelPlannerSubmitOptions = (conversationId, idempotencyKey) => ({
3307
+ conversationId,
3308
+ principal: s2TravelPlannerPrincipal,
3309
+ idempotencyKey,
3310
+ definitions: s2CoordinatorDigests
3311
+ });
3312
+ /** The structural submit slice of the coordinator Binding (`DurableAgentRuntime.submit`). */
3313
+ const s2CoordinatorSubmitAgent = { definition: {
3314
+ id: TravelCoordinator.id,
3315
+ input: TravelCoordinator.input
3316
+ } };
3317
+ /**
3318
+ * The per-invocation reservation the durable handler computes from the S1
3319
+ * delegation policy (`delegationAllocationFromPolicy`): the conservation
3320
+ * evidence in the S2 tests checks the ledger reservation rows and the
3321
+ * canonical `SubagentJoined.finalAccounting` against exactly this value.
3322
+ */
3323
+ const durableResearchAllocation = delegationAllocationFromPolicy(destinationResearchPolicy);
3324
+ /** The one scripted delegation Tool Call id of the durable coordinator Run. */
3325
+ const durableResearchCallId = "research-lhr-1";
3326
+ /** The child's own scripted guide-lookup Tool Call id. */
3327
+ const durableChildLookupCallId = (destination) => `lookup-${destination}`;
3328
+ /** The projected finding the parent joins (only the advisory crosses, SUB-015). */
3329
+ const durableResearchFinding = (destination) => ({
3330
+ destination: destinationReportFor(destination).destination,
3331
+ summary: destinationReportFor(destination).advisory
3332
+ });
3333
+ /** The coordinator's expected final shortlist for one researched destination. */
3334
+ const durableResearchShortlist = (destination) => DestinationShortlist.make({
3335
+ recommendations: [DestinationRecommendation.make({
3336
+ destination: destinationReportFor(destination).destination,
3337
+ summary: destinationReportFor(destination).advisory
3338
+ })],
3339
+ nextAction: "review"
3340
+ });
3341
+ /**
3342
+ * The deterministic guide facts in encoded (wire) form: the "supplier truth"
3343
+ * an authorized operator records through `resolveUnknown` when a child guide
3344
+ * lookup stopped at an Unknown Outcome (DUR-017 — the framework never guesses
3345
+ * or replays it).
3346
+ */
3347
+ const encodedDestinationFacts = (destination) => {
3348
+ const report = destinationReportFor(destination);
3349
+ return Schema.encodeSync(DestinationFacts)(DestinationFacts.make({
3350
+ destination: report.destination,
3351
+ highlights: report.highlights,
3352
+ advisory: report.advisory
3353
+ }));
3354
+ };
3355
+ const scriptedUsage$1 = {
3356
+ inputTokens: { total: 96 },
3357
+ outputTokens: { total: 64 }
3358
+ };
3359
+ /** One scripted model whose behavior is keyed by the global invocation index. */
3360
+ const makeInvocationCountingModel = (name, script) => Effect.gen(function* () {
3361
+ const calls = yield* Ref.make(0);
3362
+ const prompts = yield* Ref.make([]);
3363
+ return {
3364
+ model: Model.make("scripted", name, Layer.effect(LanguageModel.LanguageModel, LanguageModel.make({
3365
+ generateText: () => Effect.succeed([]),
3366
+ streamText: (request) => Stream.unwrap(Effect.gen(function* () {
3367
+ const call = yield* Ref.getAndUpdate(calls, (value) => value + 1);
3368
+ yield* Ref.update(prompts, (previous) => [...previous, JSON.stringify(request.prompt.content)]);
3369
+ return Stream.fromIterable(script(call));
3370
+ }))
3371
+ }))),
3372
+ calls: Ref.get(calls),
3373
+ prompts: Ref.get(prompts)
3374
+ };
3375
+ });
3376
+ const delegationTurnParts = (toolCallId, destination, focus) => [{
3377
+ type: "tool-call",
3378
+ id: toolCallId,
3379
+ name: "delegate_destination_research",
3380
+ params: {
3381
+ destination,
3382
+ focus
3383
+ },
3384
+ providerExecuted: false
3385
+ }, {
3386
+ type: "finish",
3387
+ reason: "tool-calls",
3388
+ usage: scriptedUsage$1
3389
+ }];
3390
+ const shortlistParts = (shortlist) => [
3391
+ {
3392
+ type: "text-start",
3393
+ id: "shortlist"
3394
+ },
3395
+ {
3396
+ type: "text-delta",
3397
+ id: "shortlist",
3398
+ delta: JSON.stringify(Schema.encodeSync(DestinationShortlist)(shortlist))
3399
+ },
3400
+ {
3401
+ type: "text-end",
3402
+ id: "shortlist"
3403
+ },
3404
+ {
3405
+ type: "finish",
3406
+ reason: "stop",
3407
+ usage: scriptedUsage$1
3408
+ }
3409
+ ];
3410
+ const researcherLookupParts$1 = (destination) => [{
3411
+ type: "tool-call",
3412
+ id: durableChildLookupCallId(destination),
3413
+ name: "lookup_destination",
3414
+ params: { destination },
3415
+ providerExecuted: false
3416
+ }, {
3417
+ type: "finish",
3418
+ reason: "tool-calls",
3419
+ usage: scriptedUsage$1
3420
+ }];
3421
+ const researcherReportParts$1 = (destination) => [
3422
+ {
3423
+ type: "text-start",
3424
+ id: "destination-report"
3425
+ },
3426
+ {
3427
+ type: "text-delta",
3428
+ id: "destination-report",
3429
+ delta: encodedDestinationReport(destination)
3430
+ },
3431
+ {
3432
+ type: "text-end",
3433
+ id: "destination-report"
3434
+ },
3435
+ {
3436
+ type: "finish",
3437
+ reason: "stop",
3438
+ usage: scriptedUsage$1
3439
+ }
3440
+ ];
3441
+ /** Runtime wiring for the durable slice: the S1 delegation plus the S2 digest declaration. */
3442
+ const durableDestinationResearchHandlersLayer = (childBinding) => SubagentRuntime.layer(destinationResearchDelegation, childBinding, {
3443
+ mapChildFailure: mapResearchChildFailure,
3444
+ durable: { targetDigests: s2ResearcherDigestStrings }
3445
+ });
3446
+ /**
3447
+ * Build the S2 Travel Planner harness: an invocation-counting scripted
3448
+ * coordinator (Turn 1 declares the one delegation call, Turn 2 writes the
3449
+ * shortlist), an invocation-counting scripted researcher (Turn 1 consults the
3450
+ * guide, Turn 2 writes the report), and both worker Bindings captured with
3451
+ * their requirement Contexts via `DurableWorkerBinding.make` under the exact
3452
+ * fixture digests. The returned `bindings` are plain values: they can be
3453
+ * registered with several `NodeDurableRuntime` stacks over the same SQLite
3454
+ * file while the counters keep counting across all of them.
3455
+ */
3456
+ const makeDurableResearchHarness = (options) => Effect.gen(function* () {
3457
+ const destination = options?.destination ?? "LHR";
3458
+ const focus = options?.focus ?? "museums";
3459
+ const guideInvocations = yield* Ref.make(0);
3460
+ const guideLayer = Layer.succeed(DestinationGuide, DestinationGuide.of({ lookup: (query) => Ref.update(guideInvocations, (count) => count + 1).pipe(Effect.andThen(destinationLookup(query))) }));
3461
+ const childToolkitLayer = DestinationResearcherToolkitLayer.pipe(Layer.provideMerge(guideLayer));
3462
+ const childModel = yield* makeInvocationCountingModel("destination-researcher-s2", (call) => call === 0 ? researcherLookupParts$1(destination) : researcherReportParts$1(destination));
3463
+ const childBinding = Agent.withModel(DestinationResearcher, childModel.model);
3464
+ const parentModel = yield* makeInvocationCountingModel("travel-coordinator-s2", (call) => call === 0 ? delegationTurnParts(durableResearchCallId, destination, focus) : shortlistParts(durableResearchShortlist(destination)));
3465
+ const parentBinding = Agent.withModel(TravelCoordinator, parentModel.model);
3466
+ const delegationLayer = durableDestinationResearchHandlersLayer(childBinding).pipe(Layer.provide(Layer.mergeAll(childToolkitLayer, SubagentReservationsMemoryLive, DeterministicIdGeneratorLayer, ResearchDispatchGate.layerOpen)));
3467
+ return {
3468
+ bindings: [yield* DurableWorkerBinding.make(parentBinding, s2CoordinatorDigests).pipe(Effect.provide(delegationLayer)), yield* DurableWorkerBinding.make(childBinding, options?.childRegistrationDigests ?? s2ResearcherDigests).pipe(Effect.provide(childToolkitLayer))],
3469
+ parentModelCalls: parentModel.calls,
3470
+ parentPrompts: parentModel.prompts,
3471
+ childModelCalls: childModel.calls,
3472
+ childPrompts: childModel.prompts,
3473
+ guideInvocations: Ref.get(guideInvocations)
3474
+ };
3475
+ });
3476
+ //#endregion
3477
+ //#region src/fixtures/travel-planner/phase6.ts
3478
+ /**
3479
+ * The Phase 6 profile: the P4/P5/S2 Travel Planner claims re-earned on the Cloudflare Durable
3480
+ * Object runtime (deployment class `DC`), where eviction and alarm redelivery replace process
3481
+ * kill and restart as the exercised recovery path. `cloudflareEquivalence` is the claim the S2
3482
+ * fixture explicitly deferred to P6 (`TravelPlannerSubagentDurabilityProfile` pins it `false`
3483
+ * for `DN`): it flips to `true` here ONLY because the phase-6 suites assert byte-equal
3484
+ * cross-platform normalized canonical evidence against one committed golden. Exactly-once
3485
+ * EXTERNAL effects remain — deliberately — unclaimed on every platform (DUR-003).
3486
+ */
3487
+ var TravelPlannerCloudflareProfile = class extends Schema.Class("@effect-agent/testing/travel-planner/TravelPlannerCloudflareProfile")({
3488
+ deploymentClass: Schema.Literal("DC"),
3489
+ durableAcceptedWork: Schema.Literal(true),
3490
+ canonicalSchemaVersion: Schema.Literal(1),
3491
+ /** P5 semantics under DC recovery: prepared/settled records, Unknown Outcomes, approvals. */
3492
+ supplierBookingUncertaintyProtocol: Schema.Literal(true),
3493
+ /** S2 semantics under DC recovery: cross-Object establishment/join, completed child never re-runs. */
3494
+ durableAttachedSubagents: Schema.Literal(true),
3495
+ /** DN and DC produce byte-equal cross-platform normalized canonical evidence (one golden). */
3496
+ cloudflareEquivalence: Schema.Literal(true),
3497
+ /** Never claimed at any phase on any platform (DUR-003). */
3498
+ exactlyOnceExternalEffects: Schema.Literal(false)
3499
+ }) {};
3500
+ const phase6TravelPlannerProfile = TravelPlannerCloudflareProfile.make({
3501
+ deploymentClass: "DC",
3502
+ durableAcceptedWork: true,
3503
+ canonicalSchemaVersion: 1,
3504
+ supplierBookingUncertaintyProtocol: true,
3505
+ durableAttachedSubagents: true,
3506
+ cloudflareEquivalence: true,
3507
+ exactlyOnceExternalEffects: false
3508
+ });
3509
+ const phase6TravelPlannerDeploymentId = Schema.decodeSync(DeploymentId)("travel-planner-p6-deployment");
3510
+ /** Producer prefix of the DC host; each Object mints `{prefix}:{conversationId}`. */
3511
+ const phase6TravelPlannerProducerPrefix = "travel-planner-p6-producer";
3512
+ /** The full producer identity one DC Conversation Object mints for itself. */
3513
+ const phase6TravelPlannerProducerId = (conversationId) => Schema.decodeSync(ProducerId)(`${phase6TravelPlannerProducerPrefix}:${conversationId}`);
3514
+ const digestOf = (character) => Schema.decodeSync(Digest)(character.repeat(64));
3515
+ /**
3516
+ * Registration digests of the GATED planner Binding: the same `TravelPlannerPhase4` definition
3517
+ * bound to a model whose first response waits on a test gate, addressable separately so the
3518
+ * admission-limits rows can hold a lane busy deterministically without touching the ordinary
3519
+ * planner registration.
3520
+ */
3521
+ const phase6GatedPlannerDefinitionDigests = DefinitionDigests.make({
3522
+ agent: digestOf("9"),
3523
+ model: digestOf("8"),
3524
+ tools: digestOf("7")
3525
+ });
3526
+ const decodeComparableJson = Schema.decodeUnknownEffect(Schema.Json);
3527
+ /** The base normal form's element shape, re-decoded so sequences can be renumbered. */
3528
+ const ComparableEnvelope = Schema.Struct({
3529
+ batchId: Schema.String,
3530
+ sequence: Schema.Number,
3531
+ record: Schema.Json
3532
+ });
3533
+ const decodeComparableEnvelopes = Schema.decodeUnknownEffect(Schema.Array(ComparableEnvelope));
3534
+ /**
3535
+ * The CROSS-PLATFORM extension of `normalizeDurableTravelPlannerEvidence` (D-P6-6): after the
3536
+ * base normalization replaces the two ledger-minted identities (which also normalizes the
3537
+ * DC-format routable `{uuidv7}:{conversationId}` Submission identities and everything derived
3538
+ * from them), this form additionally scrubs everything that legitimately differs between a DN
3539
+ * process and a DC Durable Object over the same scenario:
3540
+ *
3541
+ * - `RepairAnnotated` audit records are dropped BEFORE normalization and the canonical
3542
+ * sequence is renumbered to the surviving order: repairs are DUR-013 evidence of recovery
3543
+ * itself, legally present in a recovered run and legally absent from an uninterrupted
3544
+ * control (on DC even a CLEAN run carries one, because every pass reconciles before it
3545
+ * claims, so the ready lane's input is applied through the recovery path). Canonical ORDER
3546
+ * is the durability §5 claim; sequence contiguity is a platform artifact of who appended;
3547
+ * - the Conversation identity (DC lanes mint unique names per test run);
3548
+ * - the deployment and producer identities (host configuration, not canonical semantics);
3549
+ * - `createdAt` commit timestamps (wall clock);
3550
+ * - 64-hex digests (they hash RAW content that legally embeds run-specific identity, so they
3551
+ * can never be byte-equal across runs; chain integrity is asserted separately by the
3552
+ * adapters and the convergence helpers).
3553
+ *
3554
+ * Two runs whose cross-platform normalized evidence is byte-equal took canonically equivalent
3555
+ * histories — the exact sense in which durability §5 permits storage differences while
3556
+ * requiring the same observable ordering. Both the DN and DC suites assert equality against
3557
+ * the one committed `phase6TravelPlannerGoldenEvidence`, so DN ≡ DC transitively.
3558
+ */
3559
+ const normalizeCrossPlatformTravelPlannerEvidence = Effect.fn("TravelPlannerPhase6.normalizeCrossPlatformTravelPlannerEvidence")(function* (records, receipt, identity) {
3560
+ const base = yield* normalizeDurableTravelPlannerEvidence(records.filter((envelope) => envelope.record.payload._tag !== "RepairAnnotated"), receipt);
3561
+ const scrubbed = JSON.parse(JSON.stringify(base).replaceAll(identity.producerId, "{producerId}").replaceAll(identity.deploymentId, "{deploymentId}").replaceAll(identity.conversationId, "{conversationId}").replaceAll(/\d{4}-\d{2}-\d{2}T[0-9:.]+Z/g, "{timestamp}").replaceAll(/"[0-9a-f]{64}"/g, "\"{digest}\""));
3562
+ const renumbered = (yield* decodeComparableEnvelopes(scrubbed).pipe(Effect.mapError((error) => TravelPlannerDurableEvidenceError.make({ message: `Cross-platform normalized evidence lost the comparable shape: ${error.message}` })))).map((entry, index) => ({
3563
+ batchId: entry.batchId,
3564
+ sequence: index + 1,
3565
+ record: entry.record
3566
+ }));
3567
+ return yield* decodeComparableJson(renumbered).pipe(Effect.mapError((error) => TravelPlannerDurableEvidenceError.make({ message: `Cross-platform normalized evidence is not comparable JSON: ${error.message}` })));
3568
+ });
3569
+ const scriptedUsage = {
3570
+ inputTokens: { total: 128 },
3571
+ outputTokens: { total: 96 }
3572
+ };
3573
+ const promptAwareModel = (name, decide) => Model.make("scripted", name, Layer.effect(LanguageModel.LanguageModel, LanguageModel.make({
3574
+ generateText: () => Effect.succeed([]),
3575
+ streamText: (options) => Stream.unwrap(Effect.sync(() => decide(JSON.stringify(options.prompt))))
3576
+ })));
3577
+ /** The P1/P4 happy-path Tool Call identities (scenarios.ts, byte-stable since P1). */
3578
+ const phase6FlightCallId = "flight-call-1";
3579
+ const phase6LodgingCallId = "lodging-call-1";
3580
+ const phase6ActivityCallId = "activity-call-1";
3581
+ /** Turn 1 of the planner: the SAME three search declarations as `phase1HappyPathTurns`. */
3582
+ const plannerSearchTurnParts = [
3583
+ {
3584
+ type: "tool-call",
3585
+ id: phase6FlightCallId,
3586
+ name: "search_flights",
3587
+ params: {
3588
+ origin: "SFO",
3589
+ destination: "LHR",
3590
+ departOn: "2026-09-14",
3591
+ travelers: 2
3592
+ }
3593
+ },
3594
+ {
3595
+ type: "tool-call",
3596
+ id: phase6LodgingCallId,
3597
+ name: "search_lodging",
3598
+ params: {
3599
+ destination: "LHR",
3600
+ departOn: "2026-09-14",
3601
+ nights: 4,
3602
+ travelers: 2
3603
+ }
3604
+ },
3605
+ {
3606
+ type: "tool-call",
3607
+ id: phase6ActivityCallId,
3608
+ name: "search_activities",
3609
+ params: {
3610
+ destination: "LHR",
3611
+ departOn: "2026-09-14",
3612
+ nights: 4,
3613
+ travelers: 2
3614
+ }
3615
+ },
3616
+ {
3617
+ type: "finish",
3618
+ reason: "tool-calls",
3619
+ usage: scriptedUsage
3620
+ }
3621
+ ];
3622
+ /** Turn 2 of the planner: the SAME itinerary text as `phase1HappyPathTurns`. */
3623
+ const plannerPlanTurnParts = [
3624
+ {
3625
+ type: "text-start",
3626
+ id: "itinerary-json"
3627
+ },
3628
+ {
3629
+ type: "text-delta",
3630
+ id: "itinerary-json",
3631
+ delta: JSON.stringify(Schema.encodeSync(TravelPlan)(expectedTravelPlan))
3632
+ },
3633
+ {
3634
+ type: "text-end",
3635
+ id: "itinerary-json"
3636
+ },
3637
+ {
3638
+ type: "finish",
3639
+ reason: "stop",
3640
+ usage: scriptedUsage
3641
+ }
3642
+ ];
3643
+ const plannerDecide = (promptJson) => promptJson.includes("flight-call-1") ? Stream.fromIterable(plannerPlanTurnParts) : Stream.fromIterable(plannerSearchTurnParts);
3644
+ /**
3645
+ * The P4 planner script (`phase1HappyPathTurns`) as a prompt-aware model: once the search
3646
+ * batch is committed history, every later request gets the plan — identical parts, so the DC
3647
+ * canonical evidence is byte-equivalent to the DN ScriptedModel run after normalization.
3648
+ */
3649
+ const phase6PlannerModel = promptAwareModel("travel-planner-phase-4", plannerDecide);
3650
+ const releasedPlannerGates = /* @__PURE__ */ new Set();
3651
+ /** Release the gated planner model for one `[gate:...]` marker. */
3652
+ const releasePhase6PlannerGate = (marker) => {
3653
+ releasedPlannerGates.add(marker);
3654
+ };
3655
+ /** Re-close one gate marker (fresh suites reuse markers safely). */
3656
+ const resetPhase6PlannerGate = (marker) => {
3657
+ releasedPlannerGates.delete(marker);
3658
+ };
3659
+ const awaitPlannerGate = (marker) => Effect.gen(function* () {
3660
+ while (!releasedPlannerGates.has(marker)) yield* Effect.sleep(Duration.millis(10));
3661
+ });
3662
+ const gateMarkerFromPrompt = (promptJson) => /\[gate:([^\]]+)\]/.exec(promptJson)?.[1] ?? "unknown-gate";
3663
+ /** A trip whose request text carries the gate marker the gated model waits on. */
3664
+ const phase6GatedTrip = (marker) => Schema.decodeUnknownSync(TripRequest)({
3665
+ request: `Plan a review-only London trip, but wait for the concierge. [gate:${marker}]`,
3666
+ origin: "SFO",
3667
+ destination: "LHR",
3668
+ departOn: "2026-09-14",
3669
+ nights: 4,
3670
+ travelers: 2,
3671
+ budgetCents: 35e4,
3672
+ currency: "USD"
3673
+ });
3674
+ /**
3675
+ * The SAME planner behavior with a hanging first response: the model waits on the released
3676
+ * gate before answering, keeping its lane durably busy so queue-depth admission limits can be
3677
+ * exercised deterministically.
3678
+ */
3679
+ const phase6GatedPlannerModel = Model.make("scripted", "travel-planner-phase-4-gated", Layer.effect(LanguageModel.LanguageModel, LanguageModel.make({
3680
+ generateText: () => Effect.succeed([]),
3681
+ streamText: (options) => Stream.unwrap(Effect.sync(() => {
3682
+ const promptJson = JSON.stringify(options.prompt);
3683
+ return promptJson.includes("flight-call-1") ? plannerDecide(promptJson) : Stream.fromEffectDrain(awaitPlannerGate(gateMarkerFromPrompt(promptJson))).pipe(Stream.concat(plannerDecide(promptJson)));
3684
+ }))
3685
+ })));
3686
+ const sharedSupplierDesk = Effect.runSync(Effect.flatMap(SupplierBookingDesk, Effect.succeed).pipe(Effect.provide(SupplierBookingDesk.layer)));
3687
+ /** The shared external supplier desk instance (module-level external truth). */
3688
+ const phase6SupplierDesk = sharedSupplierDesk;
3689
+ /** Layer handing the shared desk to Bindings, reconcilers, and assertions. */
3690
+ const phase6SupplierDeskLayer = Layer.succeed(SupplierBookingDesk, sharedSupplierDesk);
3691
+ /**
3692
+ * The REAL P5 supplier reconciliation policy over the shared desk, closed to no requirements
3693
+ * so a Conversation Object can install it directly: `book_flight` recovers only from supplier
3694
+ * truth (absence stays fail-closed `Uncertain` → durable Unknown Outcome), keyed Steps are
3695
+ * provably re-enterable.
3696
+ */
3697
+ const phase6SupplierReconcilerLayer = TravelSupplierReconcilerLayer.pipe(Layer.provide(phase6SupplierDeskLayer));
3698
+ const bookingMarkerFromPrompt = (promptJson) => /\[case:([^\]]+)\]/.exec(promptJson)?.[1] ?? "unknown-case";
3699
+ /** The deterministic booking Tool Call identity for one `[case:...]` marker. */
3700
+ const phase6BookingToolCallId = (marker) => `book-${marker}`;
3701
+ /** The bookingRef the supplier desk mints for one marker's approved booking. */
3702
+ const phase6BookingRef = (marker) => supplierBookingRefFor(bookFlightIdempotencyKey(phase6BookingToolCallId(marker)));
3703
+ /** A trip whose request text carries the per-lane booking case marker. */
3704
+ const phase6BookingTrip = (marker) => Schema.decodeUnknownSync(TripRequest)({
3705
+ request: `Book the approved London flight for the traveler. [case:${marker}]`,
3706
+ origin: "SFO",
3707
+ destination: "LHR",
3708
+ departOn: "2026-09-14",
3709
+ nights: 4,
3710
+ travelers: 2,
3711
+ budgetCents: 35e4,
3712
+ currency: "USD"
3713
+ });
3714
+ const bookingCallParts = (marker) => [{
3715
+ type: "tool-call",
3716
+ id: phase6BookingToolCallId(marker),
3717
+ name: "book_flight",
3718
+ params: {
3719
+ quoteId: "quote-sfo-lhr-001",
3720
+ travelerRef: `traveler-${marker}`,
3721
+ departOn: "2026-09-14"
3722
+ },
3723
+ providerExecuted: false
3724
+ }, {
3725
+ type: "finish",
3726
+ reason: "tool-calls",
3727
+ usage: scriptedUsage
3728
+ }];
3729
+ const bookingReportParts = (marker) => [
3730
+ {
3731
+ type: "text-start",
3732
+ id: "booking-report"
3733
+ },
3734
+ {
3735
+ type: "text-delta",
3736
+ id: "booking-report",
3737
+ delta: JSON.stringify({
3738
+ summary: "trip booked",
3739
+ bookingRefs: [phase6BookingRef(marker)]
3740
+ })
3741
+ },
3742
+ {
3743
+ type: "text-end",
3744
+ id: "booking-report"
3745
+ },
3746
+ {
3747
+ type: "finish",
3748
+ reason: "stop",
3749
+ usage: scriptedUsage
3750
+ }
3751
+ ];
3752
+ /**
3753
+ * The P5 booking script as a prompt-aware model: request 1 declares the approval-gated
3754
+ * `book_flight` call (identity derived from the lane's `[case:...]` marker so supplier
3755
+ * idempotency keys never collide across lanes); once that call is committed history, the model
3756
+ * writes the booking report.
3757
+ */
3758
+ const phase6BookingModel = promptAwareModel("travel-planner-phase-5", (promptJson) => {
3759
+ const marker = bookingMarkerFromPrompt(promptJson);
3760
+ return promptJson.includes(phase6BookingToolCallId(marker)) ? Stream.fromIterable(bookingReportParts(marker)) : Stream.fromIterable(bookingCallParts(marker));
3761
+ });
3762
+ let guideInvocations = 0;
3763
+ /** Deterministic guide-lookup handler executions across every incarnation. */
3764
+ const phase6GuideInvocationCount = () => guideInvocations;
3765
+ const countingGuideLayer = Layer.succeed(DestinationGuide, DestinationGuide.of({ lookup: (query) => Effect.suspend(() => {
3766
+ guideInvocations += 1;
3767
+ return destinationLookup(query);
3768
+ }) }));
3769
+ /** The one-candidate research mission of the DC delegation slice. */
3770
+ const phase6ResearchMission = Schema.decodeUnknownSync(ResearchMission)({
3771
+ request: "Shortlist one September culture city for the DC delegation slice.",
3772
+ candidates: ["LHR"]
3773
+ });
3774
+ const phase6ResearchDestination = "LHR";
3775
+ /** The child's scripted guide-lookup Tool Call identity. */
3776
+ const phase6ChildLookupCallId = `lookup-LHR`;
3777
+ const coordinatorDelegationParts = [{
3778
+ type: "tool-call",
3779
+ id: durableResearchCallId,
3780
+ name: "delegate_destination_research",
3781
+ params: {
3782
+ destination: "LHR",
3783
+ focus: "museums"
3784
+ },
3785
+ providerExecuted: false
3786
+ }, {
3787
+ type: "finish",
3788
+ reason: "tool-calls",
3789
+ usage: scriptedUsage
3790
+ }];
3791
+ const coordinatorShortlistParts = [
3792
+ {
3793
+ type: "text-start",
3794
+ id: "shortlist"
3795
+ },
3796
+ {
3797
+ type: "text-delta",
3798
+ id: "shortlist",
3799
+ delta: JSON.stringify(Schema.encodeSync(DestinationShortlist)(durableResearchShortlist("LHR")))
3800
+ },
3801
+ {
3802
+ type: "text-end",
3803
+ id: "shortlist"
3804
+ },
3805
+ {
3806
+ type: "finish",
3807
+ reason: "stop",
3808
+ usage: scriptedUsage
3809
+ }
3810
+ ];
3811
+ const researcherLookupParts = [{
3812
+ type: "tool-call",
3813
+ id: phase6ChildLookupCallId,
3814
+ name: "lookup_destination",
3815
+ params: { destination: "LHR" },
3816
+ providerExecuted: false
3817
+ }, {
3818
+ type: "finish",
3819
+ reason: "tool-calls",
3820
+ usage: scriptedUsage
3821
+ }];
3822
+ const researcherReportParts = [
3823
+ {
3824
+ type: "text-start",
3825
+ id: "destination-report"
3826
+ },
3827
+ {
3828
+ type: "text-delta",
3829
+ id: "destination-report",
3830
+ delta: encodedDestinationReport("LHR")
3831
+ },
3832
+ {
3833
+ type: "text-end",
3834
+ id: "destination-report"
3835
+ },
3836
+ {
3837
+ type: "finish",
3838
+ reason: "stop",
3839
+ usage: scriptedUsage
3840
+ }
3841
+ ];
3842
+ /** Prompt-aware S2 coordinator: delegation call first, shortlist once it is history. */
3843
+ const phase6CoordinatorModel = promptAwareModel("travel-coordinator-p6", (promptJson) => promptJson.includes("research-lhr-1") ? Stream.fromIterable(coordinatorShortlistParts) : Stream.fromIterable(coordinatorDelegationParts));
3844
+ let researcherGateReleased = false;
3845
+ /** Allow the researcher's FIRST model response to proceed (sticky across incarnations). */
3846
+ const releasePhase6ResearcherGate = () => {
3847
+ researcherGateReleased = true;
3848
+ };
3849
+ /** Re-close the researcher gate (each delegation scenario starts gated). */
3850
+ const resetPhase6ResearcherGate = () => {
3851
+ researcherGateReleased = false;
3852
+ };
3853
+ const awaitResearcherGate = Effect.gen(function* () {
3854
+ while (!researcherGateReleased) yield* Effect.sleep(Duration.millis(10));
3855
+ });
3856
+ /**
3857
+ * Prompt-aware S2 researcher: guide lookup first, report once it is history. The FIRST
3858
+ * response waits on the researcher gate — a stand-in for real model latency. The child's own
3859
+ * Object may legally start its Attempt the moment its routed admission commits, while the
3860
+ * parent is still appending the lineage record into the child's log; a child whose first
3861
+ * batch commits during that window races the parent's append on one tail. Real models answer
3862
+ * in seconds, so establishment always wins that race in production; the gate reproduces that
3863
+ * timing deterministically instead of relying on scheduler luck.
3864
+ */
3865
+ const phase6ResearcherModel = promptAwareModel("destination-researcher-p6", (promptJson) => promptJson.includes(phase6ChildLookupCallId) ? Stream.fromIterable(researcherReportParts) : Stream.fromEffectDrain(awaitResearcherGate).pipe(Stream.concat(Stream.fromIterable(researcherLookupParts))));
3866
+ /**
3867
+ * Every phase-6 Travel Planner worker Binding, captured with its requirement Contexts
3868
+ * (spec/subagents.md §11): the P4 planner and its gated twin, the P5 booking agent over the
3869
+ * shared supplier desk, and the S2 coordinator/researcher pair wired through the durable
3870
+ * delegation Layer. A Conversation Object registers these via its `bindings` option; the
3871
+ * capture runs once per incarnation, and everything stateful the assertions rely on (desk,
3872
+ * guide counter, gates) lives at module level so it survives incarnation loss.
3873
+ */
3874
+ const makePhase6TravelPlannerBindings = Effect.gen(function* () {
3875
+ const planner = yield* DurableWorkerBinding.make(Agent.withModel(TravelPlannerPhase4, phase6PlannerModel), phase4TravelPlannerDefinitionDigests).pipe(Effect.provide(phase4TravelPlannerWorkerLayer));
3876
+ const gatedPlanner = yield* DurableWorkerBinding.make(Agent.withModel(TravelPlannerPhase4, phase6GatedPlannerModel), phase6GatedPlannerDefinitionDigests).pipe(Effect.provide(phase4TravelPlannerWorkerLayer));
3877
+ const booking = yield* DurableWorkerBinding.make(Agent.withModel(TravelPlannerPhase5, phase6BookingModel), phase5TravelPlannerDefinitionDigests).pipe(Effect.provide(phase5TravelPlannerWorkerLayer.pipe(Layer.provideMerge(phase6SupplierDeskLayer))));
3878
+ const researcherBinding = Agent.withModel(DestinationResearcher, phase6ResearcherModel);
3879
+ const childToolkitLayer = DestinationResearcherToolkitLayer.pipe(Layer.provideMerge(countingGuideLayer));
3880
+ return [
3881
+ planner,
3882
+ gatedPlanner,
3883
+ booking,
3884
+ yield* DurableWorkerBinding.make(Agent.withModel(TravelCoordinator, phase6CoordinatorModel), s2CoordinatorDigests).pipe(Effect.provide(durableDestinationResearchHandlersLayer(researcherBinding).pipe(Layer.provide(Layer.mergeAll(childToolkitLayer, SubagentReservationsMemoryLive, DeterministicIdGeneratorLayer, ResearchDispatchGate.layerOpen))))),
3885
+ yield* DurableWorkerBinding.make(researcherBinding, s2ResearcherDigests).pipe(Effect.provide(childToolkitLayer))
3886
+ ];
3887
+ });
3888
+ /**
3889
+ * The committed cross-platform normalized canonical evidence of ONE uninterrupted Travel
3890
+ * Planner planning Submission (the P1/P4 happy path: canonical input, the search Turn, three
3891
+ * Tool settlements, the plan Turn, one Settlement). `travel-planner-phase6.test.ts` asserts
3892
+ * the DN run equals this value and `travel-planner-dc.test.ts` asserts the DC run equals this
3893
+ * value, so the two platforms' canonical outcomes are byte-equivalent transitively — the P6
3894
+ * exit gate "Travel Planner produces equivalent canonical outcomes under DN and DC".
3895
+ *
3896
+ * Regenerate ONLY when the Travel Planner scenario itself changes, by printing either suite's
3897
+ * normalized value; both suites must then agree on the new golden.
3898
+ */
3899
+ const phase6TravelPlannerGoldenEvidence = [
3900
+ {
3901
+ batchId: "conversation-created:{conversationId}",
3902
+ sequence: 1,
3903
+ record: {
3904
+ recordId: "conversation-created:{conversationId}",
3905
+ family: "conversation",
3906
+ schemaVersion: 1,
3907
+ createdAt: "{timestamp}",
3908
+ deploymentId: "{deploymentId}",
3909
+ payload: {
3910
+ _tag: "ConversationCreated",
3911
+ agentId: "travel-planner-phase-4",
3912
+ definitions: {
3913
+ agent: "{digest}",
3914
+ model: "{digest}",
3915
+ tools: "{digest}"
3916
+ }
3917
+ }
3918
+ }
3919
+ },
3920
+ {
3921
+ batchId: "submission-input:{submissionId}",
3922
+ sequence: 2,
3923
+ record: {
3924
+ recordId: "input:{submissionId}",
3925
+ family: "conversation",
3926
+ schemaVersion: 1,
3927
+ createdAt: "{timestamp}",
3928
+ deploymentId: "{deploymentId}",
3929
+ payload: {
3930
+ _tag: "UserInputRecorded",
3931
+ submissionId: "{submissionId}",
3932
+ kind: "user",
3933
+ runId: "run:{submissionId}",
3934
+ input: {
3935
+ request: "Plan a review-only London trip using the deterministic flight, lodging, and activity searches.",
3936
+ origin: "SFO",
3937
+ destination: "LHR",
3938
+ departOn: "2026-09-14",
3939
+ nights: 4,
3940
+ travelers: 2,
3941
+ budgetCents: 35e4,
3942
+ currency: "USD"
3943
+ }
3944
+ }
3945
+ }
3946
+ },
3947
+ {
3948
+ batchId: "turn-response:run:{submissionId}:1",
3949
+ sequence: 3,
3950
+ record: {
3951
+ recordId: "model-response:run:{submissionId}:1",
3952
+ family: "conversation",
3953
+ schemaVersion: 1,
3954
+ createdAt: "{timestamp}",
3955
+ deploymentId: "{deploymentId}",
3956
+ payload: {
3957
+ _tag: "ModelResponseRecorded",
3958
+ runId: "run:{submissionId}",
3959
+ turnId: "turn:run:{submissionId}:1",
3960
+ turn: 1,
3961
+ messages: { content: [
3962
+ {
3963
+ options: {},
3964
+ role: "system",
3965
+ content: "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."
3966
+ },
3967
+ {
3968
+ options: {},
3969
+ role: "user",
3970
+ content: "{\"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\"}"
3971
+ },
3972
+ {
3973
+ options: {},
3974
+ role: "assistant",
3975
+ content: [
3976
+ {
3977
+ options: {},
3978
+ type: "tool-call",
3979
+ id: "flight-call-1",
3980
+ name: "search_flights",
3981
+ params: {
3982
+ origin: "SFO",
3983
+ destination: "LHR",
3984
+ departOn: "2026-09-14",
3985
+ travelers: 2
3986
+ },
3987
+ providerExecuted: false
3988
+ },
3989
+ {
3990
+ options: {},
3991
+ type: "tool-call",
3992
+ id: "lodging-call-1",
3993
+ name: "search_lodging",
3994
+ params: {
3995
+ destination: "LHR",
3996
+ departOn: "2026-09-14",
3997
+ nights: 4,
3998
+ travelers: 2
3999
+ },
4000
+ providerExecuted: false
4001
+ },
4002
+ {
4003
+ options: {},
4004
+ type: "tool-call",
4005
+ id: "activity-call-1",
4006
+ name: "search_activities",
4007
+ params: {
4008
+ destination: "LHR",
4009
+ departOn: "2026-09-14",
4010
+ nights: 4,
4011
+ travelers: 2
4012
+ },
4013
+ providerExecuted: false
4014
+ }
4015
+ ]
4016
+ }
4017
+ ] },
4018
+ messagesDigest: "{digest}"
4019
+ }
4020
+ }
4021
+ },
4022
+ {
4023
+ batchId: "turn-results:run:{submissionId}:1",
4024
+ sequence: 4,
4025
+ record: {
4026
+ recordId: "tool-settled:run:{submissionId}:1:flight-call-1",
4027
+ family: "conversation",
4028
+ schemaVersion: 1,
4029
+ createdAt: "{timestamp}",
4030
+ deploymentId: "{deploymentId}",
4031
+ payload: {
4032
+ _tag: "ToolCallSettled",
4033
+ runId: "run:{submissionId}",
4034
+ toolCallId: "flight-call-1",
4035
+ toolName: "search_flights",
4036
+ result: {
4037
+ quoteId: "quote-sfo-lhr-001",
4038
+ flight: "EA 218 · nonstop · SFO 18:40 → LHR 13:05+1",
4039
+ estimatedCents: 18e4,
4040
+ currency: "USD"
4041
+ },
4042
+ isFailure: false
4043
+ }
4044
+ }
4045
+ },
4046
+ {
4047
+ batchId: "turn-results:run:{submissionId}:1",
4048
+ sequence: 5,
4049
+ record: {
4050
+ recordId: "tool-settled:run:{submissionId}:1:lodging-call-1",
4051
+ family: "conversation",
4052
+ schemaVersion: 1,
4053
+ createdAt: "{timestamp}",
4054
+ deploymentId: "{deploymentId}",
4055
+ payload: {
4056
+ _tag: "ToolCallSettled",
4057
+ runId: "run:{submissionId}",
4058
+ toolCallId: "lodging-call-1",
4059
+ toolName: "search_lodging",
4060
+ result: {
4061
+ lodging: "Bloomsbury House · refundable studio · 4 nights",
4062
+ estimatedCents: 104e3,
4063
+ currency: "USD"
4064
+ },
4065
+ isFailure: false
4066
+ }
4067
+ }
4068
+ },
4069
+ {
4070
+ batchId: "turn-results:run:{submissionId}:1",
4071
+ sequence: 6,
4072
+ record: {
4073
+ recordId: "tool-settled:run:{submissionId}:1:activity-call-1",
4074
+ family: "conversation",
4075
+ schemaVersion: 1,
4076
+ createdAt: "{timestamp}",
4077
+ deploymentId: "{deploymentId}",
4078
+ payload: {
4079
+ _tag: "ToolCallSettled",
4080
+ runId: "run:{submissionId}",
4081
+ toolCallId: "activity-call-1",
4082
+ toolName: "search_activities",
4083
+ result: { activities: ["British Museum timed entry", "Thames evening walk"] },
4084
+ isFailure: false
4085
+ }
4086
+ }
4087
+ },
4088
+ {
4089
+ batchId: "turn:run:{submissionId}:2",
4090
+ sequence: 7,
4091
+ record: {
4092
+ recordId: "model-response:run:{submissionId}:2",
4093
+ family: "conversation",
4094
+ schemaVersion: 1,
4095
+ createdAt: "{timestamp}",
4096
+ deploymentId: "{deploymentId}",
4097
+ payload: {
4098
+ _tag: "ModelResponseRecorded",
4099
+ runId: "run:{submissionId}",
4100
+ turnId: "turn:run:{submissionId}:2",
4101
+ turn: 2,
4102
+ messages: { content: [{
4103
+ options: {},
4104
+ role: "assistant",
4105
+ content: "{\"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\"}]}"
4106
+ }] },
4107
+ messagesDigest: "{digest}"
4108
+ }
4109
+ }
4110
+ },
4111
+ {
4112
+ batchId: "submission-settlement:{submissionId}",
4113
+ sequence: 8,
4114
+ record: {
4115
+ recordId: "settlement:{submissionId}",
4116
+ family: "conversation",
4117
+ schemaVersion: 1,
4118
+ createdAt: "{timestamp}",
4119
+ deploymentId: "{deploymentId}",
4120
+ payload: {
4121
+ _tag: "SubmissionSettled",
4122
+ submissionId: "{submissionId}",
4123
+ settlementId: "settlement:{submissionId}",
4124
+ receiptId: "{receiptId}",
4125
+ outcome: "completed",
4126
+ runId: "run:{submissionId}",
4127
+ result: { itineraries: [{
4128
+ title: "Westward light, eastbound overnight",
4129
+ route: "San Francisco → London",
4130
+ dates: "14–19 September 2026",
4131
+ flight: "EA 218 · nonstop · SFO 18:40 → LHR 13:05+1",
4132
+ lodging: "Bloomsbury House · refundable studio · 4 nights",
4133
+ activities: ["British Museum timed entry", "Thames evening walk"],
4134
+ estimatedTotalCents: 284e3,
4135
+ currency: "USD",
4136
+ quoteId: "quote-sfo-lhr-001",
4137
+ assumptions: ["Two travelers sharing one studio", "Quote is read-only availability, not a reservation"],
4138
+ unresolvedConstraints: ["Traveler names and accessibility requests are intentionally omitted"],
4139
+ nextAction: "review"
4140
+ }] }
4141
+ }
4142
+ }
4143
+ }
4144
+ ];
4145
+ //#endregion
4146
+ //#region src/fixtures/travel-planner/phase7.ts
4147
+ /**
4148
+ * The P7 dual-profile claim, schema-first so the exact scope of "live
4149
+ * integration profiles" is a committed, decodable value:
4150
+ *
4151
+ * - `offlineConformanceDeterministic` / `offlineRequiresCredentials`: the
4152
+ * cumulative conformance suites stay deterministic and credential-free.
4153
+ * - `liveProfileOptIn`: live suites are excluded from ordinary gates by the
4154
+ * environment predicate (`phase7LiveProfileEnabled`), never by test-runner
4155
+ * configuration that could silently drift.
4156
+ * - `liveModelLayers` / `liveSupplierLayers`: live profiles exercise real
4157
+ * model Layers over the SAME deterministic supplier desk — no claim of a
4158
+ * live supplier integration is made anywhere (decision 9).
4159
+ * - `structurallyRedactedTranscripts`: transcript evidence a live profile
4160
+ * emits passes through the structural `Redactor` first (SEC-008,
4161
+ * testing.md §12: "live model and supplier profiles are opt-in smoke or
4162
+ * release tests, rate-limited and structurally redacted").
4163
+ * - `exactlyOnceExternalEffects`: never claimed at any phase (DUR-003).
4164
+ */
4165
+ var TravelPlannerPhase7Profile = class extends Schema.Class("@effect-agent/testing/travel-planner/TravelPlannerPhase7Profile")({
4166
+ phase: Schema.Literal("P7"),
4167
+ offlineConformanceDeterministic: Schema.Literal(true),
4168
+ offlineRequiresCredentials: Schema.Literal(false),
4169
+ liveProfileOptIn: Schema.Literal(true),
4170
+ liveModelLayers: Schema.Literal(true),
4171
+ liveSupplierLayers: Schema.Literal(false),
4172
+ structurallyRedactedTranscripts: Schema.Literal(true),
4173
+ exactlyOnceExternalEffects: Schema.Literal(false)
4174
+ }) {};
4175
+ const phase7TravelPlannerProfile = TravelPlannerPhase7Profile.make({
4176
+ phase: "P7",
4177
+ offlineConformanceDeterministic: true,
4178
+ offlineRequiresCredentials: false,
4179
+ liveProfileOptIn: true,
4180
+ liveModelLayers: true,
4181
+ liveSupplierLayers: false,
4182
+ structurallyRedactedTranscripts: true,
4183
+ exactlyOnceExternalEffects: false
4184
+ });
4185
+ /**
4186
+ * The one opt-in switch for EVERY live profile in this repository. `"1"` is
4187
+ * the only enabling value: an unset, empty, or differently-truthy value keeps
4188
+ * the suite skipped, so CI and ordinary developer runs stay offline.
4189
+ */
4190
+ const PHASE7_LIVE_GATE_ENV = "EFFECT_AGENT_LIVE";
4191
+ /** The credential a Travel Planner live-model profile additionally requires. */
4192
+ const PHASE7_LIVE_CREDENTIAL_ENV = "OPENAI_API_KEY";
4193
+ /**
4194
+ * The test-side live gate (P7 plan §6: no test-side live-gating pattern
4195
+ * existed before this — the demo gates at serve time via
4196
+ * `Config.redacted("OPENAI_API_KEY")`). Suites use it as
4197
+ * `describe.skipIf(!phase7LiveProfileEnabled(process.env))`, which keeps the
4198
+ * live block out of ordinary gates while the SAME file's ungated tests keep
4199
+ * pinning the profile schema on every run.
4200
+ */
4201
+ const phase7LiveProfileEnabled = (env) => env["EFFECT_AGENT_LIVE"] === "1" && (env["OPENAI_API_KEY"] ?? "") !== "";
4202
+ //#endregion
4203
+ export { ActivityCatalog, ActivityCatalogLayer, ActivityQuery, ActivitySearchResult, ActivityUnavailable, AirportCode, BookFlight, BookItinerary, BookingRef, BoundedSummary, CERTIFICATION_SCENARIOS, CancelBooking, CancelBookingRequest, CancellationConfirmation, CatalogLifecycle, CatalogLifecycleCounts, ChaosApprovalDecision, ChaosConvergenceFailure, ChaosLaneReport, ChaosPlan, ChaosPlanReport, ChaosResolutionKind, ChaosScenarioKind, ChaosSubmissionSpec, DEFAULT_CHAOS_SEED, DestinationBrief, DestinationFacts, DestinationGuide, DestinationGuideLayer, DestinationGuideUnavailable, DestinationQuery, DestinationRecommendation, DestinationReport, DestinationResearchFailed, DestinationResearchFindings, DestinationResearchRequest, DestinationResearchSupportLayer, DestinationResearcher, DestinationResearcherToolkit, DestinationResearcherToolkitLayer, DestinationShortlist, DeterministicIdGeneratorLayer, DocContentToolkit, DocSummarizer, DocsMcpDiscoveryEvidence, DocsResearcher, DocsResearcherToolkit, DocumentLibrary, DocumentQuery, DocumentSummary, DocumentSummaryFailed, DocumentUnavailable, DurableSearchActivities, DurableSearchFlights, DurableSearchLodging, FetchDocument, FlightBookingRequest, FlightCatalog, FlightCatalogLayer, FlightOption, FlightQuery, FlightUnavailable, GuidanceFailure, HoldItinerary, Itinerary, ItineraryBookingRequest, ItineraryConfirmation, ItineraryHold, ItineraryHoldGateway, ItineraryHoldRequest, ItineraryHoldUnavailable, LodgingCatalog, LodgingCatalogLayer, LodgingOption, LodgingQuery, LodgingUnavailable, LookupDestination, PHASE7_LIVE_CREDENTIAL_ENV, PHASE7_LIVE_GATE_ENV, QuoteId, ResearchDigest, ResearchDispatchGate, ResearchDocument, ResearchDocumentId, ResearchMission, ResearchRequest, ReverseCompletionToolkitLayer, ScriptedGeneratePart, ScriptedGenerateTurn, ScriptedModel, ScriptedStreamPart, ScriptedStreamTermination, ScriptedStreamTurn, ScriptedTurn, SearchActivities, SearchFlights, SearchLodging, SummaryBrief, SummaryFinding, SummaryRequest, SupplierBookingConfirmation, SupplierBookingDesk, SupplierBookingRecord, SupplierOperation, SupplierUnavailable, TIER2_UNREACHED_LOCATIONS, TravelBookingReport, TravelCoordinator, TravelCoordinatorToolkit, TravelGuidance, TravelGuidanceLayer, TravelPlan, TravelPlanner, TravelPlannerBookingEvidenceError, TravelPlannerBookingProfile, TravelPlannerCloudflareProfile, TravelPlannerDurabilityProfile, TravelPlannerDurableEvidenceError, TravelPlannerPersistenceProfile, TravelPlannerPhase2, TravelPlannerPhase2Toolkit, TravelPlannerPhase2ToolkitLayer, TravelPlannerPhase4, TravelPlannerPhase4Toolkit, TravelPlannerPhase4ToolkitLayer, TravelPlannerPhase5, TravelPlannerPhase5Toolkit, TravelPlannerPhase5ToolkitLayer, TravelPlannerPhase7Profile, TravelPlannerProjectionError, TravelPlannerRuntimeLayer, TravelPlannerSubagentDurabilityProfile, TravelPlannerToolkit, TravelPlannerToolkitLayer, TravelSupplierReconcilerLayer, TravelerRef, TripRequest, assertDiscoveryMatchesAuthoredToolkit, assertSettledBookingsExistAtSupplier, bookFlightIdempotencyKey, cancelBookingIdempotencyKey, certifyDurableAdapters, chaosSeedFromEnv, coordinatorConfidentialMarker, coordinatorResearchTurn, coordinatorShortlistTurn, delegateDocumentSummary, destinationLookup, destinationReportFor, destinationResearchDelegation, destinationResearchHandlersLayer, destinationResearchPolicy, docContentToolkitLayer, docsCoordinatorConfidentialMarker, docsCoordinatorDigests, docsDocumentBodySecret, docsMcpConnectorLayer, docsMcpIdentity, docsMcpMismatchedConnectorLayer, docsMcpOversizedConnectorLayer, docsMcpRequest, docsMissionConfidentialMarker, docsResearcherDeploymentId, docsResearcherPrincipal, docsResearcherProducerId, docsResearcherSubmitAgent, docsResearcherSubmitOptions, docsSummarizerDigestStrings, docsSummarizerDigests, docsSummaryHandlersLayer, documentBodyPhrase, documentSummaryFor, documentSummaryPolicy, durableChildLookupCallId, durableDestinationResearchHandlersLayer, durableResearchAllocation, durableResearchCallId, durableResearchFinding, durableResearchShortlist, encodedDestinationFacts, encodedDestinationReport, encodedDocumentSummary, expectedDestinationShortlist, expectedResearchDigest, expectedTravelPlan, fetchCallId, generateChaosPlans, itineraryStepIdempotencyKey, makeDestinationResearcherModel, makeDocsResearcherHarness, makeDurableResearchHarness, makeInvocationCountingModel, makePhase3TravelPlannerCheckpoint, makePhase4TravelPlannerAgent, makePhase6TravelPlannerBindings, mapResearchChildFailure, mapSummaryChildFailure, missionConfidentialMarker, normalizeCrossPlatformTravelPlannerEvidence, normalizeDurableTravelPlannerEvidence, phase0HappyPathTurns, phase0Trip, phase1HappyPathTurns, phase1Trip, phase3TravelPlannerBatches, phase3TravelPlannerCompletionBatch, phase3TravelPlannerConversationId, phase3TravelPlannerDefinitionDigests, phase3TravelPlannerEncodedFixture, phase3TravelPlannerInitialBatch, phase3TravelPlannerProducerId, phase3TravelPlannerProfile, phase3TravelPlannerRunId, phase4TravelPlannerDefinitionDigests, phase4TravelPlannerDeploymentId, phase4TravelPlannerPrincipal, phase4TravelPlannerProducerId, phase4TravelPlannerProfile, phase4TravelPlannerSubmitOptions, phase4TravelPlannerWorkerLayer, phase5TravelPlannerDefinitionDigests, phase5TravelPlannerDeploymentId, phase5TravelPlannerPrincipal, phase5TravelPlannerProducerId, phase5TravelPlannerProfile, phase5TravelPlannerSubmitOptions, phase5TravelPlannerWorkerLayer, phase6ActivityCallId, phase6BookingModel, phase6BookingRef, phase6BookingToolCallId, phase6BookingTrip, phase6ChildLookupCallId, phase6CoordinatorModel, phase6FlightCallId, phase6GatedPlannerDefinitionDigests, phase6GatedPlannerModel, phase6GatedTrip, phase6GuideInvocationCount, phase6LodgingCallId, phase6PlannerModel, phase6ResearchDestination, phase6ResearchMission, phase6ResearcherModel, phase6SupplierDesk, phase6SupplierDeskLayer, phase6SupplierReconcilerLayer, phase6TravelPlannerDeploymentId, phase6TravelPlannerGoldenEvidence, phase6TravelPlannerProducerId, phase6TravelPlannerProducerPrefix, phase6TravelPlannerProfile, phase7LiveProfileEnabled, phase7TravelPlannerProfile, redactedDocumentPreview, releasePhase6PlannerGate, releasePhase6ResearcherGate, researchCorpusDocumentIds, researchDocumentFor, researchDocumentLookup, researchMission, researchMissionRequest, researcherHappyPathTurns, resetPhase6PlannerGate, resetPhase6ResearcherGate, resolveTierThree, runChaosPlan, s2CoordinatorDigests, s2CoordinatorSubmitAgent, s2ResearcherDigestStrings, s2ResearcherDigests, s2TravelPlannerDeploymentId, s2TravelPlannerPrincipal, s2TravelPlannerProducerId, s2TravelPlannerProfile, s2TravelPlannerSubmitOptions, summarizeCallId, supplierBookingRefFor, tier2NeverFiredLocations, travelPlanFromDurableSettlement, travelPlanFromProjection };
4204
+
4205
+ //# sourceMappingURL=index.mjs.map