@effect-agent/testing 0.1.0-beta.91 → 0.1.0-beta.92

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/Chaos.d.mts CHANGED
@@ -3,10 +3,11 @@ import { DurableAgentRuntime, DurableRuntimeConfig } from "effect-agent/durable-
3
3
  import { SubmissionLedger } from "effect-agent/submission-ledger";
4
4
  import { DurableRuntimeFailpointTestControl } from "effect-agent/testing/durable-failpoint-test-control";
5
5
  import { ThreadStore } from "effect-agent/thread-store";
6
+ import { Arbitrary } from "effect/unstable/arbitrary";
6
7
  //#region src/Chaos.d.ts
7
8
  /**
8
9
  * P7 WP4 chaos machinery (plan §5): a Schema-first `ChaosPlan`, a seeded generator over
9
- * `effect/testing/FastCheck` (already inside the pinned Effect — no new dependency), and a
10
+ * `effect/unstable/arbitrary`, and a
10
11
  * deterministic runner that drives the durable coordinator over whatever adapter pair the test
11
12
  * provides. Every plan ends in the SAME claims the crash matrices make:
12
13
  *
@@ -97,9 +98,10 @@ interface ChaosGeneratorOptions {
97
98
  /**
98
99
  * Derive `count` chaos plans deterministically from one root seed. The same
99
100
  * `{seed, count, adapterArms}` triple always yields byte-identical plans, so a failure line
100
- * `CHAOS_SEED=<seed>` replays the exact schedule.
101
+ * `CHAOS_SEED=<seed>` replays the exact schedule with the same pinned generator version.
102
+ * Sampling is interruptible and reports bounded generation exhaustion as Arbitrary.SampleError.
101
103
  */
102
- declare const generateChaosPlans: (options: ChaosGeneratorOptions) => ReadonlyArray<ChaosPlan>;
104
+ declare const generateChaosPlans: (options: ChaosGeneratorOptions) => Effect.Effect<readonly ChaosPlan[], Arbitrary.SampleError, never>;
103
105
  /** Adapter-owned failpoint control the SQLite runner supplies; memory has none. */
