/directive:testing-ai-systemsfrom directive
Tests AI orchestrators without real API calls using createMockRunner, evaluates agent output quality, adds tracing/metrics for debugging, integrates MCP tool servers, and wires RAG pipelines.
Ships in directive. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
This skill applies when the project uses @directive-run/ai. If not found in package.json, suggest installing it: npm install @directive-run/ai.
createMockRunner or wants to mock LLM responseshardening-ai-systemsbuilding-ai-orchestratorsbuilding-ai-agentsWhat are you testing?
├── Single resolver behavior → createMockRunner + unit test
├── Full orchestrator flow → createTestOrchestrator
├── Multi-agent pipeline → createTestMultiAgentOrchestrator
├── Output quality (LLM-as-judge) → createEvaluation + assertOutputQuality
├── Regression suite in CI → evaluation suite with recorded fixtures
└── Live debug of production → enableTracing + observability plugins
import { createMockRunner } from "@directive-run/ai/testing";
// Static responses – returned in sequence
const mockRunner = createMockRunner({
responses: [
{ text: "First response.", usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 } },
{ text: "Second response.", usage: { inputTokens: 8, outputTokens: 4, totalTokens: 12 } },
],
});
// Dynamic – choose response based on prompt
const dynamicRunner = createMockRunner({
handler: async (options) => {
if (options.prompt.includes("capital")) {
return { text: "Paris", usage: { inputTokens: 5, outputTokens: 2, totalTokens: 7 } };
}
return { text: "I don't know.", usage: { inputTokens: 5, outputTokens: 4, totalTokens: 9 } };
},
});
// Simulate failures for error-path tests
const failingRunner = createMockRunner({
handler: async () => {
throw new Error("rate_limit: Too many requests");
},
});
import { createAgentOrchestrator } from "@directive-run/ai";
import { createMockRunner } from "@directive-run/ai/testing";
import { t } from "@directive-run/core";
import { describe, it, expect } from "vitest";
// Build orchestrator with injected runner – enables swapping real/mock
function buildOrchestrator(runner: AgentRunner) {
return createAgentOrchestrator({
runner,
factsSchema: {
input: t.string(),
output: t.string().optional(),
status: t.string<"idle" | "done" | "error">(),
errorMessage: t.string().optional(),
},
init: (facts) => {
facts.status = "idle";
},
constraints: {
process: {
when: (facts) => facts.status === "idle" && !!facts.input,
require: { type: "PROCESS" },
},
},
resolvers: {
process: {
requirement: "PROCESS",
resolve: async (req, context) => {
try {
const result = await context.runner.run({ prompt: context.facts.input });
context.facts.output = result.text;
context.facts.status = "done";
} catch (error) {
context.facts.status = "error";
context.facts.errorMessage = (error as Error).message;
}
},
},
},
});
}
describe("process resolver", () => {
it("sets output on success", async () => {
const orchestrator = buildOrchestrator(
createMockRunner({ responses: [{ text: "Result.", usage: { inputTokens: 5, outputTokens: 2, totalTokens: 7 } }] })
);
const result = await orchestrator.run({ input: "test input" });
expect(result.facts.status).toBe("done");
expect(result.facts.output).toBe("Result.");
});
it("captures errors in facts", async () => {
const orchestrator = buildOrchestrator(
createMockRunner({ handler: async () => { throw new Error("Provider down"); } })
);
const result = await orchestrator.run({ input: "test" });
expect(result.facts.status).toBe("error");
expect(result.facts.errorMessage).toContain("Provider down");
});
});
import { createTestMultiAgentOrchestrator, assertMultiAgentState } from "@directive-run/ai/testing";
describe("research-write pipeline", () => {
it("passes research to writer via coordinator facts", async () => {
const testOrchestrator = createTestMultiAgentOrchestrator({
agentRunners: {
researcher: createMockRunner({
responses: [{ text: "Finding: qubits enable quantum advantage.", usage: { inputTokens: 10, outputTokens: 8, totalTokens: 18 } }],
}),
writer: createMockRunner({
responses: [{ text: "Qubits are the foundation of quantum computing.", usage: { inputTokens: 20, outputTokens: 10, totalTokens: 30 } }],
}),
},
});
const result = await testOrchestrator.run({ topic: "quantum computing" });
assertMultiAgentState(result, {
"researcher.researchComplete": true,
"coordinator.phase": "done",
});
expect(result.facts.finalOutput).toContain("qubit");
});
});
import { createEvaluation, assertOutputQuality } from "@directive-run/ai/testing";
const summaryEval = createEvaluation({
name: "summarization-quality",
cases: [
{
id: "basic-summary",
input: { text: "A very long article about climate change..." },
expected: {
contains: ["climate", "temperature"],
maxWords: 50,
notContains: ["Lorem ipsum"],
},
},
],
});
describe("summarization evals", () => {
it("meets quality criteria", async () => {
for (const evalCase of summaryEval.cases) {
const result = await orchestrator.run(evalCase.input);
assertOutputQuality(result.facts.output, evalCase.expected);
}
});
});
import { createLLMJudge } from "@directive-run/ai/testing";
const judge = createLLMJudge({
runner: createAnthropicRunner({ model: "claude-haiku-4-5", apiKey: process.env.ANTHROPIC_API_KEY }),
criteria: ["Is the response factually accurate?", "Is the response concise?"],
scoringScale: { min: 1, max: 5 },
passingScore: 3.5,
});
it("produces quality output", async () => {
const result = await orchestrator.run({ input: "Explain photosynthesis." });
const judgment = await judge.evaluate(result.facts.output);
expect(judgment.passed).toBe(true);
});
import { createTracingPlugin, createLoggingPlugin, createMetricsPlugin } from "@directive-run/ai/plugins";
import { createInspector } from "@directive-run/ai/testing";
// Tracing – spans around every LLM call and resolver
const tracer = createTracingPlugin({
exportTo: "console", // "console" | "opentelemetry" | "custom"
onSpanEnd: (span) => console.log(`[${span.name}] ${span.duration}ms – ${span.status}`),
});
// Structured logging for LLM calls, guardrail violations, budget warnings
const logger = createLoggingPlugin({
level: "info",
format: "json",
include: ["runner_calls", "guardrail_violations", "budget_warnings"],
});
// Metrics – auto-collects: ai.tokens.*, ai.latency.runner, ai.guardrail.violations
const metrics = createMetricsPlugin({
onMetric: (metric) => myMetricsClient.gauge(metric.name, metric.value, metric.tags),
});
// Inspector – assert on calls and events in tests
const inspector = createInspector();
const orchestrator = createAgentOrchestrator({
runner: createMockRunner({ responses: [/* ... */] }),
plugins: [inspector],
});
await orchestrator.run({ input: "test" });
const calls = inspector.getRunnerCalls();
expect(calls).toHaveLength(1);
expect(calls[0].prompt).toContain("test");
const events = inspector.getEvents();
expect(events.some((e) => e.type === "requirement_met")).toBe(true);
import { createMCPToolProvider } from "@directive-run/ai/mcp";
import { createMockMCPProvider } from "@directive-run/ai/testing";
// Production: connect to real MCP tool server
const mcpProvider = createMCPToolProvider({
transport: "stdio", // "stdio" | "sse" | "http"
command: "npx",
args: ["@my-org/mcp-tools"],
});
// Testing: mock the tool provider
const mockMCP = createMockMCPProvider({
tools: {
web_search: async (_params) => ({
results: ["Mocked result 1", "Mocked result 2"],
}),
},
});
// Tools available in resolvers via context.tools.getAll()
resolvers: {
search: {
requirement: "SEARCH",
resolve: async (req, context) => {
const result = await context.runner.run({
prompt: context.facts.query,
tools: context.tools.getAll(),
});
context.facts.result = result.text;
},
},
},
import { createRAGProvider } from "@directive-run/ai/rag";
import { createMockRAGProvider } from "@directive-run/ai/testing";
// Production: your retrieval logic
const ragProvider = createRAGProvider({
retrieve: async (query, options) => {
const chunks = await vectorDB.similaritySearch(query, {
limit: options.topK ?? 5,
minScore: options.minScore ?? 0.7,
});
return chunks.map((chunk) => ({
content: chunk.text,
metadata: chunk.metadata,
score: chunk.score,
}));
},
});
// Testing: mock retrieval results
const mockRAG = createMockRAGProvider({
results: [
{ content: "Paris is the capital of France.", score: 0.95, metadata: {} },
],
});
// Use in resolver
resolvers: {
answer: {
requirement: "ANSWER",
resolve: async (req, context) => {
const sources = await context.rag.retrieve(context.facts.question, { topK: 3 });
const contextText = sources.map((s) => s.content).join("\n\n");
const result = await context.runner.run({
prompt: `Sources:\n${contextText}\n\nQuestion: ${context.facts.question}`,
});
context.facts.answer = result.text;
context.facts.sourceCount = sources.length;
},
},
},
// WRONG – slow, expensive, flaky, exposes keys in logs
const orchestrator = createAgentOrchestrator({
runner: createAnthropicRunner({ apiKey: process.env.ANTHROPIC_API_KEY, model: "claude-opus-4-6" }),
});
// CORRECT – always inject mock runners in tests
const orchestrator = buildOrchestrator(
createMockRunner({ responses: [{ text: "ok", usage: { inputTokens: 2, outputTokens: 1, totalTokens: 3 } }] })
);
// WRONG – brittle, breaks if impl changes
const spy = vi.spyOn(runner, "run");
expect(spy).toHaveBeenCalledOnce();
// CORRECT – test observable facts
expect(result.facts.status).toBe("done");
expect(result.facts.output).toBeTruthy();
Always use (req, context) – never (req, ctx) or (request, context).
ai-testing-evals.md – Full testing API, createMockRunner options, evaluation suite patternsai-debug-observability.md – Tracing plugins, logging config, metrics collection, inspector APIai-mcp-rag.md – MCP transport options, tool provider interface, RAG retrieval configWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
ai-testing, mock-runner, evaluation, observability, mcp, rag
Other plugins' skills for the same job
npx claudepluginhub directive-run/directive --plugin directive12 skills in this plugin
/building-ai-agentsConfigure AI provider runners (Anthropic, OpenAI, Ollama), stream tokens and structured output, and wire cross-agent communication. Use when setting up LLM provider connections, implementing token streaming, choosing between providers, or building agents that communicate results to each other./building-ai-orchestratorsCreate AI orchestration systems using createAgentOrchestrator (single agent) and createMultiAgentOrchestrator (multi-agent). Define factsSchema with t.*() builders, init state, constraints for trigger conditions, and resolvers for LLM execution. Use when building LLM-powered workflows, agent pipelines, task runners, or multi-agent coordination systems./building-directive-systemsCompose Directive modules into systems: single-module and multi-module createSystem() calls, namespaced fact/derive/event access, cross-module dependencies, initialFacts and hydration, plugins (logging, devtools, persistence, circuit breaker), React adapter hooks (useSelector, useEvent, useSystem, DirectiveProvider), and system lifecycle. Use when creating a system, connecting modules together, adding plugins, or integrating Directive with React./getting-started-with-directiveUnderstand Directive fundamentals: what modules, facts, derivations, constraints, resolvers, and systems are, and how they fit together. Use when someone is new to Directive, asks 'what is Directive', wants to understand the mental model, or needs help choosing between Directive concepts./hardening-ai-systemsAdd guardrails (input/output validation), memory strategies, token budgets, PII detection, prompt injection prevention, and circuit breakers to AI orchestrators. Use when enforcing content policies, managing costs, preventing security vulnerabilities, adding resilience, or implementing agent memory across turns./migrating-to-directiveMigrate state management code from Redux, Zustand, XState, MobX, Recoil, or Jotai to Directive. Provides concept mapping, step-by-step migration patterns, and before/after code examples. Use when asked to migrate, convert, or port existing state management to Directive.