@effect-agent/testing 0.1.0-beta.8 → 0.1.0-beta.80

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/Certification.d.mts +105 -0
  2. package/dist/Certification.mjs +592 -0
  3. package/dist/Certification.mjs.map +1 -0
  4. package/dist/Chaos.d.mts +126 -0
  5. package/dist/Chaos.mjs +755 -0
  6. package/dist/Chaos.mjs.map +1 -0
  7. package/dist/CodeExecutorConformance.d.mts +33 -0
  8. package/dist/CodeExecutorConformance.mjs +231 -0
  9. package/dist/CodeExecutorConformance.mjs.map +1 -0
  10. package/dist/CodeExecutorSubstitute.d.mts +21 -0
  11. package/dist/CodeExecutorSubstitute.mjs +368 -0
  12. package/dist/CodeExecutorSubstitute.mjs.map +1 -0
  13. package/dist/DocsResearcher.d.mts +270 -0
  14. package/dist/DocsResearcher.mjs +490 -0
  15. package/dist/DocsResearcher.mjs.map +1 -0
  16. package/dist/ScriptedModel-DAvxIiud.d.mts +220 -0
  17. package/dist/ScriptedModel.d.mts +2 -0
  18. package/dist/ScriptedModel.mjs +155 -0
  19. package/dist/ScriptedModel.mjs.map +1 -0
  20. package/dist/TravelPlanner.d.mts +1665 -0
  21. package/dist/TravelPlanner.mjs +1963 -0
  22. package/dist/TravelPlanner.mjs.map +1 -0
  23. package/dist/deterministic-layers-Eka0fMZq.mjs +358 -0
  24. package/dist/deterministic-layers-Eka0fMZq.mjs.map +1 -0
  25. package/dist/index.d.mts +2 -3406
  26. package/dist/index.mjs +2 -4771
  27. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  28. package/package.json +1 -48
  29. package/src/{certification.ts → Certification.ts} +251 -117
  30. package/src/{chaos.ts → Chaos.ts} +246 -122
  31. package/src/{code-executor-conformance.ts → CodeExecutorConformance.ts} +29 -6
  32. package/src/{code-executor-substitute.ts → CodeExecutorSubstitute.ts} +112 -45
  33. package/src/{fixtures/docs-researcher/index.ts → DocsResearcher.ts} +68 -5
  34. package/src/{scripted-model.ts → ScriptedModel.ts} +22 -25
  35. package/src/TravelPlanner.ts +232 -0
  36. package/src/fixtures/docs-researcher/definition.ts +19 -10
  37. package/src/fixtures/docs-researcher/harness.ts +41 -30
  38. package/src/fixtures/docs-researcher/mcp.ts +49 -3
  39. package/src/fixtures/travel-planner/definition.ts +15 -2
  40. package/src/fixtures/travel-planner/deterministic-layers.ts +47 -4
  41. package/src/fixtures/travel-planner/phase2.ts +4 -3
  42. package/src/fixtures/travel-planner/phase3.ts +18 -41
  43. package/src/fixtures/travel-planner/phase4.ts +23 -36
  44. package/src/fixtures/travel-planner/phase5.ts +38 -41
  45. package/src/fixtures/travel-planner/phase6.ts +187 -84
  46. package/src/fixtures/travel-planner/phase7.ts +4 -102
  47. package/src/fixtures/travel-planner/scenarios.ts +3 -4
  48. package/src/fixtures/travel-planner/subagents-durable.ts +33 -57
  49. package/src/fixtures/travel-planner/subagents.ts +35 -13
  50. package/src/index.ts +1 -11
  51. package/dist/index.mjs.map +0 -1
  52. package/src/code-executor-conformance.d.ts +0 -30
  53. package/src/fixtures/travel-planner/index.ts +0 -11
  54. package/src/fixtures/warehouse/index.ts +0 -412