104
106
  interface ChaosAdapterFailpoints {
105
107
  readonly arm: (location: string) => Effect.Effect<void>;
package/dist/Chaos.mjs CHANGED
@@ -18,12 +18,12 @@ import { AbortCommand, ApprovalDecisionCommand, IdempotencyKey, Principal, Resol
18
18
  import { DurableRuntimeFailpointTestControl } from "effect-agent/testing/durable-failpoint-test-control";
19
19
  import { verifyThreadInvariants } from "effect-agent/thread-invariants";
20
20
  import { ThreadExportRequest, ThreadStore } from "effect-agent/thread-store";
21
- import { FastCheck } from "effect/testing";
22
21
  import { ObligationThresholds } from "effect-agent/admin";
22
+ import { Arbitrary } from "effect/unstable/arbitrary";
23
23
  //#region src/Chaos.ts
24
24
  /**
25
25
  * P7 WP4 chaos machinery (plan §5): a Schema-first `ChaosPlan`, a seeded generator over
26
- * `effect/testing/FastCheck` (already inside the pinned Effect — no new dependency), and a
26
+ * `effect/unstable/arbitrary`, and a
27
27
  * deterministic runner that drives the durable coordinator over whatever adapter pair the test
28
28
  * provides. Every plan ends in the SAME claims the crash matrices make:
29
29
  *
@@ -114,36 +114,36 @@ const chaosSeedFromEnv = (env) => {
114
114
  if (raw === void 0 || raw === "") return DEFAULT_CHAOS_SEED;
115
115
  return Option.getOrElse(decodeChaosSeedFromEnvironment(raw), () => DEFAULT_CHAOS_SEED);
116
116
  };
117
- const laneArbitrary = FastCheck.constantFrom("plain", "uncertain-tool", "durable-steps", "approval", "join", "delegation").chain((kind) => kind === "join" ? FastCheck.integer({
118
- min: 2,
119
- max: 3
120
- }).map((depth) => ({
121
- kind,
122
- depth
123
- })) : kind === "plain" ? FastCheck.integer({
124
- min: 1,
125
- max: 2
126
- }).map((depth) => ({
127
- kind,
128
- depth
129
- })) : FastCheck.constant({
130
- kind,
131
- depth: 1
132
- }));
133
- const planShapeArbitrary = (adapterArms) => FastCheck.record({
134
- lanes: FastCheck.array(laneArbitrary, {
135
- minLength: 1,
136
- maxLength: 3
117
+ const GeneratedLane = Schema.Union([
118
+ Schema.Struct({
119
+ kind: Schema.Literal("join"),
120
+ depth: Schema.Literals([2, 3])
121
+ }),
122
+ Schema.Struct({
123
+ kind: Schema.Literal("plain"),
124
+ depth: Schema.Literals([1, 2])
137
125
  }),
138
- failpointArms: FastCheck.uniqueArray(FastCheck.constantFrom(...DurableRuntimeFailpointLocation.literals), { maxLength: 3 }),
139
- adapterArms: adapterArms.length === 0 ? FastCheck.constant([]) : FastCheck.uniqueArray(FastCheck.constantFrom(...adapterArms), { maxLength: 2 }),
140
- abortInjections: FastCheck.uniqueArray(FastCheck.integer({
141
- min: 0,
142
- max: 15
143
- }), { maxLength: 2 }),
144
- resolutionInjections: FastCheck.array(FastCheck.constantFrom("never-happened", "completed-from-supplier", "abort-submission"), { maxLength: 4 }),
145
- approvalDecisions: FastCheck.array(FastCheck.constantFrom("approved", "denied"), { maxLength: 2 })
146
- }).map((shape) => {
126
+ Schema.Struct({
127
+ kind: Schema.Literals([
128
+ "uncertain-tool",
129
+ "durable-steps",
130
+ "approval",
131
+ "delegation"
132
+ ]),
133
+ depth: Schema.Literal(1)
134
+ })
135
+ ]);
136
+ const planShapeArbitrary = (adapterArms) => Arbitrary.schema(Schema.Struct({
137
+ lanes: Schema.Array(GeneratedLane).check(Schema.isMinLength(1), Schema.isMaxLength(3)),
138
+ failpointArms: Schema.Array(DurableRuntimeFailpointLocation).check(Schema.isUnique(), Schema.isMaxLength(3)),
139
+ adapterArms: Schema.Array(adapterArms.length === 0 ? Schema.String : Schema.Literals(adapterArms)).check(Schema.isUnique(), Schema.isMaxLength(adapterArms.length === 0 ? 0 : 2)),
140
+ abortInjections: Schema.Array(Schema.Int.check(Schema.isBetween({
141
+ minimum: 0,
142
+ maximum: 15
143
+ }))).check(Schema.isUnique(), Schema.isMaxLength(2)),
144
+ resolutionInjections: Schema.Array(ChaosResolutionKind).check(Schema.isMaxLength(4)),
145
+ approvalDecisions: Schema.Array(ChaosApprovalDecision).check(Schema.isMaxLength(2))
146
+ })).pipe(Arbitrary.map((shape) => {
147
147
  const [first, ...rest] = shape.lanes.flatMap((lane, index) => Array.from({ length: lane.depth }, () => ChaosSubmissionSpec.make({
148
148
  lane: index,
149
149
  kind: lane.kind
@@ -158,21 +158,22 @@ const planShapeArbitrary = (adapterArms) => FastCheck.record({
158
158
  resolutionInjections: shape.resolutionInjections,
159
159
  approvalDecisions: shape.approvalDecisions
160
160
  };
161
- });
161
+ }));
162
162
  /**
163
163
  * Derive `count` chaos plans deterministically from one root seed. The same
164
164
  * `{seed, count, adapterArms}` triple always yields byte-identical plans, so a failure line
165
- * `CHAOS_SEED=<seed>` replays the exact schedule.
165
+ * `CHAOS_SEED=<seed>` replays the exact schedule with the same pinned generator version.
166
+ * Sampling is interruptible and reports bounded generation exhaustion as Arbitrary.SampleError.
166
167
  */
167
- const generateChaosPlans = (options) => {
168
- return FastCheck.sample(planShapeArbitrary(options.adapterArms ?? []), {
168
+ const generateChaosPlans = Effect.fnUntraced(function* (options) {
169
+ return (yield* Arbitrary.sampleEffect(planShapeArbitrary(options.adapterArms ?? []), {
169
170
  seed: options.seed,
170
- numRuns: options.count
171
- }).map((shape, index) => ChaosPlan.make({
171
+ count: options.count
172
+ })).map((shape, index) => ChaosPlan.make({
172
173
  ...shape,
173
174
  seed: Math.imul(options.seed, 31) + index | 0
174
175
  }));
175
- };
176
+ });
176
177
  /** Deterministic PRNG for the runner's small ordering choices (lane drive order). */
177
178
  const mulberry32 = (seed) => {
178
179
  let state = seed | 0;
@@ -1 +1 @@
1
- {"version":3,"file":"Chaos.mjs","names":[],"sources":["../src/Chaos.ts"],"sourcesContent":["import { Cause, Effect, Exit, Layer, Option, Ref, Schema, Stream } from \"effect\";\nimport { ObligationThresholds } from \"effect-agent/admin\";\nimport * as Agent from \"effect-agent/agent\";\nimport { AgentPolicy } from \"effect-agent/agent-policy\";\nimport {\n DurableWorkerBinding,\n type DurableBindingFailure,\n type ResolvedBinding,\n} from \"effect-agent/agent-registration\";\nimport {\n DurableAgentRuntime,\n DurableRuntimeConfig,\n type DurableSubmitFailure,\n type DurableWorkerFailure,\n type Receipt,\n} from \"effect-agent/durable-agent-runtime\";\nimport {\n DurableRuntimeFailpointError,\n DurableRuntimeFailpointLocation,\n} from \"effect-agent/durable-failpoint\";\nimport { DurableStep, DurableStepError, ToolExecutionClass } from \"effect-agent/durable-step\";\nimport { IdGenerator } from \"effect-agent/id-generator\";\nimport { ThreadId, RunId, ToolCallId, TurnId, type SubmissionId } from \"effect-agent/identifiers\";\nimport {\n DefinitionDigests,\n Digest,\n type CanonicalRecordEnvelope,\n type BatchId,\n type ProducerId,\n} from \"effect-agent/records\";\nimport { childThreadIdFor } from \"effect-agent/run-journal\";\nimport { RunToolAuthorization } from \"effect-agent/run-options\";\nimport * as Subagent from \"effect-agent/subagent\";\nimport { SubagentPolicy } from \"effect-agent/subagent\";\nimport { SubagentReservationsMemoryLive } from \"effect-agent/subagent-reservations\";\nimport {\n AbortCommand,\n ApprovalDecisionCommand,\n IdempotencyKey,\n Principal,\n ResolutionAbortSubmission,\n ResolutionCompletedWithResult,\n ResolutionNeverHappened,\n SubmissionLedger,\n SubmissionLookupById,\n UnknownResolutionCommand,\n type Settlement,\n type SubmissionSnapshot,\n type UnknownResolution,\n} from \"effect-agent/submission-ledger\";\nimport { DurableRuntimeFailpointTestControl } from \"effect-agent/testing/durable-failpoint-test-control\";\nimport { verifyThreadInvariants } from \"effect-agent/thread-invariants\";\nimport { ThreadExportRequest, ThreadStore } from \"effect-agent/thread-store\";\nimport { FastCheck } from \"effect/testing\";\nimport {\n LanguageModel,\n Model,\n Tool,\n Toolkit,\n type Prompt,\n type Response,\n} from \"effect/unstable/ai\";\n\n/**\n * P7 WP4 chaos machinery (plan §5): a Schema-first `ChaosPlan`, a seeded generator over\n * `effect/testing/FastCheck` (already inside the pinned Effect — no new dependency), and a\n * deterministic runner that drives the durable coordinator over whatever adapter pair the test\n * provides. Every plan ends in the SAME claims the crash matrices make:\n *\n * 1. `verifyThreadInvariants` in convergence mode over every touched Thread (the\n * shared WP1 checker — one set of claims for admin verify, certification, chaos, and soak);\n * 2. `scanObligations` returning ZERO entries (everything settled; nothing invisibly stuck);\n * 3. supplier non-fabrication wherever the deterministic desk was in play (durability §10: no\n * canonical Tool success exists that the external store did not actually produce).\n *\n * Replay contract: the memory/SQLite chaos tests derive every plan from one root seed\n * (`CHAOS_SEED` env override; see `chaosSeedFromEnv`) and print that seed plus the failing\n * plan's own seed in the failure output, so any red run is replayable byte-for-byte.\n */\n\n// ---------------------------------------------------------------------------\n// ChaosPlan schema\n// ---------------------------------------------------------------------------\n\n/** The six durable scenario flavors a chaos lane can exercise (plan §5). */\nexport const ChaosScenarioKind = Schema.Literals([\n \"plain\",\n \"uncertain-tool\",\n \"durable-steps\",\n \"approval\",\n \"join\",\n \"delegation\",\n]);\n\nexport type ChaosScenarioKind = typeof ChaosScenarioKind.Type;\n\nconst LaneIndex = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(7));\n\n/** One Submission of a plan: which lane it queues into and that lane's scenario flavor. */\nexport class ChaosSubmissionSpec extends Schema.Class<ChaosSubmissionSpec>(\n \"@effect-agent/testing/ChaosSubmissionSpec\",\n)({\n lane: LaneIndex,\n /** The lane's flavor; the FIRST spec of a lane fixes the lane's agent. */\n kind: ChaosScenarioKind,\n}) {}\n\n/** How the runner resolves a durable Unknown Outcome it encounters (DUR-017 driver). */\nexport const ChaosResolutionKind = Schema.Literals([\n /** The call provably never started: the batch resumes and executes it. */\n \"never-happened\",\n /**\n * Recovered supplier truth: resolve with the EXACT value the desk produced. Falls back to\n * `never-happened` when the desk holds no value for the call, so the runner never fabricates.\n */\n \"completed-from-supplier\",\n /** Unresolvable: route into the abort path (settles aborted, audit retained). */\n \"abort-submission\",\n]);\n\nexport type ChaosResolutionKind = typeof ChaosResolutionKind.Type;\n\nexport const ChaosApprovalDecision = Schema.Literals([\"approved\", \"denied\"]);\nexport type ChaosApprovalDecision = typeof ChaosApprovalDecision.Type;\n\nconst BoundedAdapterArm = Schema.String.check(Schema.isMaxLength(128));\n\n/**\n * One seeded chaos plan (plan §5): the full fault schedule is data, so a failing run replays\n * from the plan alone. `failpointArms` are coordinator locations; `adapterArms` are\n * adapter-owned location names the adapter test validates (the memory runner has none).\n */\nexport class ChaosPlan extends Schema.Class<ChaosPlan>(\"@effect-agent/testing/ChaosPlan\")({\n /** Identifies this plan in failure output; derived from the root seed plus the plan index. */\n seed: Schema.Int,\n /** Lane count; submissions address lanes `0..lanes-1`. */\n lanes: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(8)),\n submissions: Schema.NonEmptyArray(ChaosSubmissionSpec),\n /** Coordinator failpoint arms, consumed one per round (each fails every hit that round). */\n failpointArms: Schema.Array(DurableRuntimeFailpointLocation),\n /** Adapter-owned failpoint arms (e.g. SQLite `ledger:*`/`append:*` locations). */\n adapterArms: Schema.Array(BoundedAdapterArm),\n /** Flattened submission indices to abort mid-plan (modulo the submission count). */\n abortInjections: Schema.Array(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n /** Resolution choices for Unknown Outcomes, indexed deterministically per open call. */\n resolutionInjections: Schema.Array(ChaosResolutionKind),\n /** Approval decisions for suspended approval lanes, indexed deterministically per call. */\n approvalDecisions: Schema.Array(ChaosApprovalDecision),\n}) {}\n\n/** Per-lane verification result inside a plan report. */\nexport class ChaosLaneReport extends Schema.Class<ChaosLaneReport>(\n \"@effect-agent/testing/ChaosLaneReport\",\n)({\n threadId: ThreadId,\n kind: ChaosScenarioKind,\n submissionCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Verdict of `verifyThreadInvariants` in convergence mode. */\n verified: Schema.Boolean,\n}) {}\n\n/** The Schema-first outcome of one executed chaos plan. */\nexport class ChaosPlanReport extends Schema.Class<ChaosPlanReport>(\n \"@effect-agent/testing/ChaosPlanReport\",\n)({\n seed: Schema.Int,\n rounds: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n lanes: Schema.Array(ChaosLaneReport),\n /** `scanObligations` entries after convergence — MUST be zero. */\n openObligations: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\n/** Typed convergence/verification failure of one chaos plan (never a bare defect). */\nexport class ChaosConvergenceFailure extends Schema.TaggedError<ChaosConvergenceFailure>()(\n \"ChaosConvergenceFailure\",\n {\n seed: Schema.Int,\n message: Schema.String.check(Schema.isMaxLength(16_384)),\n },\n) {}\n\n// ---------------------------------------------------------------------------\n// Seeded generation\n// ---------------------------------------------------------------------------\n\n/** Default root seed for chaos suites; override with the `CHAOS_SEED` environment variable. */\nexport const DEFAULT_CHAOS_SEED = 20260813;\n\nconst ChaosSeedFromEnvironment = Schema.FiniteFromString.check(Schema.isInt());\nconst decodeChaosSeedFromEnvironment = Schema.decodeUnknownOption(ChaosSeedFromEnvironment);\n\n/** The root seed for this run: `CHAOS_SEED` when set to an integer, the default otherwise. */\nexport const chaosSeedFromEnv = (env: Record<string, string | undefined>): number => {\n const raw = env[\"CHAOS_SEED\"];\n\n if (raw === undefined || raw === \"\") return DEFAULT_CHAOS_SEED;\n\n return Option.getOrElse(decodeChaosSeedFromEnvironment(raw), () => DEFAULT_CHAOS_SEED);\n};\n\nexport interface ChaosGeneratorOptions {\n /** Root seed (print this in failure output for replay). */\n readonly seed: number;\n /** How many plans to derive. */\n readonly count: number;\n /** Adapter failpoint location names available to arm (empty for memory). */\n readonly adapterArms?: ReadonlyArray<string> | undefined;\n}\n\ninterface GeneratedLane {\n readonly kind: ChaosScenarioKind;\n readonly depth: number;\n}\n\nconst laneArbitrary: FastCheck.Arbitrary<GeneratedLane> = FastCheck.constantFrom<ChaosScenarioKind>(\n \"plain\",\n \"uncertain-tool\",\n \"durable-steps\",\n \"approval\",\n \"join\",\n \"delegation\",\n).chain((kind): FastCheck.Arbitrary<GeneratedLane> =>\n kind === \"join\"\n ? FastCheck.integer({ min: 2, max: 3 }).map((depth): GeneratedLane => ({ kind, depth }))\n : kind === \"plain\"\n ? FastCheck.integer({ min: 1, max: 2 }).map((depth): GeneratedLane => ({ kind, depth }))\n : FastCheck.constant<GeneratedLane>({ kind, depth: 1 }),\n);\n\ninterface ChaosPlanShape {\n readonly lanes: number;\n readonly submissions: readonly [ChaosSubmissionSpec, ...Array<ChaosSubmissionSpec>];\n readonly failpointArms: ReadonlyArray<DurableRuntimeFailpointLocation>;\n readonly adapterArms: ReadonlyArray<string>;\n readonly abortInjections: ReadonlyArray<number>;\n readonly resolutionInjections: ReadonlyArray<ChaosResolutionKind>;\n readonly approvalDecisions: ReadonlyArray<ChaosApprovalDecision>;\n}\n\nconst planShapeArbitrary = (\n adapterArms: ReadonlyArray<string>,\n): FastCheck.Arbitrary<ChaosPlanShape> =>\n FastCheck.record({\n lanes: FastCheck.array(laneArbitrary, { minLength: 1, maxLength: 3 }),\n failpointArms: FastCheck.uniqueArray(\n FastCheck.constantFrom(...DurableRuntimeFailpointLocation.literals),\n { maxLength: 3 },\n ),\n adapterArms:\n adapterArms.length === 0\n ? FastCheck.constant<Array<string>>([])\n : FastCheck.uniqueArray(FastCheck.constantFrom(...adapterArms), { maxLength: 2 }),\n abortInjections: FastCheck.uniqueArray(FastCheck.integer({ min: 0, max: 15 }), {\n maxLength: 2,\n }),\n resolutionInjections: FastCheck.array(\n FastCheck.constantFrom<ChaosResolutionKind>(\n \"never-happened\",\n \"completed-from-supplier\",\n \"abort-submission\",\n ),\n { maxLength: 4 },\n ),\n approvalDecisions: FastCheck.array(\n FastCheck.constantFrom<ChaosApprovalDecision>(\"approved\", \"denied\"),\n { maxLength: 2 },\n ),\n }).map((shape) => {\n const submissions = shape.lanes.flatMap((lane, index) =>\n Array.from({ length: lane.depth }, () =>\n ChaosSubmissionSpec.make({ lane: index, kind: lane.kind }),\n ),\n );\n\n const [first, ...rest] = submissions;\n\n // `lanes` >= 1 and every lane has depth >= 1, so `first` always exists.\n if (first === undefined) throw new Error(\"chaos generator produced an empty plan\");\n\n return {\n lanes: shape.lanes.length,\n submissions: [first, ...rest] as const,\n failpointArms: shape.failpointArms,\n adapterArms: shape.adapterArms,\n abortInjections: shape.abortInjections,\n resolutionInjections: shape.resolutionInjections,\n approvalDecisions: shape.approvalDecisions,\n };\n });\n\n/**\n * Derive `count` chaos plans deterministically from one root seed. The same\n * `{seed, count, adapterArms}` triple always yields byte-identical plans, so a failure line\n * `CHAOS_SEED=<seed>` replays the exact schedule.\n */\nexport const generateChaosPlans = (options: ChaosGeneratorOptions): ReadonlyArray<ChaosPlan> => {\n const sampled = FastCheck.sample(planShapeArbitrary(options.adapterArms ?? []), {\n seed: options.seed,\n numRuns: options.count,\n });\n\n return sampled.map((shape, index) =>\n ChaosPlan.make({ ...shape, seed: (Math.imul(options.seed, 31) + index) | 0 }),\n );\n};\n\n/** Deterministic PRNG for the runner's small ordering choices (lane drive order). */\nconst mulberry32 = (seed: number): (() => number) => {\n let state = seed | 0;\n\n return () => {\n state = (state + 0x6d2b79f5) | 0;\n let t = Math.imul(state ^ (state >>> 15), 1 | state);\n\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n};\n\n// ---------------------------------------------------------------------------\n// Lane fixtures (agents, scripted models, deterministic desk)\n// ---------------------------------------------------------------------------\n\nconst usage = { inputTokens: {}, outputTokens: {} };\n\nconst finalParts = (text: string): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"answer\" },\n { type: \"text-delta\", id: \"answer\", delta: text },\n { type: \"text-end\", id: \"answer\" },\n { type: \"finish\", reason: \"stop\", usage },\n];\n\nconst toolTurn = (\n ...calls: ReadonlyArray<Response.StreamPartEncoded>\n): ReadonlyArray<Response.StreamPartEncoded> => [\n ...calls,\n { type: \"finish\", reason: \"tool-calls\", usage },\n];\n\nconst toolCallPart = (id: string, name: string, params: unknown): Response.StreamPartEncoded => ({\n type: \"tool-call\",\n id,\n name,\n params,\n providerExecuted: false,\n});\n\n/**\n * Prompt-shaped scripted model: the response depends ONLY on the request prompt, so it stays\n * deterministic across Attempt re-invocations, batch resumes, and joined steering — no counter\n * to drift when chaos re-enters a Turn.\n */\nconst promptScriptedModel = (\n label: string,\n script: (prompt: Prompt.Prompt) => ReadonlyArray<Response.StreamPartEncoded>,\n) =>\n Model.make(\n \"scripted\",\n label,\n Layer.effect(\n LanguageModel.LanguageModel,\n LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (request) => Stream.fromIterable(script(request.prompt)),\n }),\n ),\n );\n\nconst lastRole = (prompt: Prompt.Prompt): string | undefined => prompt.content.at(-1)?.role;\n\nconst policy = AgentPolicy.make({\n maxTurns: 3,\n maxToolCalls: 4,\n maxDuration: \"30 seconds\",\n toolConcurrency: 2,\n});\n\nconst PlainInput = Schema.Struct({ question: Schema.String });\nconst PlainOutput = Schema.Struct({ answer: Schema.String });\n\nconst plainDefinition = Agent.make(\"chaos-plain\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Answer as JSON.\",\n toolkit: Toolkit.empty,\n policy,\n});\n\n/** Unannotated → fail-closed `uncertain`: enters the prepared/settled protocol (DUR-009). */\nconst BookUncertain = Tool.make(\"book\", {\n parameters: Schema.Struct({ ref: Schema.String }),\n success: Schema.Struct({ confirmation: Schema.String }),\n});\n\nconst bookTools = Toolkit.make(BookUncertain);\n\nconst bookDefinition = Agent.make(\"chaos-book\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Book it.\",\n toolkit: bookTools,\n policy,\n});\n\nconst BookApproval = Tool.make(\"book\", {\n parameters: Schema.Struct({ ref: Schema.String }),\n success: Schema.Struct({ confirmation: Schema.String }),\n needsApproval: true,\n});\n\nconst approvalTools = Toolkit.make(BookApproval);\n\nconst approvalDefinition = Agent.make(\"chaos-approval\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Book after approval.\",\n toolkit: approvalTools,\n policy,\n});\n\nconst Itinerary = Tool.make(\"itinerary\", {\n parameters: Schema.Struct({ ref: Schema.String }),\n success: Schema.Struct({ state: Schema.String }),\n failure: DurableStepError,\n dependencies: [DurableStep],\n}).annotate(ToolExecutionClass, \"uncertain\");\n\nconst itineraryTools = Toolkit.make(Itinerary);\n\nconst itineraryDefinition = Agent.make(\"chaos-itinerary\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Reserve the itinerary.\",\n toolkit: itineraryTools,\n policy,\n});\n\nconst childDefinition = Agent.make(\"chaos-child\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Answer as JSON.\",\n toolkit: Toolkit.empty,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 1,\n maxDuration: \"30 seconds\",\n toolConcurrency: 1,\n }),\n});\n\nclass ChaosDelegationFailed extends Schema.TaggedError<ChaosDelegationFailed>()(\n \"ChaosDelegationFailed\",\n { childErrorTag: Schema.String },\n) {}\n\nconst chaosDelegation = Subagent.define(\"delegate_chaos\", {\n description: \"Delegate one bounded chaos question.\",\n target: childDefinition,\n parameters: Schema.Struct({ topic: Schema.String }),\n success: Schema.Struct({ summary: Schema.String }),\n failure: ChaosDelegationFailed,\n prepareInput: ({ topic }) => Effect.succeed({ question: `chaos:${topic}` }),\n projectResult: (output) => Effect.succeed({ summary: `finding:${output.answer}` }),\n policy: SubagentPolicy.make({\n maxChildren: 2,\n maxConcurrency: 2,\n maxTurns: 4,\n maxToolCalls: 4,\n maxDuration: \"30 seconds\",\n }),\n});\n\nconst coordinatorDefinition = Agent.make(\"chaos-coordinator\", {\n input: Schema.Struct({ mission: Schema.String }),\n output: Schema.Struct({ report: Schema.String }),\n instructions: \"Delegate, then report as JSON.\",\n toolkit: Toolkit.make(chaosDelegation.tool),\n policy,\n});\n\nconst DELEGATE_CALL_ID = \"chaos-delegate-1\";\n\nconst HEX = \"0123456789abcdef\";\nconst decodeDigest = Schema.decodeSync(Digest);\n\nconst laneDigests = (lane: number): DefinitionDigests => {\n const digest = decodeDigest(HEX.charAt(lane % 8).repeat(64));\n\n return DefinitionDigests.make({ agent: digest, model: digest, tools: digest });\n};\n\nconst childDigestStrings = (lane: number) => {\n const char = HEX.charAt(8 + (lane % 8));\n\n return { agent: char.repeat(64), model: char.repeat(64), tools: char.repeat(64) } as const;\n};\n\nconst childLaneDigests = (lane: number): DefinitionDigests => {\n const strings = childDigestStrings(lane);\n\n return DefinitionDigests.make({\n agent: decodeDigest(strings.agent),\n model: decodeDigest(strings.model),\n tools: decodeDigest(strings.tools),\n });\n};\n\nconst CHAOS_PRINCIPAL = Schema.decodeSync(Principal)(\"principal-chaos\");\nconst decodeThreadId = Schema.decodeSync(ThreadId);\nconst decodeIdempotencyKey = Schema.decodeSync(IdempotencyKey);\nconst decodeToolCallId = Schema.decodeSync(ToolCallId);\nconst decodeRunId = Schema.decodeSync(RunId);\nconst decodeTurnId = Schema.decodeSync(TurnId);\n\n/** Fixture-only identity source consumed by the delegation Layer's ephemeral capture. */\nconst chaosIdentifiers = Layer.effect(\n IdGenerator,\n Effect.gen(function* () {\n const counter = yield* Ref.make(0);\n\n const next = <A>(decode: (value: string) => A, prefix: string) =>\n Ref.getAndUpdate(counter, (value) => value + 1).pipe(\n Effect.map((value) => decode(`${prefix}-${value}`)),\n );\n\n return {\n nextThreadId: next(decodeThreadId, \"chaos-fixture-thread\"),\n nextRunId: next(decodeRunId, \"chaos-fixture-run\"),\n nextTurnId: next(decodeTurnId, \"chaos-fixture-turn\"),\n };\n }),\n);\n\nconst delegationSupport = Layer.mergeAll(SubagentReservationsMemoryLive, chaosIdentifiers);\n\n/**\n * The deterministic external desk of one plan: every produced value is recorded so the final\n * non-fabrication sweep can prove each canonical Tool success came from here (durability §10).\n */\ninterface ChaosDesk {\n readonly produced: Effect.Effect<ReadonlySet<string>>;\n readonly record: (value: string) => Effect.Effect<void>;\n}\n\nconst makeChaosDesk: Effect.Effect<ChaosDesk> = Effect.gen(function* () {\n const produced = yield* Ref.make<ReadonlySet<string>>(new Set());\n\n return {\n produced: Ref.get(produced),\n record: (value: string) => Ref.update(produced, (current) => new Set(current).add(value)),\n };\n});\n\nconst bookConfirmation = (ref: string): string => `confirmed-${ref}`;\nconst flightValue = (ref: string): string => `flight-${ref}`;\nconst lodgingValue = (ref: string): string => `lodging-${ref}`;\n\n// ---------------------------------------------------------------------------\n// Runner\n// ---------------------------------------------------------------------------\n\n/** Adapter-owned failpoint control the SQLite runner supplies; memory has none. */\nexport interface ChaosAdapterFailpoints {\n readonly arm: (location: string) => Effect.Effect<void>;\n readonly clear: Effect.Effect<void>;\n}\n\nexport interface ChaosRunOptions {\n readonly adapterFailpoints?: ChaosAdapterFailpoints | undefined;\n /**\n * Executed at the end of every round. Adapters whose ownership leases block every new claim\n * until expiry (the SQLite ledger's D5 semantics — expiry only revokes the liveness\n * assumption; producer epochs stay the correctness fence) pass a deterministic\n * `TestClock.adjust` here so a dead Attempt's lane becomes reclaimable next round. The memory\n * ledger needs nothing: it allows same-producer reclaim under a live lease.\n */\n readonly betweenRounds?: Effect.Effect<void> | undefined;\n}\n\n/** Tolerate typed failures while preserving every defect and interruption reason. */\nconst tolerateTyped = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<Option.Option<A>, never, R> =>\n effect.pipe(\n Effect.exit,\n Effect.flatMap((exit) => {\n if (Exit.isSuccess(exit)) return Effect.succeed(Option.some(exit.value));\n const unexpected = exit.cause.reasons.filter((reason) => reason._tag !== \"Fail\");\n\n return unexpected.length === 0\n ? Effect.succeed(Option.none<A>())\n : Effect.failCause(Cause.fromReasons<never>(unexpected));\n }),\n );\n\ninterface LaneFixture {\n readonly index: number;\n readonly kind: ChaosScenarioKind;\n readonly threadId: ThreadId;\n readonly ref: string;\n readonly deskInPlay: boolean;\n readonly submissionIndexes: ReadonlyArray<number>;\n readonly submitOne: (flatIndex: number) => Effect.Effect<Receipt, DurableSubmitFailure>;\n readonly drives: (\n firstReceipt: Receipt | undefined,\n ) => ReadonlyArray<\n Effect.Effect<ReadonlyArray<Settlement>, DurableWorkerFailure | DurableBindingFailure>\n >;\n readonly childThreadOf: (firstReceipt: Receipt) => ThreadId | undefined;\n}\n\ninterface SubmissionState {\n readonly flatIndex: number;\n readonly lane: LaneFixture;\n receipt: Receipt | undefined;\n}\n\nconst scriptFor = (\n kind: ChaosScenarioKind,\n ref: string,\n): ((prompt: Prompt.Prompt) => ReadonlyArray<Response.StreamPartEncoded>) => {\n switch (kind) {\n case \"plain\":\n case \"join\":\n return () => finalParts('{\"answer\":\"chaos\"}');\n case \"uncertain-tool\":\n case \"approval\":\n return (prompt) =>\n lastRole(prompt) === \"tool\"\n ? finalParts('{\"answer\":\"booked\"}')\n : toolTurn(toolCallPart(`book-${ref}`, \"book\", { ref }));\n case \"durable-steps\":\n return (prompt) =>\n lastRole(prompt) === \"tool\"\n ? finalParts('{\"answer\":\"reserved\"}')\n : toolTurn(toolCallPart(`itinerary-${ref}`, \"itinerary\", { ref }));\n case \"delegation\":\n return (prompt) =>\n lastRole(prompt) === \"tool\"\n ? finalParts('{\"report\":\"done\"}')\n : toolTurn(toolCallPart(DELEGATE_CALL_ID, \"delegate_chaos\", { topic: ref }));\n }\n};\n\nconst makeLaneFixture = Effect.fn(\"Chaos.makeLaneFixture\")(function* (\n plan: ChaosPlan,\n laneIndex: number,\n kind: ChaosScenarioKind,\n submissionIndexes: ReadonlyArray<number>,\n desk: ChaosDesk,\n) {\n const runtime = yield* DurableAgentRuntime;\n const threadId = decodeThreadId(`chaos-${plan.seed}-lane-${laneIndex}`);\n const ref = `ref-l${laneIndex}`;\n const script = scriptFor(kind, ref);\n const model = promptScriptedModel(`chaos-${kind}-${laneIndex}`, script);\n const digests = laneDigests(laneIndex);\n\n const submitOptionsFor = (flatIndex: number) => ({\n threadId,\n principal: CHAOS_PRINCIPAL,\n idempotencyKey: decodeIdempotencyKey(`chaos-${plan.seed}-s${flatIndex}`),\n definitions: digests,\n });\n\n const bookToolLayerFor = (tools: typeof bookTools | typeof approvalTools) =>\n tools.toLayer({\n book: ({ ref: called }) =>\n desk\n .record(bookConfirmation(called))\n .pipe(Effect.as({ confirmation: bookConfirmation(called) })),\n });\n\n const plainLaneFixture = (\n deskInPlay: boolean,\n drive: Effect.Effect<ReadonlyArray<Settlement>, DurableWorkerFailure | DurableBindingFailure>,\n submitOne: (flatIndex: number) => Effect.Effect<Receipt, DurableSubmitFailure>,\n ): LaneFixture => ({\n index: laneIndex,\n kind,\n threadId,\n ref,\n deskInPlay,\n submissionIndexes,\n submitOne,\n drives: () => [drive],\n childThreadOf: () => undefined,\n });\n\n switch (kind) {\n case \"plain\":\n case \"join\": {\n const agent = Agent.withModel(plainDefinition, model);\n\n return plainLaneFixture(false, runtime.processThread(agent, threadId), (flatIndex) =>\n runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)),\n );\n }\n case \"uncertain-tool\": {\n const agent = Agent.withModel(bookDefinition, model);\n\n return plainLaneFixture(\n true,\n runtime.processThread(agent, threadId).pipe(Effect.provide(bookToolLayerFor(bookTools))),\n (flatIndex) =>\n runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)),\n );\n }\n case \"approval\": {\n const agent = Agent.withModel(approvalDefinition, model);\n\n return plainLaneFixture(\n true,\n runtime\n .processThread(agent, threadId)\n .pipe(Effect.provide(bookToolLayerFor(approvalTools))),\n (flatIndex) =>\n runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)),\n );\n }\n case \"durable-steps\": {\n const agent = Agent.withModel(itineraryDefinition, model);\n\n const toolLayer = itineraryTools.toLayer({\n itinerary: ({ ref: called }) =>\n Effect.gen(function* () {\n const step = yield* DurableStep;\n\n const flight = yield* step.do(\n \"reserve-flight\",\n Schema.String,\n desk.record(flightValue(called)).pipe(Effect.as(flightValue(called))),\n );\n\n const lodging = yield* step.do(\n \"reserve-lodging\",\n Schema.String,\n desk.record(lodgingValue(called)).pipe(Effect.as(lodgingValue(called))),\n );\n\n return { state: `${flight}+${lodging}` };\n }),\n });\n\n return plainLaneFixture(\n true,\n runtime.processThread(agent, threadId).pipe(Effect.provide(toolLayer)),\n (flatIndex) =>\n runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)),\n );\n }\n case \"delegation\": {\n const parentBinding = Agent.withModel(coordinatorDefinition, model);\n\n const childModel = promptScriptedModel(`chaos-child-${laneIndex}`, () =>\n finalParts('{\"answer\":\"child\"}'),\n );\n\n const childBinding = Agent.withModel(childDefinition, childModel);\n\n const delegationLayer = Subagent.layer(chaosDelegation, childBinding, {\n mapChildFailure: (failure) => ChaosDelegationFailed.make({ childErrorTag: failure._tag }),\n durable: { targetDigests: childDigestStrings(laneIndex) },\n }).pipe(Layer.provide(delegationSupport));\n\n const parentResolved: ResolvedBinding = yield* DurableWorkerBinding.make(\n parentBinding,\n digests,\n ).pipe(Effect.provide(delegationLayer));\n\n const childResolved: ResolvedBinding = yield* DurableWorkerBinding.make(\n childBinding,\n childLaneDigests(laneIndex),\n );\n\n const registeredRuntime = yield* DurableAgentRuntime.pipe(\n Effect.provide(\n DurableAgentRuntime.layerWithBindings([parentResolved, childResolved]).pipe(\n Layer.provide(RunToolAuthorization.allowAll),\n ),\n ),\n );\n\n const driveResolved = (thread: ThreadId) => registeredRuntime.processThreadResolved(thread);\n\n const fixture: LaneFixture = {\n index: laneIndex,\n kind,\n threadId,\n ref,\n deskInPlay: false,\n submissionIndexes,\n submitOne: (flatIndex) =>\n runtime.submit(\n { definition: { id: coordinatorDefinition.id, input: coordinatorDefinition.input } },\n { mission: `chaos ${flatIndex}` },\n submitOptionsFor(flatIndex),\n ),\n drives: (firstReceipt) => {\n const drives: Array<\n Effect.Effect<ReadonlyArray<Settlement>, DurableWorkerFailure | DurableBindingFailure>\n > = [driveResolved(threadId)];\n\n if (firstReceipt !== undefined) {\n drives.push(\n driveResolved(\n childThreadIdFor(firstReceipt.submissionId, decodeToolCallId(DELEGATE_CALL_ID)),\n ),\n );\n }\n\n return drives;\n },\n childThreadOf: (firstReceipt) =>\n childThreadIdFor(firstReceipt.submissionId, decodeToolCallId(DELEGATE_CALL_ID)),\n };\n\n return fixture;\n }\n }\n});\n\n/** Stable per-call index into an injection list (identical across resolution passes). */\nconst injectionIndex = (submissionFlatIndex: number, callId: string, length: number): number => {\n let hash = submissionFlatIndex + 1;\n\n for (const char of callId) hash = (Math.imul(hash, 31) + char.charCodeAt(0)) | 0;\n\n return ((hash % length) + length) % length;\n};\n\nconst resolutionFor = (\n kind: ChaosResolutionKind,\n toolName: string,\n ref: string,\n produced: ReadonlySet<string>,\n): UnknownResolution => {\n switch (kind) {\n case \"abort-submission\":\n return ResolutionAbortSubmission.make();\n case \"completed-from-supplier\": {\n if (toolName === \"book\" && produced.has(bookConfirmation(ref))) {\n return ResolutionCompletedWithResult.make({\n result: { confirmation: bookConfirmation(ref) },\n isFailure: false,\n });\n }\n if (\n toolName === \"itinerary\" &&\n produced.has(flightValue(ref)) &&\n produced.has(lodgingValue(ref))\n ) {\n return ResolutionCompletedWithResult.make({\n result: { state: `${flightValue(ref)}+${lodgingValue(ref)}` },\n isFailure: false,\n });\n }\n\n // The desk never produced a value for this call — resolving \"completed\" would fabricate.\n return ResolutionNeverHappened.make();\n }\n case \"never-happened\":\n return ResolutionNeverHappened.make();\n }\n};\n\n/** Drive one DUR-017 pass: resolve Unknown Outcomes and pending approvals from the plan. */\nconst resolutionPass = Effect.fn(\"Chaos.resolutionPass\")(function* (\n plan: ChaosPlan,\n states: ReadonlyArray<SubmissionState>,\n desk: ChaosDesk,\n) {\n const runtime = yield* DurableAgentRuntime;\n const ledger = yield* SubmissionLedger;\n const produced = yield* desk.produced;\n const nonterminal = yield* tolerateTyped(Stream.runCollect(ledger.scanNonterminal));\n\n if (Option.isNone(nonterminal)) return;\n const byId = new Map<SubmissionId, SubmissionState>();\n\n for (const state of states) {\n if (state.receipt !== undefined) byId.set(state.receipt.submissionId, state);\n }\n for (const row of nonterminal.value) {\n if (row.state !== \"unknown\" && row.state !== \"suspended\") continue;\n const state = byId.get(row.submissionId);\n const explanation = yield* tolerateTyped(runtime.explain(row.submissionId));\n\n if (Option.isNone(explanation)) continue;\n const flatIndex = state?.flatIndex ?? 0;\n const ref = state?.lane.ref ?? \"ref-child\";\n\n if (row.state === \"unknown\") {\n for (const call of explanation.value.evidence.unknownCalls) {\n if (call.resolved) continue;\n\n const kind =\n plan.resolutionInjections.length === 0\n ? \"never-happened\"\n : (plan.resolutionInjections.at(\n injectionIndex(flatIndex, call.toolCallId, plan.resolutionInjections.length),\n ) ?? \"never-happened\");\n\n yield* tolerateTyped(\n runtime.resolveUnknown(\n UnknownResolutionCommand.make({\n submissionId: row.submissionId,\n toolCallId: call.toolCallId,\n author: \"chaos-runner\",\n reason: `chaos plan ${plan.seed} resolution (${kind})`,\n resolution: resolutionFor(kind, call.toolName, ref, produced),\n }),\n ),\n );\n }\n } else {\n for (const pending of explanation.value.evidence.approvalsPending) {\n const decision =\n plan.approvalDecisions.length === 0\n ? \"approved\"\n : (plan.approvalDecisions.at(\n injectionIndex(flatIndex, pending.toolCallId, plan.approvalDecisions.length),\n ) ?? \"approved\");\n\n yield* tolerateTyped(\n runtime.resolveApproval(\n ApprovalDecisionCommand.make({\n submissionId: row.submissionId,\n toolCallId: pending.toolCallId,\n decision,\n resolver: \"chaos-runner\",\n reason: `chaos plan ${plan.seed} approval (${decision})`,\n }),\n ),\n );\n }\n }\n }\n});\n\nconst submissionIdsNamedBy = (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n): ReadonlySet<SubmissionId> => {\n const named = new Set<SubmissionId>();\n\n for (const envelope of records) {\n const payload = envelope.record.payload;\n\n if (\n payload._tag === \"UserInputRecorded\" ||\n payload._tag === \"SubmissionSettled\" ||\n payload._tag === \"AbortRequested\"\n ) {\n if (payload.submissionId !== undefined) named.add(payload.submissionId);\n }\n }\n\n return named;\n};\n\n/**\n * The final non-fabrication sweep (durability §10): every canonical Tool success recorded on a\n * desk-backed lane must be a value the desk actually produced.\n */\nconst BookResult = Schema.Struct({ confirmation: Schema.String });\nconst ItineraryResult = Schema.Struct({ state: Schema.String });\nconst decodeBookResult = Schema.decodeUnknownOption(BookResult);\nconst decodeItineraryResult = Schema.decodeUnknownOption(ItineraryResult);\nconst decodeStepOutput = Schema.decodeUnknownOption(Schema.String);\n\nconst assertNoFabrication = (\n plan: ChaosPlan,\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n produced: ReadonlySet<string>,\n): Effect.Effect<void, ChaosConvergenceFailure> => {\n const fabricated: Array<string> = [];\n\n const requireProduced = (value: string, label: string): void => {\n if (!produced.has(value)) fabricated.push(`${label} \"${value}\"`);\n };\n\n for (const envelope of records) {\n const payload = envelope.record.payload;\n\n if (payload._tag === \"ToolCallSettled\" && !payload.isFailure) {\n if (payload.toolName === \"book\") {\n const result = decodeBookResult(payload.result);\n\n if (Option.isSome(result)) requireProduced(result.value.confirmation, \"book result\");\n }\n if (payload.toolName === \"itinerary\") {\n const result = decodeItineraryResult(payload.result);\n\n if (Option.isSome(result)) {\n for (const part of result.value.state.split(\"+\")) {\n requireProduced(part, \"itinerary step result\");\n }\n }\n }\n }\n if (payload._tag === \"ToolStepSettled\") {\n const output = decodeStepOutput(payload.output);\n\n if (Option.isSome(output)) requireProduced(output.value, \"step output\");\n }\n }\n\n return fabricated.length === 0\n ? Effect.void\n : Effect.fail(\n ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `fabricated Tool results absent from the desk: ${fabricated.join(\", \")}`,\n }),\n );\n};\n\n/**\n * Execute one chaos plan against whatever adapters the ambient Layer provides and end in the\n * shared invariant claims. Deterministic: same plan + same adapters → same schedule.\n */\nexport const runChaosPlan = Effect.fn(\"Chaos.runChaosPlan\")(function* (\n plan: ChaosPlan,\n options?: ChaosRunOptions,\n) {\n const runtime = yield* DurableAgentRuntime;\n const ledger = yield* SubmissionLedger;\n const store = yield* ThreadStore;\n const config = yield* DurableRuntimeConfig;\n const failpoints = yield* DurableRuntimeFailpointTestControl;\n const random = mulberry32(plan.seed);\n const desk = yield* makeChaosDesk;\n\n // Lane fixtures: the FIRST spec of each lane fixes the lane's agent kind.\n const laneKinds = new Map<number, ChaosScenarioKind>();\n const laneSubmissions = new Map<number, Array<number>>();\n\n plan.submissions.forEach((spec, flatIndex) => {\n const lane = spec.lane % plan.lanes;\n\n if (!laneKinds.has(lane)) laneKinds.set(lane, spec.kind);\n const list = laneSubmissions.get(lane) ?? [];\n\n list.push(flatIndex);\n laneSubmissions.set(lane, list);\n });\n const lanes: Array<LaneFixture> = [];\n\n for (const [lane, kind] of laneKinds) {\n lanes.push(yield* makeLaneFixture(plan, lane, kind, laneSubmissions.get(lane) ?? [], desk));\n }\n\n const lanesByIndex = new Map(lanes.map((lane) => [lane.index, lane]));\n const states: Array<SubmissionState> = [];\n\n for (const [flatIndex, spec] of plan.submissions.entries()) {\n const laneIndex = spec.lane % plan.lanes;\n const lane = lanesByIndex.get(laneIndex);\n\n if (lane === undefined) {\n return yield* ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `submission ${flatIndex} addresses missing lane ${laneIndex}`,\n });\n }\n states.push({ flatIndex, lane, receipt: undefined });\n }\n const appliedAborts = new Set<number>();\n\n type ArmEntry =\n | { readonly family: \"coordinator\"; readonly location: DurableRuntimeFailpointLocation }\n | { readonly family: \"adapter\"; readonly location: string };\n\n const armQueue: Array<ArmEntry> = [\n ...plan.failpointArms.map((location): ArmEntry => ({ family: \"coordinator\", location })),\n ...plan.adapterArms.map((location): ArmEntry => ({ family: \"adapter\", location })),\n ];\n\n const allSettled = Effect.gen(function* () {\n if (states.some((state) => state.receipt === undefined)) return false;\n const nonterminal = yield* tolerateTyped(Stream.runCollect(ledger.scanNonterminal));\n\n return Option.isSome(nonterminal) && Array.from(nonterminal.value).length === 0;\n });\n\n const maxRounds = armQueue.length + states.length * 2 + 12;\n let rounds = 0;\n let converged = false;\n\n for (let round = 0; round < maxRounds; round++) {\n rounds = round + 1;\n const arm = armQueue[round];\n\n if (arm?.family === \"coordinator\") {\n const location = arm.location;\n\n yield* failpoints.setHandler((hit) =>\n hit === location\n ? Effect.fail(DurableRuntimeFailpointError.make({ location: hit }))\n : Effect.void,\n );\n } else if (arm?.family === \"adapter\" && options?.adapterFailpoints !== undefined) {\n yield* options.adapterFailpoints.arm(arm.location);\n }\n\n // Admission chaos: pending submissions retry under the active arm until a Receipt lands;\n // the identical (thread, principal, key) triple reattaches, never duplicates.\n for (const state of states) {\n if (state.receipt !== undefined) continue;\n const receipt = yield* tolerateTyped(state.lane.submitOne(state.flatIndex));\n\n if (Option.isSome(receipt)) state.receipt = receipt.value;\n }\n\n // Drive every lane (and discovered child lanes) in seeded order under the active arm.\n const order = lanes\n .map((lane) => ({ lane, rank: random() }))\n .sort((left, right) => left.rank - right.rank || left.lane.index - right.lane.index)\n .map(({ lane }) => lane);\n\n for (const lane of order) {\n const firstFlat = lane.submissionIndexes[0];\n const firstReceipt = firstFlat === undefined ? undefined : states[firstFlat]?.receipt;\n\n for (const drive of lane.drives(firstReceipt)) {\n yield* tolerateTyped(drive);\n }\n }\n\n // Abort injections fire once, while arms may still be active (abort:after-intent etc.).\n if (round >= 1) {\n for (const rawIndex of plan.abortInjections) {\n const index = rawIndex % states.length;\n\n if (appliedAborts.has(index)) continue;\n const receipt = states[index]?.receipt;\n\n if (receipt === undefined) continue;\n appliedAborts.add(index);\n yield* tolerateTyped(\n runtime.abort(\n AbortCommand.make({\n submissionId: receipt.submissionId,\n author: \"chaos-runner\",\n reason: `chaos plan ${plan.seed} abort injection`,\n }),\n ),\n );\n }\n }\n\n // First resolution pass runs under the arm so resolve:* locations can fire.\n yield* resolutionPass(plan, states, desk);\n\n yield* failpoints.clear;\n if (options?.adapterFailpoints !== undefined) yield* options.adapterFailpoints.clear;\n\n yield* tolerateTyped(runtime.runRecovery);\n // Second, unarmed pass guarantees forward progress for newly marked Unknown lanes.\n yield* resolutionPass(plan, states, desk);\n\n if (yield* allSettled) {\n converged = true;\n break;\n }\n if (options?.betweenRounds !== undefined) yield* options.betweenRounds;\n }\n\n if (!converged) {\n const nonterminal = yield* tolerateTyped(Stream.runCollect(ledger.scanNonterminal));\n\n const detail = Option.isSome(nonterminal)\n ? Array.from(nonterminal.value)\n .map((row: SubmissionSnapshot) => `${row.submissionId}(${row.state})`)\n .join(\", \")\n : \"ledger scan failed\";\n\n return yield* ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `plan did not converge within ${maxRounds} rounds; nonterminal: [${detail}]; pending receipts: ${states.filter((state) => state.receipt === undefined).length}`,\n });\n }\n\n // Final claims: the shared invariant checker per touched Thread, in convergence mode,\n // with the full digest chain (single known producer), plus the desk non-fabrication sweep.\n const produced = yield* desk.produced;\n const laneReports: Array<ChaosLaneReport> = [];\n\n const verifyThread = Effect.fn(\"Chaos.verifyThread\")(function* (\n threadId: ThreadId,\n kind: ChaosScenarioKind,\n deskInPlay: boolean,\n ) {\n const exported = yield* store.export(ThreadExportRequest.make({ threadId })).pipe(\n Effect.mapError((error) =>\n ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `export of ${threadId} failed: ${String(error)}`,\n }),\n ),\n );\n\n const rows: Array<SubmissionSnapshot> = [];\n\n for (const submissionId of submissionIdsNamedBy(exported.records)) {\n const found = yield* ledger.lookup(SubmissionLookupById.make({ submissionId })).pipe(\n Effect.mapError((error) =>\n ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `lookup of ${submissionId} failed: ${String(error)}`,\n }),\n ),\n );\n\n if (Option.isSome(found)) rows.push(found.value);\n }\n\n const batchProducers = new Map<BatchId, ProducerId>(\n exported.records.map((envelope) => [envelope.batchId, config.producerId]),\n );\n\n const report = yield* verifyThreadInvariants({\n export: exported,\n submissions: rows,\n batchProducers,\n requireAllSettled: true,\n });\n\n if (!report.ok) {\n const failed = report.checks\n .filter((check) => check.status === \"failed\")\n .map((check) => `${check.name}: ${check.detail ?? \"failed\"}`)\n .join(\"; \");\n\n return yield* ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `invariants failed for ${threadId} (${kind}): ${failed}`,\n });\n }\n if (deskInPlay) {\n yield* assertNoFabrication(plan, exported.records, produced);\n }\n laneReports.push(\n ChaosLaneReport.make({\n threadId,\n kind,\n submissionCount: rows.length,\n verified: report.ok,\n }),\n );\n });\n\n for (const lane of lanes) {\n yield* verifyThread(lane.threadId, lane.kind, lane.deskInPlay);\n // Delegation lanes: verify every materialized child Thread too.\n for (const flatIndex of lane.submissionIndexes) {\n const receipt = states[flatIndex]?.receipt;\n\n if (receipt === undefined) continue;\n const child = lane.childThreadOf(receipt);\n\n if (child === undefined) continue;\n\n const childExport = yield* Effect.exit(\n store.export(ThreadExportRequest.make({ threadId: child })),\n );\n\n if (Exit.isSuccess(childExport) && childExport.value.records.length > 0) {\n yield* verifyThread(child, \"plain\", false);\n }\n }\n }\n\n const obligations = yield* runtime\n .scanObligations(ObligationThresholds.make({ agingSeconds: 0, overdueSeconds: 0 }))\n .pipe(\n Effect.mapError((error) =>\n ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `scanObligations failed: ${String(error)}`,\n }),\n ),\n );\n\n if (obligations.entries.length > 0) {\n return yield* ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `open obligations after convergence: ${obligations.entries\n .map((entry) => `${entry.submissionId}(${entry.blockedOn})`)\n .join(\", \")}`,\n });\n }\n\n return ChaosPlanReport.make({\n seed: plan.seed,\n rounds,\n lanes: laneReports,\n openObligations: obligations.entries.length,\n });\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqFA,MAAa,oBAAoB,OAAO,SAAS;CAC/C;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAID,MAAM,YAAY,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,GAAG,OAAO,oBAAoB,CAAC,CAAC;;AAGlG,IAAa,sBAAb,cAAyC,OAAO,MAC9C,2CACF,CAAC,CAAC;CACA,MAAM;;CAEN,MAAM;AACR,CAAC,CAAC,CAAC,CAAC;;AAGJ,MAAa,sBAAsB,OAAO,SAAS;CAEjD;CAKA;CAEA;AACF,CAAC;AAID,MAAa,wBAAwB,OAAO,SAAS,CAAC,YAAY,QAAQ,CAAC;AAG3E,MAAM,oBAAoB,OAAO,OAAO,MAAM,OAAO,YAAY,GAAG,CAAC;;;;;;AAOrE,IAAa,YAAb,c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Y,KACV,gBAAgB,KAAK;GACnB;GACA;GACA,iBAAiB,KAAK;GACtB,UAAU,OAAO;EACnB,CAAC,CACH;CACF,CAAC;CAED,KAAK,MAAM,QAAQ,OAAO;EACxB,OAAO,aAAa,KAAK,UAAU,KAAK,MAAM,KAAK,UAAU;EAE7D,KAAK,MAAM,aAAa,KAAK,mBAAmB;GAC9C,MAAM,UAAU,OAAO,UAAU,EAAE;GAEnC,IAAI,YAAY,KAAA,GAAW;GAC3B,MAAM,QAAQ,KAAK,cAAc,OAAO;GAExC,IAAI,UAAU,KAAA,GAAW;GAEzB,MAAM,cAAc,OAAO,OAAO,KAChC,MAAM,OAAO,oBAAoB,KAAK,EAAE,UAAU,MAAM,CAAC,CAAC,CAC5D;GAEA,IAAI,KAAK,UAAU,WAAW,KAAK,YAAY,MAAM,QAAQ,SAAS,GACpE,OAAO,aAAa,OAAO,SAAS,KAAK;EAE7C;CACF;CAEA,MAAM,cAAc,OAAO,QACxB,gBAAgB,qBAAqB,KAAK;EAAE,cAAc;EAAG,gBAAgB;CAAE,CAAC,CAAC,CAAC,CAClF,KACC,OAAO,UAAU,UACf,wBAAwB,KAAK;EAC3B,MAAM,KAAK;EACX,SAAS,2BAA2B,OAAO,KAAK;CAClD,CAAC,CACH,CACF;CAEF,IAAI,YAAY,QAAQ,SAAS,GAC/B,OAAO,OAAO,wBAAwB,KAAK;EACzC,MAAM,KAAK;EACX,SAAS,uCAAuC,YAAY,QACzD,KAAK,UAAU,GAAG,MAAM,aAAa,GAAG,MAAM,UAAU,EAAE,CAAC,CAC3D,KAAK,IAAI;CACd,CAAC;CAGH,OAAO,gBAAgB,KAAK;EAC1B,MAAM,KAAK;EACX;EACA,OAAO;EACP,iBAAiB,YAAY,QAAQ;CACvC,CAAC;AACH,CAAC"}
1
+ {"version":3,"file":"Chaos.mjs","names":[],"sources":["../src/Chaos.ts"],"sourcesContent":["import { Cause, Effect, Exit, Layer, Option, Ref, Schema, Stream } from \"effect\";\nimport { ObligationThresholds } from \"effect-agent/admin\";\nimport * as Agent from \"effect-agent/agent\";\nimport { AgentPolicy } from \"effect-agent/agent-policy\";\nimport {\n DurableWorkerBinding,\n type DurableBindingFailure,\n type ResolvedBinding,\n} from \"effect-agent/agent-registration\";\nimport {\n DurableAgentRuntime,\n DurableRuntimeConfig,\n type DurableSubmitFailure,\n type DurableWorkerFailure,\n type Receipt,\n} from \"effect-agent/durable-agent-runtime\";\nimport {\n DurableRuntimeFailpointError,\n DurableRuntimeFailpointLocation,\n} from \"effect-agent/durable-failpoint\";\nimport { DurableStep, DurableStepError, ToolExecutionClass } from \"effect-agent/durable-step\";\nimport { IdGenerator } from \"effect-agent/id-generator\";\nimport { ThreadId, RunId, ToolCallId, TurnId, type SubmissionId } from \"effect-agent/identifiers\";\nimport {\n DefinitionDigests,\n Digest,\n type CanonicalRecordEnvelope,\n type BatchId,\n type ProducerId,\n} from \"effect-agent/records\";\nimport { childThreadIdFor } from \"effect-agent/run-journal\";\nimport { RunToolAuthorization } from \"effect-agent/run-options\";\nimport * as Subagent from \"effect-agent/subagent\";\nimport { SubagentPolicy } from \"effect-agent/subagent\";\nimport { SubagentReservationsMemoryLive } from \"effect-agent/subagent-reservations\";\nimport {\n AbortCommand,\n ApprovalDecisionCommand,\n IdempotencyKey,\n Principal,\n ResolutionAbortSubmission,\n ResolutionCompletedWithResult,\n ResolutionNeverHappened,\n SubmissionLedger,\n SubmissionLookupById,\n UnknownResolutionCommand,\n type Settlement,\n type SubmissionSnapshot,\n type UnknownResolution,\n} from \"effect-agent/submission-ledger\";\nimport { DurableRuntimeFailpointTestControl } from \"effect-agent/testing/durable-failpoint-test-control\";\nimport { verifyThreadInvariants } from \"effect-agent/thread-invariants\";\nimport { ThreadExportRequest, ThreadStore } from \"effect-agent/thread-store\";\nimport {\n LanguageModel,\n Model,\n Tool,\n Toolkit,\n type Prompt,\n type Response,\n} from \"effect/unstable/ai\";\nimport { Arbitrary } from \"effect/unstable/arbitrary\";\n\n/**\n * P7 WP4 chaos machinery (plan §5): a Schema-first `ChaosPlan`, a seeded generator over\n * `effect/unstable/arbitrary`, and a\n * deterministic runner that drives the durable coordinator over whatever adapter pair the test\n * provides. Every plan ends in the SAME claims the crash matrices make:\n *\n * 1. `verifyThreadInvariants` in convergence mode over every touched Thread (the\n * shared WP1 checker — one set of claims for admin verify, certification, chaos, and soak);\n * 2. `scanObligations` returning ZERO entries (everything settled; nothing invisibly stuck);\n * 3. supplier non-fabrication wherever the deterministic desk was in play (durability §10: no\n * canonical Tool success exists that the external store did not actually produce).\n *\n * Replay contract: the memory/SQLite chaos tests derive every plan from one root seed\n * (`CHAOS_SEED` env override; see `chaosSeedFromEnv`) and print that seed plus the failing\n * plan's own seed in the failure output, so any red run is replayable byte-for-byte.\n */\n\n// ---------------------------------------------------------------------------\n// ChaosPlan schema\n// ---------------------------------------------------------------------------\n\n/** The six durable scenario flavors a chaos lane can exercise (plan §5). */\nexport const ChaosScenarioKind = Schema.Literals([\n \"plain\",\n \"uncertain-tool\",\n \"durable-steps\",\n \"approval\",\n \"join\",\n \"delegation\",\n]);\n\nexport type ChaosScenarioKind = typeof ChaosScenarioKind.Type;\n\nconst LaneIndex = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(7));\n\n/** One Submission of a plan: which lane it queues into and that lane's scenario flavor. */\nexport class ChaosSubmissionSpec extends Schema.Class<ChaosSubmissionSpec>(\n \"@effect-agent/testing/ChaosSubmissionSpec\",\n)({\n lane: LaneIndex,\n /** The lane's flavor; the FIRST spec of a lane fixes the lane's agent. */\n kind: ChaosScenarioKind,\n}) {}\n\n/** How the runner resolves a durable Unknown Outcome it encounters (DUR-017 driver). */\nexport const ChaosResolutionKind = Schema.Literals([\n /** The call provably never started: the batch resumes and executes it. */\n \"never-happened\",\n /**\n * Recovered supplier truth: resolve with the EXACT value the desk produced. Falls back to\n * `never-happened` when the desk holds no value for the call, so the runner never fabricates.\n */\n \"completed-from-supplier\",\n /** Unresolvable: route into the abort path (settles aborted, audit retained). */\n \"abort-submission\",\n]);\n\nexport type ChaosResolutionKind = typeof ChaosResolutionKind.Type;\n\nexport const ChaosApprovalDecision = Schema.Literals([\"approved\", \"denied\"]);\nexport type ChaosApprovalDecision = typeof ChaosApprovalDecision.Type;\n\nconst BoundedAdapterArm = Schema.String.check(Schema.isMaxLength(128));\n\n/**\n * One seeded chaos plan (plan §5): the full fault schedule is data, so a failing run replays\n * from the plan alone. `failpointArms` are coordinator locations; `adapterArms` are\n * adapter-owned location names the adapter test validates (the memory runner has none).\n */\nexport class ChaosPlan extends Schema.Class<ChaosPlan>(\"@effect-agent/testing/ChaosPlan\")({\n /** Identifies this plan in failure output; derived from the root seed plus the plan index. */\n seed: Schema.Int,\n /** Lane count; submissions address lanes `0..lanes-1`. */\n lanes: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(8)),\n submissions: Schema.NonEmptyArray(ChaosSubmissionSpec),\n /** Coordinator failpoint arms, consumed one per round (each fails every hit that round). */\n failpointArms: Schema.Array(DurableRuntimeFailpointLocation),\n /** Adapter-owned failpoint arms (e.g. SQLite `ledger:*`/`append:*` locations). */\n adapterArms: Schema.Array(BoundedAdapterArm),\n /** Flattened submission indices to abort mid-plan (modulo the submission count). */\n abortInjections: Schema.Array(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),\n /** Resolution choices for Unknown Outcomes, indexed deterministically per open call. */\n resolutionInjections: Schema.Array(ChaosResolutionKind),\n /** Approval decisions for suspended approval lanes, indexed deterministically per call. */\n approvalDecisions: Schema.Array(ChaosApprovalDecision),\n}) {}\n\n/** Per-lane verification result inside a plan report. */\nexport class ChaosLaneReport extends Schema.Class<ChaosLaneReport>(\n \"@effect-agent/testing/ChaosLaneReport\",\n)({\n threadId: ThreadId,\n kind: ChaosScenarioKind,\n submissionCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Verdict of `verifyThreadInvariants` in convergence mode. */\n verified: Schema.Boolean,\n}) {}\n\n/** The Schema-first outcome of one executed chaos plan. */\nexport class ChaosPlanReport extends Schema.Class<ChaosPlanReport>(\n \"@effect-agent/testing/ChaosPlanReport\",\n)({\n seed: Schema.Int,\n rounds: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n lanes: Schema.Array(ChaosLaneReport),\n /** `scanObligations` entries after convergence — MUST be zero. */\n openObligations: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\n/** Typed convergence/verification failure of one chaos plan (never a bare defect). */\nexport class ChaosConvergenceFailure extends Schema.TaggedError<ChaosConvergenceFailure>()(\n \"ChaosConvergenceFailure\",\n {\n seed: Schema.Int,\n message: Schema.String.check(Schema.isMaxLength(16_384)),\n },\n) {}\n\n// ---------------------------------------------------------------------------\n// Seeded generation\n// ---------------------------------------------------------------------------\n\n/** Default root seed for chaos suites; override with the `CHAOS_SEED` environment variable. */\nexport const DEFAULT_CHAOS_SEED = 20260813;\n\nconst ChaosSeedFromEnvironment = Schema.FiniteFromString.check(Schema.isInt());\nconst decodeChaosSeedFromEnvironment = Schema.decodeUnknownOption(ChaosSeedFromEnvironment);\n\n/** The root seed for this run: `CHAOS_SEED` when set to an integer, the default otherwise. */\nexport const chaosSeedFromEnv = (env: Record<string, string | undefined>): number => {\n const raw = env[\"CHAOS_SEED\"];\n\n if (raw === undefined || raw === \"\") return DEFAULT_CHAOS_SEED;\n\n return Option.getOrElse(decodeChaosSeedFromEnvironment(raw), () => DEFAULT_CHAOS_SEED);\n};\n\nexport interface ChaosGeneratorOptions {\n /** Root seed (print this in failure output for replay). */\n readonly seed: number;\n /** How many plans to derive. */\n readonly count: number;\n /** Adapter failpoint location names available to arm (empty for memory). */\n readonly adapterArms?: ReadonlyArray<string> | undefined;\n}\n\nconst GeneratedLane = Schema.Union([\n Schema.Struct({ kind: Schema.Literal(\"join\"), depth: Schema.Literals([2, 3]) }),\n Schema.Struct({ kind: Schema.Literal(\"plain\"), depth: Schema.Literals([1, 2]) }),\n Schema.Struct({\n kind: Schema.Literals([\"uncertain-tool\", \"durable-steps\", \"approval\", \"delegation\"]),\n depth: Schema.Literal(1),\n }),\n]);\n\ninterface ChaosPlanShape {\n readonly lanes: number;\n readonly submissions: readonly [ChaosSubmissionSpec, ...Array<ChaosSubmissionSpec>];\n readonly failpointArms: ReadonlyArray<DurableRuntimeFailpointLocation>;\n readonly adapterArms: ReadonlyArray<string>;\n readonly abortInjections: ReadonlyArray<number>;\n readonly resolutionInjections: ReadonlyArray<ChaosResolutionKind>;\n readonly approvalDecisions: ReadonlyArray<ChaosApprovalDecision>;\n}\n\nconst planShapeArbitrary = (\n adapterArms: ReadonlyArray<string>,\n): Arbitrary.Arbitrary<ChaosPlanShape> =>\n Arbitrary.schema(\n Schema.Struct({\n lanes: Schema.Array(GeneratedLane).check(Schema.isMinLength(1), Schema.isMaxLength(3)),\n failpointArms: Schema.Array(DurableRuntimeFailpointLocation).check(\n Schema.isUnique(),\n Schema.isMaxLength(3),\n ),\n adapterArms: Schema.Array(\n adapterArms.length === 0 ? Schema.String : Schema.Literals(adapterArms),\n ).check(Schema.isUnique(), Schema.isMaxLength(adapterArms.length === 0 ? 0 : 2)),\n abortInjections: Schema.Array(\n Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 15 })),\n ).check(Schema.isUnique(), Schema.isMaxLength(2)),\n resolutionInjections: Schema.Array(ChaosResolutionKind).check(Schema.isMaxLength(4)),\n approvalDecisions: Schema.Array(ChaosApprovalDecision).check(Schema.isMaxLength(2)),\n }),\n ).pipe(\n Arbitrary.map((shape) => {\n const submissions = shape.lanes.flatMap((lane, index) =>\n Array.from({ length: lane.depth }, () =>\n ChaosSubmissionSpec.make({ lane: index, kind: lane.kind }),\n ),\n );\n\n const [first, ...rest] = submissions;\n\n // `lanes` >= 1 and every lane has depth >= 1, so `first` always exists.\n if (first === undefined) throw new Error(\"chaos generator produced an empty plan\");\n\n return {\n lanes: shape.lanes.length,\n submissions: [first, ...rest] as const,\n failpointArms: shape.failpointArms,\n adapterArms: shape.adapterArms,\n abortInjections: shape.abortInjections,\n resolutionInjections: shape.resolutionInjections,\n approvalDecisions: shape.approvalDecisions,\n };\n }),\n );\n\n/**\n * Derive `count` chaos plans deterministically from one root seed. The same\n * `{seed, count, adapterArms}` triple always yields byte-identical plans, so a failure line\n * `CHAOS_SEED=<seed>` replays the exact schedule with the same pinned generator version.\n * Sampling is interruptible and reports bounded generation exhaustion as Arbitrary.SampleError.\n */\nexport const generateChaosPlans = Effect.fnUntraced(function* (\n options: ChaosGeneratorOptions,\n): Effect.fn.Return<ReadonlyArray<ChaosPlan>, Arbitrary.SampleError> {\n const sampled = yield* Arbitrary.sampleEffect(planShapeArbitrary(options.adapterArms ?? []), {\n seed: options.seed,\n count: options.count,\n });\n\n return sampled.map((shape, index) =>\n ChaosPlan.make({ ...shape, seed: (Math.imul(options.seed, 31) + index) | 0 }),\n );\n});\n\n/** Deterministic PRNG for the runner's small ordering choices (lane drive order). */\nconst mulberry32 = (seed: number): (() => number) => {\n let state = seed | 0;\n\n return () => {\n state = (state + 0x6d2b79f5) | 0;\n let t = Math.imul(state ^ (state >>> 15), 1 | state);\n\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n};\n\n// ---------------------------------------------------------------------------\n// Lane fixtures (agents, scripted models, deterministic desk)\n// ---------------------------------------------------------------------------\n\nconst usage = { inputTokens: {}, outputTokens: {} };\n\nconst finalParts = (text: string): ReadonlyArray<Response.StreamPartEncoded> => [\n { type: \"text-start\", id: \"answer\" },\n { type: \"text-delta\", id: \"answer\", delta: text },\n { type: \"text-end\", id: \"answer\" },\n { type: \"finish\", reason: \"stop\", usage },\n];\n\nconst toolTurn = (\n ...calls: ReadonlyArray<Response.StreamPartEncoded>\n): ReadonlyArray<Response.StreamPartEncoded> => [\n ...calls,\n { type: \"finish\", reason: \"tool-calls\", usage },\n];\n\nconst toolCallPart = (id: string, name: string, params: unknown): Response.StreamPartEncoded => ({\n type: \"tool-call\",\n id,\n name,\n params,\n providerExecuted: false,\n});\n\n/**\n * Prompt-shaped scripted model: the response depends ONLY on the request prompt, so it stays\n * deterministic across Attempt re-invocations, batch resumes, and joined steering — no counter\n * to drift when chaos re-enters a Turn.\n */\nconst promptScriptedModel = (\n label: string,\n script: (prompt: Prompt.Prompt) => ReadonlyArray<Response.StreamPartEncoded>,\n) =>\n Model.make(\n \"scripted\",\n label,\n Layer.effect(\n LanguageModel.LanguageModel,\n LanguageModel.make({\n generateText: () => Effect.succeed([]),\n streamText: (request) => Stream.fromIterable(script(request.prompt)),\n }),\n ),\n );\n\nconst lastRole = (prompt: Prompt.Prompt): string | undefined => prompt.content.at(-1)?.role;\n\nconst policy = AgentPolicy.make({\n maxTurns: 3,\n maxToolCalls: 4,\n maxDuration: \"30 seconds\",\n toolConcurrency: 2,\n});\n\nconst PlainInput = Schema.Struct({ question: Schema.String });\nconst PlainOutput = Schema.Struct({ answer: Schema.String });\n\nconst plainDefinition = Agent.make(\"chaos-plain\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Answer as JSON.\",\n toolkit: Toolkit.empty,\n policy,\n});\n\n/** Unannotated → fail-closed `uncertain`: enters the prepared/settled protocol (DUR-009). */\nconst BookUncertain = Tool.make(\"book\", {\n parameters: Schema.Struct({ ref: Schema.String }),\n success: Schema.Struct({ confirmation: Schema.String }),\n});\n\nconst bookTools = Toolkit.make(BookUncertain);\n\nconst bookDefinition = Agent.make(\"chaos-book\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Book it.\",\n toolkit: bookTools,\n policy,\n});\n\nconst BookApproval = Tool.make(\"book\", {\n parameters: Schema.Struct({ ref: Schema.String }),\n success: Schema.Struct({ confirmation: Schema.String }),\n needsApproval: true,\n});\n\nconst approvalTools = Toolkit.make(BookApproval);\n\nconst approvalDefinition = Agent.make(\"chaos-approval\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Book after approval.\",\n toolkit: approvalTools,\n policy,\n});\n\nconst Itinerary = Tool.make(\"itinerary\", {\n parameters: Schema.Struct({ ref: Schema.String }),\n success: Schema.Struct({ state: Schema.String }),\n failure: DurableStepError,\n dependencies: [DurableStep],\n}).annotate(ToolExecutionClass, \"uncertain\");\n\nconst itineraryTools = Toolkit.make(Itinerary);\n\nconst itineraryDefinition = Agent.make(\"chaos-itinerary\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Reserve the itinerary.\",\n toolkit: itineraryTools,\n policy,\n});\n\nconst childDefinition = Agent.make(\"chaos-child\", {\n input: PlainInput,\n output: PlainOutput,\n instructions: \"Answer as JSON.\",\n toolkit: Toolkit.empty,\n policy: AgentPolicy.make({\n maxTurns: 2,\n maxToolCalls: 1,\n maxDuration: \"30 seconds\",\n toolConcurrency: 1,\n }),\n});\n\nclass ChaosDelegationFailed extends Schema.TaggedError<ChaosDelegationFailed>()(\n \"ChaosDelegationFailed\",\n { childErrorTag: Schema.String },\n) {}\n\nconst chaosDelegation = Subagent.define(\"delegate_chaos\", {\n description: \"Delegate one bounded chaos question.\",\n target: childDefinition,\n parameters: Schema.Struct({ topic: Schema.String }),\n success: Schema.Struct({ summary: Schema.String }),\n failure: ChaosDelegationFailed,\n prepareInput: ({ topic }) => Effect.succeed({ question: `chaos:${topic}` }),\n projectResult: (output) => Effect.succeed({ summary: `finding:${output.answer}` }),\n policy: SubagentPolicy.make({\n maxChildren: 2,\n maxConcurrency: 2,\n maxTurns: 4,\n maxToolCalls: 4,\n maxDuration: \"30 seconds\",\n }),\n});\n\nconst coordinatorDefinition = Agent.make(\"chaos-coordinator\", {\n input: Schema.Struct({ mission: Schema.String }),\n output: Schema.Struct({ report: Schema.String }),\n instructions: \"Delegate, then report as JSON.\",\n toolkit: Toolkit.make(chaosDelegation.tool),\n policy,\n});\n\nconst DELEGATE_CALL_ID = \"chaos-delegate-1\";\n\nconst HEX = \"0123456789abcdef\";\nconst decodeDigest = Schema.decodeSync(Digest);\n\nconst laneDigests = (lane: number): DefinitionDigests => {\n const digest = decodeDigest(HEX.charAt(lane % 8).repeat(64));\n\n return DefinitionDigests.make({ agent: digest, model: digest, tools: digest });\n};\n\nconst childDigestStrings = (lane: number) => {\n const char = HEX.charAt(8 + (lane % 8));\n\n return { agent: char.repeat(64), model: char.repeat(64), tools: char.repeat(64) } as const;\n};\n\nconst childLaneDigests = (lane: number): DefinitionDigests => {\n const strings = childDigestStrings(lane);\n\n return DefinitionDigests.make({\n agent: decodeDigest(strings.agent),\n model: decodeDigest(strings.model),\n tools: decodeDigest(strings.tools),\n });\n};\n\nconst CHAOS_PRINCIPAL = Schema.decodeSync(Principal)(\"principal-chaos\");\nconst decodeThreadId = Schema.decodeSync(ThreadId);\nconst decodeIdempotencyKey = Schema.decodeSync(IdempotencyKey);\nconst decodeToolCallId = Schema.decodeSync(ToolCallId);\nconst decodeRunId = Schema.decodeSync(RunId);\nconst decodeTurnId = Schema.decodeSync(TurnId);\n\n/** Fixture-only identity source consumed by the delegation Layer's ephemeral capture. */\nconst chaosIdentifiers = Layer.effect(\n IdGenerator,\n Effect.gen(function* () {\n const counter = yield* Ref.make(0);\n\n const next = <A>(decode: (value: string) => A, prefix: string) =>\n Ref.getAndUpdate(counter, (value) => value + 1).pipe(\n Effect.map((value) => decode(`${prefix}-${value}`)),\n );\n\n return {\n nextThreadId: next(decodeThreadId, \"chaos-fixture-thread\"),\n nextRunId: next(decodeRunId, \"chaos-fixture-run\"),\n nextTurnId: next(decodeTurnId, \"chaos-fixture-turn\"),\n };\n }),\n);\n\nconst delegationSupport = Layer.mergeAll(SubagentReservationsMemoryLive, chaosIdentifiers);\n\n/**\n * The deterministic external desk of one plan: every produced value is recorded so the final\n * non-fabrication sweep can prove each canonical Tool success came from here (durability §10).\n */\ninterface ChaosDesk {\n readonly produced: Effect.Effect<ReadonlySet<string>>;\n readonly record: (value: string) => Effect.Effect<void>;\n}\n\nconst makeChaosDesk: Effect.Effect<ChaosDesk> = Effect.gen(function* () {\n const produced = yield* Ref.make<ReadonlySet<string>>(new Set());\n\n return {\n produced: Ref.get(produced),\n record: (value: string) => Ref.update(produced, (current) => new Set(current).add(value)),\n };\n});\n\nconst bookConfirmation = (ref: string): string => `confirmed-${ref}`;\nconst flightValue = (ref: string): string => `flight-${ref}`;\nconst lodgingValue = (ref: string): string => `lodging-${ref}`;\n\n// ---------------------------------------------------------------------------\n// Runner\n// ---------------------------------------------------------------------------\n\n/** Adapter-owned failpoint control the SQLite runner supplies; memory has none. */\nexport interface ChaosAdapterFailpoints {\n readonly arm: (location: string) => Effect.Effect<void>;\n readonly clear: Effect.Effect<void>;\n}\n\nexport interface ChaosRunOptions {\n readonly adapterFailpoints?: ChaosAdapterFailpoints | undefined;\n /**\n * Executed at the end of every round. Adapters whose ownership leases block every new claim\n * until expiry (the SQLite ledger's D5 semantics — expiry only revokes the liveness\n * assumption; producer epochs stay the correctness fence) pass a deterministic\n * `TestClock.adjust` here so a dead Attempt's lane becomes reclaimable next round. The memory\n * ledger needs nothing: it allows same-producer reclaim under a live lease.\n */\n readonly betweenRounds?: Effect.Effect<void> | undefined;\n}\n\n/** Tolerate typed failures while preserving every defect and interruption reason. */\nconst tolerateTyped = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<Option.Option<A>, never, R> =>\n effect.pipe(\n Effect.exit,\n Effect.flatMap((exit) => {\n if (Exit.isSuccess(exit)) return Effect.succeed(Option.some(exit.value));\n const unexpected = exit.cause.reasons.filter((reason) => reason._tag !== \"Fail\");\n\n return unexpected.length === 0\n ? Effect.succeed(Option.none<A>())\n : Effect.failCause(Cause.fromReasons<never>(unexpected));\n }),\n );\n\ninterface LaneFixture {\n readonly index: number;\n readonly kind: ChaosScenarioKind;\n readonly threadId: ThreadId;\n readonly ref: string;\n readonly deskInPlay: boolean;\n readonly submissionIndexes: ReadonlyArray<number>;\n readonly submitOne: (flatIndex: number) => Effect.Effect<Receipt, DurableSubmitFailure>;\n readonly drives: (\n firstReceipt: Receipt | undefined,\n ) => ReadonlyArray<\n Effect.Effect<ReadonlyArray<Settlement>, DurableWorkerFailure | DurableBindingFailure>\n >;\n readonly childThreadOf: (firstReceipt: Receipt) => ThreadId | undefined;\n}\n\ninterface SubmissionState {\n readonly flatIndex: number;\n readonly lane: LaneFixture;\n receipt: Receipt | undefined;\n}\n\nconst scriptFor = (\n kind: ChaosScenarioKind,\n ref: string,\n): ((prompt: Prompt.Prompt) => ReadonlyArray<Response.StreamPartEncoded>) => {\n switch (kind) {\n case \"plain\":\n case \"join\":\n return () => finalParts('{\"answer\":\"chaos\"}');\n case \"uncertain-tool\":\n case \"approval\":\n return (prompt) =>\n lastRole(prompt) === \"tool\"\n ? finalParts('{\"answer\":\"booked\"}')\n : toolTurn(toolCallPart(`book-${ref}`, \"book\", { ref }));\n case \"durable-steps\":\n return (prompt) =>\n lastRole(prompt) === \"tool\"\n ? finalParts('{\"answer\":\"reserved\"}')\n : toolTurn(toolCallPart(`itinerary-${ref}`, \"itinerary\", { ref }));\n case \"delegation\":\n return (prompt) =>\n lastRole(prompt) === \"tool\"\n ? finalParts('{\"report\":\"done\"}')\n : toolTurn(toolCallPart(DELEGATE_CALL_ID, \"delegate_chaos\", { topic: ref }));\n }\n};\n\nconst makeLaneFixture = Effect.fn(\"Chaos.makeLaneFixture\")(function* (\n plan: ChaosPlan,\n laneIndex: number,\n kind: ChaosScenarioKind,\n submissionIndexes: ReadonlyArray<number>,\n desk: ChaosDesk,\n) {\n const runtime = yield* DurableAgentRuntime;\n const threadId = decodeThreadId(`chaos-${plan.seed}-lane-${laneIndex}`);\n const ref = `ref-l${laneIndex}`;\n const script = scriptFor(kind, ref);\n const model = promptScriptedModel(`chaos-${kind}-${laneIndex}`, script);\n const digests = laneDigests(laneIndex);\n\n const submitOptionsFor = (flatIndex: number) => ({\n threadId,\n principal: CHAOS_PRINCIPAL,\n idempotencyKey: decodeIdempotencyKey(`chaos-${plan.seed}-s${flatIndex}`),\n definitions: digests,\n });\n\n const bookToolLayerFor = (tools: typeof bookTools | typeof approvalTools) =>\n tools.toLayer({\n book: ({ ref: called }) =>\n desk\n .record(bookConfirmation(called))\n .pipe(Effect.as({ confirmation: bookConfirmation(called) })),\n });\n\n const plainLaneFixture = (\n deskInPlay: boolean,\n drive: Effect.Effect<ReadonlyArray<Settlement>, DurableWorkerFailure | DurableBindingFailure>,\n submitOne: (flatIndex: number) => Effect.Effect<Receipt, DurableSubmitFailure>,\n ): LaneFixture => ({\n index: laneIndex,\n kind,\n threadId,\n ref,\n deskInPlay,\n submissionIndexes,\n submitOne,\n drives: () => [drive],\n childThreadOf: () => undefined,\n });\n\n switch (kind) {\n case \"plain\":\n case \"join\": {\n const agent = Agent.withModel(plainDefinition, model);\n\n return plainLaneFixture(false, runtime.processThread(agent, threadId), (flatIndex) =>\n runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)),\n );\n }\n case \"uncertain-tool\": {\n const agent = Agent.withModel(bookDefinition, model);\n\n return plainLaneFixture(\n true,\n runtime.processThread(agent, threadId).pipe(Effect.provide(bookToolLayerFor(bookTools))),\n (flatIndex) =>\n runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)),\n );\n }\n case \"approval\": {\n const agent = Agent.withModel(approvalDefinition, model);\n\n return plainLaneFixture(\n true,\n runtime\n .processThread(agent, threadId)\n .pipe(Effect.provide(bookToolLayerFor(approvalTools))),\n (flatIndex) =>\n runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)),\n );\n }\n case \"durable-steps\": {\n const agent = Agent.withModel(itineraryDefinition, model);\n\n const toolLayer = itineraryTools.toLayer({\n itinerary: ({ ref: called }) =>\n Effect.gen(function* () {\n const step = yield* DurableStep;\n\n const flight = yield* step.do(\n \"reserve-flight\",\n Schema.String,\n desk.record(flightValue(called)).pipe(Effect.as(flightValue(called))),\n );\n\n const lodging = yield* step.do(\n \"reserve-lodging\",\n Schema.String,\n desk.record(lodgingValue(called)).pipe(Effect.as(lodgingValue(called))),\n );\n\n return { state: `${flight}+${lodging}` };\n }),\n });\n\n return plainLaneFixture(\n true,\n runtime.processThread(agent, threadId).pipe(Effect.provide(toolLayer)),\n (flatIndex) =>\n runtime.submit(agent, { question: `chaos ${flatIndex}` }, submitOptionsFor(flatIndex)),\n );\n }\n case \"delegation\": {\n const parentBinding = Agent.withModel(coordinatorDefinition, model);\n\n const childModel = promptScriptedModel(`chaos-child-${laneIndex}`, () =>\n finalParts('{\"answer\":\"child\"}'),\n );\n\n const childBinding = Agent.withModel(childDefinition, childModel);\n\n const delegationLayer = Subagent.layer(chaosDelegation, childBinding, {\n mapChildFailure: (failure) => ChaosDelegationFailed.make({ childErrorTag: failure._tag }),\n durable: { targetDigests: childDigestStrings(laneIndex) },\n }).pipe(Layer.provide(delegationSupport));\n\n const parentResolved: ResolvedBinding = yield* DurableWorkerBinding.make(\n parentBinding,\n digests,\n ).pipe(Effect.provide(delegationLayer));\n\n const childResolved: ResolvedBinding = yield* DurableWorkerBinding.make(\n childBinding,\n childLaneDigests(laneIndex),\n );\n\n const registeredRuntime = yield* DurableAgentRuntime.pipe(\n Effect.provide(\n DurableAgentRuntime.layerWithBindings([parentResolved, childResolved]).pipe(\n Layer.provide(RunToolAuthorization.allowAll),\n ),\n ),\n );\n\n const driveResolved = (thread: ThreadId) => registeredRuntime.processThreadResolved(thread);\n\n const fixture: LaneFixture = {\n index: laneIndex,\n kind,\n threadId,\n ref,\n deskInPlay: false,\n submissionIndexes,\n submitOne: (flatIndex) =>\n runtime.submit(\n { definition: { id: coordinatorDefinition.id, input: coordinatorDefinition.input } },\n { mission: `chaos ${flatIndex}` },\n submitOptionsFor(flatIndex),\n ),\n drives: (firstReceipt) => {\n const drives: Array<\n Effect.Effect<ReadonlyArray<Settlement>, DurableWorkerFailure | DurableBindingFailure>\n > = [driveResolved(threadId)];\n\n if (firstReceipt !== undefined) {\n drives.push(\n driveResolved(\n childThreadIdFor(firstReceipt.submissionId, decodeToolCallId(DELEGATE_CALL_ID)),\n ),\n );\n }\n\n return drives;\n },\n childThreadOf: (firstReceipt) =>\n childThreadIdFor(firstReceipt.submissionId, decodeToolCallId(DELEGATE_CALL_ID)),\n };\n\n return fixture;\n }\n }\n});\n\n/** Stable per-call index into an injection list (identical across resolution passes). */\nconst injectionIndex = (submissionFlatIndex: number, callId: string, length: number): number => {\n let hash = submissionFlatIndex + 1;\n\n for (const char of callId) hash = (Math.imul(hash, 31) + char.charCodeAt(0)) | 0;\n\n return ((hash % length) + length) % length;\n};\n\nconst resolutionFor = (\n kind: ChaosResolutionKind,\n toolName: string,\n ref: string,\n produced: ReadonlySet<string>,\n): UnknownResolution => {\n switch (kind) {\n case \"abort-submission\":\n return ResolutionAbortSubmission.make();\n case \"completed-from-supplier\": {\n if (toolName === \"book\" && produced.has(bookConfirmation(ref))) {\n return ResolutionCompletedWithResult.make({\n result: { confirmation: bookConfirmation(ref) },\n isFailure: false,\n });\n }\n if (\n toolName === \"itinerary\" &&\n produced.has(flightValue(ref)) &&\n produced.has(lodgingValue(ref))\n ) {\n return ResolutionCompletedWithResult.make({\n result: { state: `${flightValue(ref)}+${lodgingValue(ref)}` },\n isFailure: false,\n });\n }\n\n // The desk never produced a value for this call — resolving \"completed\" would fabricate.\n return ResolutionNeverHappened.make();\n }\n case \"never-happened\":\n return ResolutionNeverHappened.make();\n }\n};\n\n/** Drive one DUR-017 pass: resolve Unknown Outcomes and pending approvals from the plan. */\nconst resolutionPass = Effect.fn(\"Chaos.resolutionPass\")(function* (\n plan: ChaosPlan,\n states: ReadonlyArray<SubmissionState>,\n desk: ChaosDesk,\n) {\n const runtime = yield* DurableAgentRuntime;\n const ledger = yield* SubmissionLedger;\n const produced = yield* desk.produced;\n const nonterminal = yield* tolerateTyped(Stream.runCollect(ledger.scanNonterminal));\n\n if (Option.isNone(nonterminal)) return;\n const byId = new Map<SubmissionId, SubmissionState>();\n\n for (const state of states) {\n if (state.receipt !== undefined) byId.set(state.receipt.submissionId, state);\n }\n for (const row of nonterminal.value) {\n if (row.state !== \"unknown\" && row.state !== \"suspended\") continue;\n const state = byId.get(row.submissionId);\n const explanation = yield* tolerateTyped(runtime.explain(row.submissionId));\n\n if (Option.isNone(explanation)) continue;\n const flatIndex = state?.flatIndex ?? 0;\n const ref = state?.lane.ref ?? \"ref-child\";\n\n if (row.state === \"unknown\") {\n for (const call of explanation.value.evidence.unknownCalls) {\n if (call.resolved) continue;\n\n const kind =\n plan.resolutionInjections.length === 0\n ? \"never-happened\"\n : (plan.resolutionInjections.at(\n injectionIndex(flatIndex, call.toolCallId, plan.resolutionInjections.length),\n ) ?? \"never-happened\");\n\n yield* tolerateTyped(\n runtime.resolveUnknown(\n UnknownResolutionCommand.make({\n submissionId: row.submissionId,\n toolCallId: call.toolCallId,\n author: \"chaos-runner\",\n reason: `chaos plan ${plan.seed} resolution (${kind})`,\n resolution: resolutionFor(kind, call.toolName, ref, produced),\n }),\n ),\n );\n }\n } else {\n for (const pending of explanation.value.evidence.approvalsPending) {\n const decision =\n plan.approvalDecisions.length === 0\n ? \"approved\"\n : (plan.approvalDecisions.at(\n injectionIndex(flatIndex, pending.toolCallId, plan.approvalDecisions.length),\n ) ?? \"approved\");\n\n yield* tolerateTyped(\n runtime.resolveApproval(\n ApprovalDecisionCommand.make({\n submissionId: row.submissionId,\n toolCallId: pending.toolCallId,\n decision,\n resolver: \"chaos-runner\",\n reason: `chaos plan ${plan.seed} approval (${decision})`,\n }),\n ),\n );\n }\n }\n }\n});\n\nconst submissionIdsNamedBy = (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n): ReadonlySet<SubmissionId> => {\n const named = new Set<SubmissionId>();\n\n for (const envelope of records) {\n const payload = envelope.record.payload;\n\n if (\n payload._tag === \"UserInputRecorded\" ||\n payload._tag === \"SubmissionSettled\" ||\n payload._tag === \"AbortRequested\"\n ) {\n if (payload.submissionId !== undefined) named.add(payload.submissionId);\n }\n }\n\n return named;\n};\n\n/**\n * The final non-fabrication sweep (durability §10): every canonical Tool success recorded on a\n * desk-backed lane must be a value the desk actually produced.\n */\nconst BookResult = Schema.Struct({ confirmation: Schema.String });\nconst ItineraryResult = Schema.Struct({ state: Schema.String });\nconst decodeBookResult = Schema.decodeUnknownOption(BookResult);\nconst decodeItineraryResult = Schema.decodeUnknownOption(ItineraryResult);\nconst decodeStepOutput = Schema.decodeUnknownOption(Schema.String);\n\nconst assertNoFabrication = (\n plan: ChaosPlan,\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n produced: ReadonlySet<string>,\n): Effect.Effect<void, ChaosConvergenceFailure> => {\n const fabricated: Array<string> = [];\n\n const requireProduced = (value: string, label: string): void => {\n if (!produced.has(value)) fabricated.push(`${label} \"${value}\"`);\n };\n\n for (const envelope of records) {\n const payload = envelope.record.payload;\n\n if (payload._tag === \"ToolCallSettled\" && !payload.isFailure) {\n if (payload.toolName === \"book\") {\n const result = decodeBookResult(payload.result);\n\n if (Option.isSome(result)) requireProduced(result.value.confirmation, \"book result\");\n }\n if (payload.toolName === \"itinerary\") {\n const result = decodeItineraryResult(payload.result);\n\n if (Option.isSome(result)) {\n for (const part of result.value.state.split(\"+\")) {\n requireProduced(part, \"itinerary step result\");\n }\n }\n }\n }\n if (payload._tag === \"ToolStepSettled\") {\n const output = decodeStepOutput(payload.output);\n\n if (Option.isSome(output)) requireProduced(output.value, \"step output\");\n }\n }\n\n return fabricated.length === 0\n ? Effect.void\n : Effect.fail(\n ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `fabricated Tool results absent from the desk: ${fabricated.join(\", \")}`,\n }),\n );\n};\n\n/**\n * Execute one chaos plan against whatever adapters the ambient Layer provides and end in the\n * shared invariant claims. Deterministic: same plan + same adapters → same schedule.\n */\nexport const runChaosPlan = Effect.fn(\"Chaos.runChaosPlan\")(function* (\n plan: ChaosPlan,\n options?: ChaosRunOptions,\n) {\n const runtime = yield* DurableAgentRuntime;\n const ledger = yield* SubmissionLedger;\n const store = yield* ThreadStore;\n const config = yield* DurableRuntimeConfig;\n const failpoints = yield* DurableRuntimeFailpointTestControl;\n const random = mulberry32(plan.seed);\n const desk = yield* makeChaosDesk;\n\n // Lane fixtures: the FIRST spec of each lane fixes the lane's agent kind.\n const laneKinds = new Map<number, ChaosScenarioKind>();\n const laneSubmissions = new Map<number, Array<number>>();\n\n plan.submissions.forEach((spec, flatIndex) => {\n const lane = spec.lane % plan.lanes;\n\n if (!laneKinds.has(lane)) laneKinds.set(lane, spec.kind);\n const list = laneSubmissions.get(lane) ?? [];\n\n list.push(flatIndex);\n laneSubmissions.set(lane, list);\n });\n const lanes: Array<LaneFixture> = [];\n\n for (const [lane, kind] of laneKinds) {\n lanes.push(yield* makeLaneFixture(plan, lane, kind, laneSubmissions.get(lane) ?? [], desk));\n }\n\n const lanesByIndex = new Map(lanes.map((lane) => [lane.index, lane]));\n const states: Array<SubmissionState> = [];\n\n for (const [flatIndex, spec] of plan.submissions.entries()) {\n const laneIndex = spec.lane % plan.lanes;\n const lane = lanesByIndex.get(laneIndex);\n\n if (lane === undefined) {\n return yield* ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `submission ${flatIndex} addresses missing lane ${laneIndex}`,\n });\n }\n states.push({ flatIndex, lane, receipt: undefined });\n }\n const appliedAborts = new Set<number>();\n\n type ArmEntry =\n | { readonly family: \"coordinator\"; readonly location: DurableRuntimeFailpointLocation }\n | { readonly family: \"adapter\"; readonly location: string };\n\n const armQueue: Array<ArmEntry> = [\n ...plan.failpointArms.map((location): ArmEntry => ({ family: \"coordinator\", location })),\n ...plan.adapterArms.map((location): ArmEntry => ({ family: \"adapter\", location })),\n ];\n\n const allSettled = Effect.gen(function* () {\n if (states.some((state) => state.receipt === undefined)) return false;\n const nonterminal = yield* tolerateTyped(Stream.runCollect(ledger.scanNonterminal));\n\n return Option.isSome(nonterminal) && Array.from(nonterminal.value).length === 0;\n });\n\n const maxRounds = armQueue.length + states.length * 2 + 12;\n let rounds = 0;\n let converged = false;\n\n for (let round = 0; round < maxRounds; round++) {\n rounds = round + 1;\n const arm = armQueue[round];\n\n if (arm?.family === \"coordinator\") {\n const location = arm.location;\n\n yield* failpoints.setHandler((hit) =>\n hit === location\n ? Effect.fail(DurableRuntimeFailpointError.make({ location: hit }))\n : Effect.void,\n );\n } else if (arm?.family === \"adapter\" && options?.adapterFailpoints !== undefined) {\n yield* options.adapterFailpoints.arm(arm.location);\n }\n\n // Admission chaos: pending submissions retry under the active arm until a Receipt lands;\n // the identical (thread, principal, key) triple reattaches, never duplicates.\n for (const state of states) {\n if (state.receipt !== undefined) continue;\n const receipt = yield* tolerateTyped(state.lane.submitOne(state.flatIndex));\n\n if (Option.isSome(receipt)) state.receipt = receipt.value;\n }\n\n // Drive every lane (and discovered child lanes) in seeded order under the active arm.\n const order = lanes\n .map((lane) => ({ lane, rank: random() }))\n .sort((left, right) => left.rank - right.rank || left.lane.index - right.lane.index)\n .map(({ lane }) => lane);\n\n for (const lane of order) {\n const firstFlat = lane.submissionIndexes[0];\n const firstReceipt = firstFlat === undefined ? undefined : states[firstFlat]?.receipt;\n\n for (const drive of lane.drives(firstReceipt)) {\n yield* tolerateTyped(drive);\n }\n }\n\n // Abort injections fire once, while arms may still be active (abort:after-intent etc.).\n if (round >= 1) {\n for (const rawIndex of plan.abortInjections) {\n const index = rawIndex % states.length;\n\n if (appliedAborts.has(index)) continue;\n const receipt = states[index]?.receipt;\n\n if (receipt === undefined) continue;\n appliedAborts.add(index);\n yield* tolerateTyped(\n runtime.abort(\n AbortCommand.make({\n submissionId: receipt.submissionId,\n author: \"chaos-runner\",\n reason: `chaos plan ${plan.seed} abort injection`,\n }),\n ),\n );\n }\n }\n\n // First resolution pass runs under the arm so resolve:* locations can fire.\n yield* resolutionPass(plan, states, desk);\n\n yield* failpoints.clear;\n if (options?.adapterFailpoints !== undefined) yield* options.adapterFailpoints.clear;\n\n yield* tolerateTyped(runtime.runRecovery);\n // Second, unarmed pass guarantees forward progress for newly marked Unknown lanes.\n yield* resolutionPass(plan, states, desk);\n\n if (yield* allSettled) {\n converged = true;\n break;\n }\n if (options?.betweenRounds !== undefined) yield* options.betweenRounds;\n }\n\n if (!converged) {\n const nonterminal = yield* tolerateTyped(Stream.runCollect(ledger.scanNonterminal));\n\n const detail = Option.isSome(nonterminal)\n ? Array.from(nonterminal.value)\n .map((row: SubmissionSnapshot) => `${row.submissionId}(${row.state})`)\n .join(\", \")\n : \"ledger scan failed\";\n\n return yield* ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `plan did not converge within ${maxRounds} rounds; nonterminal: [${detail}]; pending receipts: ${states.filter((state) => state.receipt === undefined).length}`,\n });\n }\n\n // Final claims: the shared invariant checker per touched Thread, in convergence mode,\n // with the full digest chain (single known producer), plus the desk non-fabrication sweep.\n const produced = yield* desk.produced;\n const laneReports: Array<ChaosLaneReport> = [];\n\n const verifyThread = Effect.fn(\"Chaos.verifyThread\")(function* (\n threadId: ThreadId,\n kind: ChaosScenarioKind,\n deskInPlay: boolean,\n ) {\n const exported = yield* store.export(ThreadExportRequest.make({ threadId })).pipe(\n Effect.mapError((error) =>\n ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `export of ${threadId} failed: ${String(error)}`,\n }),\n ),\n );\n\n const rows: Array<SubmissionSnapshot> = [];\n\n for (const submissionId of submissionIdsNamedBy(exported.records)) {\n const found = yield* ledger.lookup(SubmissionLookupById.make({ submissionId })).pipe(\n Effect.mapError((error) =>\n ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `lookup of ${submissionId} failed: ${String(error)}`,\n }),\n ),\n );\n\n if (Option.isSome(found)) rows.push(found.value);\n }\n\n const batchProducers = new Map<BatchId, ProducerId>(\n exported.records.map((envelope) => [envelope.batchId, config.producerId]),\n );\n\n const report = yield* verifyThreadInvariants({\n export: exported,\n submissions: rows,\n batchProducers,\n requireAllSettled: true,\n });\n\n if (!report.ok) {\n const failed = report.checks\n .filter((check) => check.status === \"failed\")\n .map((check) => `${check.name}: ${check.detail ?? \"failed\"}`)\n .join(\"; \");\n\n return yield* ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `invariants failed for ${threadId} (${kind}): ${failed}`,\n });\n }\n if (deskInPlay) {\n yield* assertNoFabrication(plan, exported.records, produced);\n }\n laneReports.push(\n ChaosLaneReport.make({\n threadId,\n kind,\n submissionCount: rows.length,\n verified: report.ok,\n }),\n );\n });\n\n for (const lane of lanes) {\n yield* verifyThread(lane.threadId, lane.kind, lane.deskInPlay);\n // Delegation lanes: verify every materialized child Thread too.\n for (const flatIndex of lane.submissionIndexes) {\n const receipt = states[flatIndex]?.receipt;\n\n if (receipt === undefined) continue;\n const child = lane.childThreadOf(receipt);\n\n if (child === undefined) continue;\n\n const childExport = yield* Effect.exit(\n store.export(ThreadExportRequest.make({ threadId: child })),\n );\n\n if (Exit.isSuccess(childExport) && childExport.value.records.length > 0) {\n yield* verifyThread(child, \"plain\", false);\n }\n }\n }\n\n const obligations = yield* runtime\n .scanObligations(ObligationThresholds.make({ agingSeconds: 0, overdueSeconds: 0 }))\n .pipe(\n Effect.mapError((error) =>\n ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `scanObligations failed: ${String(error)}`,\n }),\n ),\n );\n\n if (obligations.entries.length > 0) {\n return yield* ChaosConvergenceFailure.make({\n seed: plan.seed,\n message: `open obligations after convergence: ${obligations.entries\n .map((entry) => `${entry.submissionId}(${entry.blockedOn})`)\n .join(\", \")}`,\n });\n }\n\n return ChaosPlanReport.make({\n seed: plan.seed,\n rounds,\n lanes: laneReports,\n openObligations: obligations.entries.length,\n });\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqFA,MAAa,oBAAoB,OAAO,SAAS;CAC/C;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAID,MAAM,YAAY,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,GAAG,OAAO,oBAAoB,CAAC,CAAC;;AAGlG,IAAa,sBAAb,cAAyC,OAAO,MAC9C,2CACF,CAAC,CAAC;CACA,MAAM;;C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ACH,CACF;CAEF,IAAI,YAAY,QAAQ,SAAS,GAC/B,OAAO,OAAO,wBAAwB,KAAK;EACzC,MAAM,KAAK;EACX,SAAS,uCAAuC,YAAY,QACzD,KAAK,UAAU,GAAG,MAAM,aAAa,GAAG,MAAM,UAAU,EAAE,CAAC,CAC3D,KAAK,IAAI;CACd,CAAC;CAGH,OAAO,gBAAgB,KAAK;EAC1B,MAAM,KAAK;EACX;EACA,OAAO;EACP,iBAAiB,YAAY,QAAQ;CACvC,CAAC;AACH,CAAC"}
@@ -9,16 +9,16 @@ declare namespace ScriptedModel_d_exports {
9
9
  * Generic Tool payloads remain explicitly unknown here. `LanguageModel.make`
10
10
  * performs the toolkit-specific decode when the scripted response is consumed.
11
11
  */
12
- declare const ScriptedGeneratePart: Schema.Union<readonly [Schema.toEncoded<Schema.Codec<Response.Part<{}, false>, Response.PartEncoded, never, never>>, Schema.toEncoded<Schema.Struct<{
12
+ declare const ScriptedGeneratePart: Schema.Union<readonly [Schema.toEncoded<Schema.Codec<Response.Part<{}, "decoded">, Response.PartEncoded, never, never>>, Schema.toEncoded<Schema.Struct<{
13
13
  readonly type: Schema.tag<"reasoning-delta">;
14
14
  readonly id: Schema.String;
15
15
  readonly delta: Schema.String;
16
- readonly "~effect/ai/Content/Part": Schema.withDecodingDefaultKey<Schema.tag<"~effect/ai/Content/Part">>;
16
+ readonly "~effect/ai/Response/Part": Schema.withDecodingDefaultKey<Schema.tag<"~effect/ai/Response/Part">>;
17
17
  readonly metadata: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.Codec<Schema.Json>>>;
18
18
  }>>, Schema.toEncoded<Schema.Struct<{
19
19
  readonly type: Schema.tag<"reasoning-end">;
20
20
  readonly id: Schema.String;
21
- readonly "~effect/ai/Content/Part": Schema.withDecodingDefaultKey<Schema.tag<"~effect/ai/Content/Part">>;
21
+ readonly "~effect/ai/Response/Part": Schema.withDecodingDefaultKey<Schema.tag<"~effect/ai/Response/Part">>;
22
22
  readonly metadata: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.Codec<Schema.Json>>>;
23
23
  }>>, Schema.Struct<{
24
24
  readonly metadata: Schema.optionalKey<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json, Schema.Json, never, never>>>>;
@@ -41,7 +41,7 @@ type ScriptedGeneratePart = typeof ScriptedGeneratePart.Type;
41
41
  /**
42
42
  * Schema for encoded Effect AI streaming response parts.
43
43
  */
44
- declare const ScriptedStreamPart: Schema.Union<readonly [Schema.toEncoded<Schema.Codec<Response.StreamPart<{}, false>, Response.StreamPartEncoded, never, never>>, Schema.Struct<{
44
+ declare const ScriptedStreamPart: Schema.Union<readonly [Schema.toEncoded<Schema.Codec<Response.StreamPart<{}, "decoded">, Response.StreamPartEncoded, never, never>>, Schema.Struct<{
45
45
  readonly metadata: Schema.optionalKey<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json, Schema.Json, never, never>>>>;
46
46
  readonly type: Schema.Literal<"tool-call">;
47
47
  readonly id: Schema.String;
@@ -66,16 +66,16 @@ declare const ScriptedStreamTermination: Schema.Union<readonly [Schema.TaggedStr
66
66
  type ScriptedStreamTermination = typeof ScriptedStreamTermination.Type;
67
67
  /** One non-streaming invocation and the encoded response parts it returns. */
68
68
  declare const ScriptedGenerateTurn: Schema.TaggedStruct<"Generate", {
69
- readonly parts: Schema.$Array<Schema.Union<readonly [Schema.toEncoded<Schema.Codec<Response.Part<{}, false>, Response.PartEncoded, never, never>>, Schema.toEncoded<Schema.Struct<{
69
+ readonly parts: Schema.$Array<Schema.Union<readonly [Schema.toEncoded<Schema.Codec<Response.Part<{}, "decoded">, Response.PartEncoded, never, never>>, Schema.toEncoded<Schema.Struct<{
70
70
  readonly type: Schema.tag<"reasoning-delta">;
71
71
  readonly id: Schema.String;
72
72
  readonly delta: Schema.String;
73
- readonly "~effect/ai/Content/Part": Schema.withDecodingDefaultKey<Schema.tag<"~effect/ai/Content/Part">>;
73
+ readonly "~effect/ai/Response/Part": Schema.withDecodingDefaultKey<Schema.tag<"~effect/ai/Response/Part">>;
74
74
  readonly metadata: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.Codec<Schema.Json>>>;
75
75
  }>>, Schema.toEncoded<Schema.Struct<{
76
76
  readonly type: Schema.tag<"reasoning-end">;
77
77
  readonly id: Schema.String;
78
- readonly "~effect/ai/Content/Part": Schema.withDecodingDefaultKey<Schema.tag<"~effect/ai/Content/Part">>;
78
+ readonly "~effect/ai/Response/Part": Schema.withDecodingDefaultKey<Schema.tag<"~effect/ai/Response/Part">>;
79
79
  readonly metadata: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.Codec<Schema.Json>>>;
80
80
  }>>, Schema.Struct<{
81
81
  readonly metadata: Schema.optionalKey<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json, Schema.Json, never, never>>>>;
@@ -98,7 +98,7 @@ declare const ScriptedGenerateTurn: Schema.TaggedStruct<"Generate", {
98
98
  type ScriptedGenerateTurn = typeof ScriptedGenerateTurn.Type;
99
99
  /** One streaming invocation with its encoded parts and terminal behavior. */
100
100
  declare const ScriptedStreamTurn: Schema.TaggedStruct<"Stream", {
101
- readonly parts: Schema.$Array<Schema.Union<readonly [Schema.toEncoded<Schema.Codec<Response.StreamPart<{}, false>, Response.StreamPartEncoded, never, never>>, Schema.Struct<{
101
+ readonly parts: Schema.$Array<Schema.Union<readonly [Schema.toEncoded<Schema.Codec<Response.StreamPart<{}, "decoded">, Response.StreamPartEncoded, never, never>>, Schema.Struct<{
102
102
  readonly metadata: Schema.optionalKey<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json, Schema.Json, never, never>>>>;
103
103
  readonly type: Schema.Literal<"tool-call">;
104
104
  readonly id: Schema.String;
@@ -124,16 +124,16 @@ type ScriptedStreamTurn = typeof ScriptedStreamTurn.Type;
124
124
  * Serializable grammar for one finite scripted provider invocation.
125
125
  */
126
126
  declare const ScriptedTurn: Schema.Union<readonly [Schema.TaggedStruct<"Generate", {
127
- readonly parts: Schema.$Array<Schema.Union<readonly [Schema.toEncoded<Schema.Codec<Response.Part<{}, false>, Response.PartEncoded, never, never>>, Schema.toEncoded<Schema.Struct<{
127
+ readonly parts: Schema.$Array<Schema.Union<readonly [Schema.toEncoded<Schema.Codec<Response.Part<{}, "decoded">, Response.PartEncoded, never, never>>, Schema.toEncoded<Schema.Struct<{
128
128
  readonly type: Schema.tag<"reasoning-delta">;
129
129
  readonly id: Schema.String;
130
130
  readonly delta: Schema.String;
131
- readonly "~effect/ai/Content/Part": Schema.withDecodingDefaultKey<Schema.tag<"~effect/ai/Content/Part">>;
131
+ readonly "~effect/ai/Response/Part": Schema.withDecodingDefaultKey<Schema.tag<"~effect/ai/Response/Part">>;
132
132
  readonly metadata: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.Codec<Schema.Json>>>;
133
133
  }>>, Schema.toEncoded<Schema.Struct<{
134
134
  readonly type: Schema.tag<"reasoning-end">;
135
135
  readonly id: Schema.String;
136
- readonly "~effect/ai/Content/Part": Schema.withDecodingDefaultKey<Schema.tag<"~effect/ai/Content/Part">>;
136
+ readonly "~effect/ai/Response/Part": Schema.withDecodingDefaultKey<Schema.tag<"~effect/ai/Response/Part">>;
137
137
  readonly metadata: Schema.withDecodingDefault<Schema.$Record<Schema.String, Schema.Codec<Schema.Json>>>;
138
138
  }>>, Schema.Struct<{
139
139
  readonly metadata: Schema.optionalKey<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json, Schema.Json, never, never>>>>;
@@ -153,7 +153,7 @@ declare const ScriptedTurn: Schema.Union<readonly [Schema.TaggedStruct<"Generate
153
153
  readonly preliminary: Schema.optionalKey<Schema.Boolean>;
154
154
  }>]>>;
155
155
  }>, Schema.TaggedStruct<"Stream", {
156
- readonly parts: Schema.$Array<Schema.Union<readonly [Schema.toEncoded<Schema.Codec<Response.StreamPart<{}, false>, Response.StreamPartEncoded, never, never>>, Schema.Struct<{
156
+ readonly parts: Schema.$Array<Schema.Union<readonly [Schema.toEncoded<Schema.Codec<Response.StreamPart<{}, "decoded">, Response.StreamPartEncoded, never, never>>, Schema.Struct<{
157
157
  readonly metadata: Schema.optionalKey<Schema.$Record<Schema.String, Schema.NullOr<Schema.Codec<Schema.Json, Schema.Json, never, never>>>>;
158
158
  readonly type: Schema.Literal<"tool-call">;
159
159
  readonly id: Schema.String;
@@ -217,4 +217,4 @@ declare class ScriptedModel extends ScriptedModel_base {
217
217
  }
218
218
  //#endregion
219
219
  export { ScriptedRequest as a, ScriptedStreamTermination as c, ScriptedTurnHooks as d, ScriptedTurnInput as f, ScriptedModel_d_exports as i, ScriptedStreamTurn as l, ScriptedGenerateTurn as n, ScriptedRequestKind as o, ScriptedModel as r, ScriptedStreamPart as s, ScriptedGeneratePart as t, ScriptedTurn as u };
220
- //# sourceMappingURL=ScriptedModel-DAvxIiud.d.mts.map
220
+ //# sourceMappingURL=ScriptedModel-HIvFn-5K.d.mts.map
@@ -1,2 +1,2 @@
1
- import { a as ScriptedRequest, c as ScriptedStreamTermination, d as ScriptedTurnHooks, f as ScriptedTurnInput, l as ScriptedStreamTurn, n as ScriptedGenerateTurn, o as ScriptedRequestKind, r as ScriptedModel, s as ScriptedStreamPart, t as ScriptedGeneratePart, u as ScriptedTurn } from "./ScriptedModel-DAvxIiud.mjs";
1
+ import { a as ScriptedRequest, c as ScriptedStreamTermination, d as ScriptedTurnHooks, f as ScriptedTurnInput, l as ScriptedStreamTurn, n as ScriptedGenerateTurn, o as ScriptedRequestKind, r as ScriptedModel, s as ScriptedStreamPart, t as ScriptedGeneratePart, u as ScriptedTurn } from "./ScriptedModel-HIvFn-5K.mjs";
2
2
  export { ScriptedGeneratePart, ScriptedGenerateTurn, ScriptedModel, ScriptedRequest, ScriptedRequestKind, ScriptedStreamPart, ScriptedStreamTermination, ScriptedStreamTurn, ScriptedTurn, ScriptedTurnHooks, ScriptedTurnInput };
@@ -1,4 +1,4 @@
1
- import { f as ScriptedTurnInput, r as ScriptedModel } from "./ScriptedModel-DAvxIiud.mjs";
1
+ import { f as ScriptedTurnInput, r as ScriptedModel } from "./ScriptedModel-HIvFn-5K.mjs";
2
2
  import { Context, Effect, Layer, Option, Schema } from "effect";
3
3
  import { LanguageModel, Model, Response, Tool, Toolkit } from "effect/unstable/ai";
4
4
  import * as Agent from "effect-agent/agent";
package/dist/index.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { i as ScriptedModel_d_exports } from "./ScriptedModel-DAvxIiud.mjs";
1
+ import { i as ScriptedModel_d_exports } from "./ScriptedModel-HIvFn-5K.mjs";
2
2
  export { ScriptedModel_d_exports as ScriptedModel };
package/package.json CHANGED
@@ -1 +1 @@
1
- {"name":"@effect-agent/testing","version":"0.1.0-beta.91","dependencies":{"effect-agent":"0.1.0-beta.91"},"devDependencies":{"@effect-agent/platform-node":"0.1.0-beta.91","@effect-agent/storage-memory":"0.1.0-beta.91","@effect-agent/storage-sqlite":"0.1.0-beta.91","@effect/platform-node":"4.0.0-rc.112","@effect/sql-sqlite-node":"4.0.0-rc.112","@effect/vitest":"4.0.0-rc.112","effect":"4.0.0-rc.112","typescript":"7.0.2","vite-plus":"0.3.0"},"peerDependencies":{"effect":"^4.0.0-rc.112"},"exports":{".":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"./certification":{"types":"./dist/Certification.d.mts","default":"./dist/Certification.mjs"},"./chaos":{"types":"./dist/Chaos.d.mts","default":"./dist/Chaos.mjs"},"./code-executor-conformance":{"types":"./dist/CodeExecutorConformance.d.mts","default":"./dist/CodeExecutorConformance.mjs"},"./code-executor-substitute":{"types":"./dist/CodeExecutorSubstitute.d.mts","default":"./dist/CodeExecutorSubstitute.mjs"},"./docs-researcher":{"types":"./dist/DocsResearcher.d.mts","default":"./dist/DocsResearcher.mjs"},"./scripted-model":{"types":"./dist/ScriptedModel.d.mts","default":"./dist/ScriptedModel.mjs"},"./travel-planner":{"types":"./dist/TravelPlanner.d.mts","default":"./dist/TravelPlanner.mjs"}},"description":"Scripted models, deterministic fixtures, and adapter conformance kits for testing Effect Agent applications.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/danieljvdm/effect-agent.git","directory":"packages/testing"},"files":["dist","src"],"type":"module","sideEffects":[],"publishConfig":{"access":"public"},"scripts":{"build":"vp pack","check":"tsc --noEmit -p tsconfig.json","test":"vp test --passWithNoTests"}}
1
+ {"name":"@effect-agent/testing","version":"0.1.0-beta.92","dependencies":{"effect-agent":"0.1.0-beta.92"},"devDependencies":{"@effect-agent/platform-node":"0.1.0-beta.92","@effect-agent/storage-memory":"0.1.0-beta.92","@effect-agent/storage-sqlite":"0.1.0-beta.92","@effect/platform-node":"4.0.0-rc.115","@effect/sql-sqlite-node":"4.0.0-rc.115","@effect/vitest":"4.0.0-rc.115","effect":"4.0.0-rc.115","typescript":"7.0.2","vite-plus":"0.3.0"},"peerDependencies":{"effect":"^4.0.0-rc.115"},"exports":{".":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"./certification":{"types":"./dist/Certification.d.mts","default":"./dist/Certification.mjs"},"./chaos":{"types":"./dist/Chaos.d.mts","default":"./dist/Chaos.mjs"},"./code-executor-conformance":{"types":"./dist/CodeExecutorConformance.d.mts","default":"./dist/CodeExecutorConformance.mjs"},"./code-executor-substitute":{"types":"./dist/CodeExecutorSubstitute.d.mts","default":"./dist/CodeExecutorSubstitute.mjs"},"./docs-researcher":{"types":"./dist/DocsResearcher.d.mts","default":"./dist/DocsResearcher.mjs"},"./scripted-model":{"types":"./dist/ScriptedModel.d.mts","default":"./dist/ScriptedModel.mjs"},"./travel-planner":{"types":"./dist/TravelPlanner.d.mts","default":"./dist/TravelPlanner.mjs"}},"description":"Scripted models, deterministic fixtures, and adapter conformance kits for testing Effect Agent applications.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/danieljvdm/effect-agent.git","directory":"packages/testing"},"files":["dist","src"],"type":"module","sideEffects":[],"publishConfig":{"access":"public"},"scripts":{"build":"vp pack","check":"tsc --noEmit -p tsconfig.json","test":"vp test --passWithNoTests"}}
package/src/Chaos.ts CHANGED
@@ -51,7 +51,6 @@ import {
51
51
  import { DurableRuntimeFailpointTestControl } from "effect-agent/testing/durable-failpoint-test-control";
52
52
  import { verifyThreadInvariants } from "effect-agent/thread-invariants";
53
53
  import { ThreadExportRequest, ThreadStore } from "effect-agent/thread-store";
54
- import { FastCheck } from "effect/testing";
55
54
  import {
56
55
  LanguageModel,
57
56
  Model,
@@ -60,10 +59,11 @@ import {
60
59
  type Prompt,
61
60
  type Response,
62
61
  } from "effect/unstable/ai";
62
+ import { Arbitrary } from "effect/unstable/arbitrary";
63
63
 
64
64
  /**
65
65
  * P7 WP4 chaos machinery (plan §5): a Schema-first `ChaosPlan`, a seeded generator over
66
- * `effect/testing/FastCheck` (already inside the pinned Effect — no new dependency), and a
66
+ * `effect/unstable/arbitrary`, and a
67
67
  * deterministic runner that drives the durable coordinator over whatever adapter pair the test
68
68
  * provides. Every plan ends in the SAME claims the crash matrices make:
69
69
  *
@@ -207,25 +207,14 @@ export interface ChaosGeneratorOptions {
207
207
  readonly adapterArms?: ReadonlyArray<string> | undefined;
208
208
  }
209
209
 
210
- interface GeneratedLane {
211
- readonly kind: ChaosScenarioKind;
212
- readonly depth: number;
213
- }
214
-
215
- const laneArbitrary: FastCheck.Arbitrary<GeneratedLane> = FastCheck.constantFrom<ChaosScenarioKind>(
216
- "plain",
217
- "uncertain-tool",
218
- "durable-steps",
219
- "approval",
220
- "join",
221
- "delegation",
222
- ).chain((kind): FastCheck.Arbitrary<GeneratedLane> =>
223
- kind === "join"
224
- ? FastCheck.integer({ min: 2, max: 3 }).map((depth): GeneratedLane => ({ kind, depth }))
225
- : kind === "plain"
226
- ? FastCheck.integer({ min: 1, max: 2 }).map((depth): GeneratedLane => ({ kind, depth }))
227
- : FastCheck.constant<GeneratedLane>({ kind, depth: 1 }),
228
- );
210
+ const GeneratedLane = Schema.Union([
211
+ Schema.Struct({ kind: Schema.Literal("join"), depth: Schema.Literals([2, 3]) }),
212
+ Schema.Struct({ kind: Schema.Literal("plain"), depth: Schema.Literals([1, 2]) }),
213
+ Schema.Struct({
214
+ kind: Schema.Literals(["uncertain-tool", "durable-steps", "approval", "delegation"]),
215
+ depth: Schema.Literal(1),
216
+ }),
217
+ ]);
229
218
 
230
219
  interface ChaosPlanShape {
231
220
  readonly lanes: number;
@@ -239,70 +228,66 @@ interface ChaosPlanShape {
239
228
 
240
229
  const planShapeArbitrary = (
241
230
  adapterArms: ReadonlyArray<string>,
242
- ): FastCheck.Arbitrary<ChaosPlanShape> =>
243
- FastCheck.record({
244
- lanes: FastCheck.array(laneArbitrary, { minLength: 1, maxLength: 3 }),
245
- failpointArms: FastCheck.uniqueArray(
246
- FastCheck.constantFrom(...DurableRuntimeFailpointLocation.literals),
247
- { maxLength: 3 },
248
- ),
249
- adapterArms:
250
- adapterArms.length === 0
251
- ? FastCheck.constant<Array<string>>([])
252
- : FastCheck.uniqueArray(FastCheck.constantFrom(...adapterArms), { maxLength: 2 }),
253
- abortInjections: FastCheck.uniqueArray(FastCheck.integer({ min: 0, max: 15 }), {
254
- maxLength: 2,
255
- }),
256
- resolutionInjections: FastCheck.array(
257
- FastCheck.constantFrom<ChaosResolutionKind>(
258
- "never-happened",
259
- "completed-from-supplier",
260
- "abort-submission",
231
+ ): Arbitrary.Arbitrary<ChaosPlanShape> =>
232
+ Arbitrary.schema(
233
+ Schema.Struct({
234
+ lanes: Schema.Array(GeneratedLane).check(Schema.isMinLength(1), Schema.isMaxLength(3)),
235
+ failpointArms: Schema.Array(DurableRuntimeFailpointLocation).check(
236
+ Schema.isUnique(),
237
+ Schema.isMaxLength(3),
261
238
  ),
262
- { maxLength: 4 },
263
- ),
264
- approvalDecisions: FastCheck.array(
265
- FastCheck.constantFrom<ChaosApprovalDecision>("approved", "denied"),
266
- { maxLength: 2 },
267
- ),
268
- }).map((shape) => {
269
- const submissions = shape.lanes.flatMap((lane, index) =>
270
- Array.from({ length: lane.depth }, () =>
271
- ChaosSubmissionSpec.make({ lane: index, kind: lane.kind }),
272
- ),
273
- );
239
+ adapterArms: Schema.Array(
240
+ adapterArms.length === 0 ? Schema.String : Schema.Literals(adapterArms),
241
+ ).check(Schema.isUnique(), Schema.isMaxLength(adapterArms.length === 0 ? 0 : 2)),
242
+ abortInjections: Schema.Array(
243
+ Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 15 })),
244
+ ).check(Schema.isUnique(), Schema.isMaxLength(2)),
245
+ resolutionInjections: Schema.Array(ChaosResolutionKind).check(Schema.isMaxLength(4)),
246
+ approvalDecisions: Schema.Array(ChaosApprovalDecision).check(Schema.isMaxLength(2)),
247
+ }),
248
+ ).pipe(
249
+ Arbitrary.map((shape) => {
250
+ const submissions = shape.lanes.flatMap((lane, index) =>
251
+ Array.from({ length: lane.depth }, () =>
252
+ ChaosSubmissionSpec.make({ lane: index, kind: lane.kind }),
253
+ ),
254
+ );
274
255
 
275
- const [first, ...rest] = submissions;
256
+ const [first, ...rest] = submissions;
276
257
 
277
- // `lanes` >= 1 and every lane has depth >= 1, so `first` always exists.
278
- if (first === undefined) throw new Error("chaos generator produced an empty plan");
258
+ // `lanes` >= 1 and every lane has depth >= 1, so `first` always exists.
259
+ if (first === undefined) throw new Error("chaos generator produced an empty plan");
279
260
 
280
- return {
281
- lanes: shape.lanes.length,
282
- submissions: [first, ...rest] as const,
283
- failpointArms: shape.failpointArms,
284
- adapterArms: shape.adapterArms,
285
- abortInjections: shape.abortInjections,
286
- resolutionInjections: shape.resolutionInjections,
287
- approvalDecisions: shape.approvalDecisions,
288
- };
289
- });
261
+ return {
262
+ lanes: shape.lanes.length,
263
+ submissions: [first, ...rest] as const,
264
+ failpointArms: shape.failpointArms,
265
+ adapterArms: shape.adapterArms,
266
+ abortInjections: shape.abortInjections,
267
+ resolutionInjections: shape.resolutionInjections,
268
+ approvalDecisions: shape.approvalDecisions,
269
+ };
270
+ }),
271
+ );
290
272
 
291
273
  /**
292
274
  * Derive `count` chaos plans deterministically from one root seed. The same
293
275
  * `{seed, count, adapterArms}` triple always yields byte-identical plans, so a failure line
294
- * `CHAOS_SEED=<seed>` replays the exact schedule.
276
+ * `CHAOS_SEED=<seed>` replays the exact schedule with the same pinned generator version.
277
+ * Sampling is interruptible and reports bounded generation exhaustion as Arbitrary.SampleError.
295
278
  */
296
- export const generateChaosPlans = (options: ChaosGeneratorOptions): ReadonlyArray<ChaosPlan> => {
297
- const sampled = FastCheck.sample(planShapeArbitrary(options.adapterArms ?? []), {
279
+ export const generateChaosPlans = Effect.fnUntraced(function* (
280
+ options: ChaosGeneratorOptions,
281
+ ): Effect.fn.Return<ReadonlyArray<ChaosPlan>, Arbitrary.SampleError> {
282
+ const sampled = yield* Arbitrary.sampleEffect(planShapeArbitrary(options.adapterArms ?? []), {
298
283
  seed: options.seed,
299
- numRuns: options.count,
284
+ count: options.count,
300
285
  });
301
286
 
302
287
  return sampled.map((shape, index) =>
303
288
  ChaosPlan.make({ ...shape, seed: (Math.imul(options.seed, 31) + index) | 0 }),
304
289
  );
305
- };
290
+ });
306
291
 
307
292
  /** Deterministic PRNG for the runner's small ordering choices (lane drive order). */
308
293
  const mulberry32 = (seed: number): (() => number) => {