/directive:writing-directive-modulesfrom directive
Creates and structures Directive modules with schema definitions, init functions, derivations, effects, events, constraints, and resolvers using t.* type builders and naming conventions.
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:
createModule() call and asks to extend itDo NOT invoke when:
building-directive-systems.md)testing-directive-code.md)writing-directive-constraints.md)import { createModule, t } from "@directive-run/core";
const myModule = createModule("name", {
schema: {
facts: {
phase: t.string<"idle" | "loading" | "done">(),
count: t.number(),
user: t.object<{ id: string; name: string } | null>(),
},
derivations: { // Optional – declare types here, define in derive
isLoading: t.boolean(),
displayName: t.string(),
},
events: { // Optional – declare event payloads here
increment: {},
setUser: { user: t.object<{ id: string; name: string }>() },
},
requirements: { // Optional – declare requirement payloads here
FETCH_USER: { userId: t.string() },
},
},
init: (facts) => { // Synchronous. Sets all facts to initial values.
facts.phase = "idle";
facts.count = 0;
facts.user = null;
},
derive: { // Auto-tracked – no manual deps needed
isLoading: (facts) => facts.phase === "loading",
displayName: (facts) => {
if (!facts.user) {
return "Guest";
}
return facts.user.name;
},
},
effects: { // Fire-and-forget side effects
logPhase: {
run: (facts, prevFacts) => {
if (prevFacts?.phase !== facts.phase) {
console.log(`Phase: ${facts.phase}`);
}
},
},
},
events: { // Synchronous fact mutations driven by user actions
increment: (facts) => {
facts.count += 1;
},
setUser: (facts, payload) => {
facts.user = payload.user;
},
},
constraints: { // WHEN conditions are true, REQUIRE something
fetchWhenReady: {
when: (facts) => facts.phase === "idle" && facts.count > 0,
require: (facts) => ({ type: "FETCH_USER", userId: "user-1" }),
},
},
resolvers: { // HOW to fulfill requirements
fetchUser: {
requirement: "FETCH_USER",
resolve: async (req, context) => {
context.facts.phase = "loading";
const res = await fetch(`/api/users/${req.userId}`);
context.facts.user = await res.json();
context.facts.phase = "done";
},
},
},
});
What does this code do?
├── Store a value that changes over time
│ └── schema.facts + init()
├── Compute a value from other facts (synchronous, cached)
│ └── schema.derivations + derive
├── React to fact changes (side effect, fire-and-forget)
│ └── effects
├── Respond to a user action
│ └── schema.events + events
├── Declare "when X is true, the system needs Y"
│ └── constraints
└── Fulfill a requirement with async work
└── resolvers
Value type?
├── string (possibly with union) → t.string() or t.string<"a" | "b">()
├── number (possibly with bounds) → t.number() or t.number().min(0).max(100)
├── boolean → t.boolean()
├── object / record → t.object<Shape>()
├── array → t.array<ItemType>()
├── string literal union → t.enum("a", "b", "c")
├── exact value → t.literal(42)
├── T | null → t.nullable(t.string()) or t.object<T | null>()
├── T | undefined → t.optional(t.string())
└── Map / Set / Date → t.object<Map<K,V>>() / t.object<Set<T>>() / t.object<Date>()
t.string().default("light") // Default if init doesn't set it
t.string().validate((v) => v.includes("@")) // Dev-mode validation
t.string().transform((v) => v.trim()) // Runs on every set
t.string().brand<"UserId">() // Nominal typing
t.number().min(0).max(100).describe("Player score")
t.array<string>().nonEmpty().maxLength(10)
t.object<{ url: string }>().nonNull()
schema: {
facts: {} as { count: number; name: string },
derivations: {} as { doubled: number },
},
Gives full TypeScript inference, skips runtime validation.
derive: {
isRed: (facts) => facts.phase === "red",
status: (facts, derived) => ({ // Second param accesses other derivations
phase: facts.phase,
isRed: derived.isRed,
}),
},
constraints: {
fetchUser: {
when: (facts) => facts.isAuthenticated && !facts.profile,
require: (facts) => ({ type: "FETCH_USER", userId: facts.userId }),
},
},
require: (facts) => {
if (!facts.userId) {
return null; // No requirement emitted
}
return { type: "FETCH_USER", userId: facts.userId };
},
// CORRECT
facts.items = [...facts.items, newItem];
facts.config = { ...facts.config, theme: "dark" };
// WRONG
schema: { phase: t.string(), count: t.number() }
// CORRECT
schema: { facts: { phase: t.string(), count: t.number() } }
// WRONG – these do not exist
t.map<string, User>()
t.set<string>()
t.date()
t.record<string, number>()
t.any()
// CORRECT
t.object<Map<string, User>>()
t.object<Set<string>>()
t.object<Date>()
t.object<Record<string, number>>()
t.object<unknown>()
// WRONG – init is synchronous
init: async (facts) => { facts.config = await fetch("/api/config").then(r => r.json()); }
// CORRECT – init sets defaults; async work goes in constraints/resolvers
init: (facts) => { facts.config = null; }
Always use (req, context) – never (req, ctx) or (request, context).
// WRONG – return value is ignored
resolve: async (req, context) => { return await fetchUser(req.userId); }
// CORRECT – mutate context.facts
resolve: async (req, context) => { context.facts.user = await fetchUser(req.userId); }
// WRONG
const profile = system.facts.profile as UserProfile;
// CORRECT – schema provides the type
const profile = system.facts.profile;
// WRONG – derivation just returns a fact unchanged
derive: { count: (facts) => facts.count }
// CORRECT – read the fact directly: system.facts.count
// WRONG
require: "FETCH_DATA"
// CORRECT
require: { type: "FETCH_DATA" }
// facts.self.* is only for multi-module cross-module deps contexts
// In single-module resolvers: use context.facts.fieldName directly
// WRONG
import { createModule } from "@directive-run/core/module";
// CORRECT
import { createModule } from "@directive-run/core";
// Exception: plugins use @directive-run/core/plugins
| Use | Never Use |
|---|---|
facts | state, store, atoms |
derivations / derive | computed, selectors, getters, memos |
constraints | rules, conditions, triggers |
resolvers | handlers, actions, reducers |
requirements | requests, commands |
effects | watchers, subscriptions, reactions |
(req, context) | (req, ctx) or (request, context) |
core-patterns.md – decision trees, full module example, system creation patternsschema-types.md – complete t.* builder reference, chainable methods, nonexistent typesnaming.md – req/context rules, return style, blank-line conventions, multi-module naminganti-patterns.md – 20 ranked anti-patterns with correct/wrong examplesWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub directive-run/directive --plugin directiveOther plugins' skills for the same job
12 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.