@@ -0,0 +1,592 @@
1
+ import { Cause, Clock, DateTime, Duration, Effect, Exit, Layer, Option, Ref, Schema, Stream } from "effect";
2
+ import { LanguageModel, Model, Tool, Toolkit } from "effect/unstable/ai";
3
+ import * as Subagent from "@effect-agent/capabilities/Subagent";
4
+ import { SubagentPolicy, SubagentRuntime } from "@effect-agent/capabilities/Subagent";
5
+ import { SubagentReservationsMemoryLive } from "@effect-agent/capabilities/SubagentReservations";
6
+ import * as Agent from "@effect-agent/core/Agent";
7
+ import { AgentPolicy } from "@effect-agent/core/AgentPolicy";
8
+ import { RunId, ThreadId, ToolCallId, TurnId } from "@effect-agent/core/Identifiers";
9
+ import { IdGenerator } from "@effect-agent/core/IdGenerator";
10
+ import { DurableStep, DurableStepError } from "@effect-agent/engine/DurableStep";
11
+ import { RunToolAuthorization } from "@effect-agent/engine/RunOptions";
12
+ import { DurableWorkerBinding } from "@effect-agent/thread/AgentRegistration";
13
+ import { DurableAgentRuntime, DurableRuntimeConfig } from "@effect-agent/thread/DurableAgentRuntime";
14
+ import { DurableRuntimeFailpointError, DurableRuntimeFailpointLocation } from "@effect-agent/thread/DurableFailpoint";
15
+ import { DefinitionDigests, DeploymentId, Digest, ProducerId } from "@effect-agent/thread/Records";
16
+ import { childThreadIdFor } from "@effect-agent/thread/RunJournal";
17
+ import { ApprovalDecisionCommand, DEFAULT_OWNERSHIP_LEASE_DURATION, IdempotencyKey, Principal, ResolutionSafeToRetry, SubmissionLedger, SubmissionLookupById, UnknownResolutionCommand } from "@effect-agent/thread/SubmissionLedger";
18
+ import { CertificationReport, CertificationSweepResult, CertificationTierThreeReport, CertifiedAdapterIdentity, certifyPorts } from "@effect-agent/thread/testing/Certification";
19
+ import { DurableRuntimeFailpointTestControl } from "@effect-agent/thread/testing/DurableFailpointTestControl";
20
+ import { verifyThreadInvariants } from "@effect-agent/thread/ThreadInvariants";
21
+ import { LoadCheckpointRequest, ThreadExportRequest, ThreadStore } from "@effect-agent/thread/ThreadStore";
22
+ import { ToolReconciler } from "@effect-agent/thread/ToolReconciler";
23
+ import { WakeScheduler } from "@effect-agent/thread/WakeScheduler";
24
+ import { TestClock } from "effect/testing";
25
+ //#region src/Certification.ts
26
+ /** The six Tier-2 scenario shapes in sweep order. */
27
+ const CERTIFICATION_SCENARIOS = [
28
+ "plain",
29
+ "uncertain-tool",
30
+ "durable-steps",
31
+ "approval",
32
+ "join",
33
+ "delegation"
34
+ ];
35
+ /**
36
+ * Coordinator failpoint locations that none of the six scenario shapes can reach, recorded
37
+ * honestly instead of silently claimed. These require operator, compaction, reservation, or
38
+ * background-worker paths the shapes do not take. They are pinned in-process by the P5/S2 suites
39
+ * (`packages/testing/test/durable-tools.test.ts` "resolveUnknown is idempotent across the
40
+ * intent failpoint", `durable-runtime.test.ts` abort rows,
41
+ * `durable-subagents.test.ts` abort propagation) and by the process-kill/eviction crash
42
+ * matrices. Runner tests assert the observed never-fired set equals EXACTLY this list, so a
43
+ * protocol change that silently stops exercising a location fails the certification.
44
+ */
45
+ const TIER2_UNREACHED_LOCATIONS = [
46
+ "checkpoint:before-save",
47
+ "checkpoint:after-save",
48
+ "abort:after-intent",
49
+ "compaction:before-canonical-append",
50
+ "compaction:after-canonical-append",
51
+ "policy:before-reservation-append",
52
+ "policy:after-reservation-append",
53
+ "resolve:after-intent",
54
+ "subagent:after-child-abort-intent",
55
+ "worker:before-source-append",
56
+ "worker:after-source-append",
57
+ "worker:before-origin-append",
58
+ "worker:after-origin-append",
59
+ "worker:before-completion-append",
60
+ "worker:after-completion-append",
61
+ "worker:before-subtree-append",
62
+ "worker:after-subtree-append",
63
+ "worker:before-report-append",
64
+ "worker:after-report-append",
65
+ "worker:before-report-delivery",
66
+ "worker:after-report-delivery"
67
+ ];
68
+ /** Locations of `tier2` rows whose armed fault never fired in ANY scenario, sorted. */
69
+ const tier2NeverFiredLocations = (tier2) => {
70
+ const fired = /* @__PURE__ */ new Set();
71
+ for (const row of tier2) if (row.failpointFired) fired.add(row.location);
72
+ return DurableRuntimeFailpointLocation.literals.filter((location) => !fired.has(location)).sort();
73
+ };
74
+ const SHA_A = Schema.decodeSync(Digest)("a".repeat(64));
75
+ const DIGESTS = DefinitionDigests.make({
76
+ agent: SHA_A,
77
+ model: SHA_A,
78
+ tools: SHA_A
79
+ });
80
+ const CHILD_DIGEST_STRINGS = {
81
+ agent: "b".repeat(64),
82
+ model: "c".repeat(64),
83
+ tools: "d".repeat(64)
84
+ };
85
+ const CHILD_DIGESTS = DefinitionDigests.make({
86
+ agent: Schema.decodeSync(Digest)(CHILD_DIGEST_STRINGS.agent),
87
+ model: Schema.decodeSync(Digest)(CHILD_DIGEST_STRINGS.model),
88
+ tools: Schema.decodeSync(Digest)(CHILD_DIGEST_STRINGS.tools)
89
+ });
90
+ const PRINCIPAL = Schema.decodeSync(Principal)("principal-certification");
91
+ const decodeThreadId = Schema.decodeSync(ThreadId);
92
+ const decodeIdempotencyKey = Schema.decodeSync(IdempotencyKey);
93
+ const decodeToolCallId = Schema.decodeSync(ToolCallId);
94
+ const usage = {
95
+ inputTokens: {},
96
+ outputTokens: {}
97
+ };
98
+ const finalParts = (text) => [
99
+ {
100
+ type: "text-start",
101
+ id: "answer"
102
+ },
103
+ {
104
+ type: "text-delta",
105
+ id: "answer",
106
+ delta: text
107
+ },
108
+ {
109
+ type: "text-end",
110
+ id: "answer"
111
+ },
112
+ {
113
+ type: "finish",
114
+ reason: "stop",
115
+ usage
116
+ }
117
+ ];
118
+ const toolCallPart = (id, name, params) => ({
119
+ type: "tool-call",
120
+ id,
121
+ name,
122
+ params,
123
+ providerExecuted: false
124
+ });
125
+ const toolTurn = (...calls) => [...calls, {
126
+ type: "finish",
127
+ reason: "tool-calls",
128
+ usage
129
+ }];
130
+ /**
131
+ * Stateless scripted model that decides by PROMPT SHAPE instead of call count: while the
132
+ * prompt carries no committed tool result the model declares `toolParts` (when given),
133
+ * otherwise it answers with the final text. Deciding on the canonical prompt keeps every cell
134
+ * deterministic regardless of where the injected fault fell — a re-invoked Turn re-declares
135
+ * the same batch and a resumed batch flows into the final answer, so every scenario always
136
+ * exercises its tool path and always converges.
137
+ */
138
+ const promptShapeModel = (name, finalText, toolParts) => Model.make("scripted", name, Layer.effect(LanguageModel.LanguageModel, LanguageModel.make({
139
+ generateText: () => Effect.succeed([]),
140
+ streamText: (request) => {
141
+ const hasToolResult = request.prompt.content.some((message) => message.role === "tool");
142
+ const parts = toolParts === void 0 || hasToolResult ? finalParts(finalText) : toolParts;
143
+ return Stream.fromIterable(parts);
144
+ }
145
+ })));
146
+ const CERTIFICATION_MAX_DURATION = "10 minutes";
147
+ const policy = AgentPolicy.make({
148
+ maxTurns: 4,
149
+ maxToolCalls: 4,
150
+ maxDuration: CERTIFICATION_MAX_DURATION,
151
+ toolConcurrency: 2
152
+ });
153
+ const QuestionInput = Schema.Struct({ question: Schema.String });
154
+ const AnswerOutput = Schema.Struct({ answer: Schema.String });
155
+ /** plain / join: no tools — the pure Turn/submission/join seams. */
156
+ const plainDefinition = Agent.make("certify-plain", {
157
+ input: QuestionInput,
158
+ output: AnswerOutput,
159
+ instructions: "Answer as JSON.",
160
+ toolkit: Toolkit.empty,
161
+ policy
162
+ });
163
+ /** uncertain-tool: unannotated → fail-closed `uncertain`, enters the prepared/settled protocol. */
164
+ const Book = Tool.make("book", {
165
+ parameters: Schema.Struct({ ref: Schema.String }),
166
+ success: Schema.Struct({ confirmation: Schema.String })
167
+ });
168
+ const bookToolkit = Toolkit.make(Book);
169
+ const uncertainDefinition = Agent.make("certify-uncertain", {
170
+ input: QuestionInput,
171
+ output: AnswerOutput,
172
+ instructions: "Book it.",
173
+ toolkit: bookToolkit,
174
+ policy
175
+ });
176
+ /** durable-steps: declaring `DurableStep` as a dependency is what makes the Tool durable. */
177
+ const Itinerary = Tool.make("itinerary", {
178
+ parameters: Schema.Struct({ ref: Schema.String }),
179
+ success: Schema.Struct({ state: Schema.String }),
180
+ failure: DurableStepError,
181
+ dependencies: [DurableStep]
182
+ });
183
+ const itineraryToolkit = Toolkit.make(Itinerary);
184
+ const stepsDefinition = Agent.make("certify-steps", {
185
+ input: QuestionInput,
186
+ output: AnswerOutput,
187
+ instructions: "Reserve the itinerary.",
188
+ toolkit: itineraryToolkit,
189
+ policy
190
+ });
191
+ /** approval: fail-closed — no `DurableApprovalResolver` Layer, so undecided approvals suspend. */
192
+ const BookApproval = Tool.make("book", {
193
+ parameters: Schema.Struct({ ref: Schema.String }),
194
+ success: Schema.Struct({ confirmation: Schema.String }),
195
+ needsApproval: true
196
+ });
197
+ const approvalToolkit = Toolkit.make(BookApproval);
198
+ const approvalDefinition = Agent.make("certify-approval", {
199
+ input: QuestionInput,
200
+ output: AnswerOutput,
201
+ instructions: "Book after approval.",
202
+ toolkit: approvalToolkit,
203
+ policy
204
+ });
205
+ /** delegation: durable attached child plus an ordinary uncertain sibling in ONE batch. */
206
+ const childDefinition = Agent.make("certify-child", {
207
+ input: QuestionInput,
208
+ output: AnswerOutput,
209
+ instructions: "Answer as JSON.",
210
+ toolkit: Toolkit.empty,
211
+ policy: AgentPolicy.make({
212
+ maxTurns: 2,
213
+ maxToolCalls: 1,
214
+ maxDuration: CERTIFICATION_MAX_DURATION,
215
+ toolConcurrency: 1
216
+ })
217
+ });
218
+ var CertifyDelegationFailed = class extends Schema.TaggedError()("CertifyDelegationFailed", { childErrorTag: Schema.String }) {};
219
+ const researchDelegation = Subagent.define("delegate_research", {
220
+ description: "Research one bounded question and return findings.",
221
+ target: childDefinition,
222
+ parameters: Schema.Struct({ topic: Schema.String }),
223
+ success: Schema.Struct({ summary: Schema.String }),
224
+ failure: CertifyDelegationFailed,
225
+ prepareInput: ({ topic }) => Effect.succeed({ question: `research:${topic}` }),
226
+ projectResult: (output) => Effect.succeed({ summary: `finding:${output.answer}` }),
227
+ policy: SubagentPolicy.make({
228
+ maxChildren: 2,
229
+ maxConcurrency: 2,
230
+ maxTurns: 4,
231
+ maxToolCalls: 4,
232
+ maxDuration: CERTIFICATION_MAX_DURATION
233
+ })
234
+ });
235
+ const Lookup = Tool.make("lookup", {
236
+ parameters: Schema.Struct({ key: Schema.String }),
237
+ success: Schema.Struct({ value: Schema.String })
238
+ });
239
+ const coordinatorDefinition = Agent.make("certify-coordinator", {
240
+ input: Schema.Struct({ mission: Schema.String }),
241
+ output: Schema.Struct({ report: Schema.String }),
242
+ instructions: "Delegate and look up, then answer as JSON.",
243
+ toolkit: Toolkit.make(researchDelegation.tool, Lookup),
244
+ policy: AgentPolicy.make({
245
+ maxTurns: 4,
246
+ maxToolCalls: 3,
247
+ maxDuration: CERTIFICATION_MAX_DURATION,
248
+ toolConcurrency: 2
249
+ })
250
+ });
251
+ const mapChildFailure = (failure) => CertifyDelegationFailed.make({ childErrorTag: failure._tag });
252
+ const DELEGATE_CALL = decodeToolCallId("delegate-1");
253
+ /** Fixture-only identity source consumed by the delegation Layer's ephemeral capture. */
254
+ const identifiers = Layer.effect(IdGenerator, Effect.gen(function* () {
255
+ const counter = yield* Ref.make(0);
256
+ const next = (decode, prefix) => Ref.getAndUpdate(counter, (value) => value + 1).pipe(Effect.map((value) => decode(`${prefix}-${value}`)));
257
+ return {
258
+ nextThreadId: next(decodeThreadId, "certify-fixture-thread"),
259
+ nextRunId: next(Schema.decodeSync(RunId), "certify-fixture-run"),
260
+ nextTurnId: next(Schema.decodeSync(TurnId), "certify-fixture-turn")
261
+ };
262
+ }));
263
+ const delegationSupport = Layer.mergeAll(SubagentReservationsMemoryLive, identifiers);
264
+ const submitOptionsFor = (slug, threadId) => ({
265
+ threadId,
266
+ principal: PRINCIPAL,
267
+ idempotencyKey: decodeIdempotencyKey(`certify-key-${slug}`),
268
+ definitions: DIGESTS
269
+ });
270
+ /** One single-agent cell: one lane, one Submission, one registered exact-digest binding. */
271
+ const makeSingleAgentCell = (definition, resolved, slug) => {
272
+ const threadId = decodeThreadId(`certify-${slug}`);
273
+ const submit = Effect.gen(function* () {
274
+ return [yield* (yield* DurableAgentRuntime).submit({ definition: {
275
+ id: definition.id,
276
+ input: definition.input
277
+ } }, { question: `certify ${slug}` }, submitOptionsFor(slug, threadId))];
278
+ });
279
+ return {
280
+ bindings: [resolved],
281
+ submit,
282
+ lanes: () => [threadId]
283
+ };
284
+ };
285
+ const makeCell = Effect.fn("Certification.makeCell")(function* (scenario, slug) {
286
+ switch (scenario) {
287
+ case "plain": {
288
+ const binding = Agent.withModel(plainDefinition, promptShapeModel("certify-plain", "{\"answer\":\"done\"}"));
289
+ const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS);
290
+ return makeSingleAgentCell(plainDefinition, resolved, slug);
291
+ }
292
+ case "uncertain-tool": {
293
+ const binding = Agent.withModel(uncertainDefinition, promptShapeModel("certify-uncertain", "{\"answer\":\"booked\"}", toolTurn(toolCallPart("book-1", "book", { ref: `r-${slug}` }))));
294
+ const toolLayer = bookToolkit.toLayer({ book: ({ ref }) => Effect.succeed({ confirmation: `confirmed-${ref}` }) });
295
+ const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(Effect.provide(toolLayer));
296
+ return makeSingleAgentCell(uncertainDefinition, resolved, slug);
297
+ }
298
+ case "durable-steps": {
299
+ const binding = Agent.withModel(stepsDefinition, promptShapeModel("certify-steps", "{\"answer\":\"reserved\"}", toolTurn(toolCallPart("itinerary-1", "itinerary", { ref: `trip-${slug}` }))));
300
+ const toolLayer = itineraryToolkit.toLayer({ itinerary: ({ ref }) => Effect.gen(function* () {
301
+ const step = yield* DurableStep;
302
+ return { state: `${yield* step.do("reserve-flight", Schema.String, Effect.succeed(`flight-${ref}`))}+${yield* step.do("reserve-lodging", Schema.String, Effect.succeed(`lodging-${ref}`))}` };
303
+ }) });
304
+ const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(Effect.provide(toolLayer));
305
+ return makeSingleAgentCell(stepsDefinition, resolved, slug);
306
+ }
307
+ case "approval": {
308
+ const binding = Agent.withModel(approvalDefinition, promptShapeModel("certify-approval", "{\"answer\":\"approved\"}", toolTurn(toolCallPart("book-1", "book", { ref: `r-${slug}` }))));
309
+ const toolLayer = approvalToolkit.toLayer({ book: ({ ref }) => Effect.succeed({ confirmation: `confirmed-${ref}` }) });
310
+ const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS).pipe(Effect.provide(toolLayer));
311
+ return makeSingleAgentCell(approvalDefinition, resolved, slug);
312
+ }
313
+ case "join": {
314
+ const binding = Agent.withModel(plainDefinition, promptShapeModel("certify-join", "{\"answer\":\"host answer\"}"));
315
+ const resolved = yield* DurableWorkerBinding.make(binding, DIGESTS);
316
+ const threadId = decodeThreadId(`certify-${slug}`);
317
+ const submitOne = Effect.fn("Certification.submitOne")(function* (key, question) {
318
+ return yield* (yield* DurableAgentRuntime).submit({ definition: {
319
+ id: plainDefinition.id,
320
+ input: plainDefinition.input
321
+ } }, { question }, {
322
+ threadId,
323
+ principal: PRINCIPAL,
324
+ idempotencyKey: decodeIdempotencyKey(key),
325
+ definitions: DIGESTS
326
+ });
327
+ });
328
+ return {
329
+ bindings: [resolved],
330
+ submit: Effect.gen(function* () {
331
+ return [yield* submitOne(`certify-key-${slug}-host`, "host question"), yield* submitOne(`certify-key-${slug}-queued`, "queued question")];
332
+ }),
333
+ lanes: () => [threadId]
334
+ };
335
+ }
336
+ case "delegation": {
337
+ const childBinding = Agent.withModel(childDefinition, promptShapeModel("certify-child", "{\"answer\":\"child-answer\"}"));
338
+ const parentBinding = Agent.withModel(coordinatorDefinition, promptShapeModel("certify-parent", "{\"report\":\"done\"}", toolTurn(toolCallPart("delegate-1", "delegate_research", { topic: "paris" }), toolCallPart("lookup-1", "lookup", { key: "hotels" }))));
339
+ const delegationLayer = SubagentRuntime.layer(researchDelegation, childBinding, {
340
+ mapChildFailure,
341
+ durable: { targetDigests: CHILD_DIGEST_STRINGS }
342
+ }).pipe(Layer.provide(delegationSupport));
343
+ const lookupLayer = Toolkit.make(Lookup).toLayer({ lookup: ({ key }) => Effect.succeed({ value: `found-${key}` }) });
344
+ const parentResolved = yield* DurableWorkerBinding.make(parentBinding, DIGESTS).pipe(Effect.provide(Layer.mergeAll(delegationLayer, lookupLayer)));
345
+ const childResolved = yield* DurableWorkerBinding.make(childBinding, CHILD_DIGESTS);
346
+ const threadId = decodeThreadId(`certify-${slug}`);
347
+ return {
348
+ bindings: [parentResolved, childResolved],
349
+ submit: Effect.gen(function* () {
350
+ return [yield* (yield* DurableAgentRuntime).submit({ definition: {
351
+ id: coordinatorDefinition.id,
352
+ input: coordinatorDefinition.input
353
+ } }, { mission: "plan" }, submitOptionsFor(slug, threadId))];
354
+ }),
355
+ lanes: (receipts) => {
356
+ const parent = receipts.at(0);
357
+ return parent === void 0 ? [threadId] : [threadId, childThreadIdFor(parent.submissionId, DELEGATE_CALL)];
358
+ }
359
+ };
360
+ }
361
+ }
362
+ });
363
+ /** Maximum recovery/drive/unblock rounds before a cell is reported non-convergent. */
364
+ const MAX_REDRIVE_ROUNDS = 8;
365
+ /**
366
+ * Verify one lane after convergence: canonical export + every lane Submission the ledger or
367
+ * the log names (the same collection rule as the admin `verify` member), fed to the shared
368
+ * invariant checker in convergence mode WITH the captured per-batch producer directory, so
369
+ * the digest chain is fully recomputed instead of skipped.
370
+ */
371
+ const verifyLane = Effect.fn("Certification.verifyLane")(function* (lane, batchProducers) {
372
+ const store = yield* ThreadStore;
373
+ const ledger = yield* SubmissionLedger;
374
+ const exported = yield* store.export(ThreadExportRequest.make({ threadId: lane }));
375
+ const rows = /* @__PURE__ */ new Map();
376
+ const nonterminal = yield* Stream.runCollect(ledger.scanNonterminal);
377
+ for (const submission of nonterminal) if (submission.threadId === lane) rows.set(submission.submissionId, submission);
378
+ const named = /* @__PURE__ */ new Set();
379
+ for (const envelope of exported.records) {
380
+ const payload = envelope.record.payload;
381
+ if (payload._tag === "UserInputRecorded" || payload._tag === "SubmissionSettled" || payload._tag === "AbortRequested") {
382
+ if (payload.submissionId !== void 0) named.add(payload.submissionId);
383
+ }
384
+ }
385
+ for (const submissionId of named) {
386
+ if (rows.has(submissionId)) continue;
387
+ const found = yield* ledger.lookup(SubmissionLookupById.make({ submissionId }));
388
+ if (Option.isSome(found) && found.value.threadId === lane) rows.set(submissionId, found.value);
389
+ }
390
+ const checkpoint = store.checkpoints === void 0 ? Option.none() : yield* store.checkpoints.load(LoadCheckpointRequest.make({ threadId: lane }));
391
+ return yield* verifyThreadInvariants({
392
+ export: exported,
393
+ submissions: [...rows.values()],
394
+ batchProducers,
395
+ checkpoint: Option.getOrUndefined(checkpoint),
396
+ checkpointsSupported: store.checkpoints !== void 0,
397
+ requireAllSettled: true
398
+ });
399
+ });
400
+ const failureTagOf = (cause) => {
401
+ const failure = Cause.findErrorOption(cause);
402
+ if (Option.isSome(failure)) {
403
+ const error = failure.value;
404
+ if (typeof error === "object" && error !== null && "_tag" in error) return String(error._tag);
405
+ return String(error).slice(0, 256);
406
+ }
407
+ return "defect";
408
+ };
409
+ /** One Tier-2 sweep cell: arm `location` one-shot, drive `scenario`, converge, verify. */
410
+ const runSweepCell = Effect.fn("Certification.runSweepCell")(function* (scenario, location, batchProducers, leaseAdvance) {
411
+ const ledger = yield* SubmissionLedger;
412
+ const control = yield* DurableRuntimeFailpointTestControl;
413
+ const slug = `${scenario}-${location.replaceAll(":", "-")}`;
414
+ const failed = (detail, fired) => CertificationSweepResult.make({
415
+ scenario,
416
+ location,
417
+ failpointFired: fired,
418
+ status: "failed",
419
+ digestChainVerified: false,
420
+ detail: detail.slice(0, 4096)
421
+ });
422
+ const cell = yield* makeCell(scenario, slug);
423
+ const runtime = yield* DurableAgentRuntime.pipe(Effect.provide(DurableAgentRuntime.layerWithBindings(cell.bindings).pipe(Layer.provide(RunToolAuthorization.allowAll))));
424
+ const submit = cell.submit.pipe(Effect.provideService(DurableAgentRuntime, runtime));
425
+ const fired = yield* Ref.make(false);
426
+ 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 })))));
427
+ let receipts;
428
+ const firstSubmit = yield* Effect.exit(submit);
429
+ if (Exit.isSuccess(firstSubmit)) receipts = firstSubmit.value;
430
+ else {
431
+ const secondSubmit = yield* Effect.exit(submit);
432
+ if (Exit.isFailure(secondSubmit)) {
433
+ yield* control.clear;
434
+ return failed(`submission replay did not recover: ${failureTagOf(secondSubmit.cause)}`, yield* Ref.get(fired));
435
+ }
436
+ receipts = secondSubmit.value;
437
+ }
438
+ const lanes = cell.lanes(receipts);
439
+ const driveLane = (lane) => runtime.processThreadResolved(lane);
440
+ const allSettled = Effect.gen(function* () {
441
+ for (const receipt of receipts) {
442
+ const snapshot = yield* ledger.lookup(SubmissionLookupById.make({ submissionId: receipt.submissionId }));
443
+ if (Option.isNone(snapshot) || snapshot.value.state !== "settled") return false;
444
+ }
445
+ return true;
446
+ });
447
+ let converged = false;
448
+ for (let round = 0; round < MAX_REDRIVE_ROUNDS && !converged; round++) {
449
+ yield* TestClock.adjust(leaseAdvance);
450
+ yield* Effect.exit(runtime.runRecovery);
451
+ for (const lane of lanes) yield* Effect.exit(driveLane(lane));
452
+ for (const lane of lanes) {
453
+ const explains = yield* Effect.exit(runtime.explainThread(lane));
454
+ if (Exit.isFailure(explains)) continue;
455
+ for (const explanation of explains.value) {
456
+ for (const unknown of explanation.evidence.unknownCalls) {
457
+ if (unknown.resolved) continue;
458
+ yield* Effect.exit(runtime.resolveUnknown(UnknownResolutionCommand.make({
459
+ submissionId: explanation.submission.submissionId,
460
+ toolCallId: unknown.toolCallId,
461
+ author: "certification-runner",
462
+ reason: `re-drive after injected fault at ${location}`,
463
+ resolution: ResolutionSafeToRetry.make()
464
+ })));
465
+ }
466
+ for (const pending of explanation.evidence.approvalsPending) {
467
+ if (explanation.evidence.approvalDecisions.some((decision) => decision.toolCallId === pending.toolCallId)) continue;
468
+ yield* Effect.exit(runtime.resolveApproval(ApprovalDecisionCommand.make({
469
+ submissionId: explanation.submission.submissionId,
470
+ toolCallId: pending.toolCallId,
471
+ decision: "approved",
472
+ resolver: "certification-runner",
473
+ reason: `re-drive after injected fault at ${location}`
474
+ })));
475
+ }
476
+ }
477
+ }
478
+ const settled = yield* Effect.exit(allSettled);
479
+ converged = Exit.isSuccess(settled) && settled.value;
480
+ }
481
+ yield* control.clear;
482
+ const wasFired = yield* Ref.get(fired);
483
+ if (!converged) return failed(`did not converge within ${MAX_REDRIVE_ROUNDS} re-drive rounds`, wasFired);
484
+ let digestChainVerified = true;
485
+ const failedChecks = [];
486
+ for (const lane of lanes) {
487
+ const verdict = yield* Effect.exit(verifyLane(lane, batchProducers));
488
+ if (Exit.isFailure(verdict)) return failed(`lane ${lane} could not be verified: ${failureTagOf(verdict.cause)}`, wasFired);
489
+ for (const check of verdict.value.checks) {
490
+ if (check.status === "failed") failedChecks.push(`${lane}:${check.name}${check.detail === void 0 ? "" : ` (${check.detail})`}`);
491
+ if (check.name === "digest-chain" && check.status !== "passed") digestChainVerified = false;
492
+ }
493
+ }
494
+ if (failedChecks.length > 0 || !digestChainVerified) return failed(failedChecks.length > 0 ? `invariant checks failed: ${failedChecks.join("; ")}` : "the digest chain was not fully recomputed", wasFired);
495
+ return CertificationSweepResult.make({
496
+ scenario,
497
+ location,
498
+ failpointFired: wasFired,
499
+ status: wasFired ? "converged" : "not-triggered",
500
+ digestChainVerified
501
+ });
502
+ });
503
+ /**
504
+ * Resolve the Tier-3 record honestly (plan §1): a non-durable reference adapter has no real
505
+ * loss to exercise (`not-applicable`); a supplied lever runs NOW (`exercised`); committed
506
+ * real-loss citations are recorded (`recorded-evidence`); otherwise the certificate says
507
+ * `not-exercised` — a scoped statement, never a silent claim.
508
+ */
509
+ const resolveTierThree = Effect.fn("Certification.resolveTierThree")(function* (durability, options) {
510
+ if (durability === "non-durable") return CertificationTierThreeReport.make({
511
+ status: "not-applicable",
512
+ evidence: [],
513
+ cases: [],
514
+ detail: "the adapter declares non-durable state (reference/conformance adapter); there is no real loss to exercise"
515
+ });
516
+ if (options.crashLever !== void 0) {
517
+ const cases = yield* options.crashLever;
518
+ return CertificationTierThreeReport.make({
519
+ status: cases.length === 0 ? "not-exercised" : "exercised",
520
+ evidence: options.tierThreeEvidence ?? [],
521
+ cases,
522
+ ...cases.length === 0 ? { detail: "the supplied crash lever executed no real-loss cases" } : {}
523
+ });
524
+ }
525
+ if (options.tierThreeEvidence !== void 0 && options.tierThreeEvidence.length > 0) return CertificationTierThreeReport.make({
526
+ status: "recorded-evidence",
527
+ evidence: options.tierThreeEvidence,
528
+ cases: []
529
+ });
530
+ return CertificationTierThreeReport.make({
531
+ status: "not-exercised",
532
+ evidence: [],
533
+ cases: [],
534
+ detail: "no crash lever was supplied and no committed real-loss evidence was cited; Tier 3 is NOT discharged for this adapter"
535
+ });
536
+ });
537
+ const nowUtc = Effect.map(Clock.currentTimeMillis, (millis) => DateTime.toUtc(DateTime.makeUnsafe(millis)));
538
+ /**
539
+ * Certify one durable adapter pair (plan §1, §8 WP2). Runs Tier 2 FIRST over pristine
540
+ * storage (each cell converges to all-settled before the next starts, so the recovery scan
541
+ * never sees foreign leftovers), then Tier 1's port contract cases (whose lanes deliberately
542
+ * end in every nonterminal shape), then records Tier 3. Requires `Crypto.Crypto` and a
543
+ * TestClock-backed environment; the candidate Layers are built exactly once.
544
+ */
545
+ const certifyDurableAdapters = (options) => {
546
+ const batchProducers = /* @__PURE__ */ new Map();
547
+ const capturingStore = Layer.effect(ThreadStore)(Effect.gen(function* () {
548
+ const inner = yield* ThreadStore;
549
+ return ThreadStore.of({
550
+ ...inner,
551
+ append: (request) => Effect.sync(() => {
552
+ batchProducers.set(request.batch.batchId, request.batch.producerId);
553
+ }).pipe(Effect.andThen(inner.append(request)))
554
+ });
555
+ })).pipe(Layer.provide(options.threadStore));
556
+ const environment = Layer.mergeAll(options.submissionLedger, capturingStore, options.wakeScheduler ?? WakeScheduler.layerNoop, DurableRuntimeFailpointTestControl.layer, ToolReconciler.uncertain, DurableRuntimeConfig.layer({
557
+ deploymentId: Schema.decodeSync(DeploymentId)("deployment-certification"),
558
+ producerId: Schema.decodeSync(ProducerId)("producer-certification"),
559
+ settlementPollInterval: Duration.millis(50),
560
+ leaseRenewalInterval: Duration.seconds(5),
561
+ abortPollInterval: Duration.millis(50)
562
+ }));
563
+ const leaseAdvance = Duration.millis(Duration.toMillis(options.ownershipLeaseDuration ?? DEFAULT_OWNERSHIP_LEASE_DURATION) + 1e3);
564
+ return Effect.gen(function* () {
565
+ const ledger = yield* SubmissionLedger;
566
+ const tier2 = [];
567
+ for (const scenario of CERTIFICATION_SCENARIOS) for (const location of DurableRuntimeFailpointLocation.literals) tier2.push(yield* runSweepCell(scenario, location, batchProducers, leaseAdvance));
568
+ const tier1 = yield* certifyPorts();
569
+ const capabilities = yield* ledger.capabilities;
570
+ const tier3 = yield* resolveTierThree(capabilities.durability, options);
571
+ const generatedAt = yield* nowUtc;
572
+ const ok = tier1.every((result) => result.status === "passed") && tier2.every((result) => result.status !== "failed") && tier3.cases.every((result) => result.status === "passed");
573
+ return CertificationReport.make({
574
+ format: "effect-agent/certification@2",
575
+ adapter: CertifiedAdapterIdentity.make({
576
+ name: options.adapter.name,
577
+ ...options.adapter.version === void 0 ? {} : { version: options.adapter.version },
578
+ durability: capabilities.durability
579
+ }),
580
+ generatedAt,
581
+ tier1,
582
+ tier2,
583
+ tier3,
584
+ ok,
585
+ fullyCertified: ok && capabilities.durability !== "non-durable" && tier3.status === "exercised" && tier3.cases.length > 0 && tier3.cases.every((result) => result.suite === "real-loss")
586
+ });
587
+ }).pipe(Effect.provide(environment));
588
+ };
589
+ //#endregion
590
+ export { CERTIFICATION_SCENARIOS, TIER2_UNREACHED_LOCATIONS, certifyDurableAdapters, resolveTierThree, tier2NeverFiredLocations };
591
+
592
+ //# sourceMappingURL=Certification.mjs.map