/claude-code-superpowers:state-managementfrom claude-code-superpowers
Provides patterns for reading and writing shared application state using immutable updates and atomic reducers. Helps avoid race conditions and stale UI when multiple tools or components access state concurrently.
Ships in claude-code-superpowers. 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.
None: SKILL.md is the whole skill.
Shared mutable state is wrapped in a deep-immutable type. Direct mutation is a compile error. All updates go through a single setter that accepts a pure function (prev: State) => State. Returning the same reference signals "nothing changed" and skips downstream work — no re-render, no diff.
The reducer function is atomic: the entire state object is replaced in one operation. Partial updates are expressed as spreads — the fields that didn't change carry forward from prev; only the changed fields are new values. This makes every transition explicit, traceable, and race-condition-safe.
Claude Code's AppState is a large object — UI flags, permission context, task records, session configuration — shared across tools running concurrently, React components rendering in a terminal, and background task workers. Without an immutability contract, a tool updating tasks could race with a UI component reading toolPermissionContext mid-update, producing torn reads.
The DeepImmutable<T> wrapper makes that impossible at the type level. TypeScript rejects direct assignment to any nested field. The only way to change state is through the reducer, which replaces the entire object atomically. The reference-equality short-circuit (return prev when nothing changed) prevents the scheduler from scheduling re-renders for no-op updates — important when multiple tasks call setAppState in rapid succession.
context.getAppState() — this returns the current immutable snapshot.context.setAppState(prev => next). Always return a new object; never mutate prev.tasks), spread at every level: { ...prev, tasks: { ...prev.tasks, [id]: updated } }.prev unchanged — this is the reference-equality no-op signal.prev unchanged to avoid triggering subscribers unnecessarily.context.getAppState().// Source: src/state/AppStateStore.ts
export type AppState = DeepImmutable<{
verbose: boolean
tasks: Record<string, TaskState>
toolPermissionContext: ToolPermissionContext
// ... ~100 more fields
}>
// DeepImmutable makes every field and nested field readonly.
// Direct mutation — state.verbose = true — is a TypeScript error.
// Source: src/utils/task/framework.ts
type SetAppState = (updater: (prev: AppState) => AppState) => void
export function updateTaskState<T extends TaskState>(
taskId: string,
setAppState: SetAppState,
updater: (task: T) => T,
): void {
setAppState(prev => {
const task = prev.tasks?.[taskId] as T | undefined
if (!task) return prev // no-op: task not found
const updated = updater(task)
if (updated === task) return prev // no-op: updater returned same reference
return {
...prev,
tasks: { ...prev.tasks, [taskId]: updated },
}
})
}
// Source: src/tasks/stopTask.ts
setAppState(prev => {
const prevTask = prev.tasks[taskId]
if (!prevTask || prevTask.notified) {
return prev // Return same reference — no re-render triggered
}
return {
...prev,
tasks: {
...prev.tasks,
[taskId]: { ...prevTask, notified: true },
},
}
})
The if (updated === task) return prev check in updateTaskState is subtle but important. Without it, every call to setAppState would trigger subscribers even when nothing changed — in a system where dozens of tasks poll state every second, this would saturate the React render scheduler.
Before — mutating state directly and storing it in a module-level variable:
// Wrong: module-level state — shared across calls, causes stale reads
let taskStatuses: Record<string, string> = {}
async call(args, context) {
taskStatuses[args.taskId] = 'running' // mutation, no broadcast
await doWork(args)
taskStatuses[args.taskId] = 'completed' // UI never sees this
return { data: 'done' }
}
After — atomic reducer updates through context:
async call(args, context) {
// WHY: setAppState broadcasts to all subscribers atomically
context.setAppState(prev => ({
...prev,
tasks: {
...prev.tasks,
[args.taskId]: { ...prev.tasks[args.taskId], status: 'running' },
},
}))
await doWork(args)
// WHY: return prev unchanged when condition not met — skips re-render
context.setAppState(prev => {
const task = prev.tasks[args.taskId]
if (!task || task.status !== 'running') return prev
return {
...prev,
tasks: {
...prev.tasks,
[args.taskId]: { ...task, status: 'completed' },
},
}
})
return { data: 'done' }
}
call() aren't reflected in the UI until the next full render cyclesetAppState — only values that need to survive beyond the current call or be visible to other tools or the UIsetAppState in a tight loop for progress updates — batch them or use onProgress callbacks insteaddomain-model — where AppState fits in the overall system modeltask-system — task lifecycle transitions are the most common AppState update patternasync-concurrency — concurrent tools reading and writing state safelytool-definition — how context.getAppState() and context.setAppState() are accessed from call()What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
Generated from the plugin's indexed repository (techymt/claude-code-superpowers) — no native marketplace selected
npx claudepluginhub p/techymt-claude-code-superpowers16 skills in this plugin
/async-concurrencyTeaches Claude Code's concurrency model: isConcurrencySafe() for parallel tool execution, AbortController propagation for cancellation, Promise.all() for parallel initialization, and the StreamingToolExecutor for concurrent progress streams. Use this when writing tools that could benefit from parallel execution, need to respect cancellation, or must stream partial results. Read-only tools that don't declare concurrency safety are needlessly serialized.
/build-tool-factoryTeaches how to create a new Claude Code tool using the buildTool() factory from src/Tool.ts.
Use this whenever adding a new capability to Claude Code — buildTool is the only correct entry
point. It fills in safe defaults for isConcurrencySafe, isReadOnly, isDestructive,
checkPermissions, and userFacingName so you only implement what your tool actually needs.
/creating-skillsUse when extracting an engineering pattern from a codebase and packaging it as a skill for an AI assistant. Triggered when: converting a recurring code pattern into a SKILL.md, wanting your AI to apply a specific pattern automatically, or validating whether an existing skill is good enough to ship. Covers structure, the real-code requirement, the two-layer generic/specific design, and six quality tests.
/domain-modelTeaches Claude Code's core domain model: Tool, Message, Task, ToolUseContext, AppState, and Command — the six concepts every part of the system is built around. Use this before writing any new tool, command, or feature that touches the conversation loop. Essential for understanding how Claude's capability system is structured and why the abstractions exist.
/error-handlingTeaches Claude Code's error philosophy: tool call() throws typed errors, the framework catches them and formats them for the LLM as structured tool result content, and custom error types carry structured context at system boundaries. Use this whenever writing a tool, utility function, or service that can fail. The distinction between "errors the LLM should see" and "errors that crash the session" is the core insight.
/hot-pathsTeaches Claude Code's startup and runtime performance patterns: lazySchema() for deferred Zod parsing, feature() flags for build-time dead code elimination, memoize() for expensive repeated computations, parallel initialization with Promise.all(), and profileCheckpoint() for tracking load times. Use this whenever writing code that runs at startup, on every turn, or in a hot loop. Startup latency is Claude Code's most user-visible performance metric.
Other plugins' skills for the same job