/directive:building-directive-systemsfrom directive
Composes Directive modules into systems with createSystem(), cross-module dependencies, plugins, hydration, and React adapter hooks (useSelector, useEvent, useSystem, DirectiveProvider).
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/core. If not found in package.json, suggest installing it: npm install @directive-run/core.
Auto-invoke when the user:
createSystem() and asks to extend it with more modules or pluginsuseSelector, useEvent, useSystem, or DirectiveProviderDo NOT invoke when:
writing-directive-modules.md)writing-directive-constraints.md)testing-directive-code.md)How many state domains?
├── One → createSystem({ module: myModule })
│ Direct access: system.facts.count
│
└── Two or more → createSystem({ modules: { auth, cart, ui } })
Namespaced: system.facts.auth.token
Does module A need to read module B's state in constraints/effects/derivations?
├── No → No crossModuleDeps needed
└── Yes → Declare crossModuleDeps on the consuming module
Own facts at facts.self.*, other module at facts.otherModule.*
import { createSystem } from "@directive-run/core";
import { loggingPlugin, devtoolsPlugin } from "@directive-run/core/plugins";
const system = createSystem({
module: myModule,
plugins: [loggingPlugin(), devtoolsPlugin()],
history: { maxSnapshots: 100 },
});
system.start();
await system.settle(); // Wait for all resolvers to complete
const system = createSystem({
modules: { auth: authModule, cart: cartModule, data: dataModule },
plugins: [loggingPlugin(), devtoolsPlugin()],
initialFacts: {
auth: { token: "restored-token" },
cart: { items: [] },
},
initOrder: "auto", // "auto" | "declaration" | ["auth", "data", "cart"]
});
system.start();
await system.settle();
await system.hydrate(async () => {
const stored = localStorage.getItem("app-state");
return stored ? JSON.parse(stored) : {};
});
system.start();
const chatModule = await import("./modules/chat");
system.registerModule("chat", chatModule.default);
// Now: system.facts.chat.*, system.events.chat.*, etc.
system.facts.count = 5;
const val = system.facts.count;
const loading = system.derive.isLoading;
system.events.increment();
system.events.setUser({ user: { id: "1", name: "Alice" } });
system.facts.auth.token;
system.facts.cart.items;
system.derive.auth.isAdmin;
system.derive.cart.itemCount;
system.events.auth.login({ token: "abc" });
system.events.cart.addItem({ productId: "p1", qty: 1 });
// WRONG – internal separator never used in public API
system.facts["auth::token"];
system.facts["auth_token"];
// CORRECT – dot notation through namespace proxy
system.facts.auth.token;
// Subscribe to multiple keys
const unsub = system.subscribe(["count", "isLoading"], () => {
console.log(system.facts.count, system.derive.isLoading);
});
// Multi-module keys use "module.key" format
system.subscribe(["auth.token", "cart.items"], () => { ... });
// Watch a single value with old/new
system.watch("count", (newVal, oldVal) => {
console.log(`Count: ${oldVal} -> ${newVal}`);
});
// Subscribe to all keys in a module
system.subscribeModule("cart", () => { ... });
// Wait for condition
await system.when((facts) => facts.phase === "done");
await system.when((facts) => facts.auth.isAuthenticated, { timeout: 5000 });
system.start(); // Begins constraint evaluation and reconciliation
system.stop(); // Pauses evaluation, cancels inflight resolvers
system.destroy(); // Full cleanup – subscriptions, plugins, resources
Always call destroy() when a system is no longer needed (teardown, React unmount, test cleanup).
Export the schema separately so other modules can reference it for type safety.
// modules/auth.ts
export const authSchema = {
facts: {
token: t.string<string | null>(),
isAuthenticated: t.boolean(),
},
} as const;
export const authModule = createModule("auth", {
schema: authSchema,
init: (facts) => {
facts.token = null;
facts.isAuthenticated = false;
},
events: {
login: (facts, payload) => { facts.token = payload.token; facts.isAuthenticated = true; },
logout: (facts) => { facts.token = null; facts.isAuthenticated = false; },
},
});
// modules/data.ts
import { authSchema } from "./auth";
const dataModule = createModule("data", {
schema: { facts: { items: t.array(t.string()), loaded: t.boolean() } },
crossModuleDeps: { auth: authSchema },
init: (facts) => { facts.items = []; facts.loaded = false; },
constraints: {
fetchWhenAuth: {
when: (facts) => facts.auth.isAuthenticated && !facts.self.loaded,
require: { type: "FETCH_ITEMS" },
},
},
effects: {
onAuthChange: {
run: (facts, prevFacts) => {
if (prevFacts && prevFacts.auth.isAuthenticated && !facts.auth.isAuthenticated) {
console.log("User logged out");
}
},
},
},
});
import {
loggingPlugin,
devtoolsPlugin,
persistencePlugin,
} from "@directive-run/core/plugins";
const plugins = [];
if (process.env.NODE_ENV === "development") {
plugins.push(loggingPlugin({ verbose: true })); // Logging first
plugins.push(devtoolsPlugin({ name: "My App" }));
}
plugins.push(persistencePlugin({
key: "app-state",
storage: localStorage,
exclude: ["authToken", "isLoading"], // Skip sensitive/transient
version: 1,
migrate: (old, version) => old, // Always version when persisting
}));
Plugin order matters – logging first captures all events including those from other plugins.
import type { DirectivePlugin } from "@directive-run/core";
const myPlugin: DirectivePlugin = {
name: "my-plugin",
onInit: (system) => { ... },
onStart: (system) => { ... },
onStop: (system) => { ... },
onSnapshot: (snapshot) => {
// snapshot.facts, snapshot.changedKeys
},
onRequirementEmitted: (requirement) => { ... },
onResolutionStart: (resolution) => { ... },
onResolutionComplete: (resolution) => { ... },
onError: (error, context) => { ... },
};
Import from @directive-run/react.
// system.ts – created once, imported anywhere
export const system = createSystem({ module: counterModule });
Re-renders only when the selected value changes (shallow comparison).
import { useSelector, useEvent } from "@directive-run/react";
function Counter() {
const count = useSelector(system, (s) => s.facts.count);
const doubled = useSelector(system, (s) => s.derive.doubled);
// Multi-module
const token = useSelector(system, (s) => s.facts.auth.token);
const itemCount = useSelector(system, (s) => s.derive.cart.itemCount);
const events = useEvent(system);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => events.increment()}>+1</button>
</div>
);
}
const events = useEvent(system);
events.increment();
events.auth.login({ token: "abc" }); // Multi-module
import { useSystem } from "@directive-run/react";
function GameBoard() {
const gameSystem = useSystem({ // Created on mount, destroyed on unmount
module: gameModule,
history: true,
});
const score = useSelector(gameSystem, (s) => s.facts.score);
return <div>Score: {score}</div>;
}
Use useSystem when the system's lifecycle matches a component's lifecycle (wizard, game board, modal form). For app-wide state, create outside React.
import { DirectiveProvider, useDirectiveContext } from "@directive-run/react";
function App() {
return (
<DirectiveProvider system={system}>
<Dashboard />
</DirectiveProvider>
);
}
function Dashboard() {
const system = useDirectiveContext();
const stats = useSelector(system, (s) => s.derive.dashboardStats);
return <div>{stats.totalUsers} users</div>;
}
// WRONG – resolver hasn't completed
system.start();
console.log(system.facts.user); // null
// CORRECT
system.start();
await system.settle();
console.log(system.facts.user); // resolved
// WRONG – constraints never evaluate
const system = createSystem({ module: myModule });
console.log(system.facts.phase); // "idle" – resolvers never ran
// CORRECT
system.start();
await system.settle();
// WRONG – facts.auth untyped, no reactive tracking
when: (facts) => facts.auth.isAuthenticated, // TypeScript error
// CORRECT
crossModuleDeps: { auth: authSchema },
when: (facts) => facts.auth.isAuthenticated, // Fully typed + tracked
// WRONG – in cross-module constraints, bare facts has no self properties
when: (facts) => facts.loaded,
// CORRECT
when: (facts) => facts.self.loaded,
// WRONG
system.facts["auth::token"];
// CORRECT
system.facts.auth.token;
// WRONG – new system on every render
function Counter() {
const system = createSystem({ module: counterModule }); // Bug!
}
// CORRECT – module-level or useSystem()
const system = createSystem({ module: counterModule });
// WRONG – this does not exist
const { facts, derive, events } = useDirective(system);
// CORRECT
const count = useSelector(system, (s) => s.facts.count);
const events = useEvent(system);
// WRONG – re-renders on any fact change
const allFacts = useSelector(system, (s) => s.facts);
// CORRECT – select only what you need
const name = useSelector(system, (s) => s.facts.userName);
// CORRECT – gate on environment
const plugins = process.env.NODE_ENV === "development"
? [loggingPlugin(), devtoolsPlugin()]
: [];
// WRONG – schema changes break existing users
persistencePlugin({ key: "app", storage: localStorage })
// CORRECT
persistencePlugin({ key: "app", storage: localStorage, version: 1, migrate: (old) => old })
const inspection = system.inspect();
inspection.facts; // Current fact snapshot
inspection.derivations; // Derivation values
inspection.requirements; // Active requirements
inspection.constraintDefs; // Constraint definitions and state
inspection.resolvers; // Resolver statuses
inspection.inflight; // Currently running resolvers
inspection.unmet; // Requirements with no matching resolver
system.explain("req-123"); // Why this requirement exists
system.isSettled; // boolean
multi-module.md – crossModuleDeps, module schema export pattern, subscribe/watch in multi-modulesystem-api.md – full system API reference, read(), watch(), when(), lifecycle orderplugins.md – all built-in plugins with full config, custom plugin lifecycle hooksreact-adapter.md – all React hooks with examples, common mistakes, multi-module patternsWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
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./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./reviewing-directive-codeReview Directive code for anti-patterns, naming violations, missing error boundaries, constraint/resolver misuse, and performance issues. Use when asked to review, audit, or improve existing Directive modules, systems, or orchestrators.