Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(achaos): add agent chaos infrastructure (#18667)

Arvin Xudd122b42171e
diff --git a/.agents/chaos/README.md b/.agents/chaos/README.md
new file mode 100644
index 00000000000..b31c04d9658
--- /dev/null
+++ b/.agents/chaos/README.md
@@ -0,0 +1,10 @@
+# Agent Chaos experiments
+
+Application-specific experiment fixtures live here. Every fixture must declare an environment
+allowlist, deterministic seed, bounded timeout, target adapter, effect and at least one independent
+oracle. Production environments require an external approval policy and are not enabled by the
+portable runner.
+
+Fixture provenance may be an incident (`discoveredFrom`), an evaluation finding, or an explicit
+hypothesis. Once a probabilistic run finds a failure, preserve its seed and reduce it to a stable
+fixture.
diff --git a/.agents/chaos/fixtures/L1-model-runtime/tool-failure.yaml b/.agents/chaos/fixtures/L1-model-runtime/tool-failure.yaml
new file mode 100644
index 00000000000..42f67c399ed
--- /dev/null
+++ b/.agents/chaos/fixtures/L1-model-runtime/tool-failure.yaml
@@ -0,0 +1,24 @@
+id: tool-failure
+description: A selected tool receives a deterministic provider-style failure.
+layer: L1-model-runtime
+discoveredFrom: first-phase reference scenario
+seed: tool-failure-v1
+timeoutMs: 5000
+cleanup: always
+safety:
+ allowedEnvironments: [test, ci]
+ maxInjections: 1
+target:
+ adapter: runtime
+ selector:
+ apiName: search
+ phase: tool_attempt
+trigger:
+ when: before
+ probability: 1
+effect:
+ type: throw
+ errorType: RateLimited
+oracles:
+ - name: tool-failure-observed
+ timeoutMs: 1000
diff --git a/.agents/chaos/fixtures/L2-agent-runtime/operation-reclaim.yaml b/.agents/chaos/fixtures/L2-agent-runtime/operation-reclaim.yaml
new file mode 100644
index 00000000000..f159e16a44f
--- /dev/null
+++ b/.agents/chaos/fixtures/L2-agent-runtime/operation-reclaim.yaml
@@ -0,0 +1,22 @@
+id: operation-reclaim
+description: A stale running operation is abandoned and replaced without reviving the old attempt.
+layer: L2-agent-runtime
+discoveredFrom: Goal runtime resilience canary incident
+seed: operation-reclaim-v1
+timeoutMs: 10000
+cleanup: always
+safety:
+ allowedEnvironments: [test, ci]
+ maxInjections: 1
+target:
+ adapter: state
+ selector:
+ operationStatus: running
+trigger:
+ when: immediate
+effect:
+ type: delay
+ durationMs: 300000
+oracles:
+ - name: operation-reclaimed
+ timeoutMs: 5000
diff --git a/.agents/chaos/fixtures/L3-orchestration/duplicate-completion.yaml b/.agents/chaos/fixtures/L3-orchestration/duplicate-completion.yaml
new file mode 100644
index 00000000000..38ebb905859
--- /dev/null
+++ b/.agents/chaos/fixtures/L3-orchestration/duplicate-completion.yaml
@@ -0,0 +1,23 @@
+id: duplicate-completion
+description: Completion delivery is duplicated and the consumer remains idempotent.
+layer: L3-orchestration
+discoveredFrom: first-phase reference scenario
+seed: duplicate-completion-v1
+timeoutMs: 5000
+cleanup: always
+safety:
+ allowedEnvironments: [test, ci]
+ maxInjections: 1
+target:
+ adapter: runtime
+ selector:
+ operationId: op-duplicate
+ phase: completion
+trigger:
+ when: before
+effect:
+ type: duplicate
+ count: 2
+oracles:
+ - name: completion-idempotent
+ timeoutMs: 1000
diff --git a/.agents/chaos/goal-integration.md b/.agents/chaos/goal-integration.md
new file mode 100644
index 00000000000..a2f9cf8216c
--- /dev/null
+++ b/.agents/chaos/goal-integration.md
@@ -0,0 +1,72 @@
+# Goal Chaos integration
+
+Goal consumes Agent Chaos through application-owned adapters. `@achaos/*` must not import Goal,
+Task, Drizzle schemas, QStash, or server services.
+
+## Test harness
+
+Place concrete integration code under `apps/server/src/services/goal/__chaos__/`:
+
+1. Arrange a real Goal Graph, Work Task, Topic and Agent Operation in `getTestDB()`.
+2. Register `createRuntimeChaosHooks(controller)` for preflight result replacement/drop faults. For
+ retryable failures, wrap each `executeToolWithRetry` attempt with `executeToolAttemptWithChaos`.
+3. Register an application `@achaos/database` port for scoped lease/state mutations.
+4. Drive the production action (`GoalService.tick`, completion ingestion, scheduled wake, or
+ human decision) as the runner exercise.
+5. Evaluate persisted state with application-owned oracles; never use the builder Agent's text as
+ proof.
+6. Attach the `ChaosRunResult` JSON and trace events to Acceptance evidence.
+
+## Initial campaign
+
+### Operation reclaim and restart
+
+- Inject: age the active operation lease after its worker disappears.
+- Exercise: create a fresh GoalService instance and run the next coordinator tick.
+- Safety oracle: the abandoned operation never becomes `done`.
+- Liveness oracle: a replacement attempt starts within the configured recovery bound.
+- Consistency oracle: Goal Work, Task, Topic and Operation ownership agree.
+
+This campaign requires `settleStaleRunning` / `recoverAbandonedWork` from the Goal runtime
+resilience work to be present on the target branch.
+
+### Duplicate and late completion
+
+- Inject: deliver an identical completion twice, then deliver completion from an abandoned attempt.
+- Safety oracle: Acceptance dispatch occurs at most once.
+- Safety oracle: the abandoned attempt cannot overwrite its terminal status.
+- Consistency oracle: only the lease-owning attempt advances the Work.
+
+### Tool failure and retry
+
+- Inject: throw a typed transient error from inside one `executeToolWithRetry` attempt.
+- Exercise: let the normal Agent Runtime and Goal retry policy continue.
+- Liveness oracle: the operation settles or reaches a bounded human gate.
+- Safety oracle: an external side effect is not duplicated.
+- Budget oracle: retries never exceed the Goal policy.
+
+### Verifier-driven evolution
+
+- Inject: return incomplete or contradictory Acceptance evidence.
+- Exercise: run Goal verification and the following coordinator tick.
+- Safety oracle: the Goal never reaches `achieved` while a required criterion failed.
+- Liveness oracle: a bounded repair Work or Decision is created.
+- Evidence oracle: verifier gaps are linked to the successor Work.
+
+### Human gate and resume
+
+- Inject: delay, reject and duplicate a human-intervention response.
+- Safety oracle: approval-gated tools never execute before approval.
+- Consistency oracle: one decision resolves at most once.
+- Liveness oracle: an approved Goal resumes from durable state after a server restart.
+
+## CI tiers
+
+- PR: deterministic in-process and PGlite/Postgres campaigns; no real process kill or network fault.
+- Nightly: server restart, QStash duplicate/reorder, heterogeneous Agent and real child-process kill.
+- Canary: allowlisted non-destructive experiments with a kill switch and strict blast radius.
+- Production: observation and trace capture only until a separate approval policy exists.
+
+Every campaign must preserve its seed, result JSON, trace id, baseline revision and candidate
+revision. A discovered probabilistic failure becomes a reduced deterministic fixture before it is
+accepted as regression coverage.
diff --git a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
index 1b3366e1e38..97615e50be7 100644
--- a/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
+++ b/apps/server/src/services/agentRuntime/hooks/HookDispatcher.ts
@@ -223,8 +223,10 @@ export class HookDispatcher {
const toolCallEvent: ToolCallHookEvent = {
...event,
mock: (result) => {
+ if (isMocked) return false;
isMocked = true;
mockedResult = result;
+ return true;
},
operationId,
};
@@ -236,6 +238,7 @@ export class HookDispatcher {
} catch (error) {
log('[%s][beforeToolCall] Hook error (non-fatal): %s %O', operationId, hook.id, error);
}
+ if (isMocked) break;
}
return isMocked && mockedResult ? { isMocked: true, result: mockedResult } : null;
diff --git a/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts b/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts
index 935fde3ad3f..99e4c52fc3c 100644
--- a/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts
+++ b/apps/server/src/services/agentRuntime/hooks/__tests__/HookDispatcher.test.ts
@@ -726,7 +726,10 @@ describe('HookDispatcher', () => {
});
describe('dispatchBeforeToolCall β€” edge cases', () => {
- it('should use the last mock() call when multiple handlers call mock()', async () => {
+ it('should preserve the first mock() call when multiple handlers call mock()', async () => {
+ const secondHandler = vi.fn(async (event: any) => {
+ event.mock({ content: '{"second":true}', success: true });
+ });
dispatcher.register(operationId, [
{
handler: async (event: any) => {
@@ -736,9 +739,7 @@ describe('HookDispatcher', () => {
type: 'beforeToolCall',
},
{
- handler: async (event: any) => {
- event.mock({ content: '{"second":true}', success: true });
- },
+ handler: secondHandler,
id: 'mock-2',
type: 'beforeToolCall',
},
@@ -754,8 +755,36 @@ describe('HookDispatcher', () => {
expect(result).toEqual({
isMocked: true,
- result: { content: '{"second":true}', success: true },
+ result: { content: '{"first":true}', success: true },
+ });
+ expect(secondHandler).not.toHaveBeenCalled();
+ });
+
+ it('should stop after a hook mocks and then throws', async () => {
+ const secondHandler = vi.fn();
+ dispatcher.register(operationId, [
+ {
+ handler: async (event: any) => {
+ event.mock({ content: '{"first":true}', success: true });
+ throw new Error('after mock');
+ },
+ id: 'mock-then-throw',
+ type: 'beforeToolCall',
+ },
+ { handler: secondHandler, id: 'must-not-run', type: 'beforeToolCall' },
+ ]);
+ const result = await dispatcher.dispatchBeforeToolCall(operationId, {
+ apiName: 'search',
+ args: {},
+ callIndex: 1,
+ identifier: 'twitter',
+ stepIndex: 0,
+ });
+ expect(result).toEqual({
+ isMocked: true,
+ result: { content: '{"first":true}', success: true },
});
+ expect(secondHandler).not.toHaveBeenCalled();
});
it('should return mock when only one of multiple handlers calls mock()', async () => {
diff --git a/packages/achaos/README.md b/packages/achaos/README.md
new file mode 100644
index 00000000000..b3d3576ff96
--- /dev/null
+++ b/packages/achaos/README.md
@@ -0,0 +1,13 @@
+# Agent Chaos infrastructure
+
+Agent-domain chaos engineering packages use the temporary `@achaos/*` namespace:
+
+- `@achaos/core` β€” portable experiment, effect, safety, oracle, receipt and result contracts.
+- `@achaos/runner` β€” validated fixture loading and deterministic lifecycle execution.
+- `@achaos/runtime` β€” Agent Runtime hook and completion-delivery adapters.
+- `@achaos/database` β€” schema-independent mutation and rollback port.
+- `@achaos/process` β€” ownership-checked destructive process injection.
+- `@achaos/testing` β€” deterministic test targets and scenario helpers.
+
+Application incidents and fixtures belong under `.agents/chaos`; package code contains mechanisms,
+not LobeHub business models. Goal, Agent Evals, CI and self-improvement workflows are consumers.
diff --git a/packages/achaos/core/package.json b/packages/achaos/core/package.json
new file mode 100644
index 00000000000..d9498f87d56
--- /dev/null
+++ b/packages/achaos/core/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "@achaos/core",
+ "version": "0.0.1",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "main": "./src/index.ts",
+ "dependencies": {
+ "zod": "^4.3.6"
+ }
+}
diff --git a/packages/achaos/core/src/index.ts b/packages/achaos/core/src/index.ts
new file mode 100644
index 00000000000..8970f0fdc73
--- /dev/null
+++ b/packages/achaos/core/src/index.ts
@@ -0,0 +1,3 @@
+export { createSeededRandom } from './random';
+export { chaosEffectSchema, chaosExperimentSchema } from './schema';
+export type * from './types';
diff --git a/packages/achaos/core/src/random.ts b/packages/achaos/core/src/random.ts
new file mode 100644
index 00000000000..154c9bf9ea0
--- /dev/null
+++ b/packages/achaos/core/src/random.ts
@@ -0,0 +1,20 @@
+const hashSeed = (seed: string) => {
+ let hash = 2166136261;
+ for (const character of seed) {
+ hash ^= character.codePointAt(0) ?? 0;
+ hash = Math.imul(hash, 16777619);
+ }
+ return hash >>> 0;
+};
+
+/** Deterministic Mulberry32 generator for replayable injection decisions. */
+export const createSeededRandom = (seed: string) => {
+ let state = hashSeed(seed);
+ return () => {
+ state += 0x6d2b79f5;
+ let value = state;
+ value = Math.imul(value ^ (value >>> 15), value | 1);
+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
+ return ((value ^ (value >>> 14)) >>> 0) / 4_294_967_296;
+ };
+};
diff --git a/packages/achaos/core/src/schema.test.ts b/packages/achaos/core/src/schema.test.ts
new file mode 100644
index 00000000000..b1ecb9e1a9d
--- /dev/null
+++ b/packages/achaos/core/src/schema.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+
+import { chaosExperimentSchema } from './schema';
+
+describe('chaosExperimentSchema', () => {
+ it('rejects unsafe incomplete experiment data', () => {
+ expect(() => chaosExperimentSchema.parse({ id: 'bad experiment' })).toThrow();
+ });
+
+ it('accepts a replayable experiment', () => {
+ const result = chaosExperimentSchema.parse({
+ description: 'Inject a tool timeout',
+ effect: { errorType: 'Timeout', type: 'throw' },
+ id: 'tool-timeout',
+ layer: 'L1-model-runtime',
+ oracles: [{ name: 'fallback-used' }],
+ safety: { allowedEnvironments: ['test'] },
+ seed: 'stable-seed',
+ target: { adapter: 'runtime', selector: { apiName: 'search' } },
+ timeoutMs: 1000,
+ trigger: { when: 'before' },
+ });
+ expect(result.cleanup).toBe('always');
+ });
+
+ it('rejects misspelled safety-policy keys', () => {
+ expect(() =>
+ chaosExperimentSchema.parse({
+ description: 'Unsafe typo',
+ effect: { type: 'drop' },
+ id: 'unsafe-typo',
+ layer: 'L2-agent-runtime',
+ oracles: [{ name: 'healthy' }],
+ safety: { allowedEnvironments: ['test'], maxInjection: 1 },
+ seed: 'seed',
+ target: { adapter: 'runtime', selector: {} },
+ timeoutMs: 1000,
+ trigger: { when: 'immediate' },
+ }),
+ ).toThrow(/maxInjection/);
+ });
+});
diff --git a/packages/achaos/core/src/schema.ts b/packages/achaos/core/src/schema.ts
new file mode 100644
index 00000000000..425044dbb5f
--- /dev/null
+++ b/packages/achaos/core/src/schema.ts
@@ -0,0 +1,69 @@
+import { z } from 'zod';
+
+const recordSchema = z.record(z.string(), z.unknown());
+
+export const chaosEffectSchema = z.discriminatedUnion('type', [
+ z.object({ durationMs: z.number().int().nonnegative(), type: z.literal('delay') }).strict(),
+ z.object({ count: z.number().int().min(2), type: z.literal('duplicate') }).strict(),
+ z.object({ type: z.literal('drop') }).strict(),
+ z
+ .object({
+ errorType: z.string().min(1),
+ message: z.string().optional(),
+ type: z.literal('throw'),
+ })
+ .strict(),
+ z.object({ content: z.string(), type: z.literal('replace_result') }).strict(),
+ z
+ .object({
+ signal: z.literal('SIGKILL').optional(),
+ type: z.literal('kill_process'),
+ })
+ .strict(),
+]);
+
+export const chaosExperimentSchema = z
+ .object({
+ cleanup: z.enum(['always', 'on_success', 'never']).default('always'),
+ description: z.string().min(1),
+ discoveredFrom: z.string().optional(),
+ effect: chaosEffectSchema,
+ id: z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),
+ layer: z.enum([
+ 'L0-infra',
+ 'L1-model-runtime',
+ 'L2-agent-runtime',
+ 'L3-orchestration',
+ 'L4-business-logic',
+ 'L5-human-trust',
+ ]),
+ oracles: z
+ .array(
+ z
+ .object({
+ name: z.string().min(1),
+ params: recordSchema.optional(),
+ timeoutMs: z.number().positive().optional(),
+ })
+ .strict(),
+ )
+ .min(1),
+ safety: z
+ .object({
+ allowedEnvironments: z.array(z.string().min(1)).min(1),
+ destructive: z.boolean().optional(),
+ maxInjections: z.number().int().positive().optional(),
+ })
+ .strict(),
+ seed: z.string().min(1),
+ tags: z.array(z.string()).optional(),
+ target: z.object({ adapter: z.string().min(1), selector: recordSchema }).strict(),
+ timeoutMs: z.number().int().positive(),
+ trigger: z
+ .object({
+ probability: z.number().min(0).max(1).optional(),
+ when: z.enum(['immediate', 'before', 'after']),
+ })
+ .strict(),
+ })
+ .strict();
diff --git a/packages/achaos/core/src/types.ts b/packages/achaos/core/src/types.ts
new file mode 100644
index 00000000000..5a9506c08be
--- /dev/null
+++ b/packages/achaos/core/src/types.ts
@@ -0,0 +1,136 @@
+export type ChaosLayer =
+ | 'L0-infra'
+ | 'L1-model-runtime'
+ | 'L2-agent-runtime'
+ | 'L3-orchestration'
+ | 'L4-business-logic'
+ | 'L5-human-trust';
+
+export type ChaosEffect =
+ | { durationMs: number; type: 'delay' }
+ | { count: number; type: 'duplicate' }
+ | { type: 'drop' }
+ | { errorType: string; message?: string; type: 'throw' }
+ | { content: string; type: 'replace_result' }
+ | { signal?: 'SIGKILL'; type: 'kill_process' };
+
+export interface ChaosTarget {
+ adapter: string;
+ selector: Record<string, unknown>;
+}
+
+export interface ChaosTrigger {
+ probability?: number;
+ when: 'immediate' | 'before' | 'after';
+}
+
+export interface ChaosOracleSpec {
+ name: string;
+ params?: Record<string, unknown>;
+ timeoutMs?: number;
+}
+
+export interface ChaosSafetyPolicy {
+ allowedEnvironments: string[];
+ destructive?: boolean;
+ maxInjections?: number;
+}
+
+export interface ChaosExperiment {
+ cleanup?: 'always' | 'on_success' | 'never';
+ description: string;
+ discoveredFrom?: string;
+ effect: ChaosEffect;
+ id: string;
+ layer: ChaosLayer;
+ oracles: ChaosOracleSpec[];
+ safety: ChaosSafetyPolicy;
+ seed: string;
+ tags?: string[];
+ target: ChaosTarget;
+ timeoutMs: number;
+ trigger: ChaosTrigger;
+}
+
+export type ChaosRunStatus = 'passed' | 'failed' | 'inconclusive' | 'aborted';
+
+export type ChaosJsonValue =
+ boolean | null | number | string | ChaosJsonValue[] | { [key: string]: ChaosJsonValue };
+
+export type ChaosTimelineEventType =
+ | 'run_started'
+ | 'steady_state_checked'
+ | 'fault_injected'
+ | 'system_exercised'
+ | 'oracle_evaluated'
+ | 'cleanup_started'
+ | 'cleanup_completed'
+ | 'run_completed';
+
+export interface ChaosTimelineEvent {
+ at: string;
+ data?: Record<string, unknown>;
+ type: ChaosTimelineEventType;
+}
+
+export interface ChaosEvidenceRef {
+ id: string;
+ type: 'trace' | 'operation' | 'snapshot' | 'log' | 'artifact';
+}
+
+export interface ChaosOracleResult {
+ evidence?: ChaosEvidenceRef[];
+ message: string;
+ name: string;
+ status: 'passed' | 'failed' | 'inconclusive';
+}
+
+export interface ChaosInjectionReceipt {
+ adapter: string;
+ cleanupToken?: Record<string, unknown>;
+ details?: Record<string, ChaosJsonValue>;
+ injectionId: string;
+}
+
+export interface ChaosRunResult {
+ durationMs: number;
+ error?: { message: string; name: string };
+ experimentId: string;
+ finishedAt: string;
+ injection?: Omit<ChaosInjectionReceipt, 'cleanupToken'>;
+ oracleResults: ChaosOracleResult[];
+ runId: string;
+ seed: string;
+ startedAt: string;
+ status: ChaosRunStatus;
+ timeline: ChaosTimelineEvent[];
+}
+
+export interface ChaosRunContext {
+ environment: string;
+ experiment: ChaosExperiment;
+ random: () => number;
+ runId: string;
+ signal: AbortSignal;
+}
+
+export interface ChaosAdapter {
+ /**
+ * Cancels an in-flight injection before it yields a receipt. Required whenever cleanup is
+ * provided; resolving guarantees that the pending injection cannot commit later.
+ */
+ cancelInjection?: (context: ChaosRunContext) => Promise<void>;
+ cleanup?: (receipt: ChaosInjectionReceipt, context: ChaosRunContext) => Promise<void>;
+ inject: (context: ChaosRunContext) => Promise<ChaosInjectionReceipt>;
+ name: string;
+ verifyInjection?: (receipt: ChaosInjectionReceipt, context: ChaosRunContext) => Promise<boolean>;
+}
+
+export interface ChaosOracle {
+ evaluate: (context: ChaosRunContext, spec: ChaosOracleSpec) => Promise<ChaosOracleResult>;
+ name: string;
+}
+
+export interface ChaosExercise {
+ (context: ChaosRunContext): Promise<void>;
+}
diff --git a/packages/achaos/core/tsconfig.json b/packages/achaos/core/tsconfig.json
new file mode 100644
index 00000000000..47f3a97374e
--- /dev/null
+++ b/packages/achaos/core/tsconfig.json
@@ -0,0 +1,5 @@
+{
+ "compilerOptions": { "module": "esnext", "moduleResolution": "bundler" },
+ "extends": "../../../tsconfig.json",
+ "include": ["src/**/*.ts"]
+}
diff --git a/packages/achaos/database/package.json b/packages/achaos/database/package.json
new file mode 100644
index 00000000000..ea31aad3cde
--- /dev/null
+++ b/packages/achaos/database/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "@achaos/database",
+ "version": "0.0.1",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "main": "./src/index.ts",
+ "dependencies": {
+ "@achaos/core": "workspace:*"
+ }
+}
diff --git a/packages/achaos/database/src/index.test.ts b/packages/achaos/database/src/index.test.ts
new file mode 100644
index 00000000000..8d4a8e1f33c
--- /dev/null
+++ b/packages/achaos/database/src/index.test.ts
@@ -0,0 +1,37 @@
+import type { ChaosRunContext } from '@achaos/core';
+import { describe, expect, it, vi } from 'vitest';
+
+import { createDatabaseChaosAdapter } from '.';
+
+describe('createDatabaseChaosAdapter', () => {
+ it('fails cleanup when a restorable mutation omitted its snapshot', async () => {
+ const restore = vi.fn(async () => {});
+ const adapter = createDatabaseChaosAdapter({ mutate: async () => ({}), restore });
+ await expect(
+ adapter.cleanup!(
+ { adapter: 'database', injectionId: 'missing-snapshot' },
+ {} as ChaosRunContext,
+ ),
+ ).rejects.toThrow('Database cleanup requires a mutation snapshot');
+ expect(restore).not.toHaveBeenCalled();
+ });
+
+ it('preserves a class port receiver during cancellation', async () => {
+ class StatefulPort {
+ canceled = false;
+
+ async cancel() {
+ this.canceled = true;
+ }
+
+ async mutate() {
+ return {};
+ }
+ }
+
+ const port = new StatefulPort();
+ const adapter = createDatabaseChaosAdapter(port);
+ await adapter.cancelInjection!({} as ChaosRunContext);
+ expect(port.canceled).toBe(true);
+ });
+});
diff --git a/packages/achaos/database/src/index.ts b/packages/achaos/database/src/index.ts
new file mode 100644
index 00000000000..d8e5cc44c6d
--- /dev/null
+++ b/packages/achaos/database/src/index.ts
@@ -0,0 +1,33 @@
+import type { ChaosAdapter, ChaosJsonValue, ChaosRunContext } from '@achaos/core';
+
+export interface DatabaseMutationReceipt {
+ details?: Record<string, ChaosJsonValue>;
+ snapshot?: Record<string, unknown>;
+}
+
+export interface DatabaseChaosPort {
+ cancel?: (context: ChaosRunContext) => Promise<void>;
+ mutate: (context: ChaosRunContext) => Promise<DatabaseMutationReceipt>;
+ restore?: (snapshot: Record<string, unknown>, context: ChaosRunContext) => Promise<void>;
+}
+
+/** Database adapter owns no schema; applications supply scoped mutate/restore ports. */
+export const createDatabaseChaosAdapter = (port: DatabaseChaosPort): ChaosAdapter => ({
+ cancelInjection: port.cancel ? async (context) => port.cancel!(context) : undefined,
+ cleanup: port.restore
+ ? async (receipt, context) => {
+ if (!receipt.cleanupToken) throw new Error('Database cleanup requires a mutation snapshot');
+ await port.restore!(receipt.cleanupToken, context);
+ }
+ : undefined,
+ inject: async (context) => {
+ const result = await port.mutate(context);
+ return {
+ adapter: 'database',
+ cleanupToken: result.snapshot,
+ details: result.details,
+ injectionId: `${context.runId}:database`,
+ };
+ },
+ name: 'database',
+});
diff --git a/packages/achaos/database/tsconfig.json b/packages/achaos/database/tsconfig.json
new file mode 100644
index 00000000000..47f3a97374e
--- /dev/null
+++ b/packages/achaos/database/tsconfig.json
@@ -0,0 +1,5 @@
+{
+ "compilerOptions": { "module": "esnext", "moduleResolution": "bundler" },
+ "extends": "../../../tsconfig.json",
+ "include": ["src/**/*.ts"]
+}
diff --git a/packages/achaos/process/package.json b/packages/achaos/process/package.json
new file mode 100644
index 00000000000..e932945ab50
--- /dev/null
+++ b/packages/achaos/process/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "@achaos/process",
+ "version": "0.0.1",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "main": "./src/index.ts",
+ "dependencies": {
+ "@achaos/core": "workspace:*"
+ }
+}
diff --git a/packages/achaos/process/src/index.test.ts b/packages/achaos/process/src/index.test.ts
new file mode 100644
index 00000000000..ea338f06500
--- /dev/null
+++ b/packages/achaos/process/src/index.test.ts
@@ -0,0 +1,55 @@
+import type { ChaosRunContext } from '@achaos/core';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { createProcessChaosAdapter } from '.';
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('createProcessChaosAdapter', () => {
+ it('rejects process-group PID values before consulting the allowlist', async () => {
+ const kill = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const adapter = createProcessChaosAdapter({ allowedPids: new Set([0, -123]) });
+ for (const pid of [0, -123]) {
+ const context = {
+ experiment: {
+ effect: { type: 'kill_process' },
+ safety: { destructive: true },
+ target: { selector: { pid } },
+ },
+ runId: 'run-process',
+ } as unknown as ChaosRunContext;
+ await expect(adapter.inject(context)).rejects.toThrow('positive integer pid');
+ }
+ expect(kill).not.toHaveBeenCalled();
+ });
+
+ it('rejects non-terminating signals from programmatic callers', async () => {
+ const kill = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const adapter = createProcessChaosAdapter({ allowedPids: new Set([123]) });
+ const context = {
+ experiment: {
+ effect: { signal: 'SIGSTOP', type: 'kill_process' },
+ safety: { destructive: true },
+ target: { selector: { pid: 123 } },
+ },
+ runId: 'run-process',
+ } as unknown as ChaosRunContext;
+ await expect(adapter.inject(context)).rejects.toThrow('requires uncatchable SIGKILL');
+ expect(kill).not.toHaveBeenCalled();
+ });
+
+ it('rejects catchable terminating signals', async () => {
+ const kill = vi.spyOn(process, 'kill').mockImplementation(() => true);
+ const adapter = createProcessChaosAdapter({ allowedPids: new Set([123]) });
+ const context = {
+ experiment: {
+ effect: { signal: 'SIGTERM', type: 'kill_process' },
+ safety: { destructive: true },
+ target: { selector: { pid: 123 } },
+ },
+ runId: 'run-process',
+ } as unknown as ChaosRunContext;
+ await expect(adapter.inject(context)).rejects.toThrow('requires uncatchable SIGKILL');
+ expect(kill).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/achaos/process/src/index.ts b/packages/achaos/process/src/index.ts
new file mode 100644
index 00000000000..02a00f638fd
--- /dev/null
+++ b/packages/achaos/process/src/index.ts
@@ -0,0 +1,32 @@
+import type { ChaosAdapter } from '@achaos/core';
+
+export interface ProcessChaosAdapterOptions {
+ allowedPids: ReadonlySet<number>;
+}
+
+/** Destructive adapter with explicit PID ownership; it refuses arbitrary process targets. */
+export const createProcessChaosAdapter = ({
+ allowedPids,
+}: ProcessChaosAdapterOptions): ChaosAdapter => ({
+ inject: async (context) => {
+ const pid = context.experiment.target.selector.pid;
+ if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0)
+ throw new Error('Process target requires a positive integer pid');
+ if (!allowedPids.has(pid)) throw new Error(`PID ${pid} is not owned by this chaos run`);
+ if (!context.experiment.safety.destructive)
+ throw new Error('kill_process requires safety.destructive=true');
+ const effect = context.experiment.effect;
+ if (effect.type !== 'kill_process')
+ throw new Error('Process adapter only supports kill_process');
+ const signal = effect.signal ?? 'SIGKILL';
+ if (signal !== 'SIGKILL')
+ throw new Error(`Process adapter requires uncatchable SIGKILL, received ${signal}`);
+ process.kill(pid, signal);
+ return {
+ adapter: 'process',
+ details: { pid, signal },
+ injectionId: `${context.runId}:process`,
+ };
+ },
+ name: 'process',
+});
diff --git a/packages/achaos/process/tsconfig.json b/packages/achaos/process/tsconfig.json
new file mode 100644
index 00000000000..47f3a97374e
--- /dev/null
+++ b/packages/achaos/process/tsconfig.json
@@ -0,0 +1,5 @@
+{
+ "compilerOptions": { "module": "esnext", "moduleResolution": "bundler" },
+ "extends": "../../../tsconfig.json",
+ "include": ["src/**/*.ts"]
+}
diff --git a/packages/achaos/runner/package.json b/packages/achaos/runner/package.json
new file mode 100644
index 00000000000..360e6158119
--- /dev/null
+++ b/packages/achaos/runner/package.json
@@ -0,0 +1,14 @@
+{
+ "name": "@achaos/runner",
+ "version": "0.0.1",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "main": "./src/index.ts",
+ "dependencies": {
+ "@achaos/core": "workspace:*",
+ "yaml": "^2.8.2"
+ }
+}
diff --git a/packages/achaos/runner/src/index.ts b/packages/achaos/runner/src/index.ts
new file mode 100644
index 00000000000..60b10b7fd37
--- /dev/null
+++ b/packages/achaos/runner/src/index.ts
@@ -0,0 +1,6 @@
+export type { LoadedChaosExperiment } from './load';
+export { loadChaosExperiments } from './load';
+export { ChaosRegistry } from './registry';
+export { formatChaosResult, writeChaosResult } from './reporter';
+export type { RunChaosExperimentOptions } from './run';
+export { runChaosExperiment } from './run';
diff --git a/packages/achaos/runner/src/load.test.ts b/packages/achaos/runner/src/load.test.ts
new file mode 100644
index 00000000000..ceef02be649
--- /dev/null
+++ b/packages/achaos/runner/src/load.test.ts
@@ -0,0 +1,18 @@
+import path from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+import { loadChaosExperiments } from './load';
+
+describe('loadChaosExperiments', () => {
+ it('validates and loads the first-phase YAML fixtures', async () => {
+ const fixtures = await loadChaosExperiments(
+ path.resolve(import.meta.dirname, '../../../../.agents/chaos/fixtures'),
+ );
+ expect(fixtures.map(({ experiment }) => experiment.id)).toEqual([
+ 'tool-failure',
+ 'operation-reclaim',
+ 'duplicate-completion',
+ ]);
+ });
+});
diff --git a/packages/achaos/runner/src/load.ts b/packages/achaos/runner/src/load.ts
new file mode 100644
index 00000000000..00c41002737
--- /dev/null
+++ b/packages/achaos/runner/src/load.ts
@@ -0,0 +1,33 @@
+import { readdir, readFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import type { ChaosExperiment } from '@achaos/core';
+import { chaosExperimentSchema } from '@achaos/core';
+import { parse } from 'yaml';
+
+const walk = async (directory: string): Promise<string[]> => {
+ const entries = await readdir(directory, { withFileTypes: true });
+ const nested = await Promise.all(
+ entries.map(async (entry) => {
+ const entryPath = path.join(directory, entry.name);
+ return entry.isDirectory() ? walk(entryPath) : [entryPath];
+ }),
+ );
+ return nested.flat().filter((filePath) => ['.yaml', '.yml'].includes(path.extname(filePath)));
+};
+
+export interface LoadedChaosExperiment {
+ experiment: ChaosExperiment;
+ filePath: string;
+}
+
+export const loadChaosExperiments = async (directory: string): Promise<LoadedChaosExperiment[]> => {
+ const paths = await walk(directory);
+ return Promise.all(
+ paths.sort().map(async (filePath) => {
+ const raw = parse(await readFile(filePath, 'utf8'));
+ const experiment = chaosExperimentSchema.parse(raw) as ChaosExperiment;
+ return { experiment, filePath };
+ }),
+ );
+};
diff --git a/packages/achaos/runner/src/registry.ts b/packages/achaos/runner/src/registry.ts
new file mode 100644
index 00000000000..93185ac7006
--- /dev/null
+++ b/packages/achaos/runner/src/registry.ts
@@ -0,0 +1,31 @@
+import type { ChaosAdapter, ChaosOracle } from '@achaos/core';
+
+export class ChaosRegistry {
+ readonly #adapters = new Map<string, ChaosAdapter>();
+ readonly #oracles = new Map<string, ChaosOracle>();
+
+ registerAdapter(adapter: ChaosAdapter) {
+ if (this.#adapters.has(adapter.name))
+ throw new Error(`Duplicate chaos adapter: ${adapter.name}`);
+ this.#adapters.set(adapter.name, adapter);
+ return this;
+ }
+
+ registerOracle(oracle: ChaosOracle) {
+ if (this.#oracles.has(oracle.name)) throw new Error(`Duplicate chaos oracle: ${oracle.name}`);
+ this.#oracles.set(oracle.name, oracle);
+ return this;
+ }
+
+ resolveAdapter(name: string) {
+ const adapter = this.#adapters.get(name);
+ if (!adapter) throw new Error(`Unknown chaos adapter: ${name}`);
+ return adapter;
+ }
+
+ resolveOracle(name: string) {
+ const oracle = this.#oracles.get(name);
+ if (!oracle) throw new Error(`Unknown chaos oracle: ${name}`);
+ return oracle;
+ }
+}
diff --git a/packages/achaos/runner/src/reporter.test.ts b/packages/achaos/runner/src/reporter.test.ts
new file mode 100644
index 00000000000..b919f352160
--- /dev/null
+++ b/packages/achaos/runner/src/reporter.test.ts
@@ -0,0 +1,80 @@
+import type { ChaosRunResult } from '@achaos/core';
+import { describe, expect, it } from 'vitest';
+
+import { formatChaosResult } from './reporter';
+
+describe('formatChaosResult', () => {
+ it('emits a versioned machine-readable CI result', () => {
+ const result = {
+ durationMs: 1,
+ experimentId: 'test',
+ finishedAt: '2026-01-01T00:00:00.001Z',
+ injection: {
+ adapter: 'database',
+ cleanupToken: { password: 'secret', row: { private: true } },
+ details: { table: 'operations' },
+ injectionId: 'injection',
+ },
+ oracleResults: [],
+ runId: 'run',
+ seed: 'seed',
+ startedAt: '2026-01-01T00:00:00.000Z',
+ status: 'passed',
+ timeline: [],
+ } as unknown as ChaosRunResult;
+ const report = JSON.parse(formatChaosResult(result));
+ expect(report).toMatchObject({
+ injection: { adapter: 'database', details: { table: 'operations' } },
+ schemaVersion: 1,
+ status: 'passed',
+ });
+ expect(report.injection.cleanupToken).toBeUndefined();
+ expect(formatChaosResult(result)).not.toContain('secret');
+ });
+
+ it('serializes unsupported and cyclic detail values safely', () => {
+ const details: Record<string, unknown> = { sequence: 1n };
+ details.self = details;
+ const result = {
+ durationMs: 1,
+ experimentId: 'test',
+ finishedAt: '2026-01-01T00:00:00.001Z',
+ injection: { adapter: 'custom', details, injectionId: 'injection' },
+ oracleResults: [],
+ runId: 'run',
+ seed: 'seed',
+ startedAt: '2026-01-01T00:00:00.000Z',
+ status: 'passed',
+ timeline: [],
+ } as unknown as ChaosRunResult;
+ expect(() => formatChaosResult(result)).not.toThrow();
+ expect(JSON.parse(formatChaosResult(result)).injection.details).toEqual({
+ self: '[Circular]',
+ sequence: '1n',
+ });
+ });
+
+ it('preserves repeated non-cyclic objects', () => {
+ const shared = { id: 'evidence' };
+ const result = {
+ durationMs: 1,
+ experimentId: 'test',
+ finishedAt: '2026-01-01T00:00:00.001Z',
+ injection: {
+ adapter: 'custom',
+ details: { first: shared, second: shared },
+ injectionId: 'injection',
+ },
+ oracleResults: [],
+ runId: 'run',
+ seed: 'seed',
+ startedAt: '2026-01-01T00:00:00.000Z',
+ status: 'passed',
+ timeline: [],
+ } as ChaosRunResult;
+ expect(JSON.parse(formatChaosResult(result)).injection.details).toEqual({
+ first: { id: 'evidence' },
+ second: { id: 'evidence' },
+ });
+ });
+});
diff --git a/packages/achaos/runner/src/reporter.ts b/packages/achaos/runner/src/reporter.ts
new file mode 100644
index 00000000000..90791cf51d6
--- /dev/null
+++ b/packages/achaos/runner/src/reporter.ts
@@ -0,0 +1,41 @@
+import { writeFile } from 'node:fs/promises';
+
+import type { ChaosRunResult } from '@achaos/core';
+
+const createSafeReplacer = () => {
+ const ancestors: object[] = [];
+ return function (this: object, _key: string, value: unknown) {
+ if (typeof value === 'bigint') return `${value}n`;
+ if (typeof value === 'function' || typeof value === 'symbol')
+ return `[Unsupported ${typeof value}]`;
+ if (value && typeof value === 'object') {
+ while (ancestors.length > 0 && ancestors.at(-1) !== this) ancestors.pop();
+ if (ancestors.includes(value)) return '[Circular]';
+ ancestors.push(value);
+ }
+ return value;
+ };
+};
+
+export const formatChaosResult = (result: ChaosRunResult) =>
+ JSON.stringify(
+ {
+ ...result,
+ ...(result.injection
+ ? {
+ injection: {
+ adapter: result.injection.adapter,
+ details: result.injection.details,
+ injectionId: result.injection.injectionId,
+ },
+ }
+ : {}),
+ schemaVersion: 1,
+ },
+ createSafeReplacer(),
+ 2,
+ );
+
+export const writeChaosResult = async (filePath: string, result: ChaosRunResult) => {
+ await writeFile(filePath, `${formatChaosResult(result)}\n`, 'utf8');
+};
diff --git a/packages/achaos/runner/src/run.test.ts b/packages/achaos/runner/src/run.test.ts
new file mode 100644
index 00000000000..4891eae9ab1
--- /dev/null
+++ b/packages/achaos/runner/src/run.test.ts
@@ -0,0 +1,448 @@
+import type { ChaosExperiment } from '@achaos/core';
+import { describe, expect, it, vi } from 'vitest';
+
+import { ChaosRegistry } from './registry';
+import { runChaosExperiment } from './run';
+
+const experiment: ChaosExperiment = {
+ cleanup: 'always',
+ description: 'test experiment',
+ effect: { errorType: 'Timeout', type: 'throw' },
+ id: 'test-experiment',
+ layer: 'L1-model-runtime',
+ oracles: [{ name: 'healthy' }],
+ safety: { allowedEnvironments: ['test'] },
+ seed: 'seed',
+ target: { adapter: 'test', selector: {} },
+ timeoutMs: 100,
+ trigger: { when: 'immediate' },
+};
+
+const withHealthyOracle = (registry: ChaosRegistry) =>
+ registry.registerOracle({
+ evaluate: async () => ({ message: 'healthy', name: 'healthy', status: 'passed' }),
+ name: 'healthy',
+ });
+
+describe('runChaosExperiment', () => {
+ it('runs injection, exercise, oracle and cleanup with a structured timeline', async () => {
+ const cleanup = vi.fn(async () => {});
+ const registry = new ChaosRegistry()
+ .registerAdapter({
+ cancelInjection: async () => {},
+ cleanup,
+ inject: async ({ runId }) => ({ adapter: 'test', injectionId: runId }),
+ name: 'test',
+ })
+ .registerOracle({
+ evaluate: async () => ({ message: 'healthy', name: 'healthy', status: 'passed' }),
+ name: 'healthy',
+ });
+ const result = await runChaosExperiment({
+ environment: 'test',
+ exercise: async () => {},
+ experiment,
+ registry,
+ runId: 'run-1',
+ });
+ expect(result.status).toBe('passed');
+ expect(result.timeline.map(({ type }) => type)).toEqual([
+ 'run_started',
+ 'fault_injected',
+ 'system_exercised',
+ 'oracle_evaluated',
+ 'cleanup_started',
+ 'cleanup_completed',
+ 'run_completed',
+ ]);
+ expect(cleanup).toHaveBeenCalledOnce();
+ });
+
+ it('defaults programmatic experiments to always cleanup', async () => {
+ const cleanup = vi.fn(async () => {});
+ const registry = new ChaosRegistry()
+ .registerAdapter({
+ cancelInjection: async () => {},
+ cleanup,
+ inject: async ({ runId }) => ({ adapter: 'test', injectionId: runId }),
+ name: 'test',
+ })
+ .registerOracle({
+ evaluate: async () => ({ message: 'healthy', name: 'healthy', status: 'passed' }),
+ name: 'healthy',
+ });
+ const { cleanup: _cleanup, ...withoutCleanup } = experiment;
+ await runChaosExperiment({ environment: 'test', experiment: withoutCleanup, registry });
+ expect(cleanup).toHaveBeenCalledOnce();
+ });
+
+ it('does not run on_success cleanup when an oracle fails', async () => {
+ const cleanup = vi.fn(async () => {});
+ const registry = new ChaosRegistry()
+ .registerAdapter({
+ cancelInjection: async () => {},
+ cleanup,
+ inject: async ({ runId }) => ({ adapter: 'test', injectionId: runId }),
+ name: 'test',
+ })
+ .registerOracle({
+ evaluate: async () => ({ message: 'unhealthy', name: 'healthy', status: 'failed' }),
+ name: 'healthy',
+ });
+ const result = await runChaosExperiment({
+ environment: 'test',
+ experiment: { ...experiment, cleanup: 'on_success' },
+ registry,
+ });
+ expect(result.status).toBe('failed');
+ expect(cleanup).not.toHaveBeenCalled();
+ });
+
+ it('blocks environments outside the blast-radius policy', async () => {
+ const registry = new ChaosRegistry().registerAdapter({ inject: vi.fn(), name: 'test' });
+ const result = await runChaosExperiment({ environment: 'production', experiment, registry });
+ expect(result.status).toBe('aborted');
+ expect(result.error?.name).toBe('ChaosSafetyError');
+ });
+
+ it('requires explicit external approval for production', async () => {
+ const inject = vi.fn(async () => ({ adapter: 'test', injectionId: 'production' }));
+ const registry = new ChaosRegistry().registerAdapter({ inject, name: 'test' }).registerOracle({
+ evaluate: async () => ({ message: 'healthy', name: 'healthy', status: 'passed' }),
+ name: 'healthy',
+ });
+ const productionExperiment: ChaosExperiment = {
+ ...experiment,
+ cleanup: 'never',
+ safety: { allowedEnvironments: ['production'] },
+ };
+ const blocked = await runChaosExperiment({
+ environment: 'production',
+ experiment: productionExperiment,
+ registry,
+ });
+ expect(blocked.status).toBe('aborted');
+ expect(blocked.error?.name).toBe('ChaosApprovalError');
+ expect(inject).not.toHaveBeenCalled();
+
+ const approveProduction = vi.fn(async () => true);
+ const approved = await runChaosExperiment({
+ approveProduction,
+ environment: 'production',
+ experiment: productionExperiment,
+ registry,
+ });
+ expect(approved.status).toBe('passed');
+ expect(approveProduction).toHaveBeenCalledOnce();
+ expect(inject).toHaveBeenCalledOnce();
+
+ const startedAt = Date.now();
+ const timedOut = await runChaosExperiment({
+ approveProduction: async () => new Promise<boolean>(() => {}),
+ environment: 'production',
+ experiment: { ...productionExperiment, timeoutMs: 5 },
+ registry,
+ });
+ expect(timedOut.status).toBe('aborted');
+ expect(Date.now() - startedAt).toBeLessThan(1000);
+ expect(inject).toHaveBeenCalledOnce();
+ });
+
+ it('treats unknown production aliases conservatively', async () => {
+ const inject = vi.fn();
+ const registry = withHealthyOracle(
+ new ChaosRegistry().registerAdapter({ inject, name: 'test' }),
+ );
+ const result = await runChaosExperiment({
+ environment: 'live',
+ experiment: { ...experiment, safety: { allowedEnvironments: ['live'] } },
+ registry,
+ });
+ expect(result.status).toBe('aborted');
+ expect(result.error?.name).toBe('ChaosApprovalError');
+ expect(inject).not.toHaveBeenCalled();
+ });
+
+ it('fails when an adapter reports that its fault never activated', async () => {
+ const cleanup = vi.fn(async () => {});
+ const registry = withHealthyOracle(
+ new ChaosRegistry().registerAdapter({
+ cancelInjection: async () => {},
+ cleanup,
+ inject: async () => ({ adapter: 'test', injectionId: 'inactive' }),
+ name: 'test',
+ verifyInjection: async () => false,
+ }),
+ );
+ const result = await runChaosExperiment({ environment: 'test', experiment, registry });
+ expect(result.status).toBe('failed');
+ expect(result.error?.name).toBe('ChaosInjectionNotActivatedError');
+ expect(cleanup).toHaveBeenCalledOnce();
+ });
+
+ it('rejects a programmatic experiment without an oracle', async () => {
+ const registry = new ChaosRegistry().registerAdapter({ inject: vi.fn(), name: 'test' });
+ const result = await runChaosExperiment({
+ environment: 'test',
+ experiment: { ...experiment, oracles: [] },
+ registry,
+ });
+ expect(result.status).toBe('aborted');
+ expect(result.error?.name).toBe('ChaosConfigError');
+ });
+
+ it('validates numeric constraints on programmatic experiments', async () => {
+ const inject = vi.fn();
+ const registry = new ChaosRegistry().registerAdapter({ inject, name: 'test' });
+ const result = await runChaosExperiment({
+ environment: 'test',
+ experiment: {
+ ...experiment,
+ effect: { count: 0, type: 'duplicate' },
+ } as ChaosExperiment,
+ registry,
+ });
+ expect(result.status).toBe('aborted');
+ expect(result.error?.name).toBe('ChaosConfigError');
+ expect(inject).not.toHaveBeenCalled();
+ });
+
+ it('returns a structured configuration failure for an unknown adapter', async () => {
+ const result = await runChaosExperiment({
+ environment: 'test',
+ experiment,
+ registry: new ChaosRegistry(),
+ });
+ expect(result.status).toBe('aborted');
+ expect(result.error?.name).toBe('ChaosConfigError');
+ expect(result.timeline.at(-1)).toEqual(
+ expect.objectContaining({
+ data: { reason: 'adapter_not_registered' },
+ type: 'run_completed',
+ }),
+ );
+ });
+
+ it('preflights oracle registrations before injecting a fault', async () => {
+ const inject = vi.fn(async () => ({ adapter: 'process', injectionId: 'destructive' }));
+ const registry = new ChaosRegistry().registerAdapter({ inject, name: 'test' });
+ const result = await runChaosExperiment({
+ environment: 'test',
+ experiment: { ...experiment, cleanup: 'never' },
+ registry,
+ });
+ expect(result.status).toBe('aborted');
+ expect(result.error?.name).toBe('ChaosConfigError');
+ expect(inject).not.toHaveBeenCalled();
+ });
+
+ it('rejects cleanup adapters without a cancellable injection contract', async () => {
+ const inject = vi.fn();
+ const registry = new ChaosRegistry().registerAdapter({
+ cleanup: async () => {},
+ inject,
+ name: 'test',
+ });
+ const result = await runChaosExperiment({ environment: 'test', experiment, registry });
+ expect(result.status).toBe('aborted');
+ expect(result.error?.name).toBe('ChaosConfigError');
+ expect(inject).not.toHaveBeenCalled();
+ });
+
+ it('rejects cleanup policies unsupported by an irreversible adapter', async () => {
+ const inject = vi.fn();
+ const registry = new ChaosRegistry().registerAdapter({ inject, name: 'test' });
+ const result = await runChaosExperiment({ environment: 'test', experiment, registry });
+ expect(result.status).toBe('aborted');
+ expect(result.error?.name).toBe('ChaosConfigError');
+ expect(inject).not.toHaveBeenCalled();
+ });
+
+ it('reports an unselected probabilistic trigger as inconclusive', async () => {
+ const inject = vi.fn();
+ const registry = withHealthyOracle(
+ new ChaosRegistry().registerAdapter({ inject, name: 'test' }),
+ );
+ const result = await runChaosExperiment({
+ environment: 'test',
+ experiment: {
+ ...experiment,
+ cleanup: 'never',
+ trigger: { probability: 0, when: 'immediate' },
+ },
+ registry,
+ });
+ expect(result.status).toBe('inconclusive');
+ expect(inject).not.toHaveBeenCalled();
+ });
+
+ it('reports broken registrations before probabilistic sampling', async () => {
+ const result = await runChaosExperiment({
+ environment: 'test',
+ experiment: { ...experiment, trigger: { probability: 0, when: 'immediate' } },
+ registry: new ChaosRegistry(),
+ });
+ expect(result.status).toBe('aborted');
+ expect(result.error?.name).toBe('ChaosConfigError');
+ });
+
+ it('honors an after trigger by exercising the system before injection', async () => {
+ const order: string[] = [];
+ const registry = new ChaosRegistry()
+ .registerAdapter({
+ inject: async ({ runId }) => {
+ order.push('inject');
+ return { adapter: 'test', injectionId: runId };
+ },
+ name: 'test',
+ })
+ .registerOracle({
+ evaluate: async () => ({ message: 'healthy', name: 'healthy', status: 'passed' }),
+ name: 'healthy',
+ });
+ await runChaosExperiment({
+ environment: 'test',
+ exercise: async () => {
+ order.push('exercise');
+ },
+ experiment: { ...experiment, cleanup: 'never', trigger: { when: 'after' } },
+ registry,
+ });
+ expect(order).toEqual(['exercise', 'inject']);
+ });
+
+ it('passes each oracle specification to its evaluator', async () => {
+ const evaluate = vi.fn(async () => ({
+ message: 'healthy',
+ name: 'healthy',
+ status: 'passed' as const,
+ }));
+ const registry = new ChaosRegistry()
+ .registerAdapter({
+ inject: async () => ({ adapter: 'test', injectionId: 'params' }),
+ name: 'test',
+ })
+ .registerOracle({ evaluate, name: 'healthy' });
+ const oracle = { name: 'healthy', params: { recoveryBoundMs: 500 } };
+ await runChaosExperiment({
+ environment: 'test',
+ experiment: { ...experiment, cleanup: 'never', oracles: [oracle] },
+ registry,
+ });
+ expect(evaluate).toHaveBeenCalledWith(expect.any(Object), oracle);
+ });
+
+ it('aborts a timed-out phase and gives cleanup a fresh signal', async () => {
+ let phaseWasAborted = false;
+ let cleanupWasAborted = true;
+ const registry = withHealthyOracle(
+ new ChaosRegistry().registerAdapter({
+ cancelInjection: async () => {},
+ cleanup: async (_receipt, context) => {
+ cleanupWasAborted = context.signal.aborted;
+ },
+ inject: async (context) => ({ adapter: 'test', injectionId: context.runId }),
+ name: 'test',
+ }),
+ );
+ const result = await runChaosExperiment({
+ environment: 'test',
+ exercise: async (context) =>
+ new Promise<void>((resolve) => {
+ context.signal.addEventListener(
+ 'abort',
+ () => {
+ phaseWasAborted = true;
+ resolve();
+ },
+ { once: true },
+ );
+ }),
+ experiment: { ...experiment, timeoutMs: 5 },
+ registry,
+ });
+ expect(result.status).toBe('failed');
+ expect(phaseWasAborted).toBe(true);
+ expect(cleanupWasAborted).toBe(false);
+ });
+
+ it('cancels an injection that would otherwise commit after its timeout', async () => {
+ let canceled = false;
+ let mutationCommitted = false;
+ const cleanup = vi.fn(async () => {});
+ const registry = withHealthyOracle(
+ new ChaosRegistry().registerAdapter({
+ cancelInjection: async () => {
+ canceled = true;
+ },
+ cleanup,
+ inject: async (context) => {
+ await new Promise((resolve) => setTimeout(resolve, 15));
+ if (canceled) throw new Error('mutation canceled');
+ mutationCommitted = true;
+ return { adapter: 'test', injectionId: context.runId };
+ },
+ name: 'test',
+ }),
+ );
+ const result = await runChaosExperiment({
+ environment: 'test',
+ experiment: { ...experiment, timeoutMs: 10 },
+ registry,
+ });
+ expect(result.status).toBe('failed');
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(canceled).toBe(true);
+ expect(mutationCommitted).toBe(false);
+ expect(cleanup).not.toHaveBeenCalled();
+ expect(result.injection).toBeUndefined();
+ });
+
+ it('bounds cancellation when a timed-out injection never settles', async () => {
+ const cancelInjection = vi.fn(async () => {});
+ const cleanup = vi.fn(async () => {});
+ const registry = withHealthyOracle(
+ new ChaosRegistry().registerAdapter({
+ cancelInjection,
+ cleanup,
+ inject: async () => new Promise<never>(() => {}),
+ name: 'test',
+ }),
+ );
+ const startedAt = Date.now();
+ const result = await runChaosExperiment({
+ environment: 'test',
+ experiment: { ...experiment, timeoutMs: 5 },
+ registry,
+ });
+ expect(result.status).toBe('failed');
+ expect(Date.now() - startedAt).toBeLessThan(1000);
+ expect(cancelInjection).toHaveBeenCalledOnce();
+ expect(cleanup).not.toHaveBeenCalled();
+ });
+
+ it('preserves both a phase failure and a cleanup failure', async () => {
+ const registry = withHealthyOracle(
+ new ChaosRegistry().registerAdapter({
+ cancelInjection: async () => {},
+ cleanup: async () => {
+ throw new Error('restore failed');
+ },
+ inject: async () => ({ adapter: 'test', injectionId: 'aggregate' }),
+ name: 'test',
+ }),
+ );
+ const result = await runChaosExperiment({
+ environment: 'test',
+ exercise: async () => {
+ throw new Error('exercise failed');
+ },
+ experiment,
+ registry,
+ });
+ expect(result.status).toBe('failed');
+ expect(result.error?.name).toBe('ChaosAggregateError');
+ expect(result.error?.message).toContain('exercise failed');
+ expect(result.error?.message).toContain('restore failed');
+ });
+});
diff --git a/packages/achaos/runner/src/run.ts b/packages/achaos/runner/src/run.ts
new file mode 100644
index 00000000000..a5515dccbaf
--- /dev/null
+++ b/packages/achaos/runner/src/run.ts
@@ -0,0 +1,384 @@
+import { randomUUID } from 'node:crypto';
+
+import type {
+ ChaosAdapter,
+ ChaosExercise,
+ ChaosExperiment,
+ ChaosInjectionReceipt,
+ ChaosOracle,
+ ChaosOracleResult,
+ ChaosOracleSpec,
+ ChaosRunContext,
+ ChaosRunResult,
+ ChaosTimelineEvent,
+ ChaosTimelineEventType,
+} from '@achaos/core';
+import { chaosExperimentSchema, createSeededRandom } from '@achaos/core';
+
+import type { ChaosRegistry } from './registry';
+
+const serializeError = (error: unknown) => {
+ if (error instanceof Error) return { message: error.message, name: error.name };
+ return { message: String(error), name: 'Error' };
+};
+
+const combineErrors = (primary: unknown, secondary: unknown, secondaryLabel: string) => {
+ const primaryFailure = serializeError(primary);
+ const secondaryFailure = serializeError(secondary);
+ const aggregateError = new Error(
+ `Chaos phase failed: ${primaryFailure.name}: ${primaryFailure.message}; ${secondaryLabel} also failed: ${secondaryFailure.name}: ${secondaryFailure.message}`,
+ );
+ aggregateError.name = 'ChaosAggregateError';
+ return aggregateError;
+};
+
+const reportableInjection = (injection: ChaosInjectionReceipt) => ({
+ adapter: injection.adapter,
+ details: injection.details,
+ injectionId: injection.injectionId,
+});
+
+const withTimeout = async <T>(
+ promise: Promise<T>,
+ timeoutMs: number,
+ controller: AbortController,
+) => {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let rejectOnAbort: (() => void) | undefined;
+ try {
+ return await Promise.race([
+ promise,
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => {
+ const error = new Error(`Chaos phase timed out after ${timeoutMs}ms`);
+ controller.abort(error);
+ reject(error);
+ }, timeoutMs);
+ rejectOnAbort = () => reject(controller.signal.reason);
+ controller.signal.addEventListener('abort', rejectOnAbort, { once: true });
+ }),
+ ]);
+ } finally {
+ clearTimeout(timer);
+ if (rejectOnAbort) controller.signal.removeEventListener('abort', rejectOnAbort);
+ }
+};
+
+export interface RunChaosExperimentOptions {
+ approveProduction?: (context: ChaosRunContext) => Promise<boolean>;
+ environment: string;
+ /** Explicit host classification. Unknown environment names default to production-safe handling. */
+ environmentTier?: 'non-production' | 'production';
+ exercise?: ChaosExercise;
+ experiment: ChaosExperiment;
+ now?: () => Date;
+ registry: ChaosRegistry;
+ runId?: string;
+}
+
+export const runChaosExperiment = async ({
+ approveProduction,
+ environment,
+ environmentTier,
+ exercise,
+ experiment,
+ now = () => new Date(),
+ registry,
+ runId = randomUUID(),
+}: RunChaosExperimentOptions): Promise<ChaosRunResult> => {
+ const started = now();
+ const timeline: ChaosTimelineEvent[] = [];
+ const oracleResults: ChaosOracleResult[] = [];
+ const controller = new AbortController();
+ const record = (type: ChaosTimelineEventType, data?: Record<string, unknown>) =>
+ timeline.push({ at: now().toISOString(), data, type });
+
+ record('run_started', { environment });
+
+ const parsedExperiment = chaosExperimentSchema.safeParse(experiment);
+ if (!parsedExperiment.success) {
+ const finishedAt = now();
+ record('run_completed', { reason: 'invalid_experiment' });
+ return {
+ durationMs: finishedAt.getTime() - started.getTime(),
+ error: { message: parsedExperiment.error.message, name: 'ChaosConfigError' },
+ experimentId: experiment.id,
+ finishedAt: finishedAt.toISOString(),
+ oracleResults,
+ runId,
+ seed: experiment.seed,
+ startedAt: started.toISOString(),
+ status: 'aborted',
+ timeline,
+ };
+ }
+ experiment = parsedExperiment.data;
+
+ const context: ChaosRunContext = {
+ environment,
+ experiment,
+ random: createSeededRandom(experiment.seed),
+ runId,
+ signal: controller.signal,
+ };
+
+ if (!experiment.safety.allowedEnvironments.includes(environment)) {
+ const finishedAt = now();
+ record('run_completed', { reason: 'environment_not_allowed' });
+ return {
+ durationMs: finishedAt.getTime() - started.getTime(),
+ error: { message: `Environment ${environment} is not allowed`, name: 'ChaosSafetyError' },
+ experimentId: experiment.id,
+ finishedAt: finishedAt.toISOString(),
+ oracleResults,
+ runId,
+ seed: experiment.seed,
+ startedAt: started.toISOString(),
+ status: 'aborted',
+ timeline,
+ };
+ }
+
+ const knownNonProductionEnvironments = new Set(['ci', 'development', 'local', 'staging', 'test']);
+ const resolvedEnvironmentTier =
+ environmentTier ??
+ (knownNonProductionEnvironments.has(environment) ? 'non-production' : 'production');
+ if (resolvedEnvironmentTier === 'production') {
+ const approved = approveProduction
+ ? await withTimeout(approveProduction(context), experiment.timeoutMs, controller).catch(
+ () => false,
+ )
+ : false;
+ if (!approved) {
+ const finishedAt = now();
+ record('run_completed', { reason: 'production_approval_required' });
+ return {
+ durationMs: finishedAt.getTime() - started.getTime(),
+ error: {
+ message: 'Production chaos requires explicit external approval',
+ name: 'ChaosApprovalError',
+ },
+ experimentId: experiment.id,
+ finishedAt: finishedAt.toISOString(),
+ oracleResults,
+ runId,
+ seed: experiment.seed,
+ startedAt: started.toISOString(),
+ status: 'aborted',
+ timeline,
+ };
+ }
+ }
+
+ if (experiment.oracles.length === 0) {
+ const finishedAt = now();
+ record('run_completed', { reason: 'oracle_required' });
+ return {
+ durationMs: finishedAt.getTime() - started.getTime(),
+ error: { message: 'Chaos experiments require at least one oracle', name: 'ChaosConfigError' },
+ experimentId: experiment.id,
+ finishedAt: finishedAt.toISOString(),
+ oracleResults,
+ runId,
+ seed: experiment.seed,
+ startedAt: started.toISOString(),
+ status: 'aborted',
+ timeline,
+ };
+ }
+
+ let adapter: ChaosAdapter;
+ try {
+ adapter = registry.resolveAdapter(experiment.target.adapter);
+ } catch (adapterError) {
+ const finishedAt = now();
+ record('run_completed', { reason: 'adapter_not_registered' });
+ return {
+ durationMs: finishedAt.getTime() - started.getTime(),
+ error: { ...serializeError(adapterError), name: 'ChaosConfigError' },
+ experimentId: experiment.id,
+ finishedAt: finishedAt.toISOString(),
+ oracleResults,
+ runId,
+ seed: experiment.seed,
+ startedAt: started.toISOString(),
+ status: 'aborted',
+ timeline,
+ };
+ }
+ const cleanupPolicy = experiment.cleanup ?? 'always';
+ if (cleanupPolicy !== 'never' && !adapter.cleanup) {
+ const finishedAt = now();
+ record('run_completed', { reason: 'cleanup_not_supported' });
+ return {
+ durationMs: finishedAt.getTime() - started.getTime(),
+ error: {
+ message: `Adapter ${adapter.name} does not support cleanup policy ${cleanupPolicy}`,
+ name: 'ChaosConfigError',
+ },
+ experimentId: experiment.id,
+ finishedAt: finishedAt.toISOString(),
+ oracleResults,
+ runId,
+ seed: experiment.seed,
+ startedAt: started.toISOString(),
+ status: 'aborted',
+ timeline,
+ };
+ }
+ if (adapter.cleanup && !adapter.cancelInjection) {
+ const finishedAt = now();
+ record('run_completed', { reason: 'cancellable_injection_required' });
+ return {
+ durationMs: finishedAt.getTime() - started.getTime(),
+ error: {
+ message: `Adapter ${adapter.name} provides cleanup but no cancellable injection contract`,
+ name: 'ChaosConfigError',
+ },
+ experimentId: experiment.id,
+ finishedAt: finishedAt.toISOString(),
+ oracleResults,
+ runId,
+ seed: experiment.seed,
+ startedAt: started.toISOString(),
+ status: 'aborted',
+ timeline,
+ };
+ }
+ let registeredOracles: Array<{ oracle: ChaosOracle; spec: ChaosOracleSpec }>;
+ try {
+ registeredOracles = experiment.oracles.map((spec) => ({
+ oracle: registry.resolveOracle(spec.name),
+ spec,
+ }));
+ } catch (oracleError) {
+ const finishedAt = now();
+ record('run_completed', { reason: 'oracle_not_registered' });
+ return {
+ durationMs: finishedAt.getTime() - started.getTime(),
+ error: { ...serializeError(oracleError), name: 'ChaosConfigError' },
+ experimentId: experiment.id,
+ finishedAt: finishedAt.toISOString(),
+ oracleResults,
+ runId,
+ seed: experiment.seed,
+ startedAt: started.toISOString(),
+ status: 'aborted',
+ timeline,
+ };
+ }
+ const probability = experiment.trigger.probability ?? 1;
+ if (context.random() >= probability) {
+ const finishedAt = now();
+ record('run_completed', { reason: 'trigger_not_selected', status: 'inconclusive' });
+ controller.abort('chaos_run_skipped');
+ return {
+ durationMs: finishedAt.getTime() - started.getTime(),
+ experimentId: experiment.id,
+ finishedAt: finishedAt.toISOString(),
+ oracleResults,
+ runId,
+ seed: experiment.seed,
+ startedAt: started.toISOString(),
+ status: 'inconclusive',
+ timeline,
+ };
+ }
+ let injection;
+ let injectionPromise: ReturnType<typeof adapter.inject> | undefined;
+ let error: unknown;
+
+ try {
+ const runExercise = async () => {
+ if (!exercise) return;
+ await withTimeout(exercise(context), experiment.timeoutMs, controller);
+ record('system_exercised');
+ };
+ if (experiment.trigger.when === 'after') await runExercise();
+
+ injectionPromise = adapter.inject(context);
+ injection = await withTimeout(injectionPromise, experiment.timeoutMs, controller);
+ record('fault_injected', { adapter: adapter.name, injectionId: injection.injectionId });
+
+ if (experiment.trigger.when !== 'after') await runExercise();
+ if (
+ adapter.verifyInjection &&
+ !(await withTimeout(
+ adapter.verifyInjection(injection, context),
+ experiment.timeoutMs,
+ controller,
+ ))
+ ) {
+ const activationError = new Error('Injected chaos fault did not activate');
+ activationError.name = 'ChaosInjectionNotActivatedError';
+ throw activationError;
+ }
+ for (const { oracle, spec } of registeredOracles) {
+ const result = await withTimeout(
+ oracle.evaluate(context, spec),
+ spec.timeoutMs ?? experiment.timeoutMs,
+ controller,
+ );
+ oracleResults.push(result);
+ record('oracle_evaluated', { name: result.name, status: result.status });
+ }
+ } catch (caught) {
+ error = caught;
+ } finally {
+ if (!injection && injectionPromise && adapter.cancelInjection) {
+ try {
+ const cancellationController = new AbortController();
+ await withTimeout(
+ adapter.cancelInjection({ ...context, signal: cancellationController.signal }),
+ experiment.timeoutMs,
+ cancellationController,
+ );
+ } catch (cancellationError) {
+ error = error
+ ? combineErrors(error, cancellationError, 'injection cancellation')
+ : cancellationError;
+ }
+ }
+ const oraclesPassed = oracleResults.every(({ status }) => status === 'passed');
+ const shouldCleanup =
+ injection &&
+ adapter.cleanup &&
+ (cleanupPolicy === 'always' || (cleanupPolicy === 'on_success' && !error && oraclesPassed));
+ if (shouldCleanup) {
+ record('cleanup_started');
+ try {
+ const cleanupController = new AbortController();
+ await withTimeout(
+ adapter.cleanup!(injection!, { ...context, signal: cleanupController.signal }),
+ experiment.timeoutMs,
+ cleanupController,
+ );
+ record('cleanup_completed');
+ } catch (cleanupError) {
+ error = error ? combineErrors(error, cleanupError, 'cleanup') : cleanupError;
+ }
+ }
+ controller.abort('chaos_run_completed');
+ }
+
+ const hasFailedOracle = oracleResults.some(({ status }) => status === 'failed');
+ const hasInconclusiveOracle = oracleResults.some(({ status }) => status === 'inconclusive');
+ const status =
+ error || hasFailedOracle ? 'failed' : hasInconclusiveOracle ? 'inconclusive' : 'passed';
+ const finishedAt = now();
+ record('run_completed', { status });
+
+ return {
+ durationMs: finishedAt.getTime() - started.getTime(),
+ ...(error ? { error: serializeError(error) } : {}),
+ experimentId: experiment.id,
+ finishedAt: finishedAt.toISOString(),
+ ...(injection ? { injection: reportableInjection(injection) } : {}),
+ oracleResults,
+ runId,
+ seed: experiment.seed,
+ startedAt: started.toISOString(),
+ status,
+ timeline,
+ };
+};
diff --git a/packages/achaos/runner/tsconfig.json b/packages/achaos/runner/tsconfig.json
new file mode 100644
index 00000000000..47f3a97374e
--- /dev/null
+++ b/packages/achaos/runner/tsconfig.json
@@ -0,0 +1,5 @@
+{
+ "compilerOptions": { "module": "esnext", "moduleResolution": "bundler" },
+ "extends": "../../../tsconfig.json",
+ "include": ["src/**/*.ts"]
+}
diff --git a/packages/achaos/runtime/package.json b/packages/achaos/runtime/package.json
new file mode 100644
index 00000000000..0a76593ec57
--- /dev/null
+++ b/packages/achaos/runtime/package.json
@@ -0,0 +1,14 @@
+{
+ "name": "@achaos/runtime",
+ "version": "0.0.1",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "main": "./src/index.ts",
+ "dependencies": {
+ "@achaos/core": "workspace:*",
+ "@lobechat/agent-runtime": "workspace:*"
+ }
+}
diff --git a/packages/achaos/runtime/src/adapter.ts b/packages/achaos/runtime/src/adapter.ts
new file mode 100644
index 00000000000..ed72e1fe2db
--- /dev/null
+++ b/packages/achaos/runtime/src/adapter.ts
@@ -0,0 +1,11 @@
+import type { ChaosAdapter } from '@achaos/core';
+
+import type { RuntimeChaosController } from './controller';
+
+export const createRuntimeChaosAdapter = (controller: RuntimeChaosController): ChaosAdapter => ({
+ cancelInjection: async (context) => controller.cancelRun(context.runId),
+ cleanup: async (receipt) => controller.disarm(receipt),
+ inject: async (context) => controller.arm(context),
+ name: 'runtime',
+ verifyInjection: async (receipt) => controller.wasActivated(receipt),
+});
diff --git a/packages/achaos/runtime/src/assets.d.ts b/packages/achaos/runtime/src/assets.d.ts
new file mode 100644
index 00000000000..f73d61b396c
--- /dev/null
+++ b/packages/achaos/runtime/src/assets.d.ts
@@ -0,0 +1,4 @@
+declare module '*.md' {
+ const content: string;
+ export default content;
+}
diff --git a/packages/achaos/runtime/src/completion.ts b/packages/achaos/runtime/src/completion.ts
new file mode 100644
index 00000000000..1e4b84b5394
--- /dev/null
+++ b/packages/achaos/runtime/src/completion.ts
@@ -0,0 +1,28 @@
+import type { RuntimeChaosController } from './controller';
+import { delayWithAbort } from './effects';
+
+export interface CompletionEvent {
+ operationId: string;
+ payload: unknown;
+}
+
+/** Applies deterministic drop/duplicate/delay effects to completion delivery. */
+export const deliverCompletionWithChaos = async (
+ controller: RuntimeChaosController,
+ event: CompletionEvent,
+ deliver: (event: CompletionEvent) => Promise<void>,
+) => {
+ const activations = controller.activationsFor({
+ operationId: event.operationId,
+ phase: 'completion',
+ });
+ let deliveries = 1;
+ for (const { effect, markApplied, signal } of activations) {
+ markApplied();
+ if (effect.type === 'drop') return;
+ if (effect.type === 'delay') await delayWithAbort(effect.durationMs, signal);
+ if (effect.type === 'duplicate') deliveries = effect.count;
+ if (effect.type === 'throw') throw new Error(effect.message ?? effect.errorType);
+ }
+ for (let index = 0; index < deliveries; index += 1) await deliver(event);
+};
diff --git a/packages/achaos/runtime/src/controller.ts b/packages/achaos/runtime/src/controller.ts
new file mode 100644
index 00000000000..34831e6ec6c
--- /dev/null
+++ b/packages/achaos/runtime/src/controller.ts
@@ -0,0 +1,129 @@
+import type { ChaosEffect, ChaosInjectionReceipt, ChaosRunContext } from '@achaos/core';
+
+export interface RuntimeChaosPoint {
+ apiName?: string;
+ callIndex?: number;
+ operationId: string;
+ phase: 'before_tool_call' | 'completion' | 'tool_attempt';
+ stepIndex?: number;
+}
+
+interface ArmedFault {
+ abort: AbortController;
+ activations: number;
+ claims: number;
+ detachParentAbort: () => void;
+ effect: ChaosEffect;
+ injectionId: string;
+ maxInjections: number;
+ selector: Record<string, unknown>;
+}
+
+export interface RuntimeChaosActivation {
+ effect: ChaosEffect;
+ markApplied: () => void;
+ release: () => void;
+ signal: AbortSignal;
+}
+
+const matches = (point: RuntimeChaosPoint, selector: Record<string, unknown>) =>
+ Object.entries(selector).every(([key, value]) => point[key as keyof RuntimeChaosPoint] === value);
+
+const supports = (phase: RuntimeChaosPoint['phase'], effect: ChaosEffect) => {
+ if (phase === 'before_tool_call')
+ return effect.type === 'delay' || effect.type === 'drop' || effect.type === 'replace_result';
+ if (phase === 'completion')
+ return (
+ effect.type === 'delay' ||
+ effect.type === 'drop' ||
+ effect.type === 'duplicate' ||
+ effect.type === 'throw'
+ );
+ return effect.type === 'delay' || effect.type === 'drop' || effect.type === 'throw';
+};
+
+/** Operation-scoped deterministic fault controller consumed by Runtime hook adapters. */
+export class RuntimeChaosController {
+ readonly #faults = new Map<string, ArmedFault>();
+
+ arm(context: ChaosRunContext): ChaosInjectionReceipt {
+ const injectionId = `${context.runId}:runtime`;
+ const abort = new AbortController();
+ const onParentAbort = () => {
+ abort.abort(context.signal.reason);
+ this.#faults.delete(injectionId);
+ };
+ context.signal.addEventListener('abort', onParentAbort, { once: true });
+ this.#faults.set(injectionId, {
+ abort,
+ activations: 0,
+ claims: 0,
+ detachParentAbort: () => context.signal.removeEventListener('abort', onParentAbort),
+ effect: context.experiment.effect,
+ injectionId,
+ maxInjections: context.experiment.safety.maxInjections ?? Number.POSITIVE_INFINITY,
+ selector: context.experiment.target.selector,
+ });
+ return { adapter: 'runtime', cleanupToken: { injectionId }, injectionId };
+ }
+
+ disarm(receipt: ChaosInjectionReceipt) {
+ const injectionId = receipt.cleanupToken?.injectionId;
+ if (typeof injectionId !== 'string') return;
+ const fault = this.#faults.get(injectionId);
+ if (!fault) return;
+ fault.abort.abort(new Error('Chaos fault disarmed'));
+ fault.detachParentAbort();
+ this.#faults.delete(injectionId);
+ }
+
+ cancelRun(runId: string) {
+ const fault = this.#faults.get(`${runId}:runtime`);
+ if (!fault) return;
+ this.disarm({
+ adapter: 'runtime',
+ cleanupToken: { injectionId: fault.injectionId },
+ injectionId: fault.injectionId,
+ });
+ }
+
+ wasActivated(receipt: ChaosInjectionReceipt) {
+ const injectionId = receipt.cleanupToken?.injectionId;
+ return typeof injectionId === 'string' && (this.#faults.get(injectionId)?.activations ?? 0) > 0;
+ }
+
+ activationsFor(point: RuntimeChaosPoint): RuntimeChaosActivation[] {
+ const activations: RuntimeChaosActivation[] = [];
+ for (const [injectionId, fault] of this.#faults) {
+ if (fault.abort.signal.aborted) {
+ fault.detachParentAbort();
+ this.#faults.delete(injectionId);
+ continue;
+ }
+ if (
+ !matches(point, fault.selector) ||
+ !supports(point.phase, fault.effect) ||
+ fault.claims >= fault.maxInjections
+ )
+ continue;
+ fault.claims += 1;
+ let applied = false;
+ activations.push({
+ effect: fault.effect,
+ markApplied: () => {
+ if (applied) return;
+ applied = true;
+ fault.activations += 1;
+ },
+ release: () => {
+ if (applied) return;
+ applied = true;
+ fault.claims -= 1;
+ },
+ signal: fault.abort.signal,
+ });
+ break;
+ }
+ return activations;
+ }
+}
diff --git a/packages/achaos/runtime/src/effects.ts b/packages/achaos/runtime/src/effects.ts
new file mode 100644
index 00000000000..04f8a0f1fa2
--- /dev/null
+++ b/packages/achaos/runtime/src/effects.ts
@@ -0,0 +1,15 @@
+export const delayWithAbort = async (durationMs: number, signal: AbortSignal) => {
+ if (signal.aborted) throw signal.reason;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let onAbort: (() => void) | undefined;
+ try {
+ await new Promise<void>((resolve, reject) => {
+ timer = setTimeout(resolve, durationMs);
+ onAbort = () => reject(signal.reason);
+ signal.addEventListener('abort', onAbort, { once: true });
+ });
+ } finally {
+ clearTimeout(timer);
+ if (onAbort) signal.removeEventListener('abort', onAbort);
+ }
+};
diff --git a/packages/achaos/runtime/src/index.ts b/packages/achaos/runtime/src/index.ts
new file mode 100644
index 00000000000..23f221336a3
--- /dev/null
+++ b/packages/achaos/runtime/src/index.ts
@@ -0,0 +1,9 @@
+export { createRuntimeChaosAdapter } from './adapter';
+export type { CompletionEvent } from './completion';
+export { deliverCompletionWithChaos } from './completion';
+export type { RuntimeChaosPoint } from './controller';
+export { RuntimeChaosController } from './controller';
+export type { ToolAttemptChaosPoint } from './toolAttempt';
+export { executeToolAttemptWithChaos } from './toolAttempt';
+export type { MutableToolCallEvent, RuntimeChaosHook } from './toolHook';
+export { createBeforeToolCallChaosHandler, createRuntimeChaosHooks } from './toolHook';
diff --git a/packages/achaos/runtime/src/runtime.test.ts b/packages/achaos/runtime/src/runtime.test.ts
new file mode 100644
index 00000000000..346a653767a
--- /dev/null
+++ b/packages/achaos/runtime/src/runtime.test.ts
@@ -0,0 +1,318 @@
+import type { ChaosExperiment, ChaosRunContext } from '@achaos/core';
+import { createSeededRandom } from '@achaos/core';
+import type { AgentHookEvent, AgentHookType } from '@lobechat/agent-runtime/src/types/hooks';
+import { executeToolWithRetry } from '@lobechat/agent-runtime/src/utils/runtimeRetry';
+import { describe, expect, it, vi } from 'vitest';
+
+import { createRuntimeChaosAdapter } from './adapter';
+import { deliverCompletionWithChaos } from './completion';
+import { RuntimeChaosController } from './controller';
+import { executeToolAttemptWithChaos } from './toolAttempt';
+import { createBeforeToolCallChaosHandler, createRuntimeChaosHooks } from './toolHook';
+
+const contextFor = (
+ effect: ChaosExperiment['effect'],
+ selector: Record<string, unknown>,
+ options?: { maxInjections?: number; runId?: string; signal?: AbortSignal },
+): ChaosRunContext => ({
+ environment: 'test',
+ experiment: {
+ cleanup: 'always',
+ description: 'runtime fault',
+ effect,
+ id: 'runtime-fault',
+ layer: 'L2-agent-runtime',
+ oracles: [{ name: 'noop' }],
+ safety: { allowedEnvironments: ['test'], maxInjections: options?.maxInjections },
+ seed: 'seed',
+ target: { adapter: 'runtime', selector },
+ timeoutMs: 1000,
+ trigger: { when: 'before' },
+ },
+ random: createSeededRandom('seed'),
+ runId: options?.runId ?? 'run-runtime',
+ signal: options?.signal ?? new AbortController().signal,
+});
+
+describe('runtime chaos adapter', () => {
+ it('returns hooks assignable to the execAgent hook contract', () => {
+ type ExecAgentHook = {
+ handler: (event: AgentHookEvent) => Promise<void>;
+ id: string;
+ type: AgentHookType;
+ };
+ const hooks: ExecAgentHook[] = createRuntimeChaosHooks(new RuntimeChaosController());
+ expect(hooks[0]?.type).toBe('beforeToolCall');
+ });
+
+ it('injects deterministic result replacement through beforeToolCall', async () => {
+ const controller = new RuntimeChaosController();
+ const adapter = createRuntimeChaosAdapter(controller);
+ const receipt = await adapter.inject(
+ contextFor({ content: '{"ok":false}', type: 'replace_result' }, { apiName: 'search' }),
+ );
+ const mock = vi.fn(() => true);
+ await createBeforeToolCallChaosHandler(controller)({
+ apiName: 'search',
+ callIndex: 0,
+ mock,
+ operationId: 'op-1',
+ stepIndex: 1,
+ });
+ expect(mock).toHaveBeenCalledWith({
+ content: '{"ok":false}',
+ success: true,
+ });
+ await expect(adapter.verifyInjection!(receipt, contextFor({ type: 'drop' }, {}))).resolves.toBe(
+ true,
+ );
+ });
+
+ it('reports an armed but unmatched runtime fault as inactive', async () => {
+ const controller = new RuntimeChaosController();
+ const adapter = createRuntimeChaosAdapter(controller);
+ const receipt = await adapter.inject(
+ contextFor({ type: 'drop' }, { apiName: 'missing', phase: 'before_tool_call' }),
+ );
+ await expect(adapter.verifyInjection!(receipt, contextFor({ type: 'drop' }, {}))).resolves.toBe(
+ false,
+ );
+ });
+
+ it('does not apply a non-delay fault after its parent run is aborted', async () => {
+ const parent = new AbortController();
+ const controller = new RuntimeChaosController();
+ const adapter = createRuntimeChaosAdapter(controller);
+ const receipt = await adapter.inject(
+ contextFor(
+ { type: 'drop' },
+ { apiName: 'search', phase: 'before_tool_call' },
+ { signal: parent.signal },
+ ),
+ );
+ parent.abort('run completed');
+ const mock = vi.fn(() => true);
+ await createBeforeToolCallChaosHandler(controller)({
+ apiName: 'search',
+ callIndex: 0,
+ mock,
+ operationId: 'op-later',
+ stepIndex: 2,
+ });
+ expect(mock).not.toHaveBeenCalled();
+ await expect(adapter.verifyInjection!(receipt, contextFor({ type: 'drop' }, {}))).resolves.toBe(
+ false,
+ );
+ });
+
+ it('does not mark a chaos mock applied when an earlier hook owns the mock slot', async () => {
+ const controller = new RuntimeChaosController();
+ const adapter = createRuntimeChaosAdapter(controller);
+ const receipt = await adapter.inject(
+ contextFor({ type: 'drop' }, { apiName: 'search', phase: 'before_tool_call' }),
+ );
+ const mock = vi.fn(() => false);
+ await createBeforeToolCallChaosHandler(controller)({
+ apiName: 'search',
+ callIndex: 0,
+ mock,
+ operationId: 'op-claimed',
+ stepIndex: 1,
+ });
+ expect(mock).toHaveBeenCalledOnce();
+ await expect(adapter.verifyInjection!(receipt, contextFor({ type: 'drop' }, {}))).resolves.toBe(
+ false,
+ );
+ });
+
+ it('releases a losing mock reservation for a later eligible call', async () => {
+ const controller = new RuntimeChaosController();
+ const adapter = createRuntimeChaosAdapter(controller);
+ const receipt = await adapter.inject(
+ contextFor(
+ { type: 'drop' },
+ { apiName: 'search', phase: 'before_tool_call' },
+ { maxInjections: 1 },
+ ),
+ );
+ const handler = createBeforeToolCallChaosHandler(controller);
+ const point = {
+ apiName: 'search',
+ callIndex: 0,
+ operationId: 'op-reservation',
+ stepIndex: 1,
+ };
+ await handler({ ...point, mock: vi.fn(() => false) });
+ const acceptedMock = vi.fn(() => true);
+ await handler({ ...point, callIndex: 1, mock: acceptedMock });
+ expect(acceptedMock).toHaveBeenCalledOnce();
+ await expect(adapter.verifyInjection!(receipt, contextFor({ type: 'drop' }, {}))).resolves.toBe(
+ true,
+ );
+ });
+
+ it('does not activate an effect unsupported by the matched phase', async () => {
+ const controller = new RuntimeChaosController();
+ const adapter = createRuntimeChaosAdapter(controller);
+ const receipt = await adapter.inject(
+ contextFor(
+ { content: 'unused', type: 'replace_result' },
+ { operationId: 'op-1', phase: 'completion' },
+ ),
+ );
+ const deliver = vi.fn(async () => {});
+ await deliverCompletionWithChaos(
+ controller,
+ { operationId: 'op-1', payload: undefined },
+ deliver,
+ );
+ await expect(adapter.verifyInjection!(receipt, contextFor({ type: 'drop' }, {}))).resolves.toBe(
+ false,
+ );
+ expect(deliver).toHaveBeenCalledOnce();
+ });
+
+ it('injects a retryable failure through the production retry helper', async () => {
+ const controller = new RuntimeChaosController();
+ await createRuntimeChaosAdapter(controller).inject(
+ contextFor(
+ { errorType: 'RateLimited', type: 'throw' },
+ { apiName: 'search', phase: 'tool_attempt' },
+ { maxInjections: 1 },
+ ),
+ );
+ const execute = vi.fn(async () => ({ content: 'success', success: true }));
+ const point = { apiName: 'search', callIndex: 0, operationId: 'op-1', stepIndex: 1 };
+ const result = await executeToolWithRetry(
+ () => executeToolAttemptWithChaos(controller, point, execute),
+ { maxRetries: 1 },
+ );
+ expect(result).toEqual({
+ attempts: 2,
+ result: { content: 'success', success: true },
+ });
+ expect(execute).toHaveBeenCalledOnce();
+ });
+
+ it('mocks a canceled result when a beforeToolCall delay is disarmed', async () => {
+ const controller = new RuntimeChaosController();
+ const adapter = createRuntimeChaosAdapter(controller);
+ const receipt = await adapter.inject(
+ contextFor(
+ { durationMs: 60_000, type: 'delay' },
+ { apiName: 'search', phase: 'before_tool_call' },
+ ),
+ );
+ const mock = vi.fn();
+ const pending = createBeforeToolCallChaosHandler(controller)({
+ apiName: 'search',
+ callIndex: 0,
+ mock,
+ operationId: 'op-1',
+ stepIndex: 1,
+ });
+ await adapter.cleanup!(receipt, contextFor({ type: 'drop' }, {}));
+ await expect(pending).resolves.toBeUndefined();
+ expect(mock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ error: expect.objectContaining({ errorType: 'Canceled', kind: 'stop' }),
+ success: false,
+ }),
+ );
+ });
+
+ it('stops without retrying a tool attempt when its delay is disarmed', async () => {
+ const controller = new RuntimeChaosController();
+ const adapter = createRuntimeChaosAdapter(controller);
+ const receipt = await adapter.inject(
+ contextFor(
+ { durationMs: 60_000, type: 'delay' },
+ { apiName: 'search', phase: 'tool_attempt' },
+ ),
+ );
+ const execute = vi.fn(async () => ({ content: 'success', success: true }));
+ const point = { apiName: 'search', callIndex: 0, operationId: 'op-1', stepIndex: 1 };
+ const pending = executeToolWithRetry(
+ () => executeToolAttemptWithChaos(controller, point, execute),
+ { maxRetries: 1 },
+ );
+ await adapter.cleanup!(receipt, contextFor({ type: 'drop' }, {}));
+ const result = await pending;
+ expect(result.attempts).toBe(1);
+ expect(result.result).toEqual(
+ expect.objectContaining({ error: expect.objectContaining({ kind: 'stop' }), success: false }),
+ );
+ expect(execute).not.toHaveBeenCalled();
+ });
+
+ it('duplicates a completion delivery exactly as configured', async () => {
+ const controller = new RuntimeChaosController();
+ await createRuntimeChaosAdapter(controller).inject(
+ contextFor(
+ { count: 2, type: 'duplicate' },
+ { operationId: 'op-duplicate', phase: 'completion' },
+ ),
+ );
+ const deliver = vi.fn(async () => {});
+ await deliverCompletionWithChaos(
+ controller,
+ { operationId: 'op-duplicate', payload: {} },
+ deliver,
+ );
+ expect(deliver).toHaveBeenCalledTimes(2);
+ });
+
+ it('applies only one winner when completion faults overlap', async () => {
+ const controller = new RuntimeChaosController();
+ const adapter = createRuntimeChaosAdapter(controller);
+ const duplicateReceipt = await adapter.inject(
+ contextFor(
+ { count: 2, type: 'duplicate' },
+ { operationId: 'op-conflict', phase: 'completion' },
+ { runId: 'run-duplicate' },
+ ),
+ );
+ const dropReceipt = await adapter.inject(
+ contextFor(
+ { type: 'drop' },
+ { operationId: 'op-conflict', phase: 'completion' },
+ { runId: 'run-drop' },
+ ),
+ );
+ const deliver = vi.fn(async () => {});
+ await deliverCompletionWithChaos(
+ controller,
+ { operationId: 'op-conflict', payload: {} },
+ deliver,
+ );
+ expect(deliver).toHaveBeenCalledTimes(2);
+ await expect(
+ adapter.verifyInjection!(duplicateReceipt, contextFor({ type: 'drop' }, {})),
+ ).resolves.toBe(true);
+ await expect(
+ adapter.verifyInjection!(dropReceipt, contextFor({ type: 'drop' }, {})),
+ ).resolves.toBe(false);
+ });
+
+ it('cancels a delayed completion when the runtime fault is disarmed', async () => {
+ const parent = new AbortController();
+ const controller = new RuntimeChaosController();
+ const adapter = createRuntimeChaosAdapter(controller);
+ const receipt = await adapter.inject(
+ contextFor(
+ { durationMs: 60_000, type: 'delay' },
+ { operationId: 'op-delayed', phase: 'completion' },
+ { signal: parent.signal },
+ ),
+ );
+ const deliver = vi.fn(async () => {});
+ const pending = deliverCompletionWithChaos(
+ controller,
+ { operationId: 'op-delayed', payload: {} },
+ deliver,
+ );
+ await adapter.cleanup!(receipt, contextFor({ type: 'drop' }, {}));
+ await expect(pending).rejects.toThrow('Chaos fault disarmed');
+ expect(deliver).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/achaos/runtime/src/toolAttempt.ts b/packages/achaos/runtime/src/toolAttempt.ts
new file mode 100644
index 00000000000..11c99dca43a
--- /dev/null
+++ b/packages/achaos/runtime/src/toolAttempt.ts
@@ -0,0 +1,53 @@
+import type { ToolRunResult } from '@lobechat/agent-runtime/src/transport/tool';
+
+import type { RuntimeChaosController } from './controller';
+import { delayWithAbort } from './effects';
+
+export interface ToolAttemptChaosPoint {
+ apiName: string;
+ callIndex: number;
+ operationId: string;
+ stepIndex: number;
+}
+
+const failedAttempt = (
+ message: string,
+ errorType: string,
+ kind: 'retry' | 'stop',
+): ToolRunResult => ({
+ content: JSON.stringify({ error: message, errorType }),
+ error: { errorType, kind, message },
+ success: false,
+});
+
+/** Wrap each executeToolWithRetry attempt so chaos faults exercise the real retry policy. */
+export const executeToolAttemptWithChaos = async (
+ controller: RuntimeChaosController,
+ point: ToolAttemptChaosPoint,
+ execute: () => Promise<ToolRunResult>,
+): Promise<ToolRunResult> => {
+ const activations = controller.activationsFor({ ...point, phase: 'tool_attempt' });
+ for (const { effect, markApplied, signal } of activations) {
+ markApplied();
+ if (effect.type === 'delay') {
+ try {
+ await delayWithAbort(effect.durationMs, signal);
+ } catch {
+ return failedAttempt(
+ 'Tool attempt canceled while chaos delay was active',
+ 'Canceled',
+ 'stop',
+ );
+ }
+ }
+ if (effect.type === 'drop')
+ return failedAttempt(
+ 'Tool attempt dropped by chaos experiment',
+ 'ChaosDroppedToolCall',
+ 'retry',
+ );
+ if (effect.type === 'throw')
+ return failedAttempt(effect.message ?? effect.errorType, effect.errorType, 'retry');
+ }
+ return execute();
+};
diff --git a/packages/achaos/runtime/src/toolHook.ts b/packages/achaos/runtime/src/toolHook.ts
new file mode 100644
index 00000000000..3a1facd4fa0
--- /dev/null
+++ b/packages/achaos/runtime/src/toolHook.ts
@@ -0,0 +1,81 @@
+import type { ToolRunResult } from '@lobechat/agent-runtime/src/transport/tool';
+import type { AgentHookEvent, ToolCallHookEvent } from '@lobechat/agent-runtime/src/types/hooks';
+
+import type { RuntimeChaosController } from './controller';
+import { delayWithAbort } from './effects';
+
+export type MutableToolCallEvent = Pick<
+ ToolCallHookEvent,
+ 'apiName' | 'callIndex' | 'mock' | 'operationId' | 'stepIndex'
+>;
+
+export interface RuntimeChaosHook {
+ handler: (event: AgentHookEvent) => Promise<void>;
+ id: string;
+ type: 'beforeToolCall';
+}
+
+const isMutableToolCallEvent = (
+ event: AgentHookEvent,
+): event is AgentHookEvent & MutableToolCallEvent =>
+ typeof (event as Partial<MutableToolCallEvent>).apiName === 'string' &&
+ typeof (event as Partial<MutableToolCallEvent>).callIndex === 'number' &&
+ typeof (event as Partial<MutableToolCallEvent>).mock === 'function' &&
+ typeof (event as Partial<MutableToolCallEvent>).stepIndex === 'number';
+
+const failedToolResult = (message: string, errorType: string): ToolRunResult => ({
+ content: JSON.stringify({ error: message, errorType }),
+ error: { errorType, kind: 'stop', message },
+ success: false,
+});
+
+/** Compatible with LobeHub's local beforeToolCall hook handler. */
+export const createBeforeToolCallChaosHandler =
+ (controller: RuntimeChaosController) => async (event: MutableToolCallEvent) => {
+ const activations = controller.activationsFor({
+ apiName: event.apiName,
+ callIndex: event.callIndex,
+ operationId: event.operationId,
+ phase: 'before_tool_call',
+ stepIndex: event.stepIndex,
+ });
+
+ for (const { effect, markApplied, release, signal } of activations) {
+ if (effect.type === 'delay') {
+ markApplied();
+ try {
+ await delayWithAbort(effect.durationMs, signal);
+ } catch {
+ event.mock(
+ failedToolResult('Tool call canceled while chaos delay was active', 'Canceled'),
+ );
+ return;
+ }
+ }
+ if (effect.type === 'drop') {
+ const accepted = event.mock(
+ failedToolResult('Tool call dropped by chaos experiment', 'ChaosDroppedToolCall'),
+ );
+ if (accepted) markApplied();
+ else release();
+ }
+ if (effect.type === 'replace_result') {
+ const accepted = event.mock({ content: effect.content, success: true });
+ if (accepted) markApplied();
+ else release();
+ }
+ }
+ };
+
+/** Structurally compatible with AgentRuntimeService.execAgent({ hooks }). */
+export const createRuntimeChaosHooks = (controller: RuntimeChaosController): RuntimeChaosHook[] => [
+ {
+ handler: async (event) => {
+ if (!isMutableToolCallEvent(event))
+ throw new TypeError('beforeToolCall chaos hook received an incompatible event');
+ await createBeforeToolCallChaosHandler(controller)(event);
+ },
+ id: 'agent-chaos-before-tool-call',
+ type: 'beforeToolCall',
+ },
+];
diff --git a/packages/achaos/runtime/tsconfig.json b/packages/achaos/runtime/tsconfig.json
new file mode 100644
index 00000000000..47f3a97374e
--- /dev/null
+++ b/packages/achaos/runtime/tsconfig.json
@@ -0,0 +1,5 @@
+{
+ "compilerOptions": { "module": "esnext", "moduleResolution": "bundler" },
+ "extends": "../../../tsconfig.json",
+ "include": ["src/**/*.ts"]
+}
diff --git a/packages/achaos/testing/package.json b/packages/achaos/testing/package.json
new file mode 100644
index 00000000000..f103b02d233
--- /dev/null
+++ b/packages/achaos/testing/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@achaos/testing",
+ "version": "0.0.1",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "main": "./src/index.ts",
+ "scripts": {
+ "test": "vitest run --silent='passed-only'"
+ },
+ "dependencies": {
+ "@achaos/core": "workspace:*",
+ "@achaos/runner": "workspace:*"
+ },
+ "devDependencies": {
+ "vitest": "^3.2.6"
+ }
+}
diff --git a/packages/achaos/testing/src/index.ts b/packages/achaos/testing/src/index.ts
new file mode 100644
index 00000000000..9588d498b17
--- /dev/null
+++ b/packages/achaos/testing/src/index.ts
@@ -0,0 +1,2 @@
+export type { AgentChaosTestState } from './state';
+export { createAgentChaosTestState, createStateAdapter, createStateOracle } from './state';
diff --git a/packages/achaos/testing/src/scenarios.test.ts b/packages/achaos/testing/src/scenarios.test.ts
new file mode 100644
index 00000000000..8922e7b9835
--- /dev/null
+++ b/packages/achaos/testing/src/scenarios.test.ts
@@ -0,0 +1,71 @@
+import type { ChaosExperiment } from '@achaos/core';
+import { ChaosRegistry, runChaosExperiment } from '@achaos/runner';
+import { describe, expect, it } from 'vitest';
+
+import {
+ createAgentChaosTestState,
+ createStateAdapter,
+ createStateOracle,
+ reclaimStaleOperation,
+} from './state';
+
+describe('first-phase deterministic scenarios', () => {
+ it('reclaims a stale operation and verifies the invariant independently', async () => {
+ const state = createAgentChaosTestState();
+ const registry = new ChaosRegistry().registerAdapter(createStateAdapter(state)).registerOracle(
+ createStateOracle(state, 'operation-reclaimed', (current) => ({
+ message: `operation is ${current.operationStatus}`,
+ passed: current.operationStatus === 'abandoned',
+ })),
+ );
+ const experiment: ChaosExperiment = {
+ cleanup: 'never',
+ description: 'Reclaim an operation whose durable lease expired',
+ effect: { durationMs: 300_000, type: 'delay' },
+ id: 'operation-reclaim',
+ layer: 'L2-agent-runtime',
+ oracles: [{ name: 'operation-reclaimed' }],
+ safety: { allowedEnvironments: ['test'] },
+ seed: 'operation-reclaim-v1',
+ target: { adapter: 'state', selector: { operationStatus: 'running' } },
+ timeoutMs: 1000,
+ trigger: { when: 'immediate' },
+ };
+ const result = await runChaosExperiment({
+ environment: 'test',
+ exercise: async () => reclaimStaleOperation(state),
+ experiment,
+ registry,
+ });
+ expect(result.status).toBe('passed');
+ expect(state.operationLease).toBe('stale');
+ expect(state.operationStatus).toBe('abandoned');
+ });
+
+ it('restores the prior tool result after an always-cleanup experiment', async () => {
+ const state = createAgentChaosTestState();
+ state.toolResult = 'baseline';
+ const registry = new ChaosRegistry().registerAdapter(createStateAdapter(state)).registerOracle(
+ createStateOracle(state, 'tool-failure-observed', (current) => ({
+ message: current.toolResult ?? 'missing tool result',
+ passed: current.toolResult?.includes('RateLimited') ?? false,
+ })),
+ );
+ const experiment: ChaosExperiment = {
+ cleanup: 'always',
+ description: 'Inject a transient tool failure',
+ effect: { errorType: 'RateLimited', type: 'throw' },
+ id: 'tool-failure-cleanup',
+ layer: 'L1-model-runtime',
+ oracles: [{ name: 'tool-failure-observed' }],
+ safety: { allowedEnvironments: ['test'] },
+ seed: 'tool-failure-cleanup-v1',
+ target: { adapter: 'state', selector: {} },
+ timeoutMs: 1000,
+ trigger: { when: 'immediate' },
+ };
+ const result = await runChaosExperiment({ environment: 'test', experiment, registry });
+ expect(result.status).toBe('passed');
+ expect(state.toolResult).toBe('baseline');
+ });
+});
diff --git a/packages/achaos/testing/src/state.ts b/packages/achaos/testing/src/state.ts
new file mode 100644
index 00000000000..94cf70171fb
--- /dev/null
+++ b/packages/achaos/testing/src/state.ts
@@ -0,0 +1,74 @@
+import type { ChaosAdapter, ChaosOracle } from '@achaos/core';
+
+export interface AgentChaosTestState {
+ completionDeliveries: number;
+ operationLease: 'active' | 'stale';
+ operationStatus: 'running' | 'abandoned' | 'done';
+ toolResult?: string;
+}
+
+export const createAgentChaosTestState = (): AgentChaosTestState => ({
+ completionDeliveries: 0,
+ operationLease: 'active',
+ operationStatus: 'running',
+});
+
+/** Test exercise that represents the production coordinator's reclaim behavior. */
+export const reclaimStaleOperation = (state: AgentChaosTestState) => {
+ if (state.operationLease === 'stale' && state.operationStatus === 'running') {
+ state.operationStatus = 'abandoned';
+ }
+};
+
+export const createStateAdapter = (state: AgentChaosTestState): ChaosAdapter => ({
+ cancelInjection: async () => {},
+ cleanup: async (receipt) => {
+ const previousLease = receipt.cleanupToken?.operationLease;
+ const previous = receipt.cleanupToken?.operationStatus;
+ const previousToolResult = receipt.cleanupToken?.toolResult;
+ if (previousLease === 'active' || previousLease === 'stale') {
+ state.operationLease = previousLease;
+ }
+ if (previous === 'running' || previous === 'abandoned' || previous === 'done') {
+ state.operationStatus = previous;
+ }
+ if (typeof previousToolResult === 'string') state.toolResult = previousToolResult;
+ else delete state.toolResult;
+ },
+ inject: async (context) => {
+ const previousLease = state.operationLease;
+ const previous = state.operationStatus;
+ const previousToolResult = state.toolResult;
+ if (context.experiment.effect.type === 'throw') {
+ state.toolResult = JSON.stringify({ errorType: context.experiment.effect.errorType });
+ }
+ if (
+ context.experiment.target.selector.operationStatus === 'running' &&
+ context.experiment.effect.type === 'delay'
+ ) {
+ state.operationLease = 'stale';
+ }
+ return {
+ adapter: 'state',
+ cleanupToken: {
+ operationLease: previousLease,
+ operationStatus: previous,
+ toolResult: previousToolResult,
+ },
+ injectionId: `${context.runId}:state`,
+ };
+ },
+ name: 'state',
+});
+
+export const createStateOracle = (
+ state: AgentChaosTestState,
+ name: string,
+ evaluate: (current: AgentChaosTestState) => { message: string; passed: boolean },
+): ChaosOracle => ({
+ evaluate: async () => {
+ const result = evaluate(state);
+ return { message: result.message, name, status: result.passed ? 'passed' : 'failed' };
+ },
+ name,
+});
diff --git a/packages/achaos/testing/tsconfig.json b/packages/achaos/testing/tsconfig.json
new file mode 100644
index 00000000000..fa53fc42b8f
--- /dev/null
+++ b/packages/achaos/testing/tsconfig.json
@@ -0,0 +1,9 @@
+{
+ "compilerOptions": {
+ "module": "esnext",
+ "moduleResolution": "bundler",
+ "types": ["node", "vitest/globals"]
+ },
+ "extends": "../../../tsconfig.json",
+ "include": ["src/**/*.ts"]
+}
diff --git a/packages/achaos/tracing/package.json b/packages/achaos/tracing/package.json
new file mode 100644
index 00000000000..996ec4970ae
--- /dev/null
+++ b/packages/achaos/tracing/package.json
@@ -0,0 +1,13 @@
+{
+ "name": "@achaos/tracing",
+ "version": "0.0.1",
+ "private": true,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "main": "./src/index.ts",
+ "dependencies": {
+ "@achaos/core": "workspace:*"
+ }
+}
diff --git a/packages/achaos/tracing/src/index.test.ts b/packages/achaos/tracing/src/index.test.ts
new file mode 100644
index 00000000000..f61899c3dbc
--- /dev/null
+++ b/packages/achaos/tracing/src/index.test.ts
@@ -0,0 +1,34 @@
+import type { ChaosRunResult } from '@achaos/core';
+import { describe, expect, it, vi } from 'vitest';
+
+import { recordChaosResult } from '.';
+
+describe('recordChaosResult', () => {
+ it('includes scalar timeline data in trace event attributes', () => {
+ const addEvent = vi.fn();
+ recordChaosResult({ addEvent, setAttribute: vi.fn() }, {
+ durationMs: 1,
+ experimentId: 'experiment',
+ finishedAt: '2026-01-01T00:00:00.001Z',
+ oracleResults: [],
+ runId: 'run',
+ seed: 'seed',
+ startedAt: '2026-01-01T00:00:00.000Z',
+ status: 'failed',
+ timeline: [
+ {
+ at: '2026-01-01T00:00:00.001Z',
+ data: { details: { ignored: true }, name: 'health', status: 'failed' },
+ type: 'oracle_evaluated',
+ },
+ ],
+ } satisfies ChaosRunResult);
+ expect(addEvent).toHaveBeenCalledWith(
+ 'chaos.oracle_evaluated',
+ expect.objectContaining({
+ 'chaos.event.data.name': 'health',
+ 'chaos.event.data.status': 'failed',
+ }),
+ );
+ });
+});
diff --git a/packages/achaos/tracing/src/index.ts b/packages/achaos/tracing/src/index.ts
new file mode 100644
index 00000000000..96720168127
--- /dev/null
+++ b/packages/achaos/tracing/src/index.ts
@@ -0,0 +1,29 @@
+import type { ChaosRunResult, ChaosTimelineEvent } from '@achaos/core';
+
+export interface ChaosTraceSink {
+ addEvent: (name: string, attributes: Record<string, boolean | number | string>) => void;
+ setAttribute: (name: string, value: boolean | number | string) => void;
+}
+
+const eventAttributes = (event: ChaosTimelineEvent) => {
+ const attributes: Record<string, boolean | number | string> = {
+ 'chaos.event.at': event.at,
+ 'chaos.event.type': event.type,
+ };
+ for (const [key, value] of Object.entries(event.data ?? {})) {
+ if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') {
+ attributes[`chaos.event.data.${key}`] = value;
+ }
+ }
+ return attributes;
+};
+
+/** Bridges portable chaos results to OpenTelemetry-like spans without depending on an SDK. */
+export const recordChaosResult = (sink: ChaosTraceSink, result: ChaosRunResult) => {
+ sink.setAttribute('chaos.experiment.id', result.experimentId);
+ sink.setAttribute('chaos.run.id', result.runId);
+ sink.setAttribute('chaos.seed', result.seed);
+ sink.setAttribute('chaos.status', result.status);
+ sink.setAttribute('chaos.duration_ms', result.durationMs);
+ for (const event of result.timeline) sink.addEvent(`chaos.${event.type}`, eventAttributes(event));
+};
diff --git a/packages/achaos/tracing/tsconfig.json b/packages/achaos/tracing/tsconfig.json
new file mode 100644
index 00000000000..47f3a97374e
--- /dev/null
+++ b/packages/achaos/tracing/tsconfig.json
@@ -0,0 +1,5 @@
+{
+ "compilerOptions": { "module": "esnext", "moduleResolution": "bundler" },
+ "extends": "../../../tsconfig.json",
+ "include": ["src/**/*.ts"]
+}
diff --git a/packages/achaos/vitest.config.mts b/packages/achaos/vitest.config.mts
new file mode 100644
index 00000000000..ffaeeab7d67
--- /dev/null
+++ b/packages/achaos/vitest.config.mts
@@ -0,0 +1,9 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ root: import.meta.dirname,
+ test: {
+ environment: 'node',
+ include: ['**/src/**/*.test.ts'],
+ },
+});
diff --git a/packages/agent-runtime/src/types/hooks.ts b/packages/agent-runtime/src/types/hooks.ts
index 5f6d01ccf36..96aec490f09 100644
--- a/packages/agent-runtime/src/types/hooks.ts
+++ b/packages/agent-runtime/src/types/hooks.ts
@@ -150,7 +150,8 @@ export interface ToolCallHookEvent {
args: Record<string, any>;
callIndex: number;
identifier: string;
- mock: (result: ToolRunResult) => void;
+ /** Returns false when an earlier hook already won the mock slot. */
+ mock: (result: ToolRunResult) => boolean;
operationId: string;
stepIndex: number;
}