### Create a State Machine Actor with Input and Context Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Demonstrates how to create a state machine actor using `setup` that accepts input, which is then used to initialize its context. The example shows how to pass initial input and subscribe to context changes. ```typescript import { setup, createActor } from 'xstate'; const feedbackMachine = setup({ // ... }).createMachine({ context: ({ input }) => ({ rating: input.defaultRating, }), initial: 'question', states: { question: { /* ... */ }, // ... }, }); const feedbackActor = createActor(feedbackMachine, { input: { defaultRating: 3, }, }); feedbackActor.subscribe((snapshot) => { console.log(snapshot.context); }); feedbackActor.start(); // logs { rating: 3 } ``` -------------------------------- ### Example Interaction: TypeScript Setup Source: https://github.com/juststeve/xstate-skill/blob/main/README.md Illustrates a user asking for TypeScript configuration for XState v5, prompting Claude to provide patterns using the skill. ```text You: "Set up TypeScript for XState v5" Claude: [Provides proper tsconfig and type safety patterns] ``` -------------------------------- ### Install XState Source: https://context7.com/juststeve/xstate-skill/llms.txt Install XState using npm, pnpm, or yarn. ```bash # npm npm install xstate # pnpm pnpm install xstate # yarn yarn add xstate ``` -------------------------------- ### Create a simple counter machine with XState Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md This example demonstrates creating a simple counter machine with XState, including increment, decrement, and set actions. It also shows how to create an actor, start it, subscribe to its state, and send events to it. ```javascript import { createMachine, assign, createActor } from 'xstate'; const countMachine = createMachine({ context: { count: 0, }, on: { INC: { actions: assign({ count: ({ context }) => context.count + 1, }), }, DEC: { actions: assign({ count: ({ context }) => context.count - 1, }), }, SET: { actions: assign({ count: ({ event }) => event.value, }), }, }, }); const countActor = createActor(countMachine).start(); countActor.subscribe((state) => { console.log(state.context.count); }); countActor.send({ type: 'INC' }); // logs 1 countActor.send({ type: 'INC' }); // logs 2 countActor.send({ type: 'SET', value: 5 }); // logs 5 countActor.send({ type: 'DEC' }); // logs 4 ``` -------------------------------- ### Create a Type-Safe State Machine with setup Source: https://context7.com/juststeve/xstate-skill/llms.txt Use setup to create a type-safe state machine with strongly typed context and events. Define actions and transitions. ```typescript import { setup, createActor, assign } from 'xstate'; const feedbackMachine = setup({ types: { context: {} as { feedback: string }, events: {} as | { type: 'feedback.good' } | { type: 'feedback.bad' }, }, actions: { logTelemetry: () => { console.log('Telemetry logged'); }, }, }).createMachine({ id: 'feedback', initial: 'idle', context: { feedback: '' }, states: { idle: { on: { 'feedback.good': { actions: 'logTelemetry', target: 'success' }, 'feedback.bad': { actions: 'logTelemetry', target: 'failure' } } }, success: { type: 'final' }, failure: { type: 'final' } } }); const actor = createActor(feedbackMachine); actor.subscribe((snapshot) => { console.log('State:', snapshot.value); }); actor.start(); actor.send({ type: 'feedback.good' }); // logs 'success' ``` -------------------------------- ### Create Type-Safe Machine with setup() Source: https://github.com/juststeve/xstate-skill/blob/main/SKILL.md An XState v5 machine utilizing the `setup()` function for strong TypeScript typing of context, events, and actions. This ensures type safety during machine definition and usage. Requires `setup` import. Recommended for complex applications needing robust type checking. ```typescript import { setup } from 'xstate'; const feedbackMachine = setup({ types: { context: {} as { feedback: string }, events: {} as | { type: 'feedback.good' } | { type: 'feedback.bad' }, }, actions: { logTelemetry: () => { // Implement telemetry logging }, }, }).createMachine({ // Machine config with full type inference initial: 'idle', context: { feedback: '' }, states: { idle: { on: { 'feedback.good': { actions: 'logTelemetry', target: 'success' }, 'feedback.bad': { actions: 'logTelemetry', target: 'failure' } } }, success: {}, failure: {} } }); ``` -------------------------------- ### Install XState with yarn Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Use this command to install XState using yarn. ```bash yarn add xstate ``` -------------------------------- ### XState Template Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Use this template to get started with XState in a JavaScript environment without a specific framework. ```javascript import { createMachine, interpret } from 'xstate'; const toggleMachine = createMachine({ id: 'toggle', initial: 'inactive', states: { inactive: { on: { TOGGLE: 'active' } }, active: { on: { TOGGLE: 'inactive' } } } }); const service = interpret(toggleMachine).onTransition((state) => console.log(state.value) ); service.start(); service.send('TOGGLE'); // Output: active service.send('TOGGLE'); // Output: inactive ``` -------------------------------- ### Install XState with pnpm Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Use this command to install XState using pnpm. ```bash pnpm install xstate ``` -------------------------------- ### Install XState with npm Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Use this command to install XState using npm. ```bash npm install xstate ``` -------------------------------- ### Define Machine Types with setup() Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Use the setup(...) function to define the types for your machine's context and events. This provides strong type inference for actions and the created machine. ```typescript import { setup } from 'xstate'; const feedbackMachine = setup({ types: { context: {} as { feedback: string }, events: {} as { type: 'feedback.good' } | { type: 'feedback.bad' }, }, actions: { logTelemetry: () => { // TODO: implement }, }, }).createMachine({ // ... }); ``` -------------------------------- ### Installation Commands Source: https://github.com/juststeve/xstate-skill/blob/main/SKILL.md Commands to install XState and the latest version of TypeScript using npm, pnpm, and yarn. ```bash # npm npm install xstate # pnpm pnpm install xstate # yarn yarn add xstate # TypeScript (required: v5.0+) npm install typescript@latest --save-dev ``` -------------------------------- ### Example Interaction: Callback Actors Source: https://github.com/juststeve/xstate-skill/blob/main/README.md Shows how a user can inquire about using callback actors for event listeners, with Claude referencing skill examples. ```text You: "How do I use callback actors for event listeners?" Claude: [References skill examples and provides v5 patterns] ``` -------------------------------- ### Create Toggle Machine with States Source: https://github.com/juststeve/xstate-skill/blob/main/SKILL.md An XState v5 machine with multiple states and transitions, using `setup()`. Demonstrates state entry actions and toggling between states. Requires `setup`, `createActor`, and `assign` imports. Suitable for implementing distinct modes or statuses. ```typescript import { setup, createActor, assign } from 'xstate'; const machine = setup({ /* ... */ }).createMachine({ id: 'toggle', initial: 'active', context: { count: 0 }, states: { active: { entry: assign({ count: ({ context }) => context.count + 1, }), on: { toggle: { target: 'inactive' }, }, }, inactive: { on: { toggle: { target: 'active' }, }, }, }, }); const actor = createActor(machine); actor.subscribe((snapshot) => { console.log(snapshot.value); }); actor.start(); // logs 'active' with context { count: 1 } actor.send({ type: 'toggle' }); // transitions to 'inactive' ``` -------------------------------- ### Install Latest TypeScript Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Install the latest version of TypeScript as a development dependency. XState v5 requires TypeScript 5.0 or greater. ```bash npm install typescript@latest --save-dev ``` -------------------------------- ### Example Interaction: Create Toggle Machine Source: https://github.com/juststeve/xstate-skill/blob/main/README.md Demonstrates how a user can ask Claude to create a toggle state machine using the XState skill. ```text You: "Help me create a toggle state machine with XState" Claude: [Uses the xstate skill to provide v5-compliant implementation] ``` -------------------------------- ### Agent Coordination Protocol: Before Work Source: https://github.com/juststeve/xstate-skill/blob/main/CLAUDE.md Execute these commands before starting agent work to set up the pre-task environment and restore the session. ```bash npx claude-flow@alpha hooks pre-task --description "[task]" npx claude-flow@alpha hooks session-restore --session-id "swarm-[id]" ``` -------------------------------- ### Example Console Output for State Transition Source: https://github.com/juststeve/xstate-skill/blob/main/docs/plans/2025-10-21-xstate-agent-workflow-conventions.md Illustrates the formatted console output for a state transition, showing the received event, state change, and context updates. ```text → Event: TOGGLE ✓ inactive → active 📊 Context: { count: 1 } ``` -------------------------------- ### Clone XState Skill Repository Source: https://github.com/juststeve/xstate-skill/blob/main/README.md Use this bash command to clone the XState Skill repository. This is the first step for installation. ```bash git clone https://github.com/justSteve/XState-Skill.git ``` -------------------------------- ### Extract and Install XState Skill from ZIP Source: https://github.com/juststeve/xstate-skill/blob/main/README.md Extract the XState Skill from a ZIP file and move it to the Claude Code skills directory. Remember to restart Claude Code afterwards. ```bash unzip xstate.zip -d xstate-skill # Move to skills directory mv xstate-skill ~/.claude/skills/xstate # Restart Claude Code ``` -------------------------------- ### XState + React Template Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md This template provides a starting point for integrating XState with React applications. ```javascript import React from 'react'; import { useMachine } from '@xstate/react'; import { createMachine } from 'xstate'; const toggleMachine = createMachine({ id: 'toggle', initial: 'inactive', states: { inactive: { on: { TOGGLE: 'active' } }, active: { on: { TOGGLE: 'inactive' } } } }); function Toggle() { const [state, send] = useMachine(toggleMachine); return ( ); } export default Toggle; ``` -------------------------------- ### Create a callback actor for window resize events Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md This example shows how to create a callback actor using `fromCallback` to listen for window resize events. It sends the event back to the parent and also listens for a 'stopListening' event to clean up the event listener. ```typescript import { createActor, createMachine, fromCallback, sendTo, setup, } from 'xstate'; const resizeLogic = fromCallback(({ sendBack, receive }) => { const resizeHandler = (event) => { sendBack(event); }; window.addEventListener('resize', resizeHandler); const removeListener = () => { window.removeEventListener('resize', resizeHandler); }; receive((event) => { if (event.type === 'stopListening') { console.log('Stopping listening'); removeListener(); } }); // Cleanup function return () => { console.log('Cleaning up'); removeListener(); }; }); const machine = setup({ actors: { resizeLogic, }, }).createMachine({ id: 'resize', initial: 'idle', states: { idle: { on: { START_LISTENING: { target: 'listening', actions: sendTo('resizeLogic', ({ event }) => event), // Send the START_LISTENING event to the callback actor }, }, }, listening: { invoke: { src: 'resizeLogic', }, on: { // Handle the 'resize' event sent back from the callback actor resize: { actions: (context, event) => { console.log('Window resized:', event); }, }, STOP_LISTENING: { target: 'idle', actions: sendTo('resizeLogic', { type: 'stopListening' }), // Send stopListening event to the callback actor }, }, }, }, }); const actor = createActor(machine).start(); actor.send({ type: 'START_LISTENING' }); // To stop listening after some time: // setTimeout(() => { // actor.send({ type: 'STOP_LISTENING' }); // }, 5000); ``` -------------------------------- ### Create a Basic State Machine with createMachine Source: https://context7.com/juststeve/xstate-skill/llms.txt Define a state machine using createMachine, including context, event handlers, and actions. Start an actor and subscribe to state changes. ```typescript import { createMachine, assign, createActor } from 'xstate'; const countMachine = createMachine({ context: { count: 0, }, on: { INC: { actions: assign({ count: ({ context }) => context.count + 1, }), }, DEC: { actions: assign({ count: ({ context }) => context.count - 1, }), }, SET: { actions: assign({ count: ({ event }) => event.value, }), }, }, }); const countActor = createActor(countMachine).start(); countActor.subscribe((state) => { console.log(state.context.count); }); countActor.send({ type: 'INC' }); // logs 1 countActor.send({ type: 'DEC' }); // logs 0 countActor.send({ type: 'SET', value: 10 }); // logs 10 ``` -------------------------------- ### Create an Actor Instance with createActor Source: https://context7.com/juststeve/xstate-skill/llms.txt Instantiate an actor from a machine definition using createActor. Start the actor, subscribe to its state, and send events. ```typescript import { createMachine, createActor } from 'xstate'; const toggleMachine = createMachine({ initial: 'inactive', states: { inactive: { on: { toggle: { target: 'active' }, }, }, active: { on: { toggle: { target: 'inactive' }, }, }, }, }); const toggleActor = createActor(toggleMachine); toggleActor.subscribe((snapshot) => { console.log(snapshot.value); // 'inactive' or 'active' }); toggleActor.start(); // logs 'inactive' toggleActor.send({ type: 'toggle' }); // logs 'active' toggleActor.send({ type: 'toggle' }); // logs 'inactive' ``` -------------------------------- ### Example Full-Stack Development with Claude Code Task Tool Source: https://github.com/juststeve/xstate-skill/blob/main/CLAUDE.md Demonstrates parallel agent execution for full-stack development using Claude Code's Task tool. All operations, including tasks, todos, and file writes, should be batched in a single message. ```javascript // Single message with all agent spawning via Claude Code's Task tool [Parallel Agent Execution]: Task("Backend Developer", "Build REST API with Express. Use hooks for coordination.", "backend-dev") Task("Frontend Developer", "Create React UI. Coordinate with backend via memory.", "coder") Task("Database Architect", "Design PostgreSQL schema. Store schema in memory.", "code-analyzer") Task("Test Engineer", "Write Jest tests. Check memory for API contracts.", "tester") Task("DevOps Engineer", "Setup Docker and CI/CD. Document in memory.", "cicd-engineer") Task("Security Auditor", "Review authentication. Report findings via hooks.", "reviewer") // All todos batched together TodoWrite { todos: [...8-10 todos...] } // All file operations together Write "backend/server.js" Write "frontend/App.jsx" Write "database/schema.sql" ``` -------------------------------- ### XState Actor Inspection Event Example Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Represents an inspection event emitted when an actor is created. ```js { type: '@xstate.actor', actorRef: {/* Actor reference */}, rootId: 'x:0', } ``` -------------------------------- ### XState Snapshot Inspection Event Example Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Represents an inspection event emitted when an actor's snapshot is updated. ```js { type: '@xstate.snapshot', actorRef: {/* Actor reference */}, rootId: 'x:0', snapshot: { status: 'active', context: { count: 31 }, // ... }, event: { type: 'increment' } } ``` -------------------------------- ### Get SPARC Mode Details Source: https://github.com/juststeve/xstate-skill/blob/main/CLAUDE.md Retrieve detailed information about a specific SPARC mode. Replace `` with the mode name. ```bash npx claude-flow sparc info ``` -------------------------------- ### Callback actor with input and typed events Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md This example demonstrates a callback actor that accepts input and is typed for specific event objects. The `input` property is typed as `{ defaultSize: number }` and can be accessed within the callback logic. ```typescript import { fromCallback, createActor, setup, type EventObject } from 'xstate'; const resizeLogic = fromCallback( ({ sendBack, receive, input, // Typed as { defaultSize: number } }) => { // Access input here console.log('Default size:', input.defaultSize); // e.g., 100 const resizeHandler = (event) => { // Assuming 'event' is a ResizeObserverEntry or similar sendBack({ type: 'RESIZE', payload: event }); }; window.addEventListener('resize', resizeHandler); const removeListener = () => { window.removeEventListener('resize', resizeHandler); }; receive((event) => { if (event.type === 'stopListening') { console.log('Stopping listening'); removeListener(); } }); // Cleanup function return () => { console.log('Cleaning up'); removeListener(); }; }, ); const machine = setup({ actors: { resizeLogic, }, }).createMachine({ id: 'resizeWithInput', initial: 'idle', states: { idle: { on: { START_LISTENING: { target: 'listening', actions: sendTo('resizeLogic', ({ event }) => event), // Send the START_LISTENING event to the callback actor }, }, }, listening: { invoke: { src: 'resizeLogic', input: { defaultSize: 100, // Provide the input value }, }, on: { RESIZE: { actions: (context, event) => { console.log('Window resized with payload:', event.payload); }, }, STOP_LISTENING: { target: 'idle', actions: sendTo('resizeLogic', { type: 'stopListening' }), // Send stopListening event to the callback actor }, }, }, }, }); const actor = createActor(machine).start(); actor.send({ type: 'START_LISTENING' }); // To stop listening after some time: // setTimeout(() => { // actor.send({ type: 'STOP_LISTENING' }); // }, 5000); ``` -------------------------------- ### XState Event Inspection Event Example Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Represents an inspection event emitted when an event is sent to an actor. ```js { type: '@xstate.event', actorRef: {/* Actor reference */}, rootId: 'x:0', event: { type: 'someEvent', message: 'hello' }, sourceRef: {/* Actor reference */}, } ``` -------------------------------- ### Create and Interact with a Toggle State Machine Actor Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Defines a simple toggle state machine and demonstrates how to create an actor from it, subscribe to its state changes, start it, and send events to it. Ensure the machine definition is complete. ```typescript import { createMachine, createActor } from 'xstate'; const toggleMachine = createMachine({ initial: 'inactive', states: { inactive: { on: { toggle: { target: 'active', }, }, }, active: { on: { toggle: { target: 'inactive', }, }, }, }, }); const toggleActor = createActor(toggleMachine); toggleActor.subscribe((snapshot) => { console.log(snapshot.value); // 'inactive' or 'active' }); toggleActor.start(); // logs 'inactive' toggleActor.send({ type: 'toggle' }); // logs 'active' toggleActor.send({ type: 'toggle' }); // logs 'ina ``` -------------------------------- ### Define and Subscribe to a Promise Actor Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Defines a promise actor using `fromPromise` and subscribes to its snapshots to log status and output. Starts the actor and logs initial and final states. ```typescript import { fromPromise, createActor } from 'xstate';async function getUser(id: string) { // ... return { id /* other user data */ };} const promiseLogic = fromPromise(async () => { const user = await getUser('123'); return user; }); const promiseActor = createActor(promiseLogic); promiseActor.subscribe((snapshot) => { console.log(snapshot.status, snapshot.output); }); promiseActor.start();// logs 'active', undefined// ... (after some time)// logs 'done', { id: '123', /* other user data */ } ``` -------------------------------- ### Invoke Promise-based Actor with XState Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Invokes a Promise-based actor to fetch user data. Includes setup for actor types and context. Handles potential errors by assigning them to the context. ```typescript import { setup, createActor, fromPromise, assign } from 'xstate'; const fetchUser = (userId: string) => fetch(`https://example.com/${userId}`).then((response) => response.text()); const userMachine = setup({ types: { context: {} as { userId: string; user: object | undefined; error: unknown; }, }, actors: { fetchUser: fromPromise(async ({ input }: { input: { userId: string } }) => { const user = await fetchUser(input.userId); return user; }), }, }).createMachine({ id: 'user', initial: 'idle', context: { userId: '42', user: undefined, error: und ``` ```typescript invoke: { src: 'fetchUser', onError: { target: 'failure', actions: assign({ error: ({ event }) => event.error }) } } ``` -------------------------------- ### Correct Claude Flow Workflow: Parallel Agent Execution Source: https://github.com/juststeve/xstate-skill/blob/main/CLAUDE.md This snippet demonstrates the correct way to set up and execute agents in Claude Flow using a single message for coordination. It includes optional coordination setup, spawning various agent types, and batching tasks and file operations for parallel execution. ```javascript // Step 1: MCP tools set up coordination (optional, for complex tasks) [Single Message - Coordination Setup]: mcp__claude-flow__swarm_init { topology: "mesh", maxAgents: 6 } mcp__claude-flow__agent_spawn { type: "researcher" } mcp__claude-flow__agent_spawn { type: "coder" } mcp__claude-flow__agent_spawn { type: "tester" } // Step 2: Claude Code Task tool spawns ACTUAL agents that do the work [Single Message - Parallel Agent Execution]: // Claude Code's Task tool spawns real agents concurrently Task("Research agent", "Analyze API requirements and best practices. Check memory for prior decisions.", "researcher") Task("Coder agent", "Implement REST endpoints with authentication. Coordinate via hooks.", "coder") Task("Database agent", "Design and implement database schema. Store decisions in memory.", "code-analyzer") Task("Tester agent", "Create comprehensive test suite with 90% coverage.", "tester") Task("Reviewer agent", "Review code quality and security. Document findings.", "reviewer") // Batch ALL todos in ONE call TodoWrite { todos: [ {id: "1", content: "Research API patterns", status: "in_progress", priority: "high"}, {id: "2", content: "Design database schema", status: "in_progress", priority: "high"}, {id: "3", content: "Implement authentication", status: "pending", priority: "high"}, {id: "4", content: "Build REST endpoints", status: "pending", priority: "high"}, {id: "5", content: "Write unit tests", status: "pending", priority: "medium"}, {id: "6", content: "Integration tests", status: "pending", priority: "medium"}, {id: "7", content: "API documentation", status: "pending", priority: "low"}, {id: "8", content: "Performance optimization", status: "pending", priority: "low"} ]} // Parallel file operations Bash "mkdir -p app/{src,tests,docs,config}" Write "app/package.json" Write "app/src/server.js" Write "app/tests/server.test.js" Write "app/docs/API.md" ``` -------------------------------- ### Build Project Source: https://github.com/juststeve/xstate-skill/blob/main/CLAUDE.md Compile and build the project. ```bash npm run build ``` -------------------------------- ### Invoke Actor on State Entry Source: https://context7.com/juststeve/xstate-skill/llms.txt Invokes an actor when a state is entered. The actor's lifecycle is tied to the state's lifecycle. Requires setup with `setup`, `fromPromise`, and `assign`. ```typescript import { setup, createActor, fromPromise, assign } from 'xstate'; const fetchUser = (userId: string) => fetch(`https://api.example.com/users/${userId}`).then((res) => res.json()); const userMachine = setup({ types: { context: {} as { userId: string; user: object | undefined; error: unknown; }, }, actors: { fetchUser: fromPromise(async ({ input }: { input: { userId: string } }) => { const user = await fetchUser(input.userId); return user; }), }, }).createMachine({ id: 'user', initial: 'idle', context: { userId: '42', user: undefined, error: undefined, }, states: { idle: { on: { fetch: 'loading' }, }, loading: { invoke: { src: 'fetchUser', input: ({ context }) => ({ userId: context.userId }), onDone: { target: 'success', actions: assign({ user: ({ event }) => event.output }), }, onError: { target: 'failure', actions: assign({ error: ({ event }) => event.error }), }, }, }, success: {}, failure: { on: { retry: 'loading' }, }, }, }); const userActor = createActor(userMachine); userActor.subscribe((snapshot) => { console.log('State:', snapshot.value, 'User:', snapshot.context.user); }); userActor.start(); userActor.send({ type: 'fetch' }); ``` -------------------------------- ### Create and Run a Simple XState Machine Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Defines a toggle machine with active and inactive states, initializes an actor, subscribes to its snapshots, and sends a toggle event. ```ts import { setup, createActor, assign } from 'xstate';const machine = setup({ /* ... */ }).createMachine({ id: 'toggle', initial: 'active', context: { count: 0 }, states: { active: { entry: assign({ count: ({ context }) => context.count + 1, }), on: { toggle: { target: 'inactive' }, }, }, inactive: { on: { toggle: { target: 'active' }, }, }, }, }); const actor = createActor(machine); actor.subscribe((snapshot) => { console.log(snapshot.value); }); actor.start(); // logs 'active' with context { count: 1 } actor.send({ type: 'toggle' }) ``` -------------------------------- ### Standard XState Sandbox File Structure Source: https://github.com/juststeve/xstate-skill/blob/main/docs/plans/2025-10-21-xstate-agent-workflow-conventions.md This is the standard directory structure for an XState sandbox experiment. It includes a main entry point, directories for state machine definitions and utility helpers, and configuration files. ```bash /tmp/xstate-sandbox/ ├── package.json ├── tsconfig.json ├── src/ │ ├── index.ts # Main file for current experiment │ ├── machines/ # State machine definitions │ └── helpers/ # inspect.ts, runner.ts utilities └── README.md # Quick reference for sandbox commands ``` -------------------------------- ### Run Tests Source: https://github.com/juststeve/xstate-skill/blob/main/CLAUDE.md Execute all project tests. ```bash npm run test ``` -------------------------------- ### List Available SPARC Modes Source: https://github.com/juststeve/xstate-skill/blob/main/CLAUDE.md Execute this command to see all the available modes for the SPARC methodology. ```bash npx claude-flow sparc modes ``` -------------------------------- ### Accessing System from Root Actor Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Demonstrates how to access the system from the root actor created by createActor. The system is available via the .system property. ```typescript import { createMachine, createActor } from 'xstate'; const machine = createMachine({ entry: ({ system }) => { // ... }, }); const actor = createActor(machine).start(); actor.system; ``` -------------------------------- ### Create Transition Actor with Input using fromTransition Source: https://context7.com/juststeve/xstate-skill/llms.txt Use `fromTransition` with an input function to configure the initial state of the actor. This allows for dynamic initialization based on provided input values. The actor's initial state will be determined by the return value of the input function. ```typescript import { fromTransition, createActor } from 'xstate'; const countLogic = fromTransition( (state, event) => { switch (event.type) { case 'increment': return { count: state.count + 1 }; default: return state; } }, ({ input }: { input: number }) => ({ count: input, // Initial state from input }) ); const countActor = createActor(countLogic, { input: 42, }); countActor.subscribe((snapshot) => { console.log(snapshot.context); // logs { count: 42 } }); countActor.start(); ``` -------------------------------- ### Lint Project Source: https://github.com/juststeve/xstate-skill/blob/main/CLAUDE.md Run the linter to check for code style issues. ```bash npm run lint ``` -------------------------------- ### Create Simple Counter Machine Source: https://github.com/juststeve/xstate-skill/blob/main/SKILL.md A basic XState v5 machine for a counter, demonstrating context and actions. Requires `createMachine`, `assign`, and `createActor` imports. Use when implementing simple stateful logic. ```typescript import { createMachine, assign, createActor } from 'xstate'; const countMachine = createMachine({ context: { count: 0, }, on: { INC: { actions: assign({ count: ({ context }) => context.count + 1, }), }, DEC: { actions: assign({ count: ({ context }) => context.count - 1, }), }, SET: { actions: assign({ count: ({ event }) => event.value, }), }, }, }); const countActor = createActor(countMachine).start(); countActor.subscribe((state) => { console.log(state.context.count); }); countActor.send({ type: 'INC' }); // logs 1 countActor.send({ type: 'DEC' }); // logs 0 ``` -------------------------------- ### Helper Function for Running State Machines Source: https://github.com/juststeve/xstate-skill/blob/main/docs/plans/2025-10-21-xstate-agent-workflow-conventions.md Provides a simple API to execute a sequence of events against an XState machine and log the full execution trace. ```javascript run(machine, ['TOGGLE', 'TOGGLE', 'RESET']) ``` -------------------------------- ### Run Complete TDD Workflow Source: https://github.com/juststeve/xstate-skill/blob/main/CLAUDE.md Initiate the Test-Driven Development (TDD) workflow for a specified feature. Replace `` with the desired feature name. ```bash npx claude-flow sparc tdd "" ``` -------------------------------- ### Registering Spawned Actor with System ID Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Demonstrates how to spawn a new actor and register it with a unique systemId within the parent actor's context. This allows the spawned actor to be referenced by its systemId. ```typescript import { createMachine, createActor, assign } from 'xstate'; const todoMachine = createMachine({ // ... }); const todosMachine = createMachine({ // ... on: { 'todo.add': { actions: assign({ todos: ({ context, spawn }) => { const newTodo = spawn(todoMachine, { systemId: `todo-${context.todos.length}`, }); return context.todos.concat(newTodo); }, }), }, }, }); ``` -------------------------------- ### Add MCP Servers Source: https://github.com/juststeve/xstate-skill/blob/main/CLAUDE.md Add MCP servers to your project. Claude Flow is required, while others are optional for enhanced coordination and cloud features. ```bash # Add MCP servers (Claude Flow required, others optional) claude mcp add claude-flow npx claude-flow@alpha mcp start claude mcp add ruv-swarm npx ruv-swarm mcp start # Optional: Enhanced coordination claude mcp add flow-nexus npx flow-nexus@latest mcp start # Optional: Cloud features ``` -------------------------------- ### Create Symlink for XState Skill Source: https://github.com/juststeve/xstate-skill/blob/main/README.md Create a symbolic link to the XState Skill directory in your Claude Code skills directory. This allows for easier updates. ```bash ln -s /path/to/XState-Skill ~/.claude/skills/xstate ``` -------------------------------- ### Minimal package.json for XState Sandbox Source: https://github.com/juststeve/xstate-skill/blob/main/docs/plans/2025-10-21-xstate-agent-workflow-conventions.md Defines the basic structure for a Node.js project using ES Modules, including scripts for development with live reloading and direct execution. ```json { "name": "xstate-sandbox", "type": "module", "scripts": { "dev": "tsx watch src/index.ts", "run": "tsx src/index.ts" } } ``` -------------------------------- ### Perform Type Checking Source: https://github.com/juststeve/xstate-skill/blob/main/CLAUDE.md Execute type checking for the project. ```bash npm run typecheck ``` -------------------------------- ### Create Transition Actor with Input Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Create a transition actor with initial state derived from input. The input is passed to the function that resolves the initial state, allowing for dynamic initialization. ```typescript import { fromTransition, createActor } from 'xstate'; const countLogic = fromTransition( (state, event) => { // ... }, ({ input }: { input: number }) => ({ count: input, // Initial state }), ); const countActor = createActor(countLogic, { input: 42, }, ); countActor.subscribe((snapshot) => { console.log(snapshot.context); // logs { count: 42 } }); countActor.start(); ``` -------------------------------- ### Agent Coordination Protocol: During Work Source: https://github.com/juststeve/xstate-skill/blob/main/CLAUDE.md Use these commands during agent work to post edits to files and notify about progress. Memory keys should be specific to the agent and step. ```bash npx claude-flow@alpha hooks post-edit --file "[file]" --memory-key "swarm/[agent]/[step]" npx claude-flow@alpha hooks notify --message "[what was done]" ``` -------------------------------- ### Copy XState Skill to Claude Code Directory Source: https://github.com/juststeve/xstate-skill/blob/main/README.md Copy the downloaded XState Skill to your Claude Code skills directory. This command assumes the skill is in the current directory. ```bash cp -r XState-Skill ~/.claude/skills/xstate ``` -------------------------------- ### Initialize State Machine Actor with Input Source: https://context7.com/juststeve/xstate-skill/llms.txt Configure the initial context of a state machine actor by passing input during creation. This is useful for setting default values. ```typescript import { setup, createActor } from 'xstate'; const feedbackMachine = setup({ types: { context: {} as { rating: number }, input: {} as { defaultRating: number }, }, }).createMachine({ context: ({ input }) => ({ rating: input.defaultRating, }), initial: 'question', states: { question: { on: { submit: { target: 'thanks' } } }, thanks: { type: 'final' } }, }); const feedbackActor = createActor(feedbackMachine, { input: { defaultRating: 3, }, }); feedbackActor.subscribe((snapshot) => { console.log(snapshot.context); // { rating: 3 } }); feedbackActor.start(); ``` -------------------------------- ### Explicitly Type Promise Actor Input and Output Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Demonstrates how to explicitly define the input and output types for a promise actor using generic parameters in `fromPromise`. This enhances type safety. ```typescript import { fromPromise } from 'xstate'; interface User { name: string; id: string; } const secondLogic = fromPromise( async ({ input }: { input: { id: string } }) => { const user = await getUser(input.id); // User is inferred return user; }, ); const firstLogic = fromPromise( async ({ input, self /* ... */ }) => { const user = await getUser(input.id); return user; }, ); ``` -------------------------------- ### Full Pipeline Processing with SPARC Source: https://github.com/juststeve/xstate-skill/blob/main/CLAUDE.md Process a task through the full SPARC pipeline. Replace `` with the specific task description. ```bash npx claude-flow sparc pipeline "" ``` -------------------------------- ### TypeScript Configuration for XState Sandbox Source: https://github.com/juststeve/xstate-skill/blob/main/docs/plans/2025-10-21-xstate-agent-workflow-conventions.md Minimal tsconfig.json for XState v5 development, enabling modern module resolution and strict null checks. ```json { "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "strictNullChecks": true, "skipLibCheck": true } } ``` -------------------------------- ### TypeScript Configuration Source: https://github.com/juststeve/xstate-skill/blob/main/SKILL.md Required TypeScript configuration options for XState v5 to ensure type safety. ```json { "compilerOptions": { "strictNullChecks": true, "skipLibCheck": true } } ``` -------------------------------- ### Execute SPARC Mode with Task Source: https://github.com/juststeve/xstate-skill/blob/main/CLAUDE.md Run a specific SPARC mode with a given task. Replace `` and `` with actual values. ```bash npx claude-flow sparc run "" ``` -------------------------------- ### Configure tsconfig.json for XState Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Configure your tsconfig.json file to enable strict null checks or the full strict mode for better type safety with XState. Skipping library checks is also recommended. ```json5 // tsconfig.json{ compilerOptions: { // ... strictNullChecks: true, // or set `strict` to true, which includes `strictNullChecks` // "strict": true, skipLibCheck: true, }, } ``` -------------------------------- ### Extracting Machine Types with Type Helpers Source: https://context7.com/juststeve/xstate-skill/llms.txt Leverage XState's type helpers (ActorRefFrom, SnapshotFrom, EventFrom) to extract types from machine definitions. These helpers provide strong typing for actors, snapshots, and events. ```typescript import { createMachine, createActor, type ActorRefFrom, type SnapshotFrom, type EventFrom, } from 'xstate'; const toggleMachine = createMachine({ types: { events: {} as { type: 'toggle' } | { type: 'reset' }, }, initial: 'inactive', states: { inactive: { on: { toggle: 'active' }, }, active: { on: { toggle: 'inactive', reset: 'inactive' }, }, }, }); // Extract types from the machine type ToggleActorRef = ActorRefFrom; type ToggleSnapshot = SnapshotFrom; type ToggleEvent = EventFrom; // Use in components or functions function handleToggle(actorRef: ToggleActorRef) { actorRef.send({ type: 'toggle' }); } function getStateValue(snapshot: ToggleSnapshot): string { return snapshot.value as string; } const actor = createActor(toggleMachine); actor.start(); handleToggle(actor); console.log(getStateValue(actor.getSnapshot())); // 'active' ``` -------------------------------- ### Create a Promise Actor with Input Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Creates a promise actor that accepts input, which is then used within the promise logic to fetch data. The input is provided during actor creation. ```typescript import { fromPromise, createActor } from 'xstate'; const promiseLogic = fromPromise(async ({ input }) => { const user = await getUser(input.id); return user; }); const promiseActor = createActor(promiseLogic, { input: { id: '123' }, }); ``` -------------------------------- ### Agent Coordination Protocol: After Work Source: https://github.com/juststeve/xstate-skill/blob/main/CLAUDE.md Execute these commands after agent work is completed to finalize tasks and export metrics. ```bash npx claude-flow@alpha hooks post-task --task-id "[task]" npx claude-flow@alpha hooks session-end --export-metrics true ``` -------------------------------- ### Create Transition Actor with Initial State Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Define transition actor logic using fromTransition, providing a state transition function and an initial state object. The actor can then be created and interacted with. ```typescript import { fromTransition, createActor } from 'xstate'; const countLogic = fromTransition( (state, event) => { switch (event.type) { case 'increment': { return { count: state.count + 1 }; } case 'decrement': { return { count: state.count - 1 }; } default: { return state; } } }, { count: 0 }, ); // Initial state const countActor = createActor(countLogic); countActor.subscribe((snapshot) => { console.log(snapshot.context); }); countActor.start();// logs { count: 0 } countActor.send({ type: 'increment' });// logs { count: 1 } countActor.send({ ty ``` -------------------------------- ### Spawn Actor and Store Reference in Context Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Use the spawn helper function within the assign action creator to spawn an actor and store its ActorRef in the machine's context. Ensure the ActorRef is removed from context to prevent memory leaks when the actor is no longer needed. ```typescript const parentMachine = createMachine({ entry: [ assign({ childMachineRef: ({ spawn }) => spawn(childMachine, { id: 'child' }), }), ], }); ``` -------------------------------- ### Spawn Agents Concurrently with Claude Code Task Tool Source: https://github.com/juststeve/xstate-skill/blob/main/CLAUDE.md Use Claude Code's Task tool to spawn multiple agents in parallel within a single message for efficient agent execution. This is the primary method for agent spawning. ```javascript // ✅ CORRECT: Use Claude Code's Task tool for parallel agent execution [Single Message]: Task("Research agent", "Analyze requirements and patterns...", "researcher") Task("Coder agent", "Implement core features...", "coder") Task("Tester agent", "Create comprehensive tests...", "tester") Task("Reviewer agent", "Review code quality...", "reviewer") Task("Architect agent", "Design system architecture...", "system-architect") ``` -------------------------------- ### Multi-Task Processing with SPARC Concurrent Mode Source: https://github.com/juststeve/xstate-skill/blob/main/CLAUDE.md Process multiple tasks concurrently using a specified mode and a tasks file. Replace `` and `` accordingly. ```bash npx claude-flow sparc concurrent "" ``` -------------------------------- ### Sending Events to an Actor via System Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md Illustrates sending an event to a specific actor ('notifier') within the system using system.get('actorId'). This is useful for inter-actor communication. ```typescript import { createMachine, createActor, sendTo } from 'xstate'; const formMachine = createMachine({ // ... on: { submit: { actions: sendTo(({ system }) => system.get('notifier'), { type: 'notify', message: 'Form submitted!', }), }, }, }); const feedbackMachine = createMachine({ invoke: { systemId: 'formMachine', src: formMachine, }, // ... states: { // ... form: { invoke: formMachine, }, }, }); const feedbackActor = createActor(feedbackMachine).start(); ``` -------------------------------- ### XState + Vue Template Source: https://github.com/juststeve/xstate-skill/blob/main/references/state.md This template is designed for using XState with Vue.js applications. ```javascript import { defineComponent } from 'vue'; import { useMachine } from '@xstate/vue'; import { createMachine } from 'xstate'; const toggleMachine = createMachine({ id: 'toggle', initial: 'inactive', states: { inactive: { on: { TOGGLE: 'active' } }, active: { on: { TOGGLE: 'inactive' } } } }); export default defineComponent({ name: 'Toggle', setup() { const { state, send } = useMachine(toggleMachine); return { state, send }; } }); ``` -------------------------------- ### Actor Systems for Inter-Actor Communication Source: https://context7.com/juststeve/xstate-skill/llms.txt Creates an actor system where actors can communicate via registered system IDs. Uses `sendTo` with `system.get` to target actors by ID. ```typescript import { createMachine, createActor, sendTo, setup } from 'xstate'; const formMachine = createMachine({ id: 'form', initial: 'editing', states: { editing: { on: { submit: { actions: sendTo(({ system }) => system.get('notifier'), { type: 'notify', message: 'Form submitted!', }), target: 'submitted', }, }, }, submitted: { type: 'final' }, }, }); const notifierMachine = createMachine({ id: 'notifier', on: { notify: { actions: ({ event }) => console.log('Notification:', event.message), }, }, }); const appMachine = setup({ actors: { formMachine, notifierMachine }, }).createMachine({ type: 'parallel', states: { form: { invoke: { src: 'formMachine', systemId: 'form', }, }, notifier: { invoke: { src: 'notifierMachine', systemId: 'notifier', }, }, }, }); const appActor = createActor(appMachine, { systemId: 'root', }); appActor.start(); appActor.system.get('form')?.send({ type: 'submit' }); // logs: 'Notification: Form submitted!' ``` -------------------------------- ### Parallel Execution of SPARC Modes Source: https://github.com/juststeve/xstate-skill/blob/main/CLAUDE.md Execute multiple SPARC modes in parallel for a given task. Replace `` and `` with actual values. ```bash npx claude-flow sparc batch "" ```