
ork-extras
Opt-in reference skills split out of ork: library patterns (LangGraph, RAG, MCP, Vite, Zustand, Storybook and more) and engineering domain guides (accessibility, distributed systems, DDD, release management). Skills only, no agents or hooks. Install next to ork; invoke as /ork-extras:<skill>.
- version
- 10.14.0
- GitHub stars
- 305
Install
/plugin install ork-extras@orchestkitRun it inside Claude Code after adding the marketplace with /plugin marketplace add yonatangross/orchestkit.
Contents
Discovered from sourceSkills 33
Accessibility
Comprehensive patterns for building accessible web applications: WCAG 2.2 AA compliance, keyboard focus management, React Aria component patterns, native HTML-first philosophy, cognitive inclusion, and user preference honoring. Each category has individual rule files in rules/ loaded on-demand.
Quick Reference
| Category | Rules | Impact | When to Use |
|---|---|---|---|
| WCAG Compliance | 3 | CRITICAL | Color contrast, semantic HTML, automated testing |
| POUR Exit Criteria | 1 | CRITICAL | Falsifiable pass/fail thresholds for each WCAG 2.2 AA criterion |
| Static Anti-Patterns | 1 | HIGH | Grep-able patterns detectable without a browser |
| Focus Management | 1 | HIGH | Keyboard navigation; trap/restoration mechanics live upstream |
| React Aria | 2 | HIGH | Accessible components and form hooks; overlay APIs live upstream |
| Modern Web Accessibility | 2 | CRITICAL/HIGH | Native HTML first, user preferences; cognitive ceilings in references/ork-delta.md |
Total: 10 rules across 6 categories
Quick Start
// Semantic HTML with ARIA
<main>
<article>
<header><h1>Page Title</h1></header>
<section aria-labelledby="features-heading">
<h2 id="features-heading">Features</h2>
</section>
</article>
</main>
// Focus trap with React Aria
import { FocusScope } from 'react-aria';
<FocusScope contain restoreFocus autoFocus>
<div role="dialog" aria-modal="true">
{children}
</div>
</FocusScope>
WCAG Compliance
WCAG 2.2 AA implementation for inclusive, legally compliant web applications.
| Rule | File | Key Pattern |
|---|---|---|
| Color Contrast | rules/wcag-color-contrast.md | 4.5:1 text, 3:1 UI components, focus indicators |
| Semantic HTML | rules/wcag-semantic-html.md | Landmarks, headings, ARIA labels, form structure |
| Testing | rules/wcag-testing.md | axe-core, Playwright a11y, screen reader testing |
POUR Exit Criteria
Concrete pass/fail thresholds for each WCAG 2.2 AA criterion — replaces vague "meets requirements" checks.
| Rule | File | Key Pattern |
|---|---|---|
| POUR Exit Criteria | rules/pour-exit-criteria.md | Falsifiable checklist: image alt, contrast ratios, focus indicators, touch targets, ARIA states |
Static Anti-Patterns
Grep-able anti-patterns detectable via static analysis or code review — no browser needed.
| Rule | File | Key Pattern |
|---|---|---|
| A11y Anti-Patterns (Static) | rules/a11y-antipatterns-static.md | Focus removal, missing labels, autoplay, icon-only buttons, div-click handlers |
Focus Management
Keyboard focus management patterns for accessible interactive widgets.
| Rule | File | Key Pattern |
|---|---|---|
| Keyboard Navigation | rules/focus-keyboard-nav.md | Roving tabindex, skip links, arrow keys |
Focus trap and restoration mechanics are upstream's job: use React Aria <FocusScope contain restoreFocus autoFocus> (see Upstream coverage). When React Aria is unavailable, copy scripts/focus-trap-template.tsx; the house rules for both live in references/ork-delta.md.
React Aria
Adobe React Aria hooks for building WCAG-compliant interactive UI.
| Rule | File | Key Pattern |
|---|---|---|
| Components | rules/aria-components.md | useButton, useDialog, useMenu, FocusScope |
| Forms | rules/aria-forms.md | useComboBox, useTextField, useListBox |
Overlay hook APIs (useModalOverlay, useTooltip, usePopover) are documented upstream (see Upstream coverage); the house overlay recipe (FocusScope plus shared motion presets) is in references/ork-delta.md.
Modern Web Accessibility
2026 best practices: native HTML first, cognitive inclusion, and honoring user preferences.
| Rule | File | Key Pattern |
|---|---|---|
| Native HTML First | rules/wcag-native-html-first.md | <dialog>, <details>, native over custom ARIA |
| User Preferences | rules/wcag-user-preferences.md | prefers-reduced-motion, forced-colors, prefers-contrast, zoom |
Cognitive inclusion (ADHD/autism/dyslexia support) is covered upstream by W3C COGA (see Upstream coverage); the house cognitive-load ceilings (notification cap, nav-item cap, reading-level targets) are in references/ork-delta.md.
Key Decisions
| Decision | Recommendation |
|---|---|
| Conformance level | WCAG 2.2 AA (legal standard: ADA, Section 508) |
| Contrast ratio | 4.5:1 normal text, 3:1 large text and UI components |
| Target size | 24px min (WCAG 2.5.8), 44px for touch |
| Focus indicator | 3px solid outline, 3:1 contrast |
| Component library | React Aria hooks for control, react-aria-components for speed |
| State management | react-stately hooks (designed for a11y) |
| Focus management | FocusScope for modals, roving tabindex for widgets |
| Testing | jest-axe (unit) + Playwright axe-core (E2E) |
Anti-Patterns (FORBIDDEN)
- Div soup: Using
<div>instead of semantic elements (<nav>,<main>,<article>) - Color-only information: Status indicated only by color without icon/text
- Missing labels: Form inputs without associated
<label>oraria-label - Keyboard traps: Focus that cannot escape without Escape key
- Removing focus outline:
outline: nonewithout replacement indicator - Positive tabindex: Using
tabindex > 0(disrupts natural order) - Div with onClick: Using
<div onClick>instead of<button>oruseButton - Manual focus in modals: Using
useEffect+ref.focus()instead ofFocusScope - Auto-playing media: Audio/video that plays without user action
- ARIA overuse: Using ARIA when semantic HTML suffices
Upstream coverage (do not restate)
Vendor tutorials, API references, and criterion walkthroughs removed in the 2026-07-31 wrap-plus-delta thinning. Consult the first-party source; only the ork delta (floors, scars, house decisions) lives in references/ork-delta.md.
| Topic | First-party source |
|---|---|
| WCAG 2.2 success-criterion walkthroughs and audit checklists | WCAG 2.2 quick reference and WCAG 2.2 spec |
| ARIA widget patterns and keyboard interaction models | WAI-ARIA Authoring Practices Guide |
| React Aria hook APIs (useButton, useMenu, useComboBox, useModalOverlay, useTooltip, usePopover), component checklists, worked examples | React Aria docs |
| Focus trap, focus restoration, roving tabindex, and skip-link algorithms | React Aria FocusScope and APG patterns |
| Cognitive accessibility guidance (COGA) | W3C Making Content Usable |
| Screen reader testing walkthroughs (NVDA, JAWS, VoiceOver, TalkBack) | WebAIM screen reader testing |
Detailed Documentation
| Resource | Description |
|---|---|
scripts/ | Templates: accessible form, focus trap, React Aria components |
references/ork-delta.md | Ork-specific floors, scars, and house decisions (cognitive ceilings, overlay recipe, canonical focus-trap selector) |
references/ux-thresholds-quick.md | UI/UX thresholds quick reference: contrast, touch targets, cognitive load, typography, forms |
examples/wcag-examples.md | Complete accessible form, modal, and navigation examples |
Related Skills
ork:testing-e2e- E2E testing patterns including accessibility testingdesign-system-starter- Accessible component library patternsork-extras:i18n-date-patterns- RTL layout and locale-aware formattingmotion-animation-patterns- Reduced motion and animation accessibility
Agent Orchestration
Comprehensive patterns for building and coordinating AI agents -- from single-agent reasoning loops to multi-agent systems and framework selection. Coordination and multi-scenario categories have individual rule files in rules/ loaded on-demand; loop and framework tutorials live upstream (see Upstream coverage), with house defaults in references/ork-delta.md.
CC native
/workflows(2.1.154): Claude Code now ships dynamic workflows — ask Claude to create a workflow and it orchestrates tens-to-hundreds of agents in the background; view runs with/workflows. This is complementary to the patterns here: use CC/workflowsfor large-scale, fire-and-forget background fan-out (you check back later); use the bounded foreground Agent Teams / Task-tool patterns below when ≤8 agents must coordinate within a single skill invocation via shared memory (handoff files, mesh messaging). Different scale, not a replacement.Ask only when genuinely blocked (CC 2.1.154): CC now reserves the multiple-choice question prompt for decisions it genuinely cannot make itself, rather than asking when it already has enough context to proceed. When orchestrating agents, don't gate progress on an
AskUserQuestionthe lead can resolve from available context — reserve prompts for true branch points (irreversible actions, missing requirements). This complements ork's voice-friendly decision guidance.
Quick Reference
| Category | Rules | Impact | When to Use |
|---|---|---|---|
| Agent Loops | upstream | HIGH | ReAct reasoning, plan-and-execute, self-correction |
| Multi-Agent Coordination | 2 | CRITICAL | Supervisor routing, agent debate, result synthesis |
| Alternative Frameworks | upstream | HIGH | CrewAI crews, AutoGen teams, framework comparison |
| Multi-Scenario | 2 | MEDIUM | Parallel scenario orchestration, difficulty routing |
Total: 4 rules across 4 categories. Loop and framework tutorials moved to first-party sources; the rescued house defaults live in references/ork-delta.md.
Quick Start
# ReAct agent loop
async def react_loop(question: str, tools: dict, max_steps: int = 10) -> str:
history = REACT_PROMPT.format(tools=list(tools.keys()), question=question)
for step in range(max_steps):
response = await llm.chat([{"role": "user", "content": history}])
if "Final Answer:" in response.content:
return response.content.split("Final Answer:")[-1].strip()
if "Action:" in response.content:
action = parse_action(response.content)
result = await tools[action.name](*action.args)
history += f"\nObservation: {result}\n"
return "Max steps reached without answer"
# Supervisor with fan-out/fan-in
async def multi_agent_analysis(content: str) -> dict:
agents = [("security", security_agent), ("perf", perf_agent)]
tasks = [agent(content) for _, agent in agents]
results = await asyncio.gather(*tasks, return_exceptions=True)
return await synthesize_findings(results)
Agent Loops
Patterns for autonomous LLM reasoning: ReAct (Reasoning + Acting), Plan-and-Execute with replanning, self-correction loops, and sliding-window memory management.
Key decisions: Max steps 5-15, temperature 0.3-0.7, memory window 10-20 messages.
Multi-Agent Coordination
Fan-out/fan-in parallelism, supervisor routing with dependency ordering, conflict resolution (confidence-based or LLM arbitration), result synthesis, and CC Agent Teams (mesh topology for peer messaging in CC 2.1.33+).
Key decisions: 3-8 specialists, parallelize independent agents. Pick one of three modes: the Agent tool (star) for simple work, Agent Teams (mesh) for cross-cutting concerns, and a Workflow for large background fan-out you check back on later.
Alternative Frameworks
CrewAI hierarchical crews with Flows (1.8+), OpenAI Agents SDK handoffs and guardrails (0.12+), Microsoft Agent Framework (AutoGen + SK merger), GPT-5.2-Codex for long-horizon coding, and AG2 for open-source flexibility.
Key decisions: Match framework to team expertise + use case. LangGraph for state machines, CrewAI for role-based teams, OpenAI SDK for handoff workflows, MS Agent for enterprise compliance.
Multi-Scenario
Orchestrate a single skill across 3 parallel scenarios (simple/medium/complex) with progressive difficulty scaling (1x/3x/8x), milestone synchronization, and cross-scenario result aggregation.
Key decisions: Free-running with checkpoints, always 3 scenarios, 1x/3x/8x exponential scaling, 30s/90s/300s time budgets.
Upstream coverage (do not restate)
Local tutorials for these topics were retired; consult the first-party source and keep only house deltas in references/ork-delta.md.
| Topic | First-party source |
|---|---|
| ReAct / plan-and-execute / self-correction loop implementations | OpenAI function calling guide (https://platform.openai.com/docs/guides/function-calling); LangGraph tutorials (context7: /langchain-ai/langgraph) |
| Fan-out coordination, result-synthesis boilerplate, and the generic multi-agent design checklist | Python asyncio docs (https://docs.python.org/3/library/asyncio-task.html); Anthropic "Building effective agents" (https://www.anthropic.com/research/building-effective-agents); ork-extras:langgraph supervisor patterns |
| CrewAI (crews, Flows, MCP tools, guardrails) | CrewAI docs (https://docs.crewai.com); context7: /crewaiinc/crewai |
| OpenAI Agents SDK (handoffs, sessions, guardrails, MCP) | https://openai.github.io/openai-agents-python/ ; context7: /openai/openai-agents-python |
| Microsoft Agent Framework / AutoGen (teams, termination, A2A) | https://learn.microsoft.com/en-us/agent-framework/ ; context7: /microsoft/autogen |
| GPT-5.2-Codex capabilities, pricing, IDE integrations | OpenAI model docs (https://platform.openai.com/docs/models) |
| Multi-scenario state machine, architecture and skill-agnostic template deep-dives | Superseded in-skill by rules/scenario-orchestrator.md and rules/scenario-routing.md |
References
references/ork-delta.md- House defaults and dated decisions rescued from retired tutorialsreferences/framework-comparison.md- Condensed framework decision matrix and use-case tablereferences/langgraph-implementation.md- LangGraph 1.2+ implementation of the multi-scenario orchestratorreferences/claude-code-instance-management.md- Running 3 parallel Claude Code instances for scenario demos
Key Decisions
| Decision | Recommendation |
|---|---|
| Single vs multi-agent | Single for focused tasks, multi for decomposable work |
| Max loop steps | 5-15 (prevent infinite loops) |
| Agent count | 3-8 specialists per workflow |
| Framework | Match to team expertise + use case |
| Topology | Agent tool (star) for simple; Agent Teams (mesh) for complex; Workflow for large background fan-out |
| Scenario count | Always 3: simple, medium, complex |
Common Mistakes
- No step limit in agent loops (infinite loops)
- No memory management (context overflow)
- No error isolation in multi-agent (one failure crashes all)
- Note (CC 2.1.161): parallel tool calls now fail independently — a failed Bash no longer cancels siblings in the same batch. This caveat still applies at the agent-orchestration level, not to tool batches;
claude agentsrows now showdone/totalfor fanned-out work. - Note (CC 2.1.157):
claude agentshonors theagentfield insettings.jsonfor dispatched sessions;--agent <name>overrides it — pin the agent type explicitly when dispatching.
- Note (CC 2.1.161): parallel tool calls now fail independently — a failed Bash no longer cancels siblings in the same batch. This caveat still applies at the agent-orchestration level, not to tool batches;
- Missing synthesis step (raw agent outputs not useful)
- Mixing frameworks in one project (complexity explosion)
- Using Agent Teams for simple sequential work (use the Agent tool)
- Sequential instead of parallel scenarios (defeats purpose)
Related Skills
ork-extras:langgraph- LangGraph workflow patterns (supervisor, routing, state)function-calling- Tool definitions and executionork:task-dependency-patterns- Task management with Agent Teams workflow
Capability Details
react-loop
Keywords: react, reason, act, observe, loop, agent Solves:
- Implement ReAct pattern
- Create reasoning loops
- Build iterative agents
plan-execute
Keywords: plan, execute, replan, multi-step, autonomous Solves:
- Create plan then execute steps
- Implement replanning on failure
- Build goal-oriented agents
supervisor-coordination
Keywords: supervisor, route, coordinate, fan-out, fan-in, parallel Solves:
- Route tasks to specialized agents
- Run agents in parallel
- Aggregate multi-agent results
agent-debate
Keywords: debate, conflict, resolution, arbitration, consensus Solves:
- Resolve agent disagreements
- Implement LLM arbitration
- Handle conflicting outputs
result-synthesis
Keywords: synthesize, combine, aggregate, merge, summary Solves:
- Combine outputs from multiple agents
- Create executive summaries
- Score confidence across findings
crewai-patterns
Keywords: crewai, crew, hierarchical, delegation, role-based, flows Solves:
- Build role-based agent teams
- Implement hierarchical coordination
- Use Flows for event-driven orchestration
autogen-patterns
Keywords: autogen, microsoft, agent framework, teams, enterprise, a2a Solves:
- Build enterprise agent systems
- Use AutoGen/SK merged framework
- Implement A2A protocol
framework-selection
Keywords: choose, compare, framework, decision, which, crewai, autogen, openai Solves:
- Select appropriate framework
- Compare framework capabilities
- Match framework to requirements
scenario-orchestrator
Keywords: scenario, parallel, fan-out, difficulty, progressive, demo Solves:
- Run skill across multiple difficulty levels
- Implement parallel scenario execution
- Aggregate cross-scenario results
scenario-routing
Keywords: route, synchronize, milestone, checkpoint, scaling Solves:
- Route tasks by difficulty level
- Synchronize at milestones
- Scale inputs progressively
AI UI Generation
Patterns for generating, reviewing, and integrating UI components produced by AI tools (json-render, v0.app, Google Stitch, Bolt Cloud, Cursor). json-render is the first choice for multi-surface, MCP visual output, and type-safe catalog workflows. AI-generated UI is 80% boilerplate, 20% custom — the human reviews, refactors, and owns the output. These rules ensure AI output meets design system, accessibility, and quality standards before shipping.
Tool landscape as of 2026-04:
- v0.dev → v0.app (Jan 2026 rebrand) — expanded from component scaffolding to full-stack app generation with shipping targets (Vercel, Cloudflare, Railway). v0.app MCP server (
@vercel/v0-mcp) exposes generation as an MCP tool, so agents can call it programmatically.- Google Stitch — design-first generation via
stitch.withgoogle.com/docs/mcp. Produces multi-screen apps (up to 5 interconnected screens) with React/HTML + PNG. Strong when input is a screenshot, URL, or DESIGN.md file.- Bolt Cloud (StackBlitz, 2026) — Bolt now runs the dev environment in the cloud (no local WebContainer). Integrates with GitHub and supports persistent databases. Best for full-stack prototypes with backend + deploy.
- v0.app and Stitch both integrate with shadcn/ui styles; pair with the
shadcn apply <style>CLI (v4) to reuse generated output.
Quick Reference
| Category | Rules | Impact | When to Use |
|---|---|---|---|
| json-render Integration | 1 | HIGH | Multi-surface output, MCP visual output, type-safe catalogs |
| Prompt Engineering | 2 | HIGH | Writing prompts for component generation |
| Quality Assurance | 2 | CRITICAL/HIGH | Reviewing and gating AI-generated code |
| Design System Integration | 2 | HIGH | Injecting tokens, refactoring for conformance |
| Tool Selection & Workflow | 2 | MEDIUM | Choosing the right AI tool, iterating prompts |
Total: 8 rules across 5 categories
Decision Table — json-render vs v0.app vs Stitch vs Bolt Cloud vs Cursor
| Scenario | Tool | Why |
|---|---|---|
| Multi-surface / MCP visual output | json-render | Single catalog renders to any surface — FIRST CHOICE |
| Type-safe component catalog | json-render | Schema-driven specs with per-platform registries |
| Streaming UI from AI agents | json-render | Structured JSON specs render progressively |
| New component from scratch | v0.app | Full scaffold with shadcn/ui, Tailwind, a11y. Pair with shadcn apply <style> for style consistency |
| Full-stack app with deploy | v0.app | Jan 2026 expansion — routes, DB, auth, Vercel/Cloudflare deploy in one generation |
| Design-driven (screenshot/URL/DESIGN.md) | Google Stitch | generate_screen_from_text (once; no retry) + get_screen(name="projects/{project}/screens/{screen}") |
| Multi-screen flow from a visual source | Google Stitch | Strongest when grounded in an existing design |
| Full-stack prototype with persistent backend | Bolt Cloud | Cloud dev env, GitHub integration, databases |
| Incremental change in existing codebase | Cursor | Understands project context, imports, tokens |
| Refactor existing component | Cursor | Reads surrounding code, respects conventions |
| Explore visual design variations | v0.app or Stitch | v0.app for freeform, Stitch when grounded in a reference |
| Add feature to running app | Bolt Cloud | Cloud preview, full environment, persists between sessions |
| Fix bug in existing component | Cursor | Inline edits with full project awareness |
Quick Start
Structured Prompt Example
Generate a React signup form component using:
- Framework: React 19 + TypeScript
- Styling: Tailwind CSS v4 + shadcn/ui (Luma style — rounded-4xl, shadow-md elevation)
- Style: run `npx shadcn@latest apply luma` (CLI v4, Apr 2026) after generation
- Tokens: use color.primary, color.destructive, spacing.md from our design system
- A11y: ARIA labels on all inputs, error announcements via aria-live
- States: default, loading (disabled + spinner), error (inline messages), success
- Responsive: stack on mobile (<640px), 2-col on desktop
Review Example — After AI Generation
// AI generated: hardcoded hex value
<button className="bg-[#3b82f6] text-white px-4 py-2">Submit</button>
// After human review: design token applied
<Button variant="default" size="md">Submit</Button>
Rule Details
json-render Integration
json-render is the first choice for AI UI generation when output must render across multiple surfaces (web, mobile, CLI, MCP). Define a catalog of components once, generate JSON specs from AI, and render on any target surface. See ork:json-render-catalog for catalog authoring patterns.
| Rule | File | Key Pattern |
|---|---|---|
| json-render Patterns | rules/json-render-patterns.md | Catalog-first: define once, render anywhere via per-platform registries |
Prompt Engineering
Structured prompts that specify framework, tokens, a11y, and states upfront.
| Rule | File | Key Pattern |
|---|---|---|
| Prompt Patterns | rules/ai-prompt-patterns.md | Constraint-first prompts with framework, tokens, a11y |
| Iteration Patterns | rules/ai-iteration-patterns.md | Multi-pass prompts for complex interactive states |
Quality Assurance
Systematic review and CI gating for AI-generated components.
| Rule | File | Key Pattern |
|---|---|---|
| Review Checklist | rules/ai-review-checklist.md | 10-point checklist for every AI-generated component |
| CI Gate | rules/ai-ci-gate.md | Automated quality gates before merge |
Design System Integration
Ensuring AI output uses design tokens and conforms to the design system.
| Rule | File | Key Pattern |
|---|---|---|
| Token Injection | rules/ai-token-injection.md | Pass token names in prompts, reject hardcoded values |
| Refactoring Conformance | rules/ai-refactoring-conformance.md | Steps to refactor raw AI output for design system |
Tool Selection & Workflow
Choosing the right AI tool and iterating effectively.
| Rule | File | Key Pattern |
|---|---|---|
| Tool Selection | rules/ai-tool-selection.md | Match tool to use case: v0, Bolt, Cursor |
| Iteration Patterns | rules/ai-iteration-patterns.md | Iterative refinement for complex states |
Key Principles
- Own the output — AI generates a draft; the engineer reviews, refactors, and is accountable for what ships.
- Tokens over literals — Never accept hardcoded colors, spacing, or typography values. Always map to design tokens.
- Constraint-first prompts — Specify framework, tokens, shadcn style (Luma/Nova/etc.), a11y, and states upfront. Vague prompts produce vague output.
- Iterative refinement — Complex components need 2-3 prompt passes: structure first, states second, polish third.
- CI is non-negotiable — Every AI-generated component goes through the same CI pipeline as hand-written code.
- Accessibility by default — Include a11y requirements in every prompt; verify with automated checks post-generation.
Anti-Patterns (FORBIDDEN)
- Shipping raw AI output — Never merge AI-generated code without human review and design system refactoring.
- Vague prompts — "Make a nice form" produces inconsistent, non-conformant output. Always specify constraints.
- Hardcoded hex/rgb values — AI tools default to arbitrary colors. Replace with OKLCH design tokens.
- Skipping CI for "simple" components — AI-generated code has the same bug surface as hand-written code.
- Using v0.app for incremental changes — v0.app generates from scratch; use Cursor for changes within an existing codebase.
- Single-pass complex components — Multi-state components (loading, error, empty, success) need iterative prompting.
- Trusting AI a11y claims — AI tools add ARIA attributes inconsistently. Always verify with axe-core or Storybook a11y addon.
Detailed Documentation
| Resource | Description |
|---|---|
| references/ai-ui-tool-comparison.md | json-render vs v0 vs Bolt vs Cursor vs Copilot comparison |
| references/prompt-templates-library.md | Copy-paste prompt templates for common components |
| references/ai-ui-failure-modes.md | Top 10 failure modes and fixes |
Related Skills
ork:json-render-catalog— json-render catalog authoring, schema validation, and registry patternsork:mcp-visual-output— MCP visual output rendering with json-render specsork:multi-surface-render— Cross-platform rendering from a single component catalogork-extras:ui-components— shadcn/ui component patterns and CVA variantsork-extras:accessibility— WCAG compliance, ARIA patterns, screen reader supportork-extras:animation-motion-design— Motion library animation patternsork-extras:responsive-patterns— Responsive layout and container query patternsork:design-system-tokens— Design token architecture and theming
Animation & Motion Design
Patterns for building performant, accessible animations using Motion (formerly Framer Motion, 18M+ weekly npm downloads) and the View Transitions API (cross-browser support in 2026). Covers layout animations, gesture interactions, exit transitions, micro-interactions, and motion accessibility.
Quick Reference
| Rule | File | Impact | When to Use |
|---|---|---|---|
| Layout Animations | rules/motion-layout.md | HIGH | Shared layout transitions, FLIP animations, layoutId |
| Gesture Interactions | rules/motion-gestures.md | HIGH | Drag, hover, tap with spring physics |
| Exit Animations | rules/motion-exit.md | HIGH | AnimatePresence, unmount transitions |
| View Transitions API | rules/view-transitions-api.md | HIGH | Page navigation, cross-document transitions |
| Motion Accessibility | rules/motion-accessibility.md | CRITICAL | prefers-reduced-motion, cognitive load |
| Motion Performance | rules/motion-performance.md | HIGH | 60fps, GPU compositing, layout thrash |
Total: 6 rules across 3 categories
Decision Table — Motion vs View Transitions API
| Scenario | Recommendation | Why |
|---|---|---|
| Component mount/unmount | Motion | AnimatePresence handles lifecycle |
| Page navigation transitions | View Transitions API | Built-in browser support, works with any router |
| Complex interruptible animations | Motion | Spring physics, gesture interruption |
| Simple crossfade between pages | View Transitions API | Zero JS bundle cost |
| Drag/reorder interactions | Motion | drag prop with layout animations |
| Shared element across routes | View Transitions API | viewTransitionName CSS property |
| Scroll-triggered animations | Motion | useInView, useScroll hooks |
| Multi-step orchestrated sequences | Motion | staggerChildren, variants |
Quick Start
Motion — Component Animation
import { motion, AnimatePresence } from "motion/react"
const fadeInUp = {
initial: { opacity: 0, y: 20 },
animate: { opacity: 1, y: 0 },
exit: { opacity: 0, y: -10 },
transition: { type: "spring", stiffness: 300, damping: 24 },
}
function Card({ item }: { item: Item }) {
return (
<motion.div {...fadeInUp} layout layoutId={item.id}>
{item.content}
</motion.div>
)
}
function CardList({ items }: { items: Item[] }) {
return (
<AnimatePresence mode="wait">
{items.map((item) => (
<Card key={item.id} item={item} />
))}
</AnimatePresence>
)
}
View Transitions API — Page Navigation
// React Router v7+ with View Transitions
import { Link, useNavigate } from "react-router"
function NavLink({ to, children }: { to: string; children: React.ReactNode }) {
return <Link to={to} viewTransition>{children}</Link>
}
// CSS for the transition
// ::view-transition-old(root) { animation: fade-out 200ms ease; }
// ::view-transition-new(root) { animation: fade-in 200ms ease; }
Motion — Accessible by Default
import { useReducedMotion } from "motion/react"
function AnimatedComponent() {
const shouldReduceMotion = useReducedMotion()
return (
<motion.div
animate={{ x: 100 }}
transition={shouldReduceMotion
? { duration: 0 }
: { type: "spring", stiffness: 300, damping: 24 }
}
/>
)
}
Rule Details
Layout Animations (Motion)
FLIP-based layout animations with the layout prop and shared layout transitions via layoutId.
Load:
rules/motion-layout.md
Gesture Interactions (Motion)
Drag, hover, and tap interactions with spring physics and gesture composition.
Load:
rules/motion-gestures.md
Exit Animations (Motion)
AnimatePresence for animating components as they unmount from the React tree.
Load:
rules/motion-exit.md
View Transitions API
Browser-native page transitions using document.startViewTransition() and framework integrations.
Load:
rules/view-transitions-api.md
Motion Accessibility
Respecting user motion preferences and reducing cognitive load with motion sensitivity patterns.
Load:
rules/motion-accessibility.md
Motion Performance
GPU compositing, avoiding layout thrash, and keeping animations at 60fps.
Load:
rules/motion-performance.md
Key Principles
- 60fps or nothing — Only animate
transformandopacity(composite properties). Never animatewidth,height,top, orleft. - Centralized presets — Define animation variants in a shared file, not inline on every component.
- AnimatePresence for exits — React unmounts instantly; wrap with AnimatePresence to animate out.
- Spring over duration — Springs feel natural and are interruptible. Use
stiffness/damping, notduration. - Respect user preferences — Always check
prefers-reduced-motionand provide instant alternatives.
Performance Budget
| Metric | Target | Measurement |
|---|---|---|
| Transition duration | < 400ms | User perception threshold |
| Animation properties | transform, opacity only | DevTools > Rendering > Paint flashing |
| JS bundle (Motion) | ~16KB gzipped | Import only what you use |
| First paint delay | 0ms | Animations must not block render |
| Frame drops | < 5% of frames | Performance API: PerformanceObserver |
Anti-Patterns (FORBIDDEN)
- Animating layout properties — Never animate
width,height,margin,paddingdirectly. Usetransform: scale()instead. - Missing AnimatePresence — Components unmount instantly without it; exit animations are silently lost.
- Ignoring prefers-reduced-motion — Causes vestibular disorders for ~35% of users with motion sensitivity.
- Inline transition objects — Creates new objects every render, breaking React memoization.
- duration-based springs — Motion springs use
stiffness/damping, notduration. Mixing causes unexpected behavior. - Synchronous startViewTransition — Always await or handle the promise from
document.startViewTransition().
Detailed Documentation
| Resource | Description |
|---|---|
| references/motion-vs-view-transitions.md | Comparison table, browser support, limitations |
| references/animation-presets-library.md | Copy-paste preset variants for common patterns |
| references/micro-interactions-catalog.md | Button press, toggle, checkbox, loading, success/error |
Related Skills
ork-extras:ui-components— shadcn/ui component patterns and CVA variantsork-extras:responsive-patterns— Responsive layout and container query patternsork:performance— Core Web Vitals and runtime performance optimizationork-extras:accessibility— WCAG compliance, ARIA patterns, screen reader support
Async Jobs
Background task processing with Celery, ARQ, Redis and Temporal. This skill is a wrapper, not a manual: Celery and ARQ document their own product well, so what lives here is our delta, the thresholds, working config, ordering constraints and tool-choice rules we picked. Product mechanics are linked, not restated.
Start with Read("references/ork-delta.md").
Quick Reference
| Topic | Where our part lives |
|---|---|
| Configuration | references/celery-config.md, rules/jobs-task-queue.md |
| Task Routing | references/ork-delta.md (queue taxonomy, prefetch tiers, Redis priority) |
| Canvas Workflows | rules/celery-canvas.md |
| Retry Strategies | references/ork-delta.md (backoff cap, idempotency layers, lock TTLs) |
| Scheduling | rules/jobs-scheduling.md, references/ork-delta.md (beat process model) |
| Monitoring | references/ork-delta.md (alert thresholds, histogram buckets) |
| Result Backends | rules/jobs-monitoring.md, references/ork-delta.md (return contract) |
| ARQ Patterns | rules/jobs-task-queue.md, references/ork-delta.md (budgets, pool ownership) |
| Temporal Workflows | rules/temporal-workflows.md |
| Temporal Activities | rules/temporal-activities.md |
10 topic areas, 6 rule files in rules/, house delta in references/ork-delta.md.
Quick Start
@app.task(bind=True, max_retries=3, default_retry_delay=60)
def process_payment(self, order_id: str):
try:
return gateway.charge(order_id)
except TransientError as exc:
raise self.retry(exc=exc, countdown=2 ** self.request.retries * 60)
Load more examples: Read("references/quick-start-examples.md") for Celery
retry task and ARQ/FastAPI integration patterns.
Upstream coverage (do not restate)
Fetch these when you need product mechanics. The right-hand column is the part we keep, because it is a house threshold, a working config or an ordering constraint that upstream cannot know.
| Topic | First-party source | House subset stays in |
|---|---|---|
| Celery settings, serializers, time limits, worker flags | https://docs.celeryq.dev/en/stable/userguide/configuration.html and .../optimizing.html | references/celery-config.md, rules/jobs-task-queue.md |
| Queue declarations, router classes, Redis priority mechanics | https://docs.celeryq.dev/en/stable/userguide/routing.html | references/ork-delta.md |
| chain / group / chord / signature semantics | https://docs.celeryq.dev/en/stable/userguide/canvas.html | rules/celery-canvas.md keeps the house canvas subset. Its si()-in-chords guidance is UNVERIFIED and contested: confirm the argument-passing behaviour against the upstream canvas page before relying on it |
autoretry_for, retry_backoff, Reject, task base classes | https://docs.celeryq.dev/en/stable/userguide/tasks.html | references/ork-delta.md, rules/jobs-task-queue.md |
| Beat schedules, crontab syntax, DatabaseScheduler | https://docs.celeryq.dev/en/stable/userguide/periodic-tasks.html and https://django-celery-beat.readthedocs.io/en/latest/ | rules/jobs-scheduling.md keeps our beat_schedule shapes; references/ork-delta.md keeps the process model |
Flower flags, inspect, signal names | https://docs.celeryq.dev/en/stable/userguide/monitoring.html, https://docs.celeryq.dev/en/stable/userguide/signals.html, https://flower.readthedocs.io/en/latest/config.html | references/ork-delta.md |
Result backend, AsyncResult, custom states | https://docs.celeryq.dev/en/stable/userguide/configuration.html | rules/jobs-monitoring.md keeps our status endpoints and update_state() usage |
Per-task rate_limit, control.rate_limit, Redis Lua | https://docs.celeryq.dev/en/stable/userguide/workers.html, https://redis.io/docs/latest/develop/programmability/eval-intro/ | references/ork-delta.md |
ARQ WorkerSettings, enqueue_job, _defer_by / _defer_until, Job status | https://arq-docs.helpmanual.io/ | rules/jobs-task-queue.md keeps the worker skeleton; references/ork-delta.md keeps the budgets |
| FastAPI lifespan and dependency wiring | https://fastapi.tiangolo.com/advanced/events/ | references/ork-delta.md |
Distributed locks with SET NX EX | https://redis.io/docs/latest/commands/set/ | references/ork-delta.md |
Configuration
Load: Read("references/celery-config.md").
| Decision | Recommendation |
|---|---|
| Serializer | JSON (never pickle) |
| Ack mode | Late ack (task_acks_late=True) |
| Prefetch | 1 for fair, 4-8 for throughput |
| Time limit | soft < hard (540 / 600) |
| Timezone | UTC always |
Task Routing
| Decision | Recommendation |
|---|---|
| Queue count | 5: critical / high / default / low / bulk |
| Priority levels | 0-9, with all four Redis priority switches set together |
| Worker assignment | Dedicated worker per queue |
| Prefetch | 1 critical, 2 high, 4 default, 8 low/bulk |
| Routing | Router class once past 5 routing rules |
Canvas Workflows
Load: Read("rules/celery-canvas.md").
| Decision | Recommendation |
|---|---|
| Sequential | Chain with s() |
| Parallel | Group for independent tasks |
| Fan-in | Chord (all header tasks must succeed for the body to run) |
| Ignore input | Use si() immutable signature |
| Error in chain | Reject stops the chain, retry continues it |
| Partial failures | Return an error dict from chord header tasks |
Retry Strategies
| Decision | Recommendation |
|---|---|
| Retry delay | Exponential backoff, jitter on, capped at 600s |
| Max retries | 3-5 for transient, 0 for permanent |
| Idempotency | Redis marker (86400s TTL) plus the vendor idempotency key |
| Failed tasks | DLQ for manual review |
| Singleton | Redis lock with a TTL longer than the hard time limit |
Scheduling
Load: Read("rules/jobs-scheduling.md").
| Decision | Recommendation |
|---|---|
| Schedule type | Crontab for time-based, float interval for frequency |
| Dynamic | DatabaseScheduler (django-celery-beat) |
| Overlap | Redis lock, 3600s default and 7200s for long jobs |
| Beat process | Separate process; embedded --beat is development only |
| Timezone | UTC always |
Monitoring
| Decision | Recommendation |
|---|---|
| Dashboard | Flower with persistent storage |
| Metrics | Prometheus wired to task_prerun / task_postrun / task_failure |
| Health | Broker reachable, at least one worker, queue depths |
| Alerting | critical > 100, default > 5000, workers < 1 |
| Autoscale | Queue depth > 500 |
Result Backends
Load: Read("rules/jobs-monitoring.md").
| Decision | Recommendation |
|---|---|
| Status storage | Redis result backend, status and small JSON only |
| Large results | S3 or database, task returns a reference dict |
| Progress | Custom states with update_state() |
| Result query | AsyncResult with state checks |
ARQ Patterns
Load: Read("rules/jobs-task-queue.md").
| Decision | Recommendation |
|---|---|
| Simple async | ARQ (native async), max_jobs=10, job_timeout=300 |
| Pool ownership | FastAPI lifespan, never a per-request create_pool |
| Complex workflows | Celery (chains, chords, DLQ, per-task rate limits) |
| In-process quick | FastAPI BackgroundTasks, under 30s, non-critical only |
| LLM workflows | LangGraph, not Celery |
Tool Selection
Load: Read("references/quick-start-examples.md") for the full tool
comparison table (ARQ, Celery, RQ, Dramatiq, FastAPI BackgroundTasks).
Anti-Patterns (FORBIDDEN)
Load details: Read("references/anti-patterns.md") for the full list.
Key rules: never run long tasks in request handlers, never block on results inside tasks, never store large results in Redis, always use idempotency for retried tasks.
Temporal Workflows
Load: Read("rules/temporal-workflows.md").
| Decision | Recommendation |
|---|---|
| Workflow ID | Business-meaningful, idempotent |
| Determinism | Use workflow.random(), workflow.now() |
| I/O | Always via activities, never directly |
Temporal Activities
Load: Read("rules/temporal-activities.md").
| Decision | Recommendation |
|---|---|
| Activity timeout | start_to_close for most cases |
| Error handling | Non-retryable for business errors |
| Testing | WorkflowEnvironment.start_local() for integration tests |
Related Skills
ork:python-backend- FastAPI, asyncio, SQLAlchemy patternsork-extras:langgraph- LangGraph workflow patterns (use for LLM workflows, not Celery)ork-extras:distributed-systems- Resilience patterns, circuit breakersork-extras:monitoring-observability- Metrics and alerting
Capability Details
Load details: Read("references/capability-details.md") for the keyword index
and problem-to-capability mapping.
audit-activation
Reports whether OrchestKit's specialized sub-agents are actually being activated, from real spawn telemetry — not vibes. Scope is agent activation, not skill quality.
It answers: "Do my specialized agents get spawned, or does the model default to generic Explore/general-purpose?" Read-only — it never edits agents.
Why this exists: a 2026-06 audit found only ~14% of agent spawns hit the 36-agent catalog vs ~74% generic, with 17/36 agents dormant — and that agents fire ~1:1 with how often a high-traffic skill names them via
subagent_type=. Description rewrites ("use proactively") were A/B-tested and gave Δ0, so this skill measures wiring + usage, not description prose. Seedocs/feat--activation-audit/.
Quick Reference
| Category | File | Impact | When to Use |
|---|---|---|---|
| Activation Checks | rules/activation-checks.md | HIGH | What to compute per agent |
| Classification | rules/activation-status.md | HIGH | fires / mis-triggered / niche / dead buckets |
| Output Format | references/output-format.md | MEDIUM | Report layout + the spawn-split summary |
CRITICAL: Task Management is MANDATORY (CC 2.1.16)
TaskCreate(subject="Audit activation: agent spawn analysis",
description="Computing generic-vs-specialist split + dormancy from spawn telemetry",
activeForm="Auditing agent activation")
TaskCreate(subject="Read spawn telemetry", activeForm="Reading subagent-spawns.jsonl")
TaskCreate(subject="Compute split + observed zero starts", activeForm="Computing activation events and coverage")
TaskCreate(subject="Classify & render", activeForm="Classifying agents and rendering report")
TaskUpdate(taskId="3", addBlockedBy=["2"])
TaskUpdate(taskId="4", addBlockedBy=["3"])
Workflow
-
Run the script FIRST — every audit starts by running (or, when execution is impossible, explicitly referencing) the deterministic collector:
bash "${CLAUDE_SKILL_DIR}/scripts/run-activation-audit.sh" \ --telemetry-root /path/to/consumer-project \ --stop-feed "$HOME/.claude/analytics/agent-usage.jsonl" \ --days 30 --jsonIt resolves the catalog beside its source or installed script, while every consumer telemetry root is explicit. It reports attempts, starts, and stop-feed completions separately. Never eyeball JSONL by hand when the script exists.
-
Inventory — let the script resolve its own source or installed
agents/catalog (beside it in core ork; from ork-extras it finds the core ork plugin'sagents/next to it, and--catalog-rootoverrides). Do not point it at a consumer project's agent directory. -
Read telemetry —
.claude/logs/subagent-spawns.jsonlcarries pretool intent and start events. Triangulate it with the restored global~/.claude/analytics/agent-usage.jsonlstop feed when available. The streams have no stable common event ID, so never add them together or infer unique spawns. -
Compute — all checks from
Read("rules/activation-checks.md"); the Report Contract below lists the mandatory ones. -
Classify — bucket every agent using the Four Buckets below (full procedure:
Read("rules/activation-status.md")). -
Render — output per
Read("references/output-format.md"), satisfying the Report Contract.
Report Contract (every audit MUST include all six)
- Data-source line (first line of the report) — name
scripts/run-activation-audit.sh, every explicit consumer.claude/logs/subagent-spawns.jsonlroot, the UTC window, and the spawn coverage state (observed,missing,empty, orpartial). State whether~/.claude/analytics/agent-usage.jsonlwas supplied as a stop feed. A report that presents numbers without these coverage facts is invalid. - Spawn split — generic (Explore/general-purpose/Plan) vs ork-catalog vs other-plugin, as counts AND percentages (e.g. "412 generic (74%) / 78 ork-catalog (14%) / 67 other (12%)"). Never percentages alone.
- Concentration — the top-5 agents' share of all catalog spawns as a percentage (e.g. "top-5 = 81% of catalog spawns"), plus the top-5 list with fire counts.
- Observed-zero-start list — only when spawn coverage is
observed, enumerate every catalog agent with zero start events in the supplied roots, one per line with its reference count and bucket. This is not an estate-wide or lifetime dormancy claim. Do not render the list when coverage is missing, empty, or partial. - Window caveat — state that observed-zero-start names are absent only from the supplied roots and UTC window. They are a routing signal, not proof of zero estate-wide or lifetime use.
- Four-bucket classification table (below) + fix recommendations — wiring changes only (see Hard Rules).
Classification: the Four Buckets (rules/activation-status.md)
Bucket by reference counts, never by description quality. For each observed-zero-start agent, count its real spawn references: grep -rc "subagent_type=ork:<name>" src/skills/ (plus agent:/team-map mentions in src/agents/). Show the evidence: cite that grep command in the report and put each agent's ref-count (with an example source file, e.g. src/skills/cover/SKILL.md) in the classification table. The telemetry observation proves only starts in supplied roots; the grep proves wiring. Render classification only when coverage is observed.
| Bucket | Condition | Action |
|---|---|---|
| ACTIVE | fired ≥1× in the telemetry window | none — it works |
| MIS-TRIGGERED | observed zero starts, has references but no real subagent_type= spawn from a busy skill | wire a spawn from a high-traffic skill |
| NICHE | observed zero starts, rare-by-nature domain (design, multimodal, perf, IaC, security-LLM) AND wired somewhere | keep - low use expected |
| DEAD | observed zero starts AND zero references in ANY skill or agent | prune candidate |
DEAD requires zero references anywhere — an agent with even one reference is never DEAD; it is mis-triggered or niche. Only DEAD agents are prune candidates.
Hard Rules
- Never recommend rewriting agent descriptions. A/B-tested: description rewrites gave Δ0 routing benefit. Dormancy is a skill-wiring problem — the fix is always adding a
subagent_type=ork:<name>spawn from a high-traffic skill (e.g. implement, cover, review-pr), never prose changes. - Classify by reference count, not description quality. The grep above is the evidence; "the description is vague" is not.
- State the telemetry window, supplied roots, and coverage state in EVERY answer — including classification-only or prune-decision answers. Observed-zero-start is never an estate-wide dormancy claim.
- Keep event semantics separate. Pretool is attempted intent,
source:startis started activation, andagent-usage.jsonlis a stop/completion observation. Cite all supplied sources and never sum them into a unique-spawn claim. - Answer with the report itself, never with only a description of the process. Even when you cannot execute the script in the current context, render the full contract-format report (state which numbers are from the latest available run vs illustrative).
- Read-only: this skill never edits agents.
Example report shape (illustrative numbers — imitate the FORM exactly)
Data: scripts/run-activation-audit.sh over /consumer/.claude/logs/subagent-spawns.jsonl (window: 2026-05-23T00:00:00Z to 2026-07-14T00:00:00Z; coverage: observed)
Stop feed: ~/.claude/analytics/agent-usage.jsonl supplied separately; it is not joined to starts.
## Spawn split
Total 560 spawns: 412 generic (74%) / 78 ork-catalog (14%) / 70 other-plugin (12%)
## Concentration
Top-5 = 63/78 catalog spawns (81%): web-research-analyst 26, code-quality-reviewer 21,
test-generator 8, debug-investigator 5, backend-system-architect 3
## Observed zero-start agents (6 of 20 in the supplied roots, refs via grep -rc "subagent_type=ork:<name>" src/skills/)
- emulate-engineer (3 refs) -> MIS-TRIGGERED
- expect-agent (3 refs) -> MIS-TRIGGERED
- design-system-architect (2 refs) -> NICHE (rare domain, wired)
- multimodal-specialist (1 ref) -> NICHE (rare domain, wired)
- infrastructure-architect (2 refs) -> NICHE (rare domain, wired)
- event-driven-architect (1 ref) -> MIS-TRIGGERED
Caveat: observed zero starts are absent only from the supplied telemetry roots and
window. They are not proof of zero estate-wide or lifetime use.
## Buckets (rules/activation-status.md)
ACTIVE (14) | MIS-TRIGGERED (3) | NICHE (3) | DEAD (0 — none: every agent has >=1 reference)
## Fixes (wiring only — never description rewrites)
- emulate-engineer: add subagent_type=ork:emulate-engineer spawn from cover (src/skills/cover/SKILL.md)
- expect-agent: add subagent_type=ork:expect-agent spawn from review-pr
Chain
After this audit, run the deeper experiment if you suspect descriptions: docs/feat--activation-audit/agent-routing-experiment.mjs (isolated A/B selection harness).
Related Skills
telemetry-inspect— validates the telemetry data-plane this skill reads fromanalytics— raw usage queries across projectsdoctor— broader plugin health (manifests, hooks, memory budget)
Eval note: this skill is direct-only (
disable-model-invocation: true), so quality evals run in TIER-1 unit mode (--force-skill) — routed evals are impossible by construction.
Full-Codebase Audit
Single-pass whole-project analysis leveraging Opus 5.5's extended context window. Loads entire codebases (~50K LOC) into context for cross-file vulnerability detection, architecture review, and dependency analysis.
Quick Start
audit-full # Full audit (all modes)
audit-full security # Security-focused audit
audit-full architecture # Architecture review
audit-full dependencies # Dependency audit
Opus 5.5: Uses
complexity: maxfor extended thinking across entire codebases. 1M context (default and maximum on Opus 5.5) enables cross-file reasoning that chunked approaches miss. Set effort explicitly: Opus 5.5's own default ismedium(one level below Opus 5'shigh), and CC 2.1.280+ starts a newly released model at its default rather than an older saved/effortlevel. Run audits athigh; usexhighfor one additional cross-file pattern sweep on the hardest codebases.
1M Context Required: If
CLAUDE_CODE_DISABLE_1M_CONTEXTis set, audit-full cannot perform full-codebase analysis. Check:echo $CLAUDE_CODE_DISABLE_1M_CONTEXT— if non-empty, either unset it (unset CLAUDE_CODE_DISABLE_1M_CONTEXT) or useverifyfor chunked analysis instead.
Effort (CC 2.1.111+):
xhighadds a second pass that re-reads cross-module boundaries specifically looking for patterns the first pass normalized over. Reservexhighfor the hardest codebases (see the Opus 5.5 note above for the default). Silently falls back tohighon other models;doctorwarns on mismatch.
Switching to Opus (CC 2.1.144+):
/modelnow affects the current session only — pick Opus for this audit without it persisting. Pressdin the picker only if you want it as the default for new sessions too.
STEP 0: Verify User Intent with AskUserQuestion
BEFORE creating tasks, clarify audit scope using the interactive dialog.
Load: Read("references/audit-scope-dialog.md") for the full AskUserQuestion dialog with mode options (Full/Security/Architecture/Dependencies) and scope options (Entire codebase/Specific directory/Changed files).
CRITICAL: Task Management is MANDATORY
# 1. Create main task IMMEDIATELY
TaskCreate(
subject="Full-codebase audit",
description="Single-pass audit using extended context",
activeForm="Running full-codebase audit"
)
# 2. Create subtasks for each phase
TaskCreate(subject="Estimate token budget and plan loading", activeForm="Estimating token budget") # id=2
TaskCreate(subject="Load codebase into context", activeForm="Loading codebase") # id=3
TaskCreate(subject="Run audit analysis", activeForm="Analyzing codebase") # id=4
TaskCreate(subject="Generate audit report", activeForm="Generating report") # id=5
# 3. Set dependencies for sequential phases
TaskUpdate(taskId="3", addBlockedBy=["2"]) # Loading needs budget estimate
TaskUpdate(taskId="4", addBlockedBy=["3"]) # Analysis needs codebase loaded
TaskUpdate(taskId="5", addBlockedBy=["4"]) # Report needs analysis done
# 4. Update status as you progress
TaskUpdate(taskId="2", status="in_progress") # When starting
TaskUpdate(taskId="2", status="completed") # When done — repeat for each subtask
STEP 1: Estimate Token Budget
Before loading files, estimate whether the codebase fits in context.
Load: Read("references/token-budget-planning.md") for estimation rules (tokens/line by file type), budget allocation tables, auto-exclusion list, and fallback dialog when codebase exceeds budget.
Run estimation: bash ${CLAUDE_SKILL_DIR}/scripts/estimate-tokens.sh /path/to/project
Two tiers — pick by the estimate
audit-full has two execution tiers. The estimate decides which:
| Estimate vs budget | Tier | Path |
|---|---|---|
| Fits (~≤125K LOC / ≤1M tokens) | Single-context (default — the skill's edge: whole-codebase cross-file reasoning in one window) | continue to STEP 2 |
| Exceeds budget | Map-reduce (scale tier — shard → per-shard audit → cross-shard boundary synthesis → refute) | invoke the workflow below; STEP 2–3.5 run inside it |
Over-budget → run the map-reduce workflow (don't punt, don't silently truncate the load):
# Derive shards from STEP 1 (top-level modules/dirs by size: src, apps/api, apps/web, packages/*).
Workflow({
"name": "ork:audit-full-mapreduce",
"args": { "shards": ["<repo-relative dirs>"], "mode": "<full|security|architecture|dependencies>", "effort": "<high|xhigh>" }
})
It preserves cross-file reasoning within each shard and recovers cross-shard edges (taint/auth/dep-direction that span modules) in a dedicated synthesis pass, then runs the same STEP 3.5 adversarial refutation. Its return (merged findings + refutation ledger) feeds STEP 4. The single-context tier remains the default because it's cheaper and loses no boundaries when the repo fits — only reach for map-reduce when it genuinely doesn't.
Fan-out rule: a single pass is never a fallback for an over-budget repo when the selected mode is full coverage. If the map-reduce Workflow call does not run, end the run as BLOCKED and say why; never audit a truncated load. A mode the user picks that narrows the load on purpose (directory scoping, priority loading) is a declared scope cut, not a truncated load.
STEP 2: Load Codebase into Context
Load: Read("references/report-structure.md") for loading strategy, inclusion patterns by language (TS/JS, Python, Config), and batch reading patterns.
STEP 3: Audit Analysis
With codebase loaded, perform the selected audit mode(s).
Security Audit
Load: Read("references/security-audit-guide.md") for the full checklist.
Key cross-file analysis patterns:
- Data flow tracing: Track user input from entry point → processing → storage
- Auth boundary verification: Ensure all protected routes check auth
- Secret detection: Scan for hardcoded credentials, API keys, tokens
- Injection surfaces: SQL, command, template injection across file boundaries
- OWASP Top 10 mapping: Classify findings by OWASP category
Architecture Review
Load: Read("references/architecture-review-guide.md") for the full guide.
Key analysis patterns:
- Dependency direction: Verify imports flow inward (clean architecture)
- Circular dependencies: Detect import cycles across modules
- Layer violations: Business logic in controllers, DB in routes, etc.
- Pattern consistency: Same problem solved differently across codebase
- Coupling analysis: Count cross-module imports, identify tight coupling
Dependency Audit
Load: Read("references/dependency-audit-guide.md") for the full guide.
Key analysis patterns:
- Known CVEs: Check versions against known vulnerabilities
- License compliance: Identify copyleft licenses in proprietary code
- Version currency: Flag significantly outdated dependencies
- Transitive risk: Identify deep dependency chains
- Unused dependencies: Detect installed but never imported packages
Progressive Output (CC 2.1.76)
Output findings incrementally as each audit mode completes — don't batch until the report:
- Security findings first — show critical/high vulnerabilities immediately, don't wait for architecture review
- Architecture findings — show dependency direction violations, circular deps as they surface
- Dependency findings — show CVE matches, license compliance issues
For multi-mode audits (Full), each mode's findings appear as they complete. This lets users act on critical security findings while architecture analysis is still running.
STEP 3.5: Adversarial Refutation (effort-gated)
Before the report, a separate blind refuter verifies CRITICAL/HIGH findings — the
structural fix for self-preferential bias (a single-context pass grading its own findings
anchors on its own reasoning). low/medium skip this step; high runs single advisory
refuters; xhigh runs the engine's quorum (3 for CRITICAL, 2 for HIGH).
Load the protocol + audit-full bindings: Read("references/adversarial-refutation.md")
(which loads the engine copy in references/adversarial-refutation-engine.md).
These refuters are audit-full's only sub-agent spawns (the producer is single-context),
always isolated Agent(...) with no team_name, fed only a neutral claim (category +
file:line). Deterministic ground truth is exempt — CVE/CVSS matches, failing build/test,
type errors are never refuted; only a reachability claim on top of a CVE is. Cross-file
findings the refuter can't reproduce from its narrow slice stay UPHELD (engine §5).
Refutation never silently drops a CRITICAL — the ledger (refutation-ledger.json) records
survived/killed/downgraded, and removing a CRITICAL/HIGH from the report needs user confirmation.
STEP 4: Generate Report
Load the report template: Read("assets/audit-report-template.md").
Report structure and severity classification: Read("references/report-structure.md") for finding table format, severity breakdown (CRITICAL/HIGH/MEDIUM/LOW with timelines), and architecture diagram conventions.
Severity matrix: Read("assets/severity-matrix.md") for classification criteria.
Completion Checklist
Before finalizing the report, verify with Read("checklists/audit-completion.md").
PushNotification on Completion (CC 2.1.110+)
A full-codebase 1M-context audit typically runs 15–60 minutes on medium projects and can exceed that on large ones. After the report file is written and the completion checklist passes, call PushNotification so the finding counts are visible even if the user walked away.
PushNotification(
message=f"ork-extras:audit-full complete — {SCOPE}: {critical}C/{high}H/{medium}M/{low}L · {report_path}",
status="proactive"
)
Full rule: Read("references/push-notification-on-completion.md").
When NOT to Use
| Situation | Use Instead |
|---|---|
| Small targeted check (1-5 files) | Direct Read + analysis |
| CI/CD automated scanning | security-scanning skill |
| Multi-agent graded verification | verify |
| Exploring unfamiliar codebase | explore |
| Codebase > 125K LOC (exceeds 1M) | stay here — STEP 1 routes to the map-reduce tier (workflows/audit-full-mapreduce.js); verify only if you want multi-agent graded verification instead of an audit |
Notes for whole-codebase passes
Oversized reads (CC 2.1.144+): When loading large files, Read returns a
[PARTIAL view]truncated first page instead of a hard error if the whole-file read exceeds the token limit. Detect that notice and re-read with explicitoffset/limitto page through the rest — a partial read silently omits code an audit must not miss.
When context fills (CC 2.1.141+): Use the rewind menu's "Summarize up to here" to compress earlier turns while keeping recent findings, instead of restarting the audit. Reactive compaction (CC 2.1.142+) sizes the first summarize to the actual overflow, so a wasted second pass mid-turn is now rare.
Running unattended with /goal
Set a completion condition with /goal (CC 2.1.139+) and this skill will keep working across turns until the condition is met. Works in interactive, -p, and Remote Control. The overlay panel shows live elapsed / turns / tokens.
Example completion condition for this skill:
/goal until findings.critical == 0 OR no_new_critical_for_3_turns, or stop after 30 turns
Stops when: zero critical issues remain across 3 consecutive passes, or a structural anti-pattern budget is reached. Compatible with claude.ai Remote Control runs.
Related Skills
security-scanning— Automated scanner integration (npm audit, Semgrep, etc.)ork:security-patterns— Security architecture patterns and OWASP vulnerability classificationork:architecture-patterns— Architectural pattern referenceork:quality-gates— Quality assessment criteriaork:verify— Multi-agent verification (fallback for codebases exceeding 1M context)
References
Load on demand with Read("references/<file>"):
| File | Content |
|---|---|
references/security-audit-guide.md | Cross-file vulnerability patterns |
references/architecture-review-guide.md | Pattern and coupling analysis |
references/dependency-audit-guide.md | CVE, license, currency checks |
references/adversarial-refutation.md | Blind-refuter bindings (STEP 3.5), loads the engine copy below |
references/adversarial-refutation-engine.md | Byte copy of core's shared refutation engine, so the skill runs from ork-extras (a test keeps it equal) |
references/push-notification-on-completion.md | Byte copy of core's push-notification rule, same reason |
references/token-estimation.md | File type ratios and budget planning |
assets/audit-report-template.md | Structured output format |
assets/severity-matrix.md | Finding classification criteria |
checklists/audit-completion.md | Pre-report verification |
scripts/estimate-tokens.sh | Automated LOC to token estimation |
workflows/audit-full-mapreduce.js | Scale tier — shard→audit→synthesize→refute for repos that exceed 1M context (run via the Workflow tool) |
Bare Eval — Isolated Evaluation Calls
Run claude -p --bare for fast, clean eval/grading without plugin overhead.
CC 2.1.81 required. The --bare flag skips hooks, LSP, plugin sync, and skill directory walks.
When to Use
- Grading skill outputs against assertions
- Trigger classification (which skill matches a prompt)
- Description optimization iterations
- Any scripted
-pcall that doesn't need plugins
When NOT to Use
- Testing skill routing (needs
--plugin-dir) - Testing agent orchestration (needs full plugin context)
- Interactive sessions
Prerequisites
# --bare requires ANTHROPIC_API_KEY (OAuth/keychain disabled)
export ANTHROPIC_API_KEY="sk-ant-..."
# Verify CC version
claude --version # Must be >= 2.1.81
Quick Reference
| Call Type | Command Pattern |
|---|---|
| Grading | claude -p "$prompt" --bare --max-turns 1 --output-format text |
| Trigger | claude -p "$prompt" --bare --json-schema "$schema" --output-format json |
| Streaming grade | claude -p "$prompt" --bare --max-turns 1 --output-format stream-json |
| Optimize | echo "$prompt" | claude -p --bare --max-turns 1 --output-format text |
| Force-skill | claude -p "$prompt" --bare --print --append-system-prompt "$content" |
| @-file in prompt | claude -p "grade @fixtures/case-1.md against rubric" --bare (CC 2.1.113 Remote Control autocomplete) |
Long harness runs (CC 2.1.199+): set
CLAUDE_CODE_RETRY_WATCHDOG=1for unattended eval batches: it raises the default retry count for non-capacity transient errors to 300 and lifts the cap of 15 onCLAUDE_CODE_MAX_RETRIES, so an overnight grading run survives transient API blips instead of dying mid-batch. Pair it with the three caps so a batch neither waits out a 429 storm nor sits hours on a usage limit:CLAUDE_CODE_RETRY_WATCHDOG_MAX_WAIT_MS(2.1.295),CLAUDE_CODE_RETRY_WATCHDOG_MAX_USAGE_LIMIT_WAIT_MS(2.1.301) andCLAUDE_CODE_RETRY_WATCHDOG_USAGE_LIMIT_RECHECK_MS(2.1.305);doctor's operator-permissions check offers any that are missing.
--output-format stream-json
Newline-delimited JSON events (one per token/tool-call) — lets a runner score partial output or abort early on a failing probe without waiting for the full response.
claude -p "$prompt" --bare --max-turns 1 --output-format stream-json \
| while IFS= read -r line; do
# line is a single JSON event; inspect $.type == "content_block_delta"
jq -r 'select(.type == "content_block_delta") | .delta.text' <<< "$line"
done
Use stream-json over json when:
- grading long outputs and you want incremental scoring,
- piping into another CLI step-by-step (e.g.
ork:eval-runner), - you need per-token timing data alongside the content.
Invocation Patterns
Load detailed patterns and examples:
Read("references/invocation-patterns.md")
Grading Schemas
JSON schemas for structured eval output:
Read("references/grading-schemas.md")
Pipeline Integration
OrchestKit's eval scripts (npm run eval:skill) auto-detect bare mode:
# eval-common.sh detects ANTHROPIC_API_KEY → sets BARE_MODE=true
# Scripts add --bare to all non-plugin calls automatically
Bare calls: Trigger classification, force-skill, baseline, all grading.
Never bare: run_with_skill (needs plugin context for routing tests).
CC 2.1.119: --print honors agent tools: / disallowedTools: (M122)
Before CC 2.1.119, --print mode ran with the full default tool set regardless of the agent's frontmatter tools: and disallowedTools:. Bare-eval grading was effectively ungated — graders could call any tool they wanted, even if the agent definition restricted them.
As of 2.1.119, --print enforces the agent's declared tool surface. Implications for eval design:
| Consequence | Action |
|---|---|
| Eval graders that relied on unrestricted tool access may now fail | Audit grader prompts for tools they actually need; whitelist explicitly via the agent's tools: frontmatter |
| Eval results match interactive runs | Reproducibility improves — grading what the model can actually do, not what it could do in an unsandboxed --print |
--agent <name> also honors permissionMode in --print | Permission-gated tools (Bash, Edit) require either permissionMode: acceptEdits or explicit allowlists in the agent definition |
Migration test:
# Run an eval against an agent with a deliberately tight tools: list.
# Graders that previously called Read/Bash freely will now fail unless those
# tools are declared on the agent.
claude -p "$prompt" --bare --print --agent grader-test
If the grader fails with a "tool not permitted" error, add the required tool to the agent's tools: frontmatter and re-run.
CC 2.1.121: CLAUDE_CODE_FORK_SUBAGENT=1 for grader determinism (#1545)
Before CC 2.1.121, the env var only worked in interactive sessions. As of 2.1.121, non-interactive paths (claude -p, SDK) honor it too — each grader invocation gets a fresh forked subagent context.
The cross-eval state-leak problem this fixes:
Without forking, sequential claude -p --bare graders inherit harness state:
| Inherited | Symptom |
|---|---|
| memory MCP query cache | grader sees stale hit from previous run; same fixture grades differently |
.claude/chain/*.json on disk | grader for "implement" thinks "explore" already ran (file is from previous test) |
| ToolSearch deferred-tool cache | first grader's MCP loads bleed into next grader's tool registry |
| model picker pref | grader N inherits --model=opus from grader N-1 |
This produced ~5–10% retry rate and non-reproducible scores — the eval baseline drifted between runs, engineers chased phantom regressions.
Fix: tests/evals/scripts/lib/eval-common.sh exports CLAUDE_CODE_FORK_SUBAGENT=1, so every script that sources it (run-trigger-eval, run-quality-eval, run-agent-eval, optimize-description, etc.) gets forked graders automatically. The CI workflow .github/workflows/skill-eval.yml also sets it at the workflow level (its predecessor orchestkit-eval.yml was retired 2026-08-01 — its grading phases rated description prose, not behavior). Older CC silently ignores the env var (no-op).
Determinism contract: running the same grader on the same fixture twice in a row produces the same score. Verified by tests/evals/scripts/test-grader-determinism.sh.
Performance
| Scenario | Without --bare | With --bare | Savings |
|---|---|---|---|
| Single grading call | ~3-5s startup | ~0.5-1s | 2-4x |
| Trigger (per prompt) | ~3-5s | ~0.5-1s | 2-4x |
| Full eval (50 calls) | ~150-250s overhead | ~25-50s | 3-5x |
Rules
Read("rules/_sections.md")
Troubleshooting
Read("references/troubleshooting.md")
Dynamic-workflow harness (template-in-skill)
workflows/skill-fitness.js is a runnable dynamic-workflow template — the workflow-backed complement to the static conformance grader (scripts/eval/conformance-check.mjs). It fans out one isolated-context agent per skill to score fitness (freshness / router-clarity / structure) and synthesizes a ranked scorecard, catching qualitative drift a static grep can't (description/body count mismatches, duplicate headings, install-specific absolute paths, version drift). Run it with the Workflow tool:
Workflow({ name: "ork:skill-fitness",
args: ["assess", "commit", "doctor"] })
Treat it as a template, not a verbatim script — adapt the SKILLS list and rubric per use. Cost is real (~50k tokens/skill; scoring all ~112 is ~6M tokens), so pass an explicit batch via args. Static-first: run conformance-check.mjs (zero tokens) to pre-filter, then this harness for the judgment grep can't make.
Holdout Bake-Off Grading
The holdout-promotion gate grades a champion and a challenger SKILL.md over the same sealed holdout via bare-mode forked graders — the canonical consumer of the determinism contract above: identical grader + identical ork-rubric/1.0 + identical sealed set, with CLAUDE_CODE_FORK_SUBAGENT=1 so the only variable is the version under test. Both --bare constraints apply (requires ANTHROPIC_API_KEY, bills tokens directly → on-demand / CI only). Run it with bash tests/evals/scripts/run-skill-eval.sh --holdout-promote <skill>.
Related
eval:skillnpm script — unified skill evaluation runnereval:trigger— trigger accuracy testingeval:quality— A/B quality comparisonoptimize-description.sh— iterative description improvement- Version compatibility:
doctor/references/version-compatibility.md
careful, block destructive commands for this session
Invoking this skill registers a PreToolUse hook on Bash (the hooks: block above).
Claude Code keeps a skill's hooks registered for the rest of the session, on every
later turn, so careful stays on until the session ends. There is no off switch:
start a new session to work without it.
What it blocks
| Rule | Blocks | Still allowed |
|---|---|---|
rm-rf | rm with recursive and force flags (-rf, -fr, -r -f, --recursive --force), xargs rm -rf, and any target the shell expands: $TMPDIR/x, $TMP, $TEMP, $X, $( ), globs, braces, ~ | the same command when every target is a LITERAL absolute path that lands, after following existing symlinks, strictly inside /tmp, /private/tmp or the configured TMPDIR (trusted only when it is two or more levels deep); write /tmp/build, not $TMPDIR/build, because a command can reassign TMPDIR first (TMPDIR=/ ; rm -rf $TMPDIR/usr); rm -r; rm -f file |
git-push-force | git push --force, -f (also inside -uf), --force-with-lease[=...], a +branch refspec, to any branch | git push, git push -u origin <branch> |
git-push-delete | git push origin --delete <b>, -d <b>, :<b> | git push origin <b>:<b> |
git-reset-hard | git reset --hard | git reset --soft, git reset HEAD <file> |
sql-drop | DROP TABLE, DROP DATABASE, DROP SCHEMA anywhere in the command, heredocs included | a SELECT that mentions drop |
sql-truncate | TRUNCATE TABLE, or a TRUNCATE <name> statement sent to a SQL client | truncate -s 0 file.log |
kubectl-delete | kubectl ... delete | kubectl get, kubectl logs |
terraform-destroy | terraform destroy, terraform apply -destroy, the same with tofu | terraform plan, terraform apply |
Matching is on shell words, not substrings: a commit message or grep pattern that
quotes git push --force is text, not a push. Compound commands are split on
;, &&, | and newlines, and the bodies of bash -c, eval, $( ) and the
remote command of ssh host '...' are checked as well.
When a command is blocked
The hook exits 2 and Claude sees the reason, for example:
[ork-extras:careful] blocked by rule git-push-force: git push with --force-with-lease.
careful mode is on for this session, so destructive commands do not run unattended.
To proceed, ask the operator: they can run the command themselves, or confirm it and run it outside careful mode.
Then stop and ask. Do not rewrite the command to slip past the matcher (a different flag spelling, a script file, an alias): the operator turned careful on to be asked, and a workaround defeats that even when the matcher misses it.
Limits
careful is a pattern matcher on the text of each Bash call. It is a seatbelt, not a sandbox. It does NOT see:
-
shell aliases and functions (
alias nuke='rm -rf', thennuke src); -
scripts, Makefiles, npm scripts or binaries that run these commands inside (
./deploy.sh,make clean,npm run reset-db); -
evalorbash -cbuilt from variables, base64 or other indirection it cannot read as text; it only reads literal strings; -
interpreters and other shells running the same thing (
python -c "shutil.rmtree(...)",node -e,fish -c,pwsh), or a remote shell other than plainssh host '...'; -
a link created in the same command (
ln -s / /tmp/r9 && rm -rf /tmp/r9/usr): the guard follows links that already exist when it runs (a temp path through a link to/usris denied), but one made by the command itself is out of reach for a text check, likepython -c "shutil.rmtree(...)"; -
MCP tools, file edits, and anything outside the Bash tool.
-
If the hook cannot read its input it blocks (exit 2) rather than guess.
-
To also fence file edits to one directory, use the freeze skill.
The guard is scripts/careful-guard.mjs (Node, no dependencies); its matcher
cases live in tests/unit/test-careful-guard.mjs.
Related Skills
ork-extras:freeze: fence file edits to one directory; careful covers shell commands, freeze covers the edit tools.ork:security-patterns: defense in depth, the wider picture a text matcher is one layer of.ork:commit: history hygiene and branch protection for the force pushes careful asks about.
Design Stylecards
Specs beat vibes. A stylecard is a named aesthetic recipe with exact values — the difference
between "add a nice shadow" (reinvented differently every session) and elevation/md (identical
every time, reviewed once, versioned forever).
design-stylecards list # Catalog index
design-stylecards elevation/md # Show one recipe
design-stylecards apply glass/dark to src/components/Panel.tsx
Why declarative recipes
Pipeline skills (design-to-code, design-context-extract) answer how to produce design output.
Stylecards answer what good looks like — as literal values an agent pastes, not adjectives it
interprets. Inspired by MengTo/Skills' stylecard micro-skills (MIT), consolidated into one catalog
to avoid manifest sprawl.
Workflow
1. Resolve the request to a recipe
Read("references/stylecards.md") # The catalog — always read before choosing
# Match the user's intent to ONE recipe by its Use-When line.
# No match → say so and offer the closest two; never freehand values.
2. Show or apply
- Show: print the recipe verbatim — values, Use-When, Avoid. No paraphrasing values.
- Apply: edit the target file using the recipe's exact values. Adapt only the syntax (Tailwind arbitrary class ↔ plain CSS ↔ CSS custom property), never the numbers.
3. Respect the recipe's Avoid block
Every recipe ends with falsifiable Avoid rules (e.g. "never stack two elevation recipes on one element"). Violating an Avoid rule to satisfy a user request requires saying so explicitly.
Catalog index
Full recipes with exact values: references/stylecards.md.
| Recipe | Use when |
|---|---|
elevation/sm md lg | Layered neutral shadows — compact controls / cards / hero surfaces |
glass/dark | Frosted glass panel on a dark backdrop |
border/gradient | 1px gradient border without a wrapper hack |
background/mesh | 2–3 hue radial mesh page background |
type/editorial | Display + body + mono role split with tracking values |
motion/budget | The four allowed durations + the one-signature-moment rule |
Authoring a new stylecard
Add to references/stylecards.md following the contract — a recipe without all three parts is
not shippable:
- Use when — one line, concrete surfaces ("cards, panels, popovers"), not adjectives.
- Values — copy-paste-ready code. Numbers, not descriptions.
- Avoid — falsifiable don'ts observed from real misuse.
Source recipes from shipped, reviewed UI (this repo's playground standard, production apps you've
extracted with design-context-extract) — never from imagination.
Anti-Patterns
- NEVER freehand shadow/gradient/blur values when a recipe exists — that defeats the catalog
- NEVER paraphrase a recipe's values ("roughly 6% black") — paste them exactly
- NEVER mix two recipes of the same category (two elevations, two glass treatments) on one element
Quality Bar
Done means all of these hold:
- The chosen recipe's Use-When line actually matches the user's surface (quote both if challenged)
- Applied values are byte-identical to the catalog entry — only syntax adapted, never numbers
- No Avoid rule of the applied recipe is violated in the final diff
- New recipes carry all three contract parts: Use-When, exact values, Avoid
Related Skills
ork:design-context-extract— mines new recipe candidates from real appsork:design-system-tokens— where recipes graduate into project token architectureork:design-to-code— pipeline that consumes stylecards during generation
Distributed Systems Patterns
Comprehensive patterns for building reliable distributed systems. Each category has individual rule files in rules/ loaded on-demand.
Quick Reference
| Category | Rules | Impact | When to Use |
|---|---|---|---|
| Distributed Locks | 1 | CRITICAL | Fencing tokens, owner validation; Redis/Redlock and Postgres advisory via upstream docs |
| Resilience | 3 | CRITICAL | Circuit breakers, retry with backoff, bulkhead isolation |
| Idempotency | 1 | HIGH | Idempotency keys; dedup and database-backed storage via upstream docs |
| Rate Limiting | 2 | HIGH | Token bucket, sliding window; SlowAPI integration via upstream docs |
| Edge Computing | 2 | HIGH | Edge workers, V8 isolates, CDN caching, geo-routing |
| Event-Driven | 2 | HIGH | Event sourcing, CQRS, transactional outbox, sagas |
Total: 11 rules across 6 categories. Removed topics point at first-party sources in Upstream coverage; ork-specific scars live in references/ork-delta.md.
Quick Start
# Redis distributed lock with Lua scripts
async with RedisLock(redis_client, "payment:order-123"):
await process_payment(order_id)
# Circuit breaker for external APIs
@circuit_breaker(failure_threshold=5, recovery_timeout=30)
@retry(max_attempts=3, base_delay=1.0)
async def call_external_api():
...
# Idempotent API endpoint
@router.post("/payments")
async def create_payment(
data: PaymentCreate,
idempotency_key: str = Header(..., alias="Idempotency-Key"),
):
return await idempotent_execute(db, idempotency_key, "/payments", process)
# Token bucket rate limiting
limiter = TokenBucketLimiter(redis_client, capacity=100, refill_rate=10)
if await limiter.is_allowed(f"user:{user_id}"):
await handle_request()
Distributed Locks
Coordinate exclusive access to resources across multiple service instances.
| Rule | File | Key Pattern |
|---|---|---|
| Fencing Tokens | rules/locks-fencing-tokens.md | Owner validation, TTL, heartbeat extension |
Redis single-node locks, Redlock quorum, and PostgreSQL advisory locks are first-party documented; see Upstream coverage.
Resilience
Production-grade fault tolerance for distributed systems.
| Rule | File | Key Pattern |
|---|---|---|
| Circuit Breaker | rules/resilience-circuit-breaker.md | CLOSED/OPEN/HALF_OPEN states, sliding window |
| Retry & Backoff | rules/resilience-retry-backoff.md | Exponential backoff, jitter, error classification |
| Bulkhead Isolation | rules/resilience-bulkhead.md | Semaphore tiers, rejection policies, queue depth |
Idempotency
Ensure operations can be safely retried without unintended side effects.
| Rule | File | Key Pattern |
|---|---|---|
| Idempotency Keys | rules/idempotency-keys.md | Deterministic hashing, Stripe-style headers |
Event-consumer dedup and database-backed idempotency storage follow the Stripe pattern; see Upstream coverage.
Rate Limiting
Protect APIs with distributed rate limiting using Redis.
| Rule | File | Key Pattern |
|---|---|---|
| Token Bucket | rules/ratelimit-token-bucket.md | Redis Lua scripts, burst capacity, refill rate |
| Sliding Window | rules/ratelimit-sliding-window.md | Sorted sets, precise counting, no boundary spikes |
SlowAPI + Redis wiring and tiered limits are first-party documented; see Upstream coverage.
Edge Computing
Edge runtime patterns for Cloudflare Workers, Vercel Edge, and Deno Deploy.
| Rule | File | Key Pattern |
|---|---|---|
| Edge Workers | rules/edge-workers.md | V8 isolate constraints, Web APIs, geo-routing, auth at edge |
| Edge Caching | rules/edge-caching.md | Cache-aside at edge, CDN headers, KV storage, stale-while-revalidate |
Event-Driven
Event sourcing, CQRS, saga orchestration, and reliable messaging patterns.
| Rule | File | Key Pattern |
|---|---|---|
| Event Sourcing | rules/event-sourcing.md | Event-sourced aggregates, CQRS read models, optimistic concurrency |
| Event Messaging | rules/event-messaging.md | Transactional outbox, saga compensation, idempotent consumers |
Upstream coverage (do not restate)
These topics were removed from this skill on 2026-07-31 (wrap-plus-delta thinning) because a first-party source maintains them. Consult the source; do not re-add tutorials here. Ork-specific scars for these topics live in references/ork-delta.md.
Key Decisions
| Decision | Recommendation |
|---|---|
| Lock backend | Redis for speed, PostgreSQL if already using it, Redlock for HA |
| Lock TTL | 2-3x expected operation time |
| Circuit breaker recovery | Half-open probe with sliding window |
| Retry algorithm | Exponential backoff + full jitter |
| Bulkhead isolation | Semaphore-based tiers (Critical/Standard/Optional) |
| Idempotency storage | Redis (speed) + DB (durability), 24-72h TTL |
| Rate limit algorithm | Token bucket for most APIs, sliding window for strict quotas |
| Rate limit storage | Redis (distributed, atomic Lua scripts) |
When NOT to Use
No separate event-sourcing/saga/CQRS skills exist; they are rules within distributed-systems. But most projects never need them.
| Pattern | Interview | Hackathon | MVP | Growth | Enterprise | Simpler Alternative |
|---|---|---|---|---|---|---|
| Event sourcing | OVERKILL | OVERKILL | OVERKILL | OVERKILL | WHEN JUSTIFIED | Append-only table with status column |
| Saga orchestration | OVERKILL | OVERKILL | OVERKILL | SELECTIVE | APPROPRIATE | Sequential service calls with manual rollback |
| Circuit breaker | OVERKILL | OVERKILL | BORDERLINE | APPROPRIATE | REQUIRED | Try/except with timeout |
| Distributed locks | OVERKILL | OVERKILL | BORDERLINE | APPROPRIATE | REQUIRED | Database row-level lock (SELECT FOR UPDATE) |
| CQRS | OVERKILL | OVERKILL | OVERKILL | OVERKILL | WHEN JUSTIFIED | Single model for read/write |
| Transactional outbox | OVERKILL | OVERKILL | OVERKILL | SELECTIVE | APPROPRIATE | Direct publish after commit |
| Rate limiting | OVERKILL | OVERKILL | SIMPLE ONLY | APPROPRIATE | REQUIRED | Nginx rate limit or cloud WAF |
Rule of thumb: If you have a single server process, you do not need distributed systems patterns. Use in-process alternatives. Add distribution only when you actually have multiple instances.
Anti-Patterns (FORBIDDEN)
# LOCKS: Never forget TTL (causes deadlocks)
await redis.set(f"lock:{name}", "1") # WRONG - no expiry!
# LOCKS: Never release without owner check
await redis.delete(f"lock:{name}") # WRONG - might release others' lock
# RESILIENCE: Never retry non-retryable errors
@retry(max_attempts=5, retryable_exceptions={Exception}) # Retries 401!
# RESILIENCE: Never put retry outside circuit breaker
@retry # Would retry when circuit is open!
@circuit_breaker
async def call(): ...
# IDEMPOTENCY: Never use non-deterministic keys
key = str(uuid.uuid4()) # Different every time!
# IDEMPOTENCY: Never cache error responses
if response.status_code >= 400:
await cache_response(key, response) # Errors should retry!
# RATE LIMITING: Never use in-memory counters in distributed systems
request_counts = {} # Lost on restart, not shared across instances
Detailed Documentation
| Resource | Description |
|---|---|
scripts/ | Templates: lock implementations, circuit breaker, rate limiter |
references/ork-delta.md | Ork-specific scars and house decisions kept after the wrap-plus-delta thinning |
Related Skills
caching- Redis caching patterns, cache as fallbackbackground-jobs- Job deduplication, async processing with retryobservability-monitoring- Metrics and alerting for circuit breaker state changeserror-handling-rfc9457- Structured error responses for resilience failuresauth-patterns- API key management, authentication integration
Documentation Patterns
Templates and opinionated structures for technical documentation -- READMEs, Architecture Decision Records, OpenAPI specs, changelogs, and writing style. Each category has individual rule files in rules/ loaded on-demand.
Quick Reference
| Category | Rule | Impact | When to Use |
|---|---|---|---|
| README | 1 | HIGH | Starting a project, onboarding contributors |
| ADR | 1 | HIGH | Recording architecture decisions |
| API Docs | 1 | HIGH | Documenting REST APIs with OpenAPI 3.1 |
| Changelog | 1 | MEDIUM | Maintaining release history |
| Writing Style | 1 | MEDIUM | Any technical writing task |
Total: 5 rules across 5 categories
Quick Start
## README Skeleton
# Project Name
Brief description -> Quick Start -> Installation -> Usage -> API -> Config -> Contributing -> License
## ADR Format
# ADR-001: Title
Status -> Context -> Decision -> Consequences (positive/negative) -> References
## OpenAPI Minimum
openapi: 3.1.0 with info, paths, components/schemas, error responses
## Changelog Entry
## [1.2.0] - 2026-03-05
### Added / Changed / Deprecated / Removed / Fixed / Security
## Writing Rule of Thumb
Active voice, present tense, second person, one idea per sentence
README
Complete README template with all essential sections for open-source and internal projects.
docs-readme-structure-- Project name, quick start, installation, usage, API reference, configuration, contributing, license
Architecture Decision Records
Structured format for capturing architectural decisions with context and consequences.
docs-adr-template-- Status, context, decision, consequences (positive/negative), references
API Documentation
OpenAPI 3.1 specification patterns for consistent, machine-readable API docs.
docs-api-openapi-- Path structure, operation definitions, schema components, error responses (RFC 9457)
Changelog
Keep a Changelog format for curated, human-readable release history.
docs-changelog-format-- Added, Changed, Deprecated, Removed, Fixed, Security sections with semver
Writing Style
Technical writing conventions for clear, scannable documentation.
docs-writing-style-- Active voice, present tense, concise sentences, API doc checklist
Related Skills
ork:api-design-- API design patterns (complements OpenAPI documentation)ork:architecture-decision-record-- ADR workflow and lifecycleork-extras:release-management-- Release process including changelog updates
Version: 1.0.0 (March 2026)
Domain-Driven Design Tactical Patterns
Model complex business domains with entities, value objects, and bounded contexts.
Overview
- Modeling complex business logic
- Separating domain from infrastructure
- Establishing clear boundaries between subdomains
- Building rich domain models with behavior
- Implementing ubiquitous language in code
Building Blocks Overview
┌─────────────────────────────────────────────────────────────┐
│ DDD Building Blocks │
├─────────────────────────────────────────────────────────────┤
│ ENTITIES VALUE OBJECTS AGGREGATES │
│ Order (has ID) Money (no ID) [Order]→Items │
│ │
│ DOMAIN SERVICES REPOSITORIES DOMAIN EVENTS │
│ PricingService IOrderRepository OrderSubmitted │
│ │
│ FACTORIES SPECIFICATIONS MODULES │
│ OrderFactory OverdueOrderSpec orders/, payments/ │
└─────────────────────────────────────────────────────────────┘
Quick Reference
Entity (Has Identity)
from dataclasses import dataclass, field
from uuid import UUID
from uuid_utils import uuid7
@dataclass
class Order:
"""Entity: Has identity, mutable state, lifecycle."""
id: UUID = field(default_factory=uuid7)
customer_id: UUID = field(default=None)
status: str = "draft"
def __eq__(self, other: object) -> bool:
if not isinstance(other, Order):
return NotImplemented
return self.id == other.id # Identity equality
def __hash__(self) -> int:
return hash(self.id)
ID generation is a house rule, not a taste call: Read("references/ork-delta.md").
Value Object (Immutable)
from dataclasses import dataclass
from decimal import Decimal
@dataclass(frozen=True) # MUST be frozen!
class Money:
"""Value Object: Defined by attributes, not identity."""
amount: Decimal
currency: str
def __add__(self, other: "Money") -> "Money":
if self.currency != other.currency:
raise ValueError("Cannot add different currencies")
return Money(self.amount + other.amount, self.currency)
Canonical Address / DateRange boilerplate is not restated here. See the upstream coverage table below.
Key Decisions
| Decision | Recommendation |
|---|---|
| Entity vs VO | Has unique ID + lifecycle? Entity. Otherwise VO |
| Entity equality | By ID, not attributes |
| Value object mutability | Always immutable (frozen=True) |
| Repository scope | One per aggregate root |
| Domain events | Collect in entity, publish after persist |
| Context boundaries | By business capability, not technical |
Rules Quick Reference
| Rule | Impact | What It Covers |
|---|---|---|
aggregate-boundaries (load rules/aggregate-boundaries.md) | HIGH | Aggregate root design, reference by ID, one-per-transaction |
aggregate-invariants (load rules/aggregate-invariants.md) | HIGH | Business rule enforcement, specification pattern |
aggregate-sizing (load rules/aggregate-sizing.md) | HIGH | Right-sizing, when to split, eventual consistency |
When NOT to Use
Under 5 entities? Skip DDD entirely. The ceremony costs more than the benefit.
| Pattern | Interview | Hackathon | MVP | Growth | Enterprise | Simpler Alternative |
|---|---|---|---|---|---|---|
| Aggregates | OVERKILL | OVERKILL | OVERKILL | SELECTIVE | APPROPRIATE | Plain dataclasses with validation |
| Bounded contexts | OVERKILL | OVERKILL | OVERKILL | BORDERLINE | APPROPRIATE | Python packages with clear imports |
| CQRS | OVERKILL | OVERKILL | OVERKILL | OVERKILL | WHEN JUSTIFIED | Single model for read/write |
| Value objects | OVERKILL | OVERKILL | BORDERLINE | APPROPRIATE | REQUIRED | Typed fields on the entity |
| Domain events | OVERKILL | OVERKILL | OVERKILL | SELECTIVE | APPROPRIATE | Direct method calls between services |
| Repository pattern | OVERKILL | OVERKILL | BORDERLINE | APPROPRIATE | REQUIRED | Direct ORM queries in service layer |
Rule of thumb: DDD adds ~40% code overhead. Only worth it when domain complexity genuinely demands it (5+ entities with invariants spanning multiple objects). A CRUD app with DDD is a red flag.
Anti-Patterns (FORBIDDEN)
# NEVER have anemic domain models (data-only classes)
@dataclass
class Order:
id: UUID
items: list # WRONG - no behavior!
# NEVER leak infrastructure into domain
class Order:
def save(self, session: Session): # WRONG - knows about DB!
# NEVER use mutable value objects
@dataclass # WRONG - missing frozen=True
class Money:
amount: Decimal
# NEVER have repositories return ORM models
async def get(self, id: UUID) -> OrderModel: # WRONG - return domain!
Upstream coverage (do not restate)
These topics are documented first-party. Read the source instead of re-deriving them here; only the
house consequences are kept, in references/ork-delta.md.
| Topic | Source |
|---|---|
Entity / value-object dataclass mechanics: frozen, __post_init__, inherited field ordering, kw_only | https://docs.python.org/3/library/dataclasses.html |
| Domain event definition, deferred dispatch, handler wiring, dispatch before vs after commit | https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/domain-events-design-implementation |
| Bounded contexts, context map, ubiquitous language, integration patterns (shared kernel, customer-supplier, conformist, open host service, published language) | https://learn.microsoft.com/en-us/azure/architecture/microservices/model/domain-analysis |
| Anti-corruption layer: what it translates and what it costs | https://learn.microsoft.com/en-us/azure/architecture/patterns/anti-corruption-layer |
| UUIDv7 generation, server side and in Python | https://www.postgresql.org/docs/18/functions-uuid.html and https://github.com/aminalaee/uuid-utils |
| Payment amounts in minor units, zero-decimal currencies | https://docs.stripe.com/currencies |
Publishing events to a Redis Stream (XADD field maps, pipelining) | https://redis.io/docs/latest/commands/xadd/ |
| Layered architecture enforcement, project-structure validation, test standards | the architecture-patterns skill in this plugin |
Two subjects deliberately stay in this skill rather than routing upstream: the repository and
Unit of Work implementation, which lives in full in references/repositories.md, and aggregate
boundaries, invariants, and sizing, which live in full in rules/.
Related Skills
rules/aggregate-boundaries.md,rules/aggregate-invariants.md,rules/aggregate-sizing.md- aggregate design, in this skillork:architecture-patterns- Layer boundaries and project structure validationork-extras:distributed-systems- Cross-aggregate coordinationork:database-patterns- Schema design for DDD
References
Load on demand with Read("references/<file>"):
| File | Content |
|---|---|
ork-delta.md | House rules: UUIDv7, event drain ordering, ACL boundary, source layout |
repositories.md | Repository pattern, Unit of Work, SQLAlchemy mapping |
Capability Details
entities
Keywords: entity, identity, lifecycle, mutable, domain object
Solves: Identity equality by ID, and the house UUIDv7 ID rule in references/ork-delta.md. Dataclass mechanics route upstream.
value-objects
Keywords: value object, immutable, frozen, dataclass, structural equality
Solves: When to use VO vs entity. frozen=True semantics and inherited field ordering route upstream.
domain-services
Keywords: domain service, business logic, cross-aggregate, stateless Solves: When to use domain service, logic spanning aggregates
repositories
Keywords: repository, persistence, collection, IRepository, protocol Solves: Implement repository pattern, abstract DB access, ORM mapping
bounded-contexts
Keywords: bounded context, context map, ACL, subdomain, ubiquitous language
Solves: The house ACL boundary and context-first source layout in references/ork-delta.md. Context mapping and integration patterns route upstream.
Figma Design Handoff
Figma dominates design tooling in 2026, with the majority of product teams using it as their primary design tool. A structured handoff workflow eliminates design drift — the gap between what designers create and what developers build. This skill covers the full pipeline: Figma Variables to design tokens, component spec extraction, Dev Mode inspection, Auto Layout to CSS mapping, and visual regression testing.
Quick Reference
| Rule | File | Impact | When to Use |
|---|---|---|---|
| Figma Variables & Tokens | rules/figma-variables-tokens.md | CRITICAL | Converting Figma Variables to W3C design tokens JSON |
| Component Specs | rules/figma-component-specs.md | HIGH | Extracting component props, variants, states from Figma |
| Dev Mode Inspection | rules/figma-dev-mode.md | HIGH | Measurements, spacing, typography, asset export |
| Auto Layout → CSS | rules/figma-auto-layout.md | HIGH | Mapping Auto Layout to Flexbox/Grid |
| Visual Regression | rules/figma-visual-regression.md | MEDIUM | Comparing production UI against Figma designs |
Total: 5 rules across 1 category
Figma Dev Mode MCP Server (2026 default path)
The Figma Dev Mode MCP Server replaces most manual REST + Dev Mode inspection. Configure it once and any Claude Code session with Figma access can pull design context, tokens, and code mappings directly.
Key tools (16 documented — developers.figma.com/docs/figma-mcp-server/tools-and-prompts):
| Tool | Returns | Use for |
|---|---|---|
get_design_context | Component tree + layout + typography + spacing | First call on any Figma node → grounds every other tool |
get_variable_defs | Token collections (variables + modes + aliases) | Straight export to W3C DTCG JSON — skip the REST pipeline |
get_code_connect_map | Figma node → codebase component mapping | Linking generated code to existing repo components |
get_screenshot | PNG of a node or frame | Screenshot for visual diffing / embed in chat |
search_design_system | Token/component search across libraries | Finding existing tokens before generating new ones |
use_figma (beta) | Writes back to the Figma canvas | Code-to-design round-trip (write-to-canvas) |
generate_figma_design (beta) | Creates a design frame from a prompt | AI-generated design stubs for handoff |
Install: Enable in the Figma desktop app under Preferences → Dev Mode MCP Server, or use the remote MCP endpoint (no desktop required for read tools). Pair with Code Connect UI (GA 2026) to map Figma node IDs → codebase components without manual JSON wiring.
// .claude/mcp-servers/figma.json — sample config
{
"figma": {
"command": "figma-mcp",
"args": ["--mode=dev"],
"env": { "FIGMA_ACCESS_TOKEN": "${FIGMA_TOKEN}" }
}
}
Quick Start
# 1. Export Figma Variables (Figma REST API)
curl -s -H "X-Figma-Token: $FIGMA_TOKEN" \
"https://api.figma.com/v1/files/$FILE_KEY/variables/local" \
> tokens/figma-local.json
# 2. Convert that response to W3C Design Tokens. This skill does NOT ship a
# converter — the mapping (variables, modes, aliases, and the $value/$type
# shape) is specified in rules/figma-variables-tokens.md, and the right
# implementation depends on which collections and modes your file uses.
# Earlier revisions of this Quick Start piped into a
# `scripts/figma-to-w3c-tokens.js` that has never existed in this skill.
# Result: tokens/figma-raw.json
# 3. Transform with Style Dictionary
npx style-dictionary build --config sd.config.js
# 4. Output: CSS custom properties + Tailwind theme
# tokens/
# figma-raw.json ← W3C Design Tokens format
# css/variables.css ← --color-primary: oklch(0.65 0.15 250);
# tailwind/theme.js ← module.exports = { colors: { primary: ... } }
// W3C Design Tokens Format (DTCG)
{
"color": {
"primary": {
"$type": "color",
"$value": "{color.blue.600}",
"$description": "Primary brand color"
},
"surface": {
"$type": "color",
"$value": "{color.neutral.50}",
"$extensions": {
"mode": {
"dark": "{color.neutral.900}"
}
}
}
}
}
// Style Dictionary config for Figma Variables
import StyleDictionary from 'style-dictionary';
export default {
source: ['tokens/figma-raw.json'],
platforms: {
css: {
transformGroup: 'css',
buildPath: 'tokens/css/',
files: [{ destination: 'variables.css', format: 'css/variables' }],
},
tailwind: {
transformGroup: 'js',
buildPath: 'tokens/tailwind/',
files: [{ destination: 'theme.js', format: 'javascript/module' }],
},
},
};
Handoff Workflow
The design-to-code pipeline follows five stages:
- Design in Figma — Designer creates components with Variables, Auto Layout, and proper naming
- Extract Specs — Use Dev Mode to inspect spacing, typography, colors, and export assets
- Export Tokens — Figma Variables → W3C tokens JSON via REST API or plugin
- Build Components — Map Auto Layout to CSS Flexbox/Grid, apply tokens, implement variants
- Visual QA — Compare production screenshots against Figma frames with Applitools
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
│ Figma File │────▶│ Dev Mode │────▶│ tokens.json │
│ (Variables, │ │ (Inspect, │ │ (W3C DTCG │
│ Auto Layout)│ │ Export) │ │ format) │
└─────────────┘ └──────────────┘ └───────┬───────┘
│
▼
┌─────────────┐ ┌──────────────┐ ┌───────────────┐
│ Visual QA │◀────│ Components │◀────│ Style │
│ (Applitools,│ │ (React + │ │ Dictionary │
│ Chromatic) │ │ Tailwind) │ │ (CSS/Tailwind)│
└─────────────┘ └──────────────┘ └───────────────┘
Rules
Each rule is loaded on-demand from the rules/ directory:
Auto Layout to CSS Mapping
Quick reference for the most common mappings:
| Figma Auto Layout | CSS Equivalent | Tailwind Class |
|---|---|---|
| Direction: Horizontal | flex-direction: row | flex-row |
| Direction: Vertical | flex-direction: column | flex-col |
| Gap: 16 | gap: 16px | gap-4 |
| Padding: 16 | padding: 16px | p-4 |
| Padding: 16, 24 | padding: 16px 24px | py-4 px-6 |
| Align: Center | align-items: center | items-center |
| Justify: Space between | justify-content: space-between | justify-between |
| Fill container | flex: 1 1 0% | flex-1 |
| Hug contents | width: fit-content | w-fit |
| Fixed width: 200 | width: 200px | w-[200px] |
| Min width: 100 | min-width: 100px | min-w-[100px] |
| Max width: 400 | max-width: 400px | max-w-[400px] |
| Wrap | flex-wrap: wrap | flex-wrap |
| Absolute position | position: absolute | absolute |
Visual QA Loop
// Applitools Eyes + Figma Plugin — CI integration
import { Eyes, Target } from '@applitools/eyes-playwright';
const eyes = new Eyes();
await eyes.open(page, 'MyApp', 'Homepage — Figma Comparison');
// Capture full page
await eyes.check('Full Page', Target.window().fully());
// Capture specific component
await eyes.check(
'Hero Section',
Target.region('#hero').ignoreDisplacements()
);
await eyes.close();
The Applitools Figma Plugin overlays production screenshots on Figma frames to catch:
- Color mismatches (token not applied or wrong mode)
- Spacing drift (padding/margin deviations)
- Typography inconsistencies (font size, weight, line height)
- Missing states (hover, focus, disabled not implemented)
Key Decisions
| Decision | Recommendation |
|---|---|
| Token format | W3C Design Tokens Community Group (DTCG) JSON |
| Token pipeline | Figma REST API → Style Dictionary → CSS/Tailwind |
| Color format | OKLCH for perceptually uniform theming |
| Layout mapping | Auto Layout → CSS Flexbox (Grid for 2D layouts) |
| Visual QA tool | Applitools Eyes + Figma Plugin for design-dev diff |
| Spec format | TypeScript interfaces matching Figma component props |
| Mode handling | Figma Variable modes → CSS media queries / class toggles |
Anti-Patterns (FORBIDDEN)
- Hardcoded values: Never hardcode colors, spacing, or typography — always reference tokens
- Skipping Dev Mode: Do not eyeball measurements — use Dev Mode for exact values
- Manual token sync: Do not manually copy values from Figma — automate with REST API
- Ignoring modes: Variables with light/dark modes must map to theme toggles, not separate files
- Screenshot-only QA: Visual comparison without structured regression testing misses subtle drift
- Flat token structure: Use nested W3C DTCG format, not flat key-value pairs
References
| Resource | Description |
|---|---|
| references/figma-to-code-workflow.md | End-to-end workflow, toolchain options |
| references/design-dev-communication.md | PR templates, component status tracking |
| references/applitools-figma-plugin.md | Setup, CI integration, comparison config |
Related Skills
ork:design-system-tokens— W3C token architecture and Style Dictionary transformsork-extras:ui-components— shadcn/ui and Radix component patternsork-extras:accessibility— WCAG compliance for components extracted from Figma
freeze, keep edits inside one directory
State for this session:
!node "${CLAUDE_SKILL_DIR}/scripts/freeze-guard.mjs" arm "${CLAUDE_PROJECT_DIR}" "${CLAUDE_SESSION_ID}" "$ARGUMENTS"
The line above ran when the skill was invoked: it resolved the argument against the
project dir, followed symlinks, and recorded the real path for this session in
.claude/state/freeze/<session-id>.json. The argument is double-quoted, so a name with
spaces or an apostrophe arrives as typed; a $, backtick or double quote in a dir
name would be interpreted by the shell and is not supported. Report that line to the operator as it reads. If it says NOT changed,
the freeze did not move; say so and stop.
How it works
Invoking this skill also registers a PreToolUse hook on Edit|Write|MultiEdit|NotebookEdit
(the hooks: block above). Claude Code keeps a skill's hooks registered for the rest
of the session, so the fence holds on every later turn. For each edit the hook
resolves where the write would actually land and denies it (exit 2) when that is
outside the frozen dir:
| Target | Verdict |
|---|---|
<frozen>/a.ts, or a new file in a new subdir of <frozen> | allowed |
<frozen>/../other/b.ts | denied |
<frozen>-evil/x.ts (a prefix sibling) | denied |
<frozen>/link/b.ts where link points outside | denied, symlinks are followed |
<frozen>/dangling.ts, a link to a missing file outside | denied, the link is chased |
| an edit call with no path | denied |
Usage
/ork-extras:freeze src/hooks # fence edits to src/hooks
/ork-extras:freeze # show the current fence
/ork-extras:freeze off # lift it
Invoking again with another dir moves the fence; a dir that does not exist is refused and the previous fence stays.
When an edit is blocked
The deny reason names the target and the frozen dir. Stop and ask the operator to
widen or lift the freeze. Do not route the change through Bash (sed -i, cat >,
cp) instead: the fence covers the edit tools only, and using Bash to get around it
defeats the reason it was turned on.
Limits
- Edit tools only. Bash, MCP tools and subprocesses can still write anywhere. Pair with careful for destructive shell commands, or with a worktree for real isolation.
- One fence per session, stored under the project's
.claude/state/freeze/. - If the hook cannot read its input or the state file it blocks rather than guess.
The fence is scripts/freeze-guard.mjs (Node, no dependencies); its cases live in
tests/unit/test-freeze-guard.mjs.
Related Skills
ork-extras:careful: block destructive shell commands; freeze covers the edit tools, careful covers Bash.ork:implement: parallel feature work in worktrees, the real isolation freeze points to.ork:fix-issue: a bug fix that should stay inside one package or module.
Golden Dataset
Comprehensive patterns for building, managing, and validating golden datasets for AI/ML evaluation. Each category has individual rule files in rules/ loaded on-demand.
Quick Reference
| Category | Rules | Impact | When to Use |
|---|---|---|---|
| Curation | 2 | HIGH | Content collection, annotation pipelines |
| Management | 2 | HIGH | Versioning, backup/restore |
| Validation | 1 | CRITICAL | Regression testing |
| Add Workflow | 1 | HIGH | 9-phase curation, quality scoring, bias detection, silver-to-gold |
Total: 6 rules across 4 categories. House thresholds and scars: references/ork-delta.md.
Curation
Content collection, multi-agent annotation, and diversity analysis for golden datasets.
| Rule | File | Key Pattern |
|---|---|---|
| Collection | rules/curation-collection.md | Content type classification, quality thresholds, duplicate prevention |
| Annotation | rules/curation-annotation.md | Multi-agent pipeline, consensus aggregation, Langfuse tracing |
Difficulty ladder, coverage floors, and duplicate thresholds: references/ork-delta.md.
Management
Versioning, storage, and CI/CD automation for golden datasets.
| Rule | File | Key Pattern |
|---|---|---|
| Versioning | rules/management-versioning.md | JSON backup format, embedding regeneration, disaster recovery |
| Storage | rules/management-storage.md | Backup strategies, URL contract, data integrity checks |
CI automation for backups is upstream's job; see "Upstream coverage" below.
Validation
Quality scoring, drift detection, and regression testing for golden datasets.
| Rule | File | Key Pattern |
|---|---|---|
| Regression | rules/validation-regression.md | Difficulty distribution, pre-commit hooks, full dataset validation |
Schema validation and duplicate detection are upstream's job (see "Upstream coverage"
below); the house thresholds they must enforce live in references/ork-delta.md.
Add Workflow
Structured workflow for adding new documents to the golden dataset.
| Rule | File | Key Pattern |
|---|---|---|
| Add Document | rules/curation-add-workflow.md | 9-phase curation, parallel quality analysis, bias detection |
Quick Start Example
async def validate_before_add(document: dict, source_url_map: dict) -> dict:
"""Pre-addition validation for golden dataset entries."""
errors = []
# 1. URL contract check
if "placeholder" in document.get("source_url", ""):
errors.append("URL must be canonical, not a placeholder")
# 2. Content quality
if len(document.get("title", "")) < 10:
errors.append("Title too short (min 10 chars)")
# 3. Tag requirements
if len(document.get("tags", [])) < 2:
errors.append("At least 2 domain tags required")
return {"valid": len(errors) == 0, "errors": errors}
Key Decisions
| Decision | Recommendation |
|---|---|
| Backup format | JSON (version controlled, portable) |
| Embedding storage | Exclude from backup (regenerate on restore) |
| Quality threshold | >= 0.70 quality score for inclusion |
| Confidence threshold | >= 0.65 for auto-include |
| Duplicate threshold | >= 0.90 similarity blocks, >= 0.85 warns |
| Min tags per entry | 2 domain tags |
| Min test queries | 3 per document |
| Difficulty balance | Trivial 3, Easy 3, Medium 5, Hard 3 minimum |
| CI frequency | Weekly automated backup (Sunday 2am UTC) |
Common Mistakes
- Using placeholder URLs instead of canonical source URLs
- Skipping embedding regeneration after restore
- Not validating referential integrity between documents and queries
- Over-indexing on articles (neglecting tutorials, research papers)
- Missing difficulty distribution balance in test queries
- Not running verification after backup/restore operations
- Testing restore procedures in production instead of staging
- Committing SQL dumps instead of JSON (not version-control friendly)
Running a dataset as an experiment
Curating a dataset is half the job; the other half is running something against it and scoring the result. Both Langfuse SDKs ship a runner, and their shapes differ.
Python (SDK 4.x): see monitoring-observability/references/experiments-api.md.
JS/TS (SDK 5.x): @langfuse/client exposes the runner directly on a fetched dataset.
import { LangfuseClient } from "@langfuse/client";
const langfuse = new LangfuseClient();
const dataset = await langfuse.dataset.get("my-evaluation-dataset");
const result = await dataset.runExperiment({
name: "Retrieval quality",
task: myTask, // (params) => Promise<any>
evaluators: [myEvaluator], // per-item: (params) => Promise<Evaluation | Evaluation[]>
});
| Type | Scores | Use for |
|---|---|---|
Evaluator | one item | Per-example quality (faithfulness, relevance) |
RunEvaluator | the whole run | Aggregate assertions — pass rate, mean score, regression checks |
Evaluation | — | { name, value, comment?, metadata?, dataType?, configId? } |
A per-item Evaluator cannot see the other items, so anything comparative belongs in a
RunEvaluator. createEvaluatorFromAutoevals wraps an autoevals scorer instead of hand-writing
one, and RegressionError is thrown when a run regresses against a configured baseline — catch it
to fail CI on a quality drop rather than only on an exception.
Full JS surface: monitoring-observability/references/langfuse-js-v5.md.
Evaluations
See test-cases.json for 9 test cases across all categories.
Upstream coverage (do not restate)
| Topic | First-party source |
|---|---|
| Dataset schema validation (JSON Schema, field constraints) | https://json-schema.org and https://zod.dev |
| Duplicate detection via embeddings, cosine similarity | https://github.com/pgvector/pgvector |
| Scheduled backup automation (cron workflows, commit bots) | https://docs.github.com/actions/using-workflows/events-that-trigger-workflows#schedule |
| Dataset runs, experiment scoring, annotation queues | https://langfuse.com/docs/datasets |
| Backup and restore mechanics for postgres datasets | https://www.postgresql.org/docs/current/backup.html |
House thresholds these must enforce: references/ork-delta.md.
Related Skills
ork-extras:rag-retrieval- Retrieval evaluation using golden datasetork-extras:monitoring-observability- Langfuse tracing patterns for curation workflowsork:testing-llm- Evaluation harnesses that consume golden datasetsork:testing-unit- Unit testing patterns and strategies
Capability Details
curation
Keywords: golden dataset, curation, content collection, annotation, quality criteria
Solves:
- Classify document content types for golden dataset
- Run multi-agent quality analysis pipelines
- Generate test queries for new documents
management
Keywords: golden dataset, backup, restore, versioning, disaster recovery
Solves:
- Backup and restore golden datasets with JSON
- Regenerate embeddings after restore
- Automate backups with CI/CD
validation
Keywords: golden dataset, validation, schema, duplicate detection, quality metrics
Solves:
- Validate entries against document schema
- Detect duplicate or near-duplicate entries
- Analyze dataset coverage and distribution gaps
i18n and Localization Patterns
Overview
This skill provides comprehensive guidance for implementing internationalization in React applications. It ensures ALL user-facing strings, date displays, currency, lists, and time calculations are locale-aware.
When to use this skill:
- Adding ANY user-facing text to components
- Formatting dates, times, currency, lists, or ordinals
- Implementing complex pluralization
- Embedding React components in translated text
- Supporting RTL languages (Hebrew, Arabic)
Bundled Resources (load with Read("<path>")):
references/formatting-utilities.md- useFormatting hook API referencereferences/ork-delta.md- House decisions and working config that upstream docs do not carrychecklists/i18n-checklist.md- Implementation and review checklistexamples/component-i18n-example.md- Complete component example
Canonical Reference: See docs/i18n-standards.md for the full i18n standards document.
Core Patterns
1. useTranslation Hook (All UI Strings)
Every visible string MUST use the translation function:
import { useTranslation } from 'react-i18next';
function MyComponent() {
const { t } = useTranslation(['patients', 'common']);
return (
<div>
<h1>{t('patients:title')}</h1>
<button>{t('common:actions.save')}</button>
</div>
);
}
2. useFormatting Hook (Locale-Aware Data)
All locale-sensitive formatting MUST use the centralized hook:
import { useFormatting } from '@/hooks';
function PriceDisplay({ amount, items }) {
const { formatILS, formatList, formatOrdinal } = useFormatting();
return (
<div>
<p>Price: {formatILS(amount)}</p> {/* ₪1,500.00 */}
<p>Items: {formatList(items)}</p> {/* "a, b, and c" */}
<p>Position: {formatOrdinal(3)}</p> {/* "3rd" */}
</div>
);
}
Load Read("references/formatting-utilities.md") for the complete API.
3. Date Formatting
All dates MUST use the centralized @/lib/dates library:
import { formatDate, formatDateShort, calculateWaitTime } from '@/lib/dates';
const date = formatDate(appointment.date); // "Jan 6, 2026"
const waitTime = calculateWaitTime('09:30'); // "15 min"
4. ICU MessageFormat (Complex Plurals)
Use ICU syntax in translation files for pluralization:
{
"patients": "{count, plural, =0 {No patients} one {# patient} other {# patients}}"
}
t('patients', { count: 5 }) // → "5 patients"
House rules for plurals live in rules/i18n-icu-plurals.md. For the full ICU grammar
see the upstream table below.
5. Trans Component (Rich Text)
For embedded React components in translated text:
import { Trans } from 'react-i18next';
<Trans
i18nKey="richText.welcome"
values={{ name: userName }}
components={{ strong: <strong /> }}
/>
House rules for <Trans> live in rules/i18n-trans-component.md; the plural-plus-rich-text
ordering constraint lives in references/ork-delta.md. For the full component API see the
upstream table below.
Upstream coverage (do not restate)
These topics are owned by first-party docs. Read them there instead of re-deriving them here.
| Topic | First-party source | House subset kept here |
|---|---|---|
| ICU plural, select, selectordinal, offset and nested message grammar | https://formatjs.github.io/docs/core-concepts/icu-syntax/ and https://unicode-org.github.io/icu/userguide/format_parse/messages/ | rules/i18n-icu-plurals.md keeps the house subset in full: no ternary pluralization, the mandatory other arm, =0 for zero states, Hebrew dual and Arabic categories |
| Which plural categories a given locale actually has | https://cldr.unicode.org/index/cldr-spec/plural-rules | none, read upstream |
ICU number skeletons inside a message (::currency/ILS) | https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html | references/ork-delta.md keeps only the ILS skeleton decision |
In-message date and time forms ({date, date, medium}) and offset: plurals | https://unicode-org.github.io/icu/userguide/format_parse/messages/ | nothing; fetch it upstream |
<Trans> API: named vs indexed tags, self-closing tags, TransProps typing | https://react.i18next.com/latest/trans-component | rules/i18n-trans-component.md keeps the house subset in full: never split a sentence across t() calls, never dangerouslySetInnerHTML, prefer named tags over indexed |
| Wiring the ICU parser into i18next | https://github.com/i18next/i18next-icu | references/ork-delta.md keeps the decision and why suffix keys are not enough |
Intl.ListFormat primitive behind useFormatting | https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat | references/formatting-utilities.md keeps the house hook API |
Intl.NumberFormat primitive behind useFormatting | https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat | references/formatting-utilities.md keeps the house hook API |
Translation File Structure
frontend/src/i18n/locales/
├── en/
│ ├── common.json # Shared: actions, status, time
│ ├── patients.json # Patient-related strings
│ ├── dashboard.json # Dashboard strings
│ ├── owner.json # Owner portal strings
│ └── invoices.json # Invoice strings
└── he/
└── (same structure)
Anti-Patterns (FORBIDDEN)
// ❌ NEVER hardcode strings
<h1>מטופלים</h1> // Use t('patients:title')
<button>Save</button> // Use t('common:actions.save')
// ❌ NEVER use .join() for lists
items.join(', ') // Use formatList(items)
// ❌ NEVER hardcode currency
"₪" + price // Use formatILS(price)
// ❌ NEVER use new Date() for formatting
new Date().toLocaleDateString() // Use formatDate() from @/lib/dates
// ❌ NEVER use inline plural logic
count === 1 ? 'item' : 'items' // Use ICU MessageFormat
// ❌ NEVER leave console.log in production
console.log('debug') // Remove before commit
// ❌ NEVER use dangerouslySetInnerHTML for i18n
dangerouslySetInnerHTML // Use <Trans> component
Quick Reference
| Need | Solution |
|---|---|
| UI text | t('namespace:key') from useTranslation |
| Currency | formatILS(amount) from useFormatting |
| Lists | formatList(items) from useFormatting |
| Ordinals | formatOrdinal(n) from useFormatting |
| Dates | formatDate(date) from @/lib/dates |
| Plurals | ICU MessageFormat in translation files |
| Rich text | <Trans> component |
| RTL check | isRTL from useFormatting |
Checklist
Load Read("checklists/i18n-checklist.md") for complete implementation and review checklists.
Integration with Agents
Frontend UI Developer
- Uses all i18n patterns for components
- References this skill for formatting
- Ensures no hardcoded strings
Code Quality Reviewer
- Checks for anti-patterns (
.join(),console.log, etc.) - Validates translation key coverage
- Ensures RTL compatibility
Skill Version: 1.2.0 Last Updated: 2026-01-06 Maintained by: Yonatan Gross
Related Skills
ork:testing-e2e- E2E testing patterns including accessibility testing for i18nork:react-server-components-framework- Server-side locale detection and RSC i18n patternsork-extras:accessibility- RTL-aware focus management for bidirectional UI navigation
Key Decisions
| Decision | Choice | Rationale |
|---|---|---|
| Translation Library | react-i18next | React-native hooks, namespace support, ICU format |
| Date Library | dayjs | Lightweight, locale plugins, immutable API |
| Message Format | ICU MessageFormat | Industry standard, complex plural/select support |
| Locale Storage | Per-namespace JSON | Code-splitting, lazy loading per feature |
| RTL Detection | CSS logical properties | Native browser support, no JS overhead |
Capability Details
translation-hooks
Keywords: useTranslation, t(), i18n hook, translation hook Solves:
- Translate UI strings with useTranslation
- Implement namespaced translations
- Handle missing translation keys
formatting-hooks
Keywords: useFormatting, formatCurrency, formatList, formatOrdinal Solves:
- Format currency values with locale
- Format lists with proper separators
- Handle ordinal numbers across locales
icu-messageformat
Keywords: ICU, MessageFormat, plural, pluralization Solves:
- Apply the house Hebrew plural-category decision (see
references/ork-delta.md) - ICU
select, gender forms and nested message grammar are routed upstream (see Upstream coverage) - Build complex message patterns
date-time-formatting
Keywords: date format, time format, dayjs, locale date, calendar Solves:
- Format dates with dayjs and locale
- Handle timezone-aware formatting
- Build calendar components with i18n
rtl-support
Keywords: RTL, right-to-left, hebrew, arabic, direction Solves:
- Support RTL languages like Hebrew
- Handle bidirectional text
- Configure RTL-aware layouts
trans-component
Keywords: Trans, rich text, embedded JSX, interpolation Solves:
- Embed React components in translations
- Handle rich text formatting
- Implement safe HTML in translations
Interaction Patterns
Codifiable UI interaction patterns that prevent common UX failures. Covers loading states, content pagination, disclosure patterns, overlays, drag-and-drop, tab overflow, and notification systems — all with accessibility baked in.
Quick Reference
| Rule | File | Impact | When to Use |
|---|---|---|---|
| Skeleton Loading | rules/interaction-skeleton-loading.md | HIGH | Content-shaped placeholders for async data |
| Infinite Scroll | rules/interaction-infinite-scroll.md | CRITICAL | Paginated content with a11y and keyboard support |
| Progressive Disclosure | rules/interaction-progressive-disclosure.md | HIGH | Revealing complexity based on user need |
| Modal / Drawer / Inline | rules/interaction-modal-drawer-inline.md | HIGH | Choosing overlay vs inline display patterns |
| Drag & Drop | rules/interaction-drag-drop.md | CRITICAL | Reorderable lists with keyboard alternatives |
| Tabs Overflow | rules/interaction-tabs-overflow.md | MEDIUM | Tab bars with 7+ items or dynamic tabs |
| Toast Notifications | rules/interaction-toast-notifications.md | HIGH | Success/error feedback and notification stacking |
| Cognitive Load Thresholds | rules/interaction-cognitive-load-thresholds.md | HIGH | Enforcing Miller's Law, Hick's Law, and Doherty Threshold with numeric limits |
| Form UX | rules/interaction-form-ux.md | HIGH | Target sizing, label placement, error prevention, and smart defaults |
| Persuasion Ethics | rules/interaction-persuasion-ethics.md | HIGH | Detecting dark patterns and applying ethical engagement principles |
Total: 10 rules across 6 categories
Decision Table — Loading States
| Scenario | Pattern | Why |
|---|---|---|
| List/card content loading | Skeleton | Matches content shape, reduces perceived latency |
| Form submission | Spinner | Indeterminate, short-lived action |
| File upload | Progress bar | Measurable operation with known total |
| Image loading | Blur placeholder | Prevents layout shift, progressive reveal |
| Route transition | Skeleton | Preserves layout while data loads |
| Background sync | None / subtle indicator | Non-blocking, low priority |
Quick Start
Skeleton Loading
function CardSkeleton() {
return (
<div className="animate-pulse space-y-3">
<div className="h-48 w-full rounded-lg bg-muted" />
<div className="h-4 w-3/4 rounded bg-muted" />
<div className="h-4 w-1/2 rounded bg-muted" />
</div>
)
}
function CardList({ items, isLoading }: { items: Item[]; isLoading: boolean }) {
if (isLoading) {
return (
<div className="grid grid-cols-3 gap-4">
{Array.from({ length: 6 }).map((_, i) => (
<CardSkeleton key={i} />
))}
</div>
)
}
return (
<div className="grid grid-cols-3 gap-4">
{items.map((item) => <Card key={item.id} item={item} />)}
</div>
)
}
Infinite Scroll with Accessibility
function InfiniteList({ fetchNextPage, hasNextPage, items }: Props) {
const sentinelRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const observer = new IntersectionObserver(
([entry]) => { if (entry.isIntersecting && hasNextPage) fetchNextPage() },
{ rootMargin: "200px" }
)
if (sentinelRef.current) observer.observe(sentinelRef.current)
return () => observer.disconnect()
}, [fetchNextPage, hasNextPage])
return (
<div role="feed" aria-busy={isFetching}>
{items.map((item) => (
<article key={item.id} aria-posinset={item.index} aria-setsize={-1}>
<ItemCard item={item} />
</article>
))}
<div ref={sentinelRef} />
{hasNextPage && (
<button onClick={() => fetchNextPage()}>Load more items</button>
)}
<div aria-live="polite" className="sr-only">
{`Showing ${items.length} items`}
</div>
</div>
)
}
Rule Details
Skeleton Loading
Content-shaped placeholders that match the final layout. Use skeleton for lists, cards, and text blocks.
Load:
rules/interaction-skeleton-loading.md
Infinite Scroll
Accessible infinite scroll with IntersectionObserver, screen reader announcements, and "Load more" fallback.
Load:
rules/interaction-infinite-scroll.md
Progressive Disclosure
Reveal complexity progressively: tooltip, accordion, wizard, contextual panel.
Load:
rules/interaction-progressive-disclosure.md
Modal / Drawer / Inline
Choose the right overlay pattern: modal for confirmations, drawer for detail views, inline for simple toggles.
Load:
rules/interaction-modal-drawer-inline.md
Drag & Drop
Drag-and-drop with mandatory keyboard alternatives using @dnd-kit/core.
Load:
rules/interaction-drag-drop.md
Tabs Overflow
Scrollable tab bars with overflow menus for dynamic or numerous tabs.
Load:
rules/interaction-tabs-overflow.md
Toast Notifications
Positioned, auto-dismissing notifications with ARIA roles and stacking.
Load:
rules/interaction-toast-notifications.md
Cognitive Load Thresholds
Miller's Law (max 7 items per group), Hick's Law (max 1 primary CTA), and Doherty Threshold (400ms feedback) with specific, countable limits.
Load:
rules/interaction-cognitive-load-thresholds.md
Form UX
Fitts's Law touch targets (44px mobile), top-aligned labels, Poka-Yoke error prevention with blur-only validation, and smart defaults.
Load:
rules/interaction-form-ux.md
Persuasion Ethics
13 dark pattern red flags to detect and reject, the Hook Model ethical test (aware, reversible, user-benefits), and EU DSA Art. 25 compliance.
Load:
rules/interaction-persuasion-ethics.md
Key Principles
- Keyboard parity — Every mouse interaction MUST have a keyboard equivalent. No drag-only, no hover-only.
- Skeleton over spinner — Use content-shaped placeholders for data loading; reserve spinners for indeterminate actions.
- Native HTML first — Prefer
<dialog>,<details>,role="feed"over custom implementations. - Progressive enhancement — Features should work without JS where possible, then enhance with interaction.
- Announce state changes — Use
aria-liveregions to announce dynamic content changes to screen readers. - Respect scroll position — Back navigation must restore scroll position; infinite scroll must not lose user's place.
Anti-Patterns (FORBIDDEN)
- Spinner for content loading — Spinners give no spatial hint. Use skeletons matching the content shape.
- Infinite scroll without Load More — Screen readers and keyboard users cannot reach footer content. Always provide a button fallback.
- Modal for browsable content — Modals trap focus and block interaction. Use drawers or inline expansion for browsing.
- Drag-only reorder — Excludes keyboard and assistive tech users. Always provide arrow key + Enter alternatives.
- Toast without ARIA role — Toasts are invisible to screen readers. Use
role="status"for success,role="alert"for errors. - Auto-dismiss error toasts — Users need time to read errors. Never auto-dismiss error notifications.
Detailed Documentation
| Resource | Description |
|---|---|
| references/loading-states-decision-tree.md | Decision tree for skeleton vs spinner vs progress bar |
| references/interaction-pattern-catalog.md | Catalog of 15+ interaction patterns with when-to-use guidance |
| references/keyboard-interaction-matrix.md | Keyboard shortcuts matrix for all interactive patterns (WAI-ARIA APG) |
Related Skills
ork-extras:ui-components— shadcn/ui component patterns and CVA variantsork-extras:animation-motion-design— Motion library and View Transitions APIork-extras:accessibility— WCAG compliance, ARIA patterns, screen reader supportork-extras:responsive-patterns— Responsive layout and container query patternsork:performance— Core Web Vitals and runtime performance optimization
LangGraph Workflow Patterns
Comprehensive patterns for building production LangGraph workflows. LangGraph 1.x is LTS (Long Term Support) — the first stable major release, powering agents at Uber, LinkedIn, and Klarna. Each category has individual rule files in rules/ loaded on-demand.
LangGraph 1.2 (shipped 2026-05-12) — the fault-tolerance release. Everything below is on
StateGraph.add_node(...)unless noted:
- Per-node timeouts —
timeout=acceptsfloat | timedelta | TimeoutPolicy.TimeoutPolicy(run_timeout=, idle_timeout=, refresh_on="auto"|"heartbeat")separates a hard wall-clock cap from an idle cap that progress refreshes. On expiry LangGraph raisesNodeTimeoutError(carryingkind="idle"|"run"andelapsed), drops that attempt's writes, and defers to the retry policy. Cooperative: it rides asyncio cancellation, so a node blocking the GIL is not interrupted. Seerules/resilience-node-timeouts.md.- Node error handlers —
error_handler=registers a recovery node that runs once the retry budget is exhausted. It receives failure context by declaring a parameter typedNodeError(fieldsnode,error) and returns aCommandto update state and reroute. Seerules/resilience-error-handlers.md.RunControl(langgraph.runtime) — cooperative graceful shutdown.request_drain(reason)from any thread; nodes pollruntime.drain_requestedand stop at a checkpoint boundary, leaving a resumable thread instead of a half-applied superstep. Seerules/resilience-graceful-drain.md.DeltaChannel(langgraph.channels.delta, beta) — checkpoints store only incremental writes and replay them through a batch reducer, with a snapshot everysnapshot_frequencyupdates. Fixes checkpoint cost growing with thread length. Its reducer takes a batch and must be batching-invariant. Seerules/state-delta-channel.md.runtime.heartbeat()— explicit progress signal, the only one that refreshes an idle timeout underrefresh_on="heartbeat".Landed earlier, in 1.1 — not 1.2 (they are current and supported; only their release attribution was wrong in prior versions of this skill): deferred nodes (
defer=True), node-level caching (CachePolicy+graph.compile(cache=...)), and model middleware (before_model/after_model) oncreate_agent.
Quick Reference
| Category | Rules | Impact | When to Use |
|---|---|---|---|
| State Management | 5 | CRITICAL | Designing workflow state schemas, accumulators, reducers, delta channels |
| Resilience | 3 | CRITICAL | Node timeouts, error handlers, graceful drain (1.2+) |
| Routing & Branching | 4 | HIGH | Dynamic routing, retry loops, semantic routing, cross-graph |
| Parallel Execution | 3 | HIGH | Fan-out/fan-in, map-reduce, concurrent agents |
| Supervisor Patterns | 3 | HIGH | Central coordinators, round-robin, priority dispatch |
| Tool Calling | 4 | CRITICAL | Binding tools, ToolNode, dynamic selection, approvals |
| Checkpointing | 3 | HIGH | Persistence, recovery, cross-thread Store memory |
| Human-in-Loop | 3 | MEDIUM | Approval gates, feedback loops, interrupt/resume |
| Streaming | 3 | MEDIUM | Real-time updates, token streaming, custom events |
| Subgraphs | 3 | MEDIUM | Modular composition, nested graphs, state mapping |
| Functional API | 3 | MEDIUM | @entrypoint/@task decorators, migration from StateGraph |
| Platform | 3 | HIGH | Deployment, RemoteGraph, double-texting strategies |
Total: 41 rules across 12 categories
State Management
State schemas determine how data flows between nodes. Wrong schemas cause silent data loss.
| Rule | File | Key Pattern |
|---|---|---|
| TypedDict State | rules/state-typeddict.md | TypedDict + Annotated[list, add] for accumulators |
| Pydantic Validation | rules/state-pydantic.md | BaseModel at boundaries, TypedDict internally |
| MessagesState | rules/state-messages.md | MessagesState or add_messages reducer |
| Custom Reducers | rules/state-reducers.md | Annotated[T, reducer_fn] for merge/overwrite |
| Delta Channels (1.2, beta) | rules/state-delta-channel.md | DeltaChannel(reducer, snapshot_frequency=) for large accumulators |
Resilience
Fault tolerance for nodes that talk to the outside world. New in 1.2 — before it, the only lever was
retry_policy, which cannot help a node that never fails because it never returns.
| Rule | File | Key Pattern |
|---|---|---|
| Node Timeouts | rules/resilience-node-timeouts.md | add_node(..., timeout=TimeoutPolicy(run_timeout=, idle_timeout=)) |
| Error Handlers | rules/resilience-error-handlers.md | add_node(..., error_handler=) + param typed NodeError → Command |
| Graceful Drain | rules/resilience-graceful-drain.md | RunControl().request_drain() + runtime.drain_requested |
from langgraph.types import RetryPolicy, TimeoutPolicy
from langgraph.errors import NodeError
builder.add_node(
"call_vendor",
call_vendor,
timeout=TimeoutPolicy(run_timeout=300, idle_timeout=30),
retry_policy=RetryPolicy(max_attempts=3),
error_handler=lambda state, error: Command(
update={"failure": f"{error.node}: {error.error}"}, goto="degraded_path"
),
)
Routing & Branching
Control flow between nodes. Always include END fallback to prevent hangs.
| Rule | File | Key Pattern |
|---|---|---|
| Conditional Edges | rules/routing-conditional.md | add_conditional_edges with explicit mapping |
| Retry Loops | rules/routing-retry-loops.md | Loop-back edges with max retry counter |
| Semantic Routing | rules/routing-semantic.md | Embedding similarity or Command API routing |
| Cross-Graph Navigation | rules/routing-cross-graph.md | Command(graph=Command.PARENT) for parent/sibling routing |
Parallel Execution
Run independent nodes concurrently. Use Annotated[list, add] to accumulate results.
| Rule | File | Key Pattern |
|---|---|---|
| Fan-Out/Fan-In | rules/parallel-fanout-fanin.md | Send API for dynamic parallel branches |
| Map-Reduce | rules/parallel-map-reduce.md | asyncio.gather + result aggregation |
| Error Isolation | rules/parallel-error-isolation.md | return_exceptions=True + per-branch timeout |
Supervisor Patterns
Central coordinator routes to specialized workers. Workers return to supervisor.
| Rule | File | Key Pattern |
|---|---|---|
| Basic Supervisor | rules/supervisor-basic.md | Command API for state update + routing |
| Priority Routing | rules/supervisor-priority.md | Priority dict ordering agent execution |
| Round-Robin | rules/supervisor-round-robin.md | Completion tracking with agents_completed |
Tool Calling
Integrate function calling into LangGraph agents. Keep tools under 10 per agent.
| Rule | File | Key Pattern |
|---|---|---|
| Tool Binding | rules/tools-bind.md | model.bind_tools(tools) + tool_choice |
| ToolNode Execution | rules/tools-toolnode.md | ToolNode(tools) prebuilt parallel executor |
| Dynamic Selection | rules/tools-dynamic.md | Embedding-based tool relevance filtering |
| Tool Interrupts | rules/tools-interrupts.md | interrupt() for approval gates on tools |
Checkpointing
Persist workflow state for recovery and debugging.
| Rule | File | Key Pattern |
|---|---|---|
| Checkpointer Setup | rules/checkpoints-setup.md | MemorySaver dev / PostgresSaver prod |
| State Recovery | rules/checkpoints-recovery.md | thread_id resume + get_state_history |
| Cross-Thread Store | rules/checkpoints-store.md | Store for long-term memory across threads |
Node-Level Caching (1.2+)
Independent of checkpointing. Cache individual node output so re-runs with identical inputs skip execution entirely.
from langgraph.graph import StateGraph
from langgraph.types import CachePolicy
from langgraph.cache.sqlite import SqliteCache
graph = StateGraph(State)
graph.add_node(
"expensive_fetch",
fetch_fn,
cache_policy=CachePolicy(ttl=3600, key_func=lambda s: s["query"]),
)
# RedisCache(url=...) for distributed workers
compiled = graph.compile(cache=SqliteCache("cache.db"))
Use when a node is idempotent and expensive (embeddings, external APIs). Do not use for nodes whose output depends on wall-clock time or mutable external state unless key_func captures that variance.
Deferred Nodes & Model Middleware (1.2+)
# defer=True — node execution is deferred until the run is about to end,
# i.e. after every other upstream node has completed
graph.add_node("aggregate", aggregate_fn, defer=True)
# Model middleware — no subclassing required.
# create_react_agent is @deprecated since v1.0; use create_agent from langchain.agents.
# The legacy pre_model_hook/post_model_hook are now before_model/after_model middleware.
from langchain.agents import create_agent
agent = create_agent(
model=model,
tools=tools,
middleware=[compress_history, redact_pii], # before_model / after_model hooks
system_prompt="...", # prompt= renamed to system_prompt
)
Human-in-Loop
Pause workflows for human intervention. Requires checkpointer for state persistence.
| Rule | File | Key Pattern |
|---|---|---|
| Interrupt/Resume | rules/human-in-loop-interrupt.md | interrupt() function + Command(resume=) |
| Approval Gate | rules/human-in-loop-approval.md | interrupt_before + state update + resume |
| Feedback Loop | rules/human-in-loop-feedback.md | Iterative interrupt until approved |
Streaming
Real-time updates and progress tracking for workflows. LangGraph 1.2 supports version="v2" (introduced in 1.1), an opt-in streaming format with full type safety on stream(), astream(), invoke(), and ainvoke().
| Rule | File | Key Pattern |
|---|---|---|
| Stream Modes | rules/streaming-modes.md | 5 modes: values, updates, messages, custom, debug |
| Token Streaming | rules/streaming-tokens.md | messages mode with node/tag filtering |
| Custom Events | rules/streaming-custom-events.md | get_stream_writer() for progress events |
| Streaming v2 | rules/streaming-v2-format.md | version="v2" for typed streaming (LG 1.1+) |
Subgraphs
Compose modular, reusable workflow components with nested graphs.
| Rule | File | Key Pattern |
|---|---|---|
| Invoke from Node | rules/subgraphs-invoke.md | Different schemas, explicit state mapping |
| Add as Node | rules/subgraphs-add-as-node.md | Shared state, add_node(name, compiled_graph) |
| State Mapping | rules/subgraphs-state-mapping.md | Boundary transforms between parent/child |
Functional API
Build workflows using @entrypoint and @task decorators instead of explicit graph construction.
| Rule | File | Key Pattern |
|---|---|---|
| @entrypoint | rules/functional-entrypoint.md | Workflow entry point with optional checkpointer |
| @task | rules/functional-task.md | Returns futures, .result() to block |
| Migration | rules/functional-migration.md | StateGraph to Functional API conversion |
Platform
Deploy graphs as managed APIs with persistence, streaming, and multi-tenancy.
| Rule | File | Key Pattern |
|---|---|---|
| Deployment | rules/platform-deployment.md | langgraph.json + CLI + Assistants API |
| RemoteGraph | rules/platform-remote-graph.md | RemoteGraph for calling deployed graphs |
| Double Texting | rules/platform-double-texting.md | 4 strategies: reject, rollback, enqueue, interrupt |
Quick Start Example
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command
from typing import TypedDict, Annotated, Literal
from operator import add
class State(TypedDict):
input: str
results: Annotated[list[str], add]
def supervisor(state) -> Command[Literal["worker", END]]:
if not state.get("results"):
return Command(update={"input": state["input"]}, goto="worker")
return Command(goto=END)
def worker(state) -> dict:
return {"results": [f"Processed: {state['input']}"]}
graph = StateGraph(State)
graph.add_node("supervisor", supervisor)
graph.add_node("worker", worker)
graph.add_edge(START, "supervisor")
graph.add_edge("worker", "supervisor")
app = graph.compile()
2026 Key Patterns
- Streaming v2 (LG 1.1): Use
version="v2"for type-safe streaming — fully typedstream()andastream()returns. Default remains"v1"for backwards compat. - Command API: Use
Command(update=..., goto=...)when updating state AND routing together - context_schema: Pass runtime config (temperature, provider) without polluting state
- CachePolicy: Cache expensive node results with TTL via
SqliteCache(prod) orInMemoryCachefromlanggraph.cache.memory(dev) - RemainingSteps: Proactively handle recursion limits
- Store: Cross-thread memory separate from Checkpointer (thread-scoped)
- interrupt(): Dynamic interrupts inside node logic (replaces
interrupt_beforefor conditional cases) - add_edge(START, node): Not
set_entry_point()(deprecated) - LTS release: LangGraph 1.x is LTS — will remain ACTIVE until v2.0
Key Decisions
| Decision | Recommendation |
|---|---|
| State type | TypedDict internally, Pydantic at boundaries |
| Entry point | add_edge(START, node) not set_entry_point() |
| Routing + state update | Command API |
| Routing only | Conditional edges |
| Accumulators | Annotated[list[T], add] always |
| Dev checkpointer | MemorySaver |
| Prod checkpointer | PostgresSaver |
| Short-term memory | Checkpointer (thread-scoped) |
| Long-term memory | Store (cross-thread, namespaced) |
| Max parallel branches | 5-10 concurrent |
| Tools per agent | 5-10 max (dynamic selection for more) |
| Approval gates | interrupt() for high-risk operations |
| Stream modes | ["updates", "custom"] for most UIs |
| Subgraph pattern | Invoke for isolation, Add-as-Node for shared state |
| Functional vs Graph | Functional for simple flows, Graph for complex topology |
Common Mistakes
- Forgetting
addreducer (overwrites instead of accumulates) - Mutating state in place (breaks checkpointing)
- No END fallback in routing (workflow hangs)
- Infinite retry loops (no max counter)
- Side effects in router functions
- Too many tools per agent (context overflow)
- Raising exceptions in tools (crashes agent loop)
- No checkpointer in production (lose progress on crash)
- Wrapping
interrupt()in try/except (breaks the mechanism) - Not transforming state at subgraph boundaries
- Forgetting
.result()on Functional API tasks - Using
set_entry_point()(deprecated, useadd_edge(START, ...))
Evaluations
See test-cases.json for consolidated test cases across all categories.
Related Skills
ork-extras:agent-orchestration- Higher-level multi-agent coordination, ReAct loop patterns, and framework comparisonstemporal-io- Durable execution alternativeork-extras:llm-integration- General LLM function callingtype-safety-validation- Pydantic model patterns
LLM Integration
Patterns for integrating LLMs into production applications: tool use, streaming, local inference, and fine-tuning. Each category has individual rule files in rules/ loaded on-demand.
Quick Reference
| Category | Rules | Impact | When to Use |
|---|---|---|---|
| Function Calling | 3 | CRITICAL | Tool definitions, parallel execution, input validation |
| Streaming | 3 | HIGH | SSE endpoints, structured streaming, backpressure handling |
| Local Inference | 3 | HIGH | Ollama setup, model selection, GPU optimization |
| Fine-Tuning | 3 | HIGH | LoRA/QLoRA training, dataset preparation, evaluation |
| Context Optimization | 2 | HIGH | Window management, compression, caching, budget scaling |
| Evaluation | 2 | HIGH | LLM-as-judge, RAGAS metrics, quality gates, benchmarks |
| Prompt Engineering | 4 | HIGH | CoT, few-shot, versioning, DSPy optimization, ReAct, cost optimization |
Total: 20 rules across 7 categories
Quick Start
# Function calling: strict mode tool definition
tools = [{
"type": "function",
"function": {
"name": "search_documents",
"description": "Search knowledge base",
"strict": True,
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"},
"limit": {"type": "integer", "description": "Max results"}
},
"required": ["query", "limit"],
"additionalProperties": False
}
}
}]
# Streaming: SSE endpoint with FastAPI
@app.get("/chat/stream")
async def stream_chat(prompt: str):
async def generate():
async for token in async_stream(prompt):
yield {"event": "token", "data": token}
yield {"event": "done", "data": ""}
return EventSourceResponse(generate())
# Local inference: Ollama with LangChain
llm = ChatOllama(
model="deepseek-r1:70b",
base_url="http://localhost:11434",
temperature=0.0,
num_ctx=32768,
)
# Fine-tuning: QLoRA with Unsloth
model, tokenizer = FastLanguageModel.from_pretrained(
model_name="unsloth/Meta-Llama-3.1-8B",
max_seq_length=2048, load_in_4bit=True,
)
model = FastLanguageModel.get_peft_model(model, r=16, lora_alpha=32)
Function Calling
Enable LLMs to use external tools and return structured data. Use strict mode schemas (2026 best practice) for reliability. On Claude keep the tools array stable across turns so the prompt cache holds; add tools mid-session with an inline tool_addition (beta inline-tools-2026-09-15, Claude API only, available on Sonnet 5.5 but not on Sonnet 5) instead of swapping subsets (https://platform.claude.com/docs/en/build-with-claude/mid-conversation-system-messages#mid-conversation-tool-changes). For large tool sets, use a non-deferred tool search tool with defer_loading: true on the rest, never defer_loading alone (a request cannot have every tool deferred). Forced tool_choice (any or a named tool) returns a 400 on Sonnet 5.5, Opus 5.5, Fable 5.1 and Mythos 5.1; use auto with strict: true tools. Validate all inputs with Pydantic/Zod, and return errors as tool results.
calling-tool-definition.md-- Strict mode schemas, OpenAI/Anthropic formats, LangChain bindingcalling-parallel.md-- Parallel tool execution, asyncio.gather, strict mode constraintscalling-validation.md-- Input validation, error handling, tool execution loops
Streaming
Deliver LLM responses in real-time for better UX. Use SSE for web, WebSocket for bidirectional. Handle backpressure with bounded queues.
streaming-sse.md-- FastAPI SSE endpoints, frontend consumers, async iteratorsstreaming-structured.md-- Streaming with tool calls, partial JSON parsing, chunk accumulationstreaming-backpressure.md-- Backpressure handling, bounded buffers, cancellation
Local Inference
Run LLMs locally with Ollama for cost savings (93% vs cloud), privacy, and offline development. Pre-warm models, use provider factory for cloud/local switching.
local-ollama-setup.md-- Installation, model pulling, environment configurationlocal-model-selection.md-- Model comparison by task, hardware profiles, quantizationlocal-gpu-optimization.md-- Apple Silicon tuning, keep-alive, CI integration
Fine-Tuning
Customize LLMs with parameter-efficient techniques. Fine-tune ONLY after exhausting prompt engineering and RAG. Requires 1000+ quality examples.
tuning-lora.md-- LoRA/QLoRA configuration, Unsloth training, adapter mergingtuning-dataset-prep.md-- Synthetic data generation, quality validation, deduplicationtuning-evaluation.md-- DPO alignment, evaluation metrics, anti-patterns
Context Optimization
Manage context windows, compression, and attention-aware positioning. Optimize for tokens-per-task.
context-window-management.md-- Five-layer architecture, anchored summarization, compression triggerscontext-caching.md-- Just-in-time loading, budget scaling, probe evaluation, CC 2.1.32+
Evaluation
Evaluate LLM outputs with multi-dimension scoring, quality gates, and benchmarks.
evaluation-metrics.md-- LLM-as-judge, RAGAS metrics, hallucination detectionevaluation-benchmarks.md-- Quality gates, batch evaluation, pairwise comparison
Prompt Engineering
Design, version, and optimize prompts for production LLM applications.
prompt-design.md-- Chain-of-Thought, few-shot learning, pattern selection guideprompt-testing.md-- Langfuse versioning, DSPy optimization, A/B testing, self-consistencyprompt-react-pattern.md-- ReAct loop for tool-using agents, thought-action-observation formatprompt-optimization.md-- Token reduction, cost optimization, model tiering, prompt spec format
Upstream coverage (do not restate)
These topics are covered by their vendors' own documentation. This skill points
at them instead of teaching them; the rules above keep only our floors, ceilings
and scars. Our delta on all of it is in references/ork-delta.md.
| Topic | First-party source |
|---|---|
| Strict-mode tool schemas, structured outputs | https://platform.openai.com/docs/guides/function-calling |
Anthropic input_schema / tool_use | https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview |
| SSE client mechanics, reconnection, cancellation | https://developer.mozilla.org/en-US/docs/Web/API/EventSource |
| LoRA / QLoRA config, target modules, adapter merging | https://huggingface.co/docs/peft/developer_guides/lora |
| Unsloth training loop, 4-bit loading | https://docs.unsloth.ai/get-started/fine-tuning-llms-guide |
| DPO, preference pairs, beta tuning, RLHF comparison | https://huggingface.co/docs/trl/dpo_trainer |
| SFT dataset formats (Alpaca, ChatML) | https://huggingface.co/docs/trl/sft_trainer |
| Embedding similarity for dataset dedup | https://sbert.net/ |
| Fine-tune vs prompt vs RAG decision framework | https://platform.openai.com/docs/guides/optimizing-llm-accuracy |
| Vendor token pricing (never hardcode it here) | https://platform.openai.com/docs/pricing |
Supporting Files
references/ork-delta.md-- our delta: scars, house ceilings, retired-file provenancereferences/model-selection.md-- local model comparison by task and hardwarescripts/create-lora-config.md-- LoRA config scaffold with auto-detected model type
Key Decisions
| Decision | Recommendation |
|---|---|
| Tool schema mode | strict: true (2026 best practice) |
| Tool count | Load roughly 5-15 up front; defer the rest behind a non-deferred tool search tool |
| Streaming protocol | SSE for web, WebSocket for bidirectional |
| Buffer size | 50-200 tokens |
| Local model (reasoning) | deepseek-r1:70b |
| Local model (coding) | qwen2.5-coder:32b |
| Fine-tuning approach | LoRA/QLoRA (try prompting first) |
| LoRA rank | 16-64 typical |
| Training epochs | 1-3 (more risks overfitting) |
| Context compression | Anchored iterative (60-80%) |
| Compress trigger | 70% utilization, target 50% |
| Judge model | claude-haiku-5-5 (cost tier), gpt-5.5, or gemini-3.8-flash (Google's GA general-purpose model and a third vendor for the different-model rule; price lives in models.vocab.json, not here) |
| Quality threshold | 0.7 production, 0.6 drafts |
| Few-shot examples | 3-5 diverse, representative |
| Prompt versioning | Langfuse with labels |
| Auto-optimization | DSPy MIPROv2 |
Related Skills
ork-extras:rag-retrieval-- Embedding patterns, when RAG is better than fine-tuningagent-loops-- Multi-step tool use with reasoningllm-evaluation-- Evaluate fine-tuned and local modelslangfuse-observability-- Track training experiments
Capability Details
function-calling
Keywords: tool, function, define tool, tool schema, function schema, strict mode, parallel tools Solves:
- Define tools with clear descriptions and strict schemas
- Execute tool calls in parallel with asyncio.gather
- Validate inputs and handle errors in tool execution loops
streaming
Keywords: streaming, SSE, Server-Sent Events, real-time, backpressure, token stream Solves:
- Stream LLM tokens via SSE endpoints
- Handle tool calls within streams
- Manage backpressure with bounded queues
local-inference
Keywords: Ollama, local, self-hosted, model selection, GPU, Apple Silicon Solves:
- Set up Ollama for local LLM inference
- Select models based on task and hardware
- Optimize GPU usage and CI integration
fine-tuning
Keywords: LoRA, QLoRA, fine-tune, DPO, synthetic data, PEFT, alignment Solves:
- Configure LoRA/QLoRA for parameter-efficient training
- Generate and validate synthetic training data
- Align models with DPO and evaluate results
MCP Patterns
Patterns for building, composing, and securing Model Context Protocol servers. Based on the 2025-11-25 specification — the latest stable release maintained by the Agentic AI Foundation (Linux Foundation), co-founded by Anthropic, Block, and OpenAI.
Scaffolding a new server? Use Anthropic's
mcp-builderskill (from theanthropics/skillsmarketplace:/plugin marketplace add anthropics/skills) for project setup and evaluation creation. This skill focuses on patterns, security, and advanced features after initial setup.Deploying to Cloudflare? See the
building-mcp-server-on-cloudflareskill for Workers-specific deployment patterns.
Pin
mcp<2until you migrate. Every Python snippet in this skill targets the v1 SDK (from mcp.server.fastmcp import FastMCP). The Python SDK released 2.0.0,pip install mcpnow resolves to it, and upstream's own README says to keep a<2upper bound on your requirement until you have migrated.FastMCPdoes not appear anywhere in the 2.0 README, so treat these snippets as v1-only rather than assuming they still apply. v1.x continues to receive critical bug and security fixes on its own branch. Verified 2026-07-31. Migration guide: https://py.sdk.modelcontextprotocol.io/migration/
Decision Tree — Which Rule to Read
What are you building?
│
├── New MCP server
│ ├── Setup & primitives ──────► rules/server-setup.md
│ ├── Transport selection ─────► rules/server-transport.md
│ └── Scaffolding ─────────────► mcp-builder skill (anthropics/skills)
│
├── Authentication & authorization
│ └── OAuth 2.1 + OIDC ───────► rules/auth-oauth21.md
│
├── Advanced server features
│ ├── Tool composition ────────► rules/advanced-composition.md
│ ├── Resource caching ────────► rules/advanced-resources.md
│ ├── Elicitation (user input) ► rules/elicitation.md
│ ├── Sampling (agent loops) ──► rules/sampling-tools.md
│ └── Interactive UI ──────────► rules/apps-ui.md
│
├── Client-side consumption
│ └── Connecting to servers ───► rules/client-patterns.md
│
├── Security hardening
│ ├── Prompt injection defense ► rules/security-injection.md
│ └── Zero-trust & verification ► rules/security-hardening.md
│
├── Testing & debugging
│ └── Inspector + unit tests ──► rules/testing-debugging.md
│
├── Discovery & ecosystem
│ └── Registries & catalogs ──► rules/registry-discovery.md
│
└── Browser-native tools
└── WebMCP (W3C) ───────────► rules/webmcp-browser.md
Quick Reference
| Category | Rule | Impact | Key Pattern |
|---|---|---|---|
| Server | server-setup.md | HIGH | FastMCP lifespan, Tool/Resource/Prompt primitives |
| Server | server-transport.md | HIGH | stdio for CLI, Streamable HTTP for production |
| Auth | auth-oauth21.md | HIGH | PKCE, RFC 8707 resource indicators, token validation |
| Advanced | advanced-composition.md | MEDIUM | Pipeline, parallel, and branching tool composition |
| Advanced | advanced-resources.md | MEDIUM | Resource caching with TTL, LRU eviction, lifecycle |
| Advanced | elicitation.md | MEDIUM | Server-initiated structured input from users |
| Advanced | sampling-tools.md | MEDIUM | Server-side agent loops with tool calling |
| Advanced | apps-ui.md | MEDIUM | Interactive UI via MCP Apps + @mcp-ui/* SDK |
| Client | client-patterns.md | MEDIUM | TypeScript/Python MCP client connection patterns |
| Security | security-injection.md | HIGH | Description sanitization, encoding normalization |
| Security | security-hardening.md | HIGH | Zero-trust allowlist, hash verification, rug pull detection |
| Quality | testing-debugging.md | MEDIUM | MCP Inspector, unit tests, transport debugging |
| Ecosystem | registry-discovery.md | LOW | Official registry API, server metadata |
| Ecosystem | webmcp-browser.md | LOW | W3C browser-native agent tools (complementary) |
Total: 14 rules across 6 categories
Key Decisions
| Decision | Recommendation |
|---|---|
| Transport | stdio for CLI/Desktop, Streamable HTTP for production (SSE deprecated) |
| Language | TypeScript for production (better SDK support, type safety) |
| Auth | OAuth 2.1 with PKCE (S256) + RFC 8707 resource indicators |
| Server lifecycle | Always use FastMCP lifespan for resource management |
| Error handling | Return errors as text content (Claude can interpret and retry) |
| Tool composition | Pipeline for sequential, asyncio.gather for parallel |
| Resource caching | TTL + LRU eviction with memory cap |
| Tool trust model | Zero-trust: explicit allowlist + hash verification |
| User input | Elicitation for runtime input; never request PII via elicitation |
| Interactive UI | MCP Apps with @mcp-ui/* SDK; sandbox all iframes |
| Token handling | Never pass through client tokens to downstream services |
| Large results | Use _meta["anthropic/maxResultSizeChars"] annotation (up to 500K) for results that lose meaning when truncated (CC 2.1.91) |
Spec & Governance
- Protocol: Model Context Protocol, spec version 2025-11-25 (latest stable)
- Governance: Agentic AI Foundation (Linux Foundation, Dec 2025)
- Platinum members: AWS, Anthropic, Block, Bloomberg, Cloudflare, Google, Microsoft, OpenAI
- Adoption: 10,000+ servers; Claude, Cursor, Copilot, Gemini, ChatGPT, VS Code
- Spec URL: https://modelcontextprotocol.io/specification/2025-11-25
- 2026 model: Working Groups and Interest Groups are now the primary vehicle for protocol evolution (no more milestone-based releases). Enterprise readiness lands as extensions, not core spec changes.
Feature Maturity
| Feature | Spec Version | Status |
|---|---|---|
| Tools, Resources, Prompts | 2024-11-05 | Stable |
| Streamable HTTP transport | 2025-03-26 | Stable (replaces SSE) |
| OAuth 2.1 + Elicitation (form) | 2025-06-18 | Stable |
| Sampling with tool calling | 2025-11-25 | Stable |
| Elicitation URL mode | 2025-11-25 | Stable |
| MCP Apps (UI extension) | 2026-01-26 | Extension (ext-apps) |
| WebMCP (browser-native) | 2026-02-14 | W3C Community Draft |
SDK landscape (2026-Q2)
| Package | What it is | When to use |
|---|---|---|
mcp (PyPI) >=1.27 | Official Python SDK — includes the FastMCP helper, transport adapters, Inspector | New Python servers. This is the canonical package. |
@modelcontextprotocol/sdk (npm) >=1.29 | Official TypeScript SDK | New TS servers |
fastmcp (PyPI) | Standalone fork by jlowin — predates mcp; API-compatible but diverges on lifespan and middleware | Existing projects pinned to it. New projects should prefer mcp. |
The
fastmcpfork and themcp.server.fastmcpmodule are not the same package. Imports andpyproject.tomlentries must agree or stacktraces become cryptic.
Debugging with Claude Code
Pass --mcp-debug to Claude Code when troubleshooting server wiring — it surfaces the raw JSON-RPC frames, handshake failures, and tool-registration events that the default logger swallows:
claude --mcp-debug "query the local test server"
# or per-session:
export CLAUDE_MCP_DEBUG=1
Use alongside the MCP Inspector (npx @modelcontextprotocol/inspector <cmd>) — Inspector gives you the client-side frame view, --mcp-debug gives you what Claude actually saw.
CC 2.1.128 — reconnect tool summarization: when a server reconnects mid-session, re-announced tools are summarized as
mcp__<server>__* (N tools re-registered)instead of being enumerated line-by-line. Use the initial connect event as the source of truth for tool inventory; treat reconnect summaries as deltas only. Seereferences/mcp-audit-runbook.mdfor grep recipes that work across both formats.
CC 2.1.133 — MCP OAuth honors HTTP(S)_PROXY / NO_PROXY / mTLS: the full MCP OAuth flow (discovery, dynamic client registration, token exchange, token refresh) now respects standard proxy and client-certificate env vars end-to-end. Enterprise deployments behind corporate proxies no longer need OAuth-specific workarounds — the same
HTTPS_PROXY/NO_PROXY/NODE_EXTRA_CA_CERTSconfig that already routes MCP transport now also routes auth. Seeconfigure/references/cc-version-settings.md(CC 2.1.133 section) for the env-var example. The companion deployment skillbuilding-mcp-server-on-cloudflarecan drop any prior "proxy-aware OAuth requires manual handling" caveat at this floor.
CC 2.1.169 — managed MCP policies enforced everywhere: enterprise
allowedMcpServers/deniedMcpServersnow apply on reconnect, IDE-typed configs,--mcp-configservers in the first session after install, and before remote settings load (previously all four paths skipped enforcement). Orgs without remote settings also get faster cold starts. If a previously-working server stops connecting after 2.1.169, check the managed policy before debugging the server.
CC 2.1.163 — stdio servers get
CLAUDE_CODE_SESSION_ID: on--resume, stdio MCP servers now receive the sameCLAUDE_CODE_SESSION_IDenv var that hooks and Bash already get. Read it inside the server to correlate logs/telemetry across resumed sessions instead of minting your own session key — but never store auth tokens keyed off it (see Common Mistake #7).
Example
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("my-server")
@mcp.tool()
async def search(query: str) -> str:
"""Search documents. Returns matching results."""
results = await db.search(query)
return "\n".join(r.title for r in results[:10])
Common Mistakes
- No lifecycle management (connection/resource leaks on shutdown)
- Missing input validation on tool arguments
- Returning secrets in tool output (API keys, credentials)
- CC 2.1.161 mitigates this at the CLI layer:
claude mcp list/get/addno longer expands${VAR}references and redacts credential headers and URL secrets in terminal output — but server code must still never return secrets in tool results./mcpalso collapses never-signed-in connectors behind a "Show unused connectors" row. - CC 2.1.186 adds
claude mcp login <name>/claude mcp logout <name>for OAuth-backed servers (HTTP/SSE/connector). Pass--no-browserto print the authorization URL instead of opening a browser — the supported path for SSH/headless/remote sessions (paste the redirect URL back when prompted), so interactive-only auth never blocks automated setup.
- CC 2.1.161 mitigates this at the CLI layer:
- Unbounded response sizes without
_metaannotation — use_meta["anthropic/maxResultSizeChars"]to declare intentionally large results (DB schemas, API specs) so clients/hooks don't truncate them - Trusting tool descriptions without sanitization (injection risk)
- No hash verification on tool invocations (rug pull vulnerability)
- Storing auth tokens in session IDs (credential leak)
- Blocking synchronous code in async server (use
asyncio.to_thread()) - Using SSE transport instead of Streamable HTTP (deprecated since March 2025)
- Passing through client tokens to downstream services (confused deputy)
Ecosystem
| Resource | What For |
|---|---|
mcp-builder skill (anthropics/skills) | Scaffold new MCP servers + create evals |
building-mcp-server-on-cloudflare skill | Deploy MCP servers on Cloudflare Workers |
@mcp-ui/* packages (npm) | Implement MCP Apps UI standard |
| MCP Registry | Discover servers: https://registry.modelcontextprotocol.io/ |
| MCP Inspector | Debug and test servers interactively |
Related Skills
ork-extras:llm-integration— LLM function calling patternsork:security-patterns— General input sanitization and layered securityork:api-design— REST/GraphQL API design patterns
Monitoring & Observability
A wrap around Prometheus, Grafana, OpenTelemetry and Langfuse, not a re-teaching of them. This
skill carries OrchestKit's delta (version floors, house decisions, scars) and points at the
vendor for everything else. Start at references/ork-delta.md.
Upstream coverage (do not restate)
These topics are fully covered first-party. Read the source, do not add a local copy.
| Topic | First-party source |
|---|---|
| Prometheus metric types, RED method, cardinality, PromQL | https://prometheus.io/docs/practices/ |
| Alertmanager grouping, inhibition, escalation, runbooks | https://prometheus.io/docs/alerting/latest/configuration/ |
| Grafana dashboards, Loki and LogQL, Promtail | https://grafana.com/docs/ |
| OpenTelemetry spans, sampling, context propagation | https://opentelemetry.io/docs/ |
Langfuse Python SDK (@observe, as_type, score_current_span, should_export_span, LangfuseMedia) | https://langfuse.com/docs/sdk/python |
| Langfuse v2 to v4 Python and v3 to v5 JS migration paths | https://langfuse.com/docs/sdk/python/v4-migration |
| Langfuse self-hosting (ClickHouse, Redis, S3, Helm) | https://langfuse.com/docs/deployment/self-host |
| Langfuse cost tracking, model pricing, Metrics API v2 | https://langfuse.com/docs/model-usage-and-cost |
| Langfuse scores, online evaluators, annotation queues, prompt management | https://langfuse.com/docs/scores/overview |
| Langfuse framework integrations (LangChain, LangGraph, CrewAI, Pydantic AI, Bedrock, LiveKit) | https://langfuse.com/docs/integrations |
| Agent Graphs, observation types, rendered tool calls | https://langfuse.com/docs/tracing-features/agent-graphs |
| PSI, KS test, KL and JS divergence, Wasserstein, embedding drift | https://www.evidentlyai.com/blog/data-drift-detection-large-datasets |
| EWMA control charts | https://www.itl.nist.gov/div898/handbook/pmc/section3/pmc324.htm |
| structlog, Winston, correlation IDs, log sampling | https://www.structlog.org/en/stable/ |
Quick Reference
| Category | Rules | Impact | When to Use |
|---|---|---|---|
| Infrastructure Monitoring | 1 | CRITICAL | Grafana dashboards, Golden Signals, SLO/SLI |
| LLM Observability | 1 | HIGH | Langfuse tracing, observation types, agent graphs |
| Silent Failures | 3 | HIGH | Tool skipping, quality degradation, loop/token spike alerting |
Total: 5 rules across 3 categories. Drift detection, cost tracking, eval scoring, Prometheus instrumentation and alert-rule authoring moved to the upstream sources listed above.
Quick Start
# Langfuse v4 LLM tracing: semantic as_type plus inline scoring
from langfuse import observe, get_client
@observe(as_type="generation", name="analyze_content")
async def analyze_content(content: str):
get_client().update_current_trace(
user_id="user_123", session_id="session_abc",
tags=["production", "orchestkit"],
)
result = await llm.generate(content)
get_client().score_current_span(name="response_quality", value=0.85)
return result
# Prometheus RED method, wired the way this repo expects (bounded labels only)
from prometheus_client import Counter, Histogram
http_requests = Counter('http_requests_total', 'Total requests', ['method', 'endpoint', 'status'])
http_duration = Histogram('http_request_duration_seconds', 'Request latency',
buckets=[0.01, 0.05, 0.1, 0.5, 1, 2, 5])
Infrastructure Monitoring
Dashboard and health-check patterns. Metric instrumentation and alert-rule syntax are upstream.
| Rule | File | Key Pattern |
|---|---|---|
| Grafana Dashboards | rules/monitoring-grafana.md | Golden Signals, SLO/SLI, health checks |
CC 2.1.161 — OTEL resource attributes as metric labels:
OTEL_RESOURCE_ATTRIBUTESvalues are now attached as labels on metric datapoints, so usage metrics can be sliced by custom dimensions (team, repo, environment). Add label selectors to dashboards for multi-tenant / per-team cost and usage tracking.
LLM Observability
Langfuse-based tracing for LLM applications. Cost tracking, scoring and drift statistics are upstream; what stays here is how this repo wires traces.
| Rule | File | Key Pattern |
|---|---|---|
| Langfuse Traces | rules/llm-langfuse-traces.md | @observe decorator, OTEL spans, agent graphs |
Silent Failures
Detection and alerting for silent failures in LLM agents.
| Rule | File | Key Pattern |
|---|---|---|
| Tool Skipping | rules/silent-tool-skipping.md | Expected vs actual tool calls, Langfuse traces |
| Quality Degradation | rules/silent-degraded-quality.md | Heuristics + LLM-as-judge, z-score baselines |
| Silent Alerting | rules/silent-alerting.md | Loop detection, token spikes, escalation workflow |
CC 2.1.169 — OTEL client-cert paths require trust: untrusted project settings can no longer set OTEL client-certificate paths without a trust confirmation. If your OTEL exporter uses client certs configured in project
.claude/settings.json, expect a one-time trust prompt on first use in an untrusted project — telemetry silently not flowing after 2.1.169 is usually this gate, not the collector.
Key Decisions
| Decision | Recommendation | Rationale |
|---|---|---|
| Metric methodology | RED method (Rate, Errors, Duration) | Industry standard, covers essential service health |
| Log format | Structured JSON | Machine-parseable, supports log aggregation |
| Tracing | OpenTelemetry | Vendor-neutral, auto-instrumentation, broad ecosystem |
| LLM observability | Langfuse (not LangSmith) | Open-source, self-hosted, built-in prompt management |
| LLM tracing API | @observe(as_type=...) + score_current_span() | v4: semantic types, inline scoring, span filtering |
| Langfuse APIs | Observations API v2 + Metrics API v2 | v4 (Mar 2026): faster querying, aggregations at scale |
| Hook telemetry transport | JSONL under ~/.claude/analytics/, never an SDK in-process | Hooks are per-event processes; SDK init would be paid on every spawn (references/ork-delta.md) |
Detailed Documentation
| Resource | Description |
|---|---|
references/ork-delta.md | Start here. Floors, house decisions and scars that upstream docs do not carry |
references/langfuse-js-v5.md | JS/TS SDK v5 delta from Python 4.x: package map, phantom packages, SpanProcessor vs exporter. Read before writing any JS Langfuse code |
references/experiments-api.md | Langfuse experiments and dataset runs as this repo uses them |
references/evaluation-scores.md | Score shapes and scoring pipeline wiring |
references/session-tracking.md | Session and user grouping across multi-step workflows |
references/metrics-collection.md | Claude Code OTEL metric inventory and collector-side joins |
references/dashboards.md | Dashboard layout conventions |
references/structured-logging.md | Structured log field conventions |
references/dev-agent-lens.md | LiteLLM proxy layer (or Bifrost) for API-boundary observability |
examples/orchestkit-monitoring-dashboard.md | Worked monitoring dashboard example |
scripts/ | Templates: Prometheus, OpenTelemetry, health checks, Langfuse |
Related Skills
defense-in-depth- Layer 8 observability as part of security architecturedevops-deployment- Observability integration with CI/CD and Kubernetesresilience-patterns- Monitoring circuit breakers and failure scenariosllm-evaluation- Evaluation patterns that integrate with Langfuse scoringcaching- Caching strategies that reduce costs tracked by Langfuse
Multimodal LLM Patterns
Integrate vision, audio, and video generation capabilities from leading multimodal models. Covers image analysis, document understanding, real-time voice agents, speech-to-text, text-to-speech, and AI video generation (Kling v3, Sora 2, Veo 3.1 std/lite/fast tiers, Runway Gen-4.5 via gen4_turbo).
Canonical model IDs (Google IDs checked against ai.google.dev/gemini-api/docs/models on 2026-09-23):
Provider Model IDs Anthropic claude-opus-5-5(recommended, the default Opus since CC 2.1.280, same 2,576 px budget as Opus 5),claude-opus-5,claude-opus-4-8,claude-opus-4-7,claude-opus-4-6,claude-sonnet-5-5,claude-sonnet-4-6,claude-haiku-4-5-20251001.claude-fable-5is Anthropic's frontier tier above Opus (GA 2026-07). Premium cost, never auto-pin it; the fable-spend-consent gate requires explicit user consent before any Fable spendOpenAI gpt-5.5(current flagship)gemini-3.1-pro-preview(flagship),gemini-3.1-flash-lite(cost)Veo veo-3.1-generate-preview/veo-3.1-lite-generate-preview/veo-3.1-fast-generate-previewKling kling-v3(model_name field in Kling API)Runway gen4_turbo(product label: Gen-4.5)
Quick Reference
| Category | Rules | Impact | When to Use |
|---|---|---|---|
| Vision: Image Analysis | 1 | HIGH | Image captioning, VQA, multi-image comparison, object detection |
| Vision: Document Understanding | 1 | HIGH | OCR, chart/diagram analysis, PDF processing, table extraction |
| Vision: Model Selection | 1 | MEDIUM | Choosing provider, cost optimization, image size limits |
| Audio: Speech-to-Text | 1 | HIGH | Transcription, speaker diarization, long-form audio |
| Audio: Text-to-Speech | 1 | MEDIUM | Voice synthesis, expressive TTS, multi-speaker dialogue |
| Audio: Model Selection | 1 | MEDIUM | Real-time voice agents, provider comparison, pricing |
| Video: Model Selection | 1 | HIGH | Choosing video gen provider (Kling, Sora, Veo, Runway) |
| Video: API Patterns | 1 | HIGH | Async task polling, SDK integration, webhook callbacks |
| Video: Multi-Shot | 1 | HIGH | Storyboarding, character elements, scene consistency |
Total: 9 rules across 3 categories (Vision, Audio, Video Generation)
Vision: Image Analysis
Send images to multimodal LLMs for captioning, visual QA, and object detection. Always set max_tokens and resize images before encoding.
| Rule | File | Key Pattern |
|---|---|---|
| Image Analysis | rules/vision-image-analysis.md | Base64 encoding, multi-image, bounding boxes |
Vision: Document Understanding
Extract structured data from documents, charts, and PDFs using vision models.
| Rule | File | Key Pattern |
|---|---|---|
| Document Vision | rules/vision-document.md | PDF page ranges, detail levels, OCR strategies |
Vision: Model Selection
Choose the right vision provider based on accuracy, cost, and context window needs.
| Rule | File | Key Pattern |
|---|---|---|
| Vision Models | rules/vision-models.md | Provider comparison, token costs, image limits |
Audio: Speech-to-Text
Convert audio to text with speaker diarization, timestamps, and sentiment analysis.
| Rule | File | Key Pattern |
|---|---|---|
| Speech-to-Text | rules/audio-speech-to-text.md | Gemini long-form, GPT-4o-Transcribe, AssemblyAI features |
Audio: Text-to-Speech
Generate natural speech from text with voice selection and expressive cues.
| Rule | File | Key Pattern |
|---|---|---|
| Text-to-Speech | rules/audio-text-to-speech.md | Gemini TTS, voice config, auditory cues |
Audio: Model Selection
Select the right audio/voice provider for real-time, transcription, or TTS use cases.
| Rule | File | Key Pattern |
|---|---|---|
| Audio Models | rules/audio-models.md | Real-time voice comparison, STT benchmarks, pricing |
Video: Model Selection
Choose the right video generation provider based on use case, duration, and budget.
| Rule | File | Key Pattern |
|---|---|---|
| Video Models | rules/video-generation-models.md | Kling vs Sora vs Veo vs Runway, pricing, capabilities |
Video: API Patterns
Integrate video generation APIs with proper async polling, SDKs, and webhook callbacks.
| Rule | File | Key Pattern |
|---|---|---|
| API Integration | rules/video-generation-patterns.md | Kling REST, fal.ai SDK, Vercel AI SDK, task polling |
Video: Multi-Shot
Generate multi-scene videos with consistent characters using storyboarding and character elements.
| Rule | File | Key Pattern |
|---|---|---|
| Multi-Shot | rules/video-multi-shot.md | Kling v3 character elements, 6-shot storyboards, identity binding |
Key Decisions
| Decision | Recommendation |
|---|---|
| High accuracy vision | claude-opus-5-5 (default Opus since CC 2.1.280, 2,576 px vision budget, 3× what Opus 4.6 allotted; give it crop/analyze tools rather than more thinking, which is the cheaper lever on this model). (claude-fable-5 is the frontier SOTA option, GA 2026-07 — premium cost, use only with explicit consent via the fable-spend-consent gate) |
| Long documents | gemini-3.1-pro-preview (1M+ context) |
| Cost-efficient vision | gemini-3.1-flash-lite (GA successor of the Flash-Lite preview, which was shut down 2026-05-25; shutdown scheduled 2027-05-07) |
| Video analysis | gemini-3.1-pro-preview (native video, supersedes 2.5 Pro) |
| Voice assistant | Grok Voice Agent on Grok 4.20 (fastest, <1s) |
| Emotional voice AI | Gemini Live API |
| Long audio transcription | gemini-3.1-pro-preview (9.5hr) |
| Speaker diarization | AssemblyAI or Gemini |
| Self-hosted STT | Whisper Large V3 |
| Character-consistent video | kling-v3 (Character Elements 3.0) |
| Narrative video / storytelling | Sora 2 (best cause-and-effect coherence) |
| Cinematic B-roll | veo-3.1-generate-preview (camera control + polished motion) |
| Budget drafts | veo-3.1-lite-generate-preview (~$0.05/s, 720/1080p) |
| Mid-tier fast renders | veo-3.1-fast-generate-preview |
| Professional VFX | Runway gen4_turbo (Act-Two motion transfer) |
| High-volume social video | kling-v3 Standard (~$0.20/video) |
| Open-source video gen | Wan 2.6 or LTX-2 |
| Lip-sync / avatar video | kling-v3 (native lip-sync API) |
Example
import anthropic, base64
client = anthropic.Anthropic()
with open("image.png", "rb") as f:
b64 = base64.standard_b64encode(f.read()).decode("utf-8")
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": [
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": b64}},
{"type": "text", "text": "Describe this image"}
]}]
)
Common Mistakes
- Not setting
max_tokenson vision requests (responses truncated) - Sending oversized images without resizing (>2048px)
- Using
highdetail level for simple yes/no classification - Using STT+LLM+TTS pipeline instead of native speech-to-speech
- Not leveraging barge-in support for natural voice conversations
- Using deprecated models (GPT-4V, Whisper-1)
- Ignoring rate limits on vision and audio endpoints
- Calling video generation APIs synchronously (they're async — poll or use callbacks)
- Generating separate clips without character elements (characters look different each time)
- Using Sora for high-volume social content (expensive, slow — use Kling Standard instead)
Related Skills
ork-extras:rag-retrieval- Multimodal RAG with image + text retrievalork-extras:llm-integration- General LLM function calling patternsstreaming-api-patterns- WebSocket patterns for real-time audioork:demo-producer- Terminal demo videos (VHS, asciinema) — not AI video gen
Portless Integration
Named .localhost URLs for local development. Replaces localhost:3000 with https://myapp.localhost.
Full CLI reference: Load
Read("references/upstream.md")for complete command docs.
New in 2026-04 → 2026-07 (portless 0.10.x → 0.15.0)
portless doctor(0.15.0) — read-only diagnostics that check Node.js, the state directory, proxy liveness, route entries, hostname resolution, HTTPS CA trust, and LAN prerequisites, then print suggested fixes. Run it before filing an issue or when a.localhostURL won't resolve.- HTTP/2 Host forwarding fix (0.15.0) — the proxy now forwards the HTTP/2
:authorityasHostto HTTP/1.1 backends, fixing apps that readHostand previously saw127.0.0.1for browser traffic.--forcetakeover cleanup now removes only routes still owned by the exiting process, so a forced takeover no longer deregisters the new owner's route. --ngrokflag (0.14.0) — share an app publicly via ngrok while local access keeps its.localhostURL. Pair with the existing Tailscale/Funnel options when you need a public URL without giving up the named-subdomain dev experience.- Node.js 24+ required (0.13.1, BREAKING) — the proxy and CLI now require Node.js 24 or newer; older runtimes are unsupported. This release also hardens startup-service persistence so
.localhostURLs survive reboot reliably. - State directory moved to
~/.portless(0.11, BREAKING) — state relocated from scattered/temp locations to~/.portless; override withPORTLESS_STATE_DIR. Old state from pre-0.11 installs is not migrated automatically. - OS startup service (0.13.0) —
portless service install/service status/service uninstallregister a native startup service for the HTTPS proxy across macOS launchd, Linux systemd, and Windows Task Scheduler..localhostURLs survive reboot without a manualportless proxy start.portless cleanremoves the service alongside CA + hosts cleanup. - Tailscale readiness preflight (0.13.0) —
--tailscaleand--funnelnow validate Tailscale HTTPS + Funnel prerequisites before starting the child process, surfacing actionable errors instead of hanging during registration. - Tailscale integration (0.12.0) —
--tailscaleshares your app over your tailnet with automatic HTTPS on port 443;--funnelexposes it publicly via Tailscale Funnel. Apps receivePORTLESS_TAILSCALE_URLso they can reference their own public address.portless listnow shows tailnet URLs. - Zero-config mode (0.11.0) — bare
portlessauto-discovers dev scripts frompackage.json. Multi-app monorepos get automatic subdomain assignment; Turborepo task-graph integration is wired in.portless.jsonconfig file supported.--scriptoverrides the default "dev" script. portless prune— removes orphaned dev servers and stale Tailscale registrations.portless clean(extended) — now also tears down Tailscale registrations alongside CA + hosts cleanup.- Rsbuild + VitePlus auto-port injection — same auto-wiring as Vite/Next.
- State directory moved to
~/.portless(was scattered). - HTTPS on 443 by default (breaking from 0.9.x http:1355). Valid cert, no setup.
--no-tlsreverts. NODE_EXTRA_CA_CERTSauto-injected (0.10.2) into child processes — node HTTPS calls trust portless CA with zero setup.--wildcardsubdomains —https://*.myapp.localhostfor multi-tenant / preview routing.portless alias <name> <port>— map a docker-compose / emulate port to a named URL without a long-runningrunprocess.portless clean— full teardown: stops proxy, removes CA, wipes state, cleans/etc/hosts.--lanmode — mDNS.localhostnames reachable across wifi (phone, tablet, other machines) without router config.- Fixed app ports —
--app-port 3000/PORTLESS_APP_PORTfor tools that need a known port (debuggers, docker). - hosts-sync on by default for Safari compat (disable with
PORTLESS_SYNC_HOSTS=0). - HTTP/2 HMR fixes for Vite/VitePlus/Next.js dev — websocket upgrades no longer break under h2.
- Expo / React Native support —
portless run expo startgives Metro a stable URL for device QR codes.
When to Use
- Starting a dev server that agents or browser tests will target
- Running multiple services locally (API + frontend + docs)
- Working in git worktrees (branch-named subdomains)
- Local OAuth flows (stable callback URLs)
- Connecting emulate API mocks to named URLs
Quick Start
# Instead of: npm run dev (random port)
portless run npm run dev
# → https://myapp.localhost (stable, named, HTTPS on 443 — default in 0.10+)
# Multi-service
portless run --name api npm run dev:api
portless run --name web npm run dev:web
# → https://api.localhost, https://web.localhost
# LAN mode (0.10.0) — reachable from phone/tablet via mDNS
portless proxy start --lan
portless run npm run dev
# → https://myapp.local (resolves across the local network, no router config)
# Full teardown (0.10.1) — stops proxy, removes CA, wipes state, cleans /etc/hosts
portless clean
# Boot persistence (0.13.0) — install native startup service (launchd / systemd / Task Scheduler)
portless service install
portless service status
# Removed automatically by `portless clean`, or explicitly:
portless service uninstall
0.10.x breaking change: default switched from
https://app.localhosttohttps://app.localhoston port 443. Use--no-tlsto revert.NODE_EXTRA_CA_CERTSis injected into child processes automatically (0.10.2) — no manual cert setup./etc/hostsis synced automatically for Safari; disable withPORTLESS_SYNC_HOSTS=0.
Framework-Specific Setup
Load
Read("references/framework-integration.md")for full framework recipes.
Most frameworks (Next.js, Vite, Express) work with portless run <cmd>. Some need explicit flags:
| Framework | Auto-detected? | Extra flags needed |
|---|---|---|
| Next.js | Yes | None |
| Vite / Astro | Yes | None |
| Express / Fastify / Hono | Yes | None (reads PORT env var) |
| Ruby on Rails | Yes | None |
| FastAPI / uvicorn | No | --port $PORT --host $HOST |
| Django | No | $HOST:$PORT positional arg |
Why .localhost?
| Feature | .localhost (RFC 6761) | 127.0.0.1:PORT | /etc/hosts hack |
|---|---|---|---|
No /etc/hosts editing | Yes | Yes | No |
| HTTPS with valid cert | Yes | No | Manual |
| Wildcard subdomains | Yes | No | No |
| Works in all browsers | Yes | Yes | Varies |
| Cookie isolation per service | Yes | No | Yes |
| No port conflicts | Yes | No | Yes |
Key Environment Variables
When portless runs your command, it injects:
| Variable | Value | Use in agents |
|---|---|---|
PORT | Assigned ephemeral port (4000-4999) | Internal only |
HOST | 127.0.0.1 | Internal only |
PORTLESS_URL | https://myapp.localhost | Use this in agent prompts |
NODE_EXTRA_CA_CERTS | Path to portless CA (auto-injected 0.10.2) | Child node processes trust portless certs without setup |
Toggle env vars
| Variable | Effect |
|---|---|
PORTLESS=0 | Bypass portless entirely (CI) |
PORTLESS_SYNC_HOSTS=0 | Disable auto /etc/hosts sync (default: on in 0.10.1+) |
PORTLESS_STATE_DIR | Override state dir (default: ~/.portless or /tmp/portless for privileged ports) |
OrchestKit Integration Patterns
1. Agent-Accessible Dev Server
# Start with portless, then agents can target PORTLESS_URL
portless run npm run dev
# In ork:expect or agent-browser:
agent-browser open $PORTLESS_URL
2. Emulate + Portless (Named API Mocks)
# Register emulate ports as named aliases
portless alias github-api 4001
portless alias vercel-api 4000
portless alias google-api 4002
# Now agents can target:
# https://github-api.localhost — GitHub emulator
# https://vercel-api.localhost — Vercel emulator
3. Git Worktree Dev
# In worktree for feature/auth-flow:
portless run npm run dev
# → https://auth-flow.myapp.localhost (auto branch prefix)
4. Bypass in CI
# Disable portless in CI — direct port access
PORTLESS=0 npm run dev
Anti-Patterns
| Don't | Do Instead |
|---|---|
Hardcode localhost:3000 in tests | Use PORTLESS_URL or process.env.PORTLESS_URL |
| Run portless in CI | Set PORTLESS=0 in CI environments |
| Use numeric ports in AGENTS.md | Document the portless URL |
References
| File | Content |
|---|---|
references/upstream.md | Full portless CLI reference (synced from Vercel) |
references/upstream-oauth.md | OAuth callback patterns with stable URLs |
references/framework-integration.md | Framework recipes (FastAPI, Django, Docker, gotchas) |
checklists/new-project-setup.md | Step-by-step: add portless to a new project |
prompt-focus
Where did your attention go, and what do you keep telling your agents again and again? This skill answers from your own input history, on your machine.
Quick Reference
| Command | What it does | Output |
|---|---|---|
scan | read history, attribute, aggregate | agg.json (counts only) |
report | scan, then build the page | report.html |
daily [YYYY-MM-DD] [--force] | append one finished day (yesterday by default), once; today needs --force and is written as a partial row that a later run replaces | daily.jsonl |
demo [path] | the same page from synthetic data | a shareable demo page |
selftest | synthetic run with privacy asserts | exit 0 or an assert |
Output dir: $PROMPT_FOCUS_DIR, default ~/.claude/prompt-focus. The exact call shape for Claude Code is in references/claude-code.md.
Quick Start Example
python3 "${CLAUDE_SKILL_DIR}/scripts/prompt_focus.py" report # writes ~/.claude/prompt-focus/report.html
python3 "${CLAUDE_SKILL_DIR}/scripts/prompt_focus.py" demo /tmp/prompt-focus-demo.html # synthetic data, safe to share
Optional ~/.claude/prompt-focus/config.json:
{"areas": {"billing": ["invoice", "stripe"]}, "brief_patterns": ["^\\s*TASK-\\d+:"], "weeks": 20}
Workflow
- Run
report, then openreport.htmlfor the user. - Lead with the verdict line from the page: the top area, prompts per week, and the nudge and words-per-prompt trend.
- Point at the re-typed asks. Each one has its first-4 vs last-4 weeks trend and a proposed default; the page's copy-as-prompt turns the ticked ones into one request.
- If the user runs several agents that paste briefs into the terminal, check 20 random rows before trusting the split, and add their brief markers to
brief_patterns. See references/how-it-works.md.
Key Decisions
- Your words only. A paste counts as one event, not as words; a slash command or shell line counts apart; text matching
brief_patternsis an agent's, not yours. - Counts only.
agg.json,daily.jsonland the page hold numbers and category names. Prompt text is read in memory and never written. - Rolling window. Always the last 20 weeks ending today (
weeksin config). - Areas. Your project folder by default; add
areasregexes inconfig.jsonto group by topic instead.
Common Mistakes
- Sharing your real
report.htmlpublicly: it names your projects. Usedemofor anything public. - Reading the split as exact without a control: brief patterns are text rules, and they miss some agent text.
- Expecting other tools: only Claude Code and Codex input history are read.
Rules
- Read only. Never write to
~/.claude/history.jsonl,~/.claude/paste-cache/or~/.codex/. - Never quote prompt text back in chat beyond the user's own short asks they asked to see.
RAG Retrieval
Comprehensive patterns for building production RAG systems. Each category has individual rule files in rules/ loaded on-demand.
House thresholds, fusion ordering, and the latency and quality budgets we assert live in House delta below. Vendor documentation is linked, not restated (see Upstream coverage).
Quick Reference
| Category | Rules | Impact | When to Use |
|---|---|---|---|
| Core RAG | 4 | CRITICAL | Basic RAG, citations, hybrid search, context management |
| Embeddings | 3 | HIGH | Model selection, chunking, batch/cache optimization |
| Contextual Retrieval | 3 | HIGH | Context-prepending, hybrid BM25+vector, pipeline |
| HyDE | 3 | HIGH | Vocabulary mismatch, hypothetical document generation |
| Agentic RAG | 4 | HIGH | Self-RAG, CRAG, knowledge graphs, adaptive routing |
| Multimodal RAG | 3 | MEDIUM | Image+text retrieval, PDF chunking, cross-modal search |
| Query Decomposition | 3 | MEDIUM | Multi-concept queries, parallel retrieval, RRF fusion |
| Reranking | 3 | MEDIUM | Cross-encoder, LLM scoring, combined signals |
| PGVector | 4 | HIGH | PostgreSQL hybrid search, HNSW indexes, schema design |
Total: 30 rules across 9 categories
Core RAG
Fundamental patterns for retrieval, generation, and pipeline composition.
| Rule | File | Key Pattern |
|---|---|---|
| Basic RAG | rules/core-basic-rag.md | Retrieve + context + generate with citations |
| Hybrid Search | rules/core-hybrid-search.md | RRF fusion (k=60) for semantic + keyword |
| Context Management | rules/core-context-management.md | Token budgeting + sufficiency check |
| Pipeline Composition | rules/core-pipeline-composition.md | Composable Decompose → HyDE → Retrieve → Rerank |
Embeddings
Embedding models, chunking strategies, and production optimization.
| Rule | File | Key Pattern |
|---|---|---|
| Models & API | rules/embeddings-models.md | Model selection, batch API, similarity |
| Chunking | rules/embeddings-chunking.md | Semantic boundary splitting, 512 token sweet spot |
| Advanced | rules/embeddings-advanced.md | Redis cache, Matryoshka dims, batch processing |
Contextual Retrieval
Anthropic's context-prepending technique — 67% fewer retrieval failures.
| Rule | File | Key Pattern |
|---|---|---|
| Context Prepending | rules/contextual-prepend.md | LLM-generated context + prompt caching |
| Hybrid Search | rules/contextual-hybrid.md | 40% BM25 / 60% vector weight split |
| Complete Pipeline | rules/contextual-pipeline.md | End-to-end indexing + hybrid retrieval |
HyDE
Hypothetical Document Embeddings for bridging vocabulary gaps.
| Rule | File | Key Pattern |
|---|---|---|
| Generation | rules/hyde-generation.md | Embed hypothetical doc, not query |
| Per-Concept | rules/hyde-per-concept.md | Parallel HyDE for multi-topic queries |
| Fallback | rules/hyde-fallback.md | 2-3s timeout → direct embedding fallback |
Agentic RAG
Self-correcting retrieval with LLM-driven decision making.
| Rule | File | Key Pattern |
|---|---|---|
| Self-RAG | rules/agentic-self-rag.md | Binary document grading for relevance |
| Corrective RAG | rules/agentic-corrective-rag.md | CRAG workflow with web fallback |
| Knowledge Graph | rules/agentic-knowledge-graph.md | KG + vector hybrid for entity-rich domains |
| Adaptive Retrieval | rules/agentic-adaptive-retrieval.md | Query routing to optimal strategy |
Multimodal RAG
Image + text retrieval with cross-modal search.
| Rule | File | Key Pattern |
|---|---|---|
| Embeddings | rules/multimodal-embeddings.md | CLIP, SigLIP 2, Voyage multimodal-3 |
| Chunking | rules/multimodal-chunking.md | PDF extraction preserving images |
| Pipeline | rules/multimodal-pipeline.md | Dedup + hybrid retrieval + generation |
Query Decomposition
Breaking complex queries into concepts for parallel retrieval.
| Rule | File | Key Pattern |
|---|---|---|
| Detection | rules/query-detection.md | Heuristic indicators (<1ms fast path) |
| Decompose + RRF | rules/query-decompose.md | LLM concept extraction + parallel retrieval |
| HyDE Combo | rules/query-hyde-combo.md | Decompose + HyDE for maximum coverage |
Reranking
Post-retrieval re-scoring for higher precision.
| Rule | File | Key Pattern |
|---|---|---|
| Cross-Encoder | rules/reranking-cross-encoder.md | ms-marco-MiniLM (~50ms, free) |
| LLM Reranking | rules/reranking-llm.md | Batch scoring + Cohere API |
| Combined | rules/reranking-combined.md | Multi-signal weighted scoring |
PGVector
Production hybrid search with PostgreSQL.
| Rule | File | Key Pattern |
|---|---|---|
| Schema | rules/pgvector-schema.md | HNSW index + pre-computed tsvector |
| Hybrid Search | rules/pgvector-hybrid-search.md | SQLAlchemy RRF with FULL OUTER JOIN |
| Indexing | rules/pgvector-indexing.md | HNSW (17x faster) vs IVFFlat |
| Metadata | rules/pgvector-metadata.md | Filtering, boosting, Redis 8 comparison |
Quick Start Example
from openai import OpenAI
client = OpenAI()
async def rag_query(question: str, top_k: int = 5) -> dict:
"""Basic RAG with citations."""
docs = await vector_db.search(question, limit=top_k)
context = "\n\n".join([f"[{i+1}] {doc.text}" for i, doc in enumerate(docs)])
response = await llm.chat([
{"role": "system", "content": "Answer with inline citations [1], [2]. Use ONLY provided context."},
{"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"}
])
return {"answer": response.content, "sources": [d.metadata['source'] for d in docs]}
Key Decisions
| Decision | Recommendation |
|---|---|
| Embedding model | text-embedding-3-small (general), voyage-3.5 (production) |
| Chunk size | 256-1024 tokens (512 typical) |
| Hybrid weight | 40% BM25 / 60% vector |
| Top-k | 3-10 documents |
| Temperature | 0.1-0.3 (factual) |
| Context budget | 4K-8K tokens |
| Reranking | Retrieve 50, rerank to 10 |
| Vector index | HNSW (production), IVFFlat (high-volume) |
| HyDE timeout | 2-3 seconds with fallback |
| Query decomposition | Heuristic first, LLM only if multi-concept |
Upstream coverage (do not restate)
Fetch these from the source instead of restating them here. Where a row says the house subset stays, that named file carries only the tuned values and the reason, not a tutorial.
| Topic | Source |
|---|---|
| pgvector install, operators, index build syntax, "why isn't my index used" | https://github.com/pgvector/pgvector; house subset (HNSW m=16, ef_construction=64, halfvec, binary quantize) stays in rules/pgvector-indexing.md and rules/pgvector-schema.md |
Postgres full-text search: tsvector, tsquery, GIN, ts_rank_cd | https://www.postgresql.org/docs/current/textsearch.html; house subset (generated STORED column) stays in rules/pgvector-schema.md |
| Reading query plans, confirming an index is used, VACUUM/ANALYZE | https://www.postgresql.org/docs/current/using-explain.html |
| RRF mechanics: rank constant, rank window size, tie handling | https://www.elastic.co/docs/reference/elasticsearch/rest-apis/reciprocal-rank-fusion; house subset (k=60, 3x fetch) stays in rules/core-hybrid-search.md and rules/pgvector-hybrid-search.md |
| Field-weighted boosting and scoring profiles as a concept | https://learn.microsoft.com/en-us/azure/search/index-add-scoring-profiles; our boost factors and their ordering are in House delta and rules/pgvector-metadata.md |
Embedding API mechanics: batch limits, input_type, dimensions, pricing | https://docs.voyageai.com/docs/embeddings and https://platform.openai.com/docs/guides/embeddings; model choice stays in rules/embeddings-models.md |
| Retrieval metric definitions (precision@k, recall@k, MRR, nDCG) and building the query set | ork skill golden-dataset |
| Search endpoint shape, pagination, error bodies | ork skill api-design |
| Tracing and dashboarding search calls | ork skill monitoring-observability |
| Writing the integration test that runs these assertions | ork skill testing-integration |
Common Mistakes
- No citation tracking (unverifiable answers)
- Context too large (dilutes relevance)
- Single retrieval method (misses keyword matches)
- Not chunking long documents (context gets lost)
- Embedding queries differently than documents
- No fallback path in agentic RAG (workflow hangs)
- Infinite rewrite loops (no retry limit)
- Using wrong similarity metric (cosine vs euclidean)
- Not caching embeddings (recomputing unchanged content)
- Missing image captions in multimodal RAG (limits text search)
Evaluations
See test-cases.json for 30 test cases across all categories.
There is no pass-rate, precision, recall, or MRR floor for this skill. Earlier
wording here promised those numbers; they were never measured and are written down
nowhere. They are left unset rather than filled in with plausible-looking values,
because a threshold nobody measured is worse than an absent one: it gets cited in
review as though it means something, and passes or fails changes for no defensible
reason. test-cases.json is the right substrate for establishing real ones, and a
baseline run over those 30 cases would produce numbers worth asserting.
The one budget this skill does assert is latency, in House delta.
Related Skills
ork-extras:langgraph- LangGraph workflow patterns (for agentic RAG workflows)ork-extras:golden-dataset- Evaluate retrieval qualityork-extras:llm-integration- Local embeddings with nomic-embed-textork-extras:multimodal-llm- Image analysis for multimodal RAGork:database-patterns- Schema design for vector searchork:performance- Caching repeated RAG responses
Capability Details
retrieval-patterns
Keywords: retrieval, context, chunks, relevance, rag Solves:
- Retrieve relevant context for LLM
- Implement RAG pipeline with citations
- Optimize retrieval quality
hybrid-search
Keywords: hybrid, bm25, vector, fusion, rrf Solves:
- Combine keyword and semantic search
- Implement reciprocal rank fusion
- Balance precision and recall
embeddings
Keywords: embedding, text to vector, vectorize, chunk, similarity Solves:
- Convert text to vector embeddings
- Choose embedding models and dimensions
- Implement chunking strategies
contextual-retrieval
Keywords: contextual, anthropic, context-prepend, bm25 Solves:
- Prepend context to chunks for better retrieval
- Reduce retrieval failures by 67%
- Implement hybrid BM25+vector search
hyde
Keywords: hyde, hypothetical, vocabulary mismatch Solves:
- Bridge vocabulary gaps in semantic search
- Generate hypothetical documents for embedding
- Handle abstract or conceptual queries
agentic-rag
Keywords: self-rag, crag, corrective, adaptive, grading Solves:
- Build self-correcting RAG workflows
- Grade document relevance
- Implement web search fallback
multimodal-rag
Keywords: multimodal, image, clip, vision, pdf Solves:
- Build RAG with images and text
- Cross-modal search (text → image)
- Process PDFs with mixed content
query-decomposition
Keywords: decompose, multi-concept, complex query Solves:
- Break complex queries into concepts
- Parallel retrieval per concept
- Improve coverage for compound questions
reranking
Keywords: rerank, cross-encoder, precision, scoring Solves:
- Improve search precision post-retrieval
- Score relevance with cross-encoder or LLM
- Combine multiple scoring signals
pgvector-search
Keywords: pgvector, postgresql, hnsw, tsvector, hybrid Solves:
- Production hybrid search with PostgreSQL
- HNSW vs IVFFlat index selection
- SQL-based RRF fusion
House delta
Inlined rather than placed in references/: this skill carries its house knowledge
in rules/ (32 files) and has never had a references/ directory, so a lone
delta file there would be the only occupant.
Embedding-model choice, chunking algorithms, vector-index tuning, reranker APIs and the query-rewriting literature are vendor and upstream territory; see Upstream coverage for where each lives. What follows is only what OrchestKit adds, contradicts, or has to warn about.
Retrieval latency budget: p95 under 500ms end to end
Source: checklists/rag-quality.md:57, the only retrieval budget this skill has ever
actually asserted. It covers the whole path a user waits on (embed the query, search,
rerank, assemble context), not one stage in isolation. A pipeline that clears 500ms
per stage and blows it in aggregate has failed this budget.
Measure at p95, not mean. Retrieval latency is dominated by tail behaviour (cold index shards, reranker queueing), and a mean hides exactly the requests users complain about.
Corpus-specific tuning does not transfer
Fusion weights, rerank depth and hybrid alpha are properties of a corpus, not of the technique. A weighting that lifts recall on prose documentation regularly hurts it on code or tabular data, so values copied between projects are noise rather than a starting point. Re-derive them per corpus against that corpus's own eval set.
Apply metadata boosting after RRF fusion, never before
Why: boost factors multiply onto the RRF score of an already-fused result set and the list is then re-sorted, using section-title match 1.5x, section-path match 1.15x, and code block on a technical query 1.2x; boosting per-method scores before fusion destroys the property RRF depends on (it fuses by rank, not by score) and lets a lone strong keyword hit outrank a document both methods agreed on, and this exact order is what produced the +6% MRR credited to boosting in rules/pgvector-metadata.md (distilled from the retired checklists/search-implementation-checklist.md and examples/examples/orchestkit-retrieval.md; no traced incident).
Upstream: https://learn.microsoft.com/en-us/azure/search/index-add-scoring-profiles
Stop raising the RRF fetch multiplier past 3x
Why: measured pass rate on the reference corpus went 87.2% at 1x, 89.5% at 2x, 91.1% at 3x, 91.3% at 4x, so the fourth multiple bought 0.2 points for a third more rows scanned per method, which is why 3x is the house default hard-coded in rules/core-hybrid-search.md and rules/pgvector-hybrid-search.md; raise it only with a golden-set number that beats this curve (distilled from the retired examples/examples/orchestkit-retrieval.md; no traced incident).
Upstream: https://www.elastic.co/docs/reference/elasticsearch/rest-apis/reciprocal-rank-fusion
Gate every retrieval change on the golden-set thresholds
Why: the house bar before a retrieval change ships is pass rate at least 90% on the golden query set, precision@10 at least 0.70, recall@10 at least 0.85, and MRR at least 0.65, floors set just under the reference pipeline's observed 91.6% pass rate and 0.777 overall MRR (0.695 on the hard slice) so that a real regression trips them instead of a noisy run (distilled from the retired checklists/search-implementation-checklist.md and examples/examples/orchestkit-retrieval.md; no traced incident).
Upstream: ork skill golden-dataset
Assert search latency per stage, not just end to end
Why: the integration test asserts vector search under 100ms, keyword search under 50ms, and fused hybrid under 150ms separately, against an observed 415-chunk baseline of P50 15ms / P95 32ms / P99 62ms, because a single total-latency assertion stays green while one stage silently doubles, which is precisely the shape of an index that quietly stopped being used (distilled from the retired checklists/search-implementation-checklist.md and examples/examples/orchestkit-retrieval.md; no traced incident). Upstream: https://www.postgresql.org/docs/current/using-explain.html
Budget the embedding call before tuning the index
Why: in the reference measurement the query embedding was P50 8ms of a 15ms end-to-end search against 2ms for vector search and 3ms for keyword search, and it was the throughput ceiling at roughly 120 requests per second, so cache and batch embeddings first because index tuning below that ceiling moves the total by single-digit percent (distilled from the retired examples/examples/orchestkit-retrieval.md; no traced incident). Upstream: https://docs.voyageai.com/docs/embeddings
Release Management
Automate releases with gh release, semantic versioning, and changelog generation.
CC ≥ 2.1.118 (M122):
claude plugin tag <version>validates the plugin manifest hierarchy (marketplace.json, plugin.json, package.json, version.txt) before tagging. Runs--dry-runin CI before release-please opens its release PR; catches manifest drift early. Seesrc/skills/chain-patterns/references/plugin-tag.md.
CRITICAL: Task Management is MANDATORY (CC 2.1.16)
BEFORE doing ANYTHING else, create tasks to track progress:
# 1. Create main task IMMEDIATELY
TaskCreate(
subject="Release: {version}",
description="Creating release with semantic versioning and changelog",
activeForm="Releasing {version}"
)
# 2. Create subtasks for each release phase
TaskCreate(subject="Version & changelog", activeForm="Determining version and generating changelog")
TaskCreate(subject="Create release", activeForm="Creating GitHub release")
TaskCreate(subject="Verify & announce", activeForm="Verifying release and announcing")
# 3. Set dependencies for sequential phases
TaskUpdate(taskId="3", addBlockedBy=["2"])
TaskUpdate(taskId="4", addBlockedBy=["3"])
# 4. Update status as you progress
TaskUpdate(taskId="2", status="in_progress") # When starting
TaskUpdate(taskId="2", status="completed") # When done
Quick Reference
Create Release
# Auto-generate notes from PRs
gh release create v1.2.0 --generate-notes
# With custom title
gh release create v1.2.0 --title "Version 1.2.0: Performance Update" --generate-notes
# Draft release (review before publishing)
gh release create v1.2.0 --draft --generate-notes
# Pre-release (beta, rc)
gh release create v1.2.0-beta.1 --prerelease --generate-notes
# With custom notes
gh release create v1.2.0 --notes "## Highlights
- New auth system
- 50% faster search"
# From notes file
gh release create v1.2.0 --notes-file RELEASE_NOTES.md
List & View Releases
# List all releases
gh release list
# View specific release
gh release view v1.2.0
# View in browser
gh release view v1.2.0 --web
# JSON output
gh release list --json tagName,publishedAt,isPrerelease
Verify Releases (gh CLI 2.86.0+)
# Verify release attestation (sigstore)
gh release verify v1.2.0
# Verify specific asset
gh release verify-asset v1.2.0 ./dist/app.zip
# Verify with custom trust policy
gh release verify v1.2.0 --owner myorg
Manage Releases
# Edit release
gh release edit v1.2.0 --title "New Title" --notes "Updated notes"
# Delete release
gh release delete v1.2.0
# Upload assets
gh release upload v1.2.0 ./dist/app.zip ./dist/app.tar.gz
Semantic Versioning
MAJOR.MINOR.PATCH
│ │ │
│ │ └── Bug fixes (backwards compatible)
│ └──────── New features (backwards compatible)
└────────────── Breaking changes
Examples:
1.0.0 → 1.0.1 (patch: bug fix)
1.0.1 → 1.1.0 (minor: new feature)
1.1.0 → 2.0.0 (major: breaking change)
Pre-release:
2.0.0-alpha.1 (early testing)
2.0.0-beta.1 (feature complete)
2.0.0-rc.1 (release candidate)
Release Workflows
Standard and hotfix release procedures using git tags and gh release.
Load Read("references/release-workflows.md") for step-by-step standard and hotfix release workflows.
Changelog Generation
Auto-generated from PRs, custom .github/release.yml templates, and manual CHANGELOG.md format.
Load Read("references/changelog-generation.md") for changelog template examples and Keep-a-Changelog format.
Release Automation & Checklist
GitHub Actions workflow for tag-triggered releases, version bumping script, and pre/post-release checklist.
Load Read("references/release-automation.md") for CI workflow, bump script, and release checklist.
Best Practices
- Use semantic versioning - Communicate change impact
- Draft releases first - Review notes before publishing
- Generate notes from PRs - Accurate, automatic history
- Close milestone on release - Track completion
- Tag main only - Never tag feature branches
- Announce breaking changes - Prominent in release notes
Related Skills
ork:github-operations: Milestones, issues, and CLI referenceork:github-operations: Branch management and git operations
References
Load on demand with Read("references/<file>"):
| File | Content |
|---|---|
semver.md | Semantic versioning rules and decision tree |
release-workflows.md | Standard and hotfix release procedures |
changelog-generation.md | Auto-generated, template, and manual changelog formats |
release-automation.md | GitHub Actions workflow, bump script, and checklist |
Responsive Patterns
Modern responsive design patterns using Container Queries, fluid typography, and mobile-first strategies for React applications (2026 best practices).
Overview
- Building reusable components that adapt to their container
- Implementing fluid typography that scales smoothly
- Creating responsive layouts without media query overload
- Building design system components for multiple contexts
- Optimizing for variable container sizes (sidebars, modals, grids)
Core Concepts
Container Queries vs Media Queries
| Feature | Media Queries | Container Queries |
|---|---|---|
| Responds to | Viewport size | Container size |
| Component reuse | Context-dependent | Truly portable |
| Browser support | Universal | Baseline 2023+ |
| Use case | Page layouts | Component layouts |
Modern CSS Layout
Load
Read("rules/css-subgrid.md")for CSS Subgrid patterns: nested grid alignment, card layouts with aligned titles/content/actions, two-dimensional subgrid.
Load
Read("rules/css-intrinsic-responsive.md")for intrinsically responsive layouts: auto-fit/minmax grids, clamp() for fluid everything, container queries for component logic, zero media query patterns.
Load
Read("rules/responsive-foldables.md")for foldable/multi-screen device support: env(safe-area-inset-*), viewport segment queries, dual-screen layouts, progressive enhancement.
Key patterns covered: CSS Subgrid alignment, intrinsic responsive grids (auto-fit + minmax), fluid clamp() scales, foldable device layouts, safe area insets, viewport segment queries.
CSS Patterns
Load
Read("rules/css-patterns.md")for complete CSS examples: container queries, cqi/cqb units, fluid typography with clamp(), mobile-first breakpoints, CSS Grid patterns, and scroll-queries.
Key patterns covered: Container Query basics, Container Query Units (cqi/cqb), Fluid Typography with clamp(), Container-Based Fluid Typography, Mobile-First Breakpoints, CSS Grid Responsive Patterns, Container Scroll-Queries (Chrome 126+).
React Patterns
Load
Read("rules/react-patterns.md")for complete React examples: ResponsiveCard component, Tailwind container queries, useContainerQuery hook, and responsive images.
Key patterns covered: Responsive Component with Container Queries, Tailwind CSS Container Queries, useContainerQuery Hook, Responsive Images Pattern.
Accessibility Considerations
/* IMPORTANT: Always include rem in fluid typography */
/* This ensures user font preferences are respected */
/* ❌ WRONG: Viewport-only ignores user preferences */
font-size: 5vw;
/* ✅ CORRECT: Include rem to respect user settings */
font-size: clamp(1rem, 0.5rem + 2vw, 2rem);
/* User zooming must still work */
@media (min-width: 768px) {
/* Use em/rem, not px, for breakpoints in ideal world */
/* (browsers still use px, but consider user zoom) */
}
Anti-Patterns (FORBIDDEN)
/* ❌ NEVER: Use only viewport units for text */
.title {
font-size: 5vw; /* Ignores user font preferences! */
}
/* ❌ NEVER: Use cqw/cqh (use cqi/cqb instead) */
.card {
padding: 5cqw; /* cqw = container width, not logical */
}
/* ✅ CORRECT: Use logical units */
.card {
padding: 5cqi; /* Container inline = logical direction */
}
/* ❌ NEVER: Container queries without container-type */
@container (min-width: 400px) {
/* Won't work without container-type on parent! */
}
/* ❌ NEVER: Desktop-first media queries */
.element {
display: grid;
grid-template-columns: repeat(4, 1fr);
}
@media (max-width: 768px) {
.element {
grid-template-columns: 1fr; /* Overriding = more CSS */
}
}
/* ❌ NEVER: Fixed pixel breakpoints for text */
@media (min-width: 768px) {
body { font-size: 18px; } /* Use rem! */
}
/* ❌ NEVER: Over-nesting container queries */
@container a {
@container b {
@container c {
/* Too complex, reconsider architecture */
}
}
}
Browser Support
| Feature | Chrome | Safari | Firefox | Edge |
|---|---|---|---|---|
| Container Size Queries | 105+ | 16+ | 110+ | 105+ |
| Container Style Queries | 111+ | ❌ | ❌ | 111+ |
| Container Scroll-State | 126+ | ❌ | ❌ | 126+ |
| cqi/cqb units | 105+ | 16+ | 110+ | 105+ |
| clamp() | 79+ | 13.1+ | 75+ | 79+ |
| Subgrid | 117+ | 16+ | 71+ | 117+ |
Rules
Each category has individual rule files in rules/ loaded on-demand:
| Category | Rule | Impact | Key Pattern |
|---|---|---|---|
| Modern CSS Layout | rules/css-subgrid.md | HIGH | CSS Subgrid for nested grid alignment, card layouts |
| Modern CSS Layout | rules/css-intrinsic-responsive.md | HIGH | Intrinsic responsive layouts, auto-fit/minmax, clamp(), zero breakpoints |
| Modern CSS Layout | rules/responsive-foldables.md | MEDIUM | Foldable devices, safe area insets, viewport segments |
| CSS | rules/css-patterns.md | HIGH | Container queries, cqi/cqb, fluid typography, grid, scroll-queries |
| React | rules/react-patterns.md | HIGH | Container query components, Tailwind, useContainerQuery, responsive images |
| PWA | rules/pwa-service-worker.md | HIGH | Workbox caching strategies, VitePWA, update management |
| PWA | rules/pwa-offline.md | HIGH | Offline hooks, background sync, install prompts |
| Animation | rules/animation-motion.md | HIGH | Motion presets, AnimatePresence, View Transitions |
| Animation | rules/animation-scroll.md | MEDIUM | CSS scroll-driven animations, parallax, progressive enhancement |
| Touch & Mobile | rules/touch-interaction.md | HIGH | Touch targets (44px min), thumb zones, pinch-to-zoom, safe areas, gestures |
Total: 10 rules across 6 categories
Key Decisions
| Decision | Option A | Option B | Recommendation |
|---|---|---|---|
| Query type | Media queries | Container queries | Container for components, Media for layout |
| Container units | cqw/cqh | cqi/cqb | cqi/cqb (logical, i18n-ready) |
| Fluid type base | vw only | rem + vw | rem + vw (accessibility) |
| Mobile-first | Yes | Desktop-first | Mobile-first (less CSS, progressive) |
| Grid pattern | auto-fit | auto-fill | auto-fit for cards, auto-fill for icons |
Related Skills
design-system-starter- Building responsive design systemsork:performance- CLS, responsive images, and image optimizationork-extras:i18n-date-patterns- RTL/LTR responsive considerations
Capability Details
container-queries
Keywords: @container, container-type, inline-size, container-name Solves: Component-level responsive design
fluid-typography
Keywords: clamp(), fluid, vw, rem, scale, typography Solves: Smooth font scaling without breakpoints
responsive-images
Keywords: srcset, sizes, picture, art direction Solves: Responsive images for different viewports
mobile-first-strategy
Keywords: min-width, mobile, progressive, breakpoints Solves: Efficient responsive CSS architecture
grid-flexbox-patterns
Keywords: auto-fit, auto-fill, subgrid, minmax Solves: Responsive grid and flexbox layouts
container-units
Keywords: cqi, cqb, container width, container height Solves: Sizing relative to container dimensions
References
Load on demand with Read("references/<file>"):
| File | Content |
|---|---|
container-queries.md | Container query patterns |
fluid-typography.md | Accessible fluid type scales |
Storybook Testing — Storybook 10
Overview
Storybook 10 unifies component testing into a single workflow: interaction tests via play() functions, visual regression via Chromatic TurboSnap, and accessibility audits via the a11y addon — all running through Vitest. Stories are executable test specifications, not just documentation.
What's new in Storybook 10 (vs 9):
- ESM-only enforced — the single breaking change; Node 20.16+ / 22.19+ / 24+ required; 29% smaller install
- Module automocking (
sb.mock) — build-time module mocking, scoped per-project in preview.ts - CSF factories (React, preview) —
defineMain→definePreview→preview.meta()→meta.story()chain - Essential addons in core — viewport, controls, interactions, actions no longer separate deps
- Import path changes —
@storybook/test→storybook/test(old paths still work as aliases) - React Server Component story support — test RSC in isolation
- Vitest 4 support —
experimental-addon-testrenamed toaddon-vitest
When to use this skill:
- Writing component stories in CSF3 format with TypeScript
- Setting up interaction tests with
play()functions - Configuring Chromatic visual regression with TurboSnap
- Using module automocking at the story level
- Running accessibility tests in CI via the a11y addon
- Generating living documentation with autodocs
- Migrating from Storybook 9 to 10
Quick Reference
| Rule | Impact | Description |
|---|---|---|
storybook-csf3-factories | HIGH | Typesafe CSF3 story factories with satisfies Meta |
storybook-play-functions | CRITICAL | Interaction testing with play() and @storybook/test |
storybook-vitest-integration | HIGH | Run stories as Vitest tests via @storybook/addon-vitest |
storybook-chromatic-turbosnap | HIGH | TurboSnap reduces snapshot cost 60-90% |
storybook-sb-mock | HIGH | Story-level module mocking with sb.mock |
storybook-a11y-testing | CRITICAL | Automated axe-core accessibility scans in CI |
storybook-autodocs | MEDIUM | Auto-generated docs from stories |
Storybook Testing Pyramid
┌──────────────┐
│ Visual │ Chromatic TurboSnap
│ Regression │ (snapshot diffs)
├──────────────┤
│ Accessibility│ @storybook/addon-a11y
│ (a11y) │ (axe-core scans)
├──────────────┤
│ Interaction │ play() functions
│ Tests │ (@storybook/test)
├──────────────┤
│ Unit Tests │ Vitest + storybookTest
│ (stories) │ plugin
└──────────────┘
Each layer catches different defects: unit tests validate logic, interaction tests verify user flows, a11y tests catch accessibility violations, and visual tests catch unintended UI regressions.
Quick Start
CSF3 Story with Play Function
// Button.stories.tsx
import type { Meta, StoryObj } from '@storybook/react'
import { expect, fn, userEvent, within } from 'storybook/test'
import { Button } from './Button'
const meta = {
component: Button,
args: {
onClick: fn(),
},
} satisfies Meta<typeof Button>
export default meta
type Story = StoryObj<typeof meta>
export const Primary: Story = {
args: {
label: 'Click me',
variant: 'primary',
},
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement)
const button = canvas.getByRole('button', { name: /click me/i })
await userEvent.click(button)
await expect(args.onClick).toHaveBeenCalledOnce()
await expect(button).toHaveStyle({ backgroundColor: 'rgb(37, 99, 235)' })
},
}
Vitest Configuration
// vitest.config.ts
import { storybookTest } from '@storybook/addon-vitest/vitest-plugin'
import { defineConfig } from 'vitest/config'
export default defineConfig({
plugins: [storybookTest()],
test: {
setupFiles: ['./vitest.setup.ts'],
},
})
Key Principles
- Stories are tests. Every story with a
play()function is an executable interaction test that runs in Vitest. - CSF3 +
satisfiesfor type safety. Usesatisfies Meta<typeof Component>for full type inference on args and play functions. - Module automocking (SB 10). Register
sb.mock(import(...))in.storybook/preview.ts, configure per-story withmocked()inbeforeEach. Never usevi.mockin story files. No factory functions —sb.mockis build-time, not runtime. - TurboSnap for CI speed. Only snapshot stories affected by code changes — reduces Chromatic usage by 60-90%.
- Accessibility is not optional. The a11y addon runs axe-core scans on every story and gates CI on violations.
- Living documentation. Autodocs generates prop tables and usage examples directly from stories — no separate docs site needed.
Anti-Patterns (FORBIDDEN)
| Anti-Pattern | Why It Fails | Use Instead |
|---|---|---|
CSF2 Template.bind({}) | Deprecated, no type inference, will be removed in SB 11 | CSF3 object stories with satisfies |
@storybook/test-runner package | Deprecated since Storybook 9 | @storybook/addon-vitest |
vi.mock() in story files | Leaks between stories, breaks isolation | Register sb.mock(import(...)) in preview.ts, configure with mocked() in beforeEach |
| Full Chromatic snapshots on every PR | Expensive and slow | TurboSnap with onlyChanged: true |
| Manual accessibility checking | Misses violations, not repeatable | @storybook/addon-a11y in CI pipeline |
| Separate documentation site | Drifts from actual component behavior | Autodocs with tags: ['autodocs'] |
| Testing implementation details | Brittle, breaks on refactors | Test user-visible behavior via play() |
| CJS imports in stories | ESM-only since SB 9/10 | Use ESM imports, set "module": "ESNext" in tsconfig |
Storybook MCP Integration (addon-mcp)
When @storybook/addon-mcp is installed, agents can run tests and preview stories via MCP instead of CLI. This enables the generate → test → self-heal loop.
MCP Tools for Testing
| Tool | Purpose |
|---|---|
run-story-tests | Run component + a11y tests via MCP, returns pass/fail + violation details |
preview-stories | Returns preview URLs for visual verification in chat |
get-storybook-story-instructions | Guidance on writing effective stories + interaction tests |
Agent Testing Loop
# 1. Generate component + CSF3 story
# 2. Run tests via MCP
results = run-story-tests(
stories=[{ "storyId": "button--primary" }],
a11y=True
)
# 3. If failures: read violations, fix, retry (max 3)
# 4. Preview in chat for visual confirmation
preview-stories(stories=[{ "storyId": "button--primary" }])
Setup
npx storybook add @storybook/addon-mcp # current: 0.6.0, Apr 2026
# Enable docs toolset in .storybook/main.ts:
# componentsManifest: true # was experimentalComponentsManifest (SB 10.3 rename, default-on)
npx mcp-add --type http --url "http://localhost:6006/mcp" --scope project
See the Storybook mode of the design-to-code skill for full tool reference and patterns.
References
references/storybook-migration-guide.md— Migration path from Storybook 9 to 10references/storybook-ci-strategy.md— CI pipeline configuration for visual, interaction, and a11y testingreferences/storybook-addon-ecosystem.md— Essential addons for Storybook 10 in 2026
Related Skills
design-to-code(Storybook mode): Storybook MCP tools for component discovery, testing, previewsreact-server-components-framework— React 19 + Next.js 16 patterns (component architecture)accessibility— Broader accessibility patterns beyond Storybookdevops-deployment— CI/CD pipeline patterns for automated testing
swarm-migrate — Cross-Repo Migration Swarm
One command, N repos, one coordinator, one ledger.
When to use
Use when the same transformation needs to land in 3 or more repos with the same shape (workflow bump, dependency upgrade, codemod, lint-rule introduction, secret rotation, runbook header). Don't use for one-repo work — that's implement. Don't use for novel exploration — that's brainstorm.
This skill exists because the 275-session insights showed 25 sessions burned coordinating PR cascades manually (M164 deploy-migration, M17 yg-mcp-core extraction, @v1 reusable workflow rollout across 14 repos). The pattern was always: pick a repo, branch, apply, push, watch CI, repeat. This automates the repeat.
vs CC
/workflows(2.1.154): CC's dynamic workflows orchestrate tens-to-hundreds of agents in the background and report via/workflows.swarm-migrateis different on purpose: it's a coordinator-led, foreground DAG with CI gates, conflict auto-rebase, and stop-on-novel-failure — you watch it and it stops on the first unexpected failure. Reach for CC/workflowswhen you want large-scale fire-and-forget background fan-out; reach forswarm-migratewhen each step needs a CI gate and a human-visible ledger. CC 2.1.202 adds a Dynamic workflow size setting in/config(small / medium / large agent counts) that advises/workflowson how many agents to spawn — it's a hint, not an enforced cap, so check it before hand-capping fan-out.
Inputs
A YAML spec at swarm-specs/<name>.yaml:
name: bump-actions-checkout-v4
description: "Pin @actions/checkout to v4 across all repos"
# Topology — repos in dependency order. Coordinator only proceeds
# to a downstream repo after every upstream parent has merged green.
repos:
- path: ~/coding/yonatan-hq/platform
upstream: []
- path: ~/coding/yonatan-hq/ventures/jobscraper
upstream: [platform] # waits for platform to merge first
# Transformation — applied identically per repo. The agent runs this
# inside the isolated worktree, then verifies with the next field.
transform:
type: codemod # codemod | regex | command
command: |
grep -rl 'actions/checkout@v3' .github/workflows | \
xargs sed -i '' 's|actions/checkout@v3|actions/checkout@v4|g'
# Verification — must pass before PR opens. Coordinator skips the repo
# if it fails locally (records skip-reason in ledger).
verify:
- command: "git diff --quiet"
expect: nonzero # must have changes
- command: "grep -r 'actions/checkout@v3' .github/workflows"
expect: nonzero # zero matches = clean
# PR shape — title, body, base branch
pr:
branch_prefix: chore/bump-checkout-v4
title: "chore(ci): pin @actions/checkout to v4"
body_file: swarm-specs/bump-actions-checkout-v4.pr.md
base: main
labels: [chore, ci]
# CI gate — coordinator waits for required checks to pass before
# moving downstream. Set to false for dry-run, or in repos without CI.
ci_gate:
required_checks: ["build", "test"]
timeout_minutes: 20
on_failure: pause # pause | skip | abort
# Limits
max_parallel: 4
abort_on_novel_failure: true
How it works
┌────────────────────────────────┐
│ COORDINATOR (you) │
│ reads spec → builds DAG → │
│ writes .swarm-state.json │
└─────────────────┬──────────────┘
┌────────────┼────────────┐
┌──────────┐ ┌──────────┐ ┌──────────┐
│ WORKER A │ │ WORKER B │ │ WORKER C │
│ (repo 1) │ │ (repo 2) │ │ (repo 3) │
└────┬─────┘ └────┬─────┘ └────┬─────┘
└─────────── isolated worktrees ─────┘
│ each: clone branch, transform,
│ verify, push, open PR, wait for CI, report
▼
┌────────────────────────────────┐
│ .swarm-state.json │
│ rolling ledger of {repo, │
│ status, pr_url, ci_state, │
│ last_action_at} │
└────────────────────────────────┘
Each worker is a Agent tool invocation (subagent type git-operations-engineer for plumbing or backend-system-architect for schema-flavored migrations). The coordinator (you, this skill) reads the ledger between waves and decides whether to release downstream waves or pause.
Push, do not poll (CC 2.1.224+)
Workers report state changes (CI green, CI red, novel failure, skipped) by MESSAGING
the coordinator via SendMessage instead of the coordinator re-reading the ledger
between waves:
Cross-session replies land in the parent (CC 2.1.248): when a subagent sends
SendMessageto another session, the reply is delivered to the parent session's conversation, never to the subagent; a subagent sends and moves on, the parent reads the answer. Cross-sessionSendMessage/ListAgentsalso work on Bedrock, Vertex and Foundry and with telemetry disabled (CC 2.1.248).
- Workers spawned as Agent-tool subagents use in-session
SendMessage(available since CC 2.1.77). - Workers running as separate sessions or
claude -pprocesses use cross-session messaging (CC 2.1.224, see chain-patterns Pattern 10). A-pworker must run withcrossSessionInbound: "accept"in--settingsto receive replies.
CRITICAL: cross-session delivery is not guaranteed - inbound controls can hold or
refuse a message. .swarm-state.json REMAINS the authoritative durable record, and
every state change is still written there. Messages are the low-latency signal; the
ledger is the truth.
Phase 1 — Spec validation
Load <spec-file.yaml>. Verify:
- Every
repos[].pathexists and is a git repo (usegit -C <path> rev-parsechecks). - The
transform.commandreturns 0 in a dry-run mode (ortransform.type: codemodresolves to a known codemod registered inswarm-specs/codemods/). - Every
upstreamreference points to a declared repo (no dangling deps). pr.body_fileexists and is non-empty.
If any check fails, abort and print the table of failures. Do NOT proceed.
Phase 2 — Topology sort
Build a DAG from upstream edges. Detect cycles → abort. Group nodes by topological wave (wave 0 = no deps, wave 1 = depends only on wave 0, …). Coordinator releases one wave at a time.
Write .swarm-state.json at the repo root running the skill:
{
"spec": "swarm-specs/bump-actions-checkout-v4.yaml",
"started_at": "2026-05-16T17:00:00Z",
"waves": [
{ "id": 0, "repos": ["platform"] },
{ "id": 1, "repos": ["jobscraper"] }
],
"repos": {
"platform": { "status": "pending", "pr_url": null, "ci_state": null, "last_action_at": null },
"jobscraper": { "status": "blocked", "blocked_on": ["platform"], "pr_url": null }
}
}
Phase 3 — Dispatch wave
For each repo in the current wave, in parallel (bounded by max_parallel):
- Worktree — create an isolated worktree at
<repo>/../<repo>-swarm-<spec-name>offorigin/<base>. Never mutate the live working tree. - Branch —
git checkout -b <branch_prefix>-<short-sha>. - Transform — run
transform.command(or apply codemod). Capture stdout to.swarm-logs/<repo>-transform.log. - Verify — run each
verify[].command, assert exit matchesexpect. On mismatch, mark reposkippedin ledger with reason, do not push. - Push + PR — push branch, open PR via
gh pr create. Update ledger with PR URL. - Watch CI — poll
gh pr checks <n>every 45s up toci_gate.timeout_minutes. Updateci_statein ledger on every state transition.
Use the Agent tool with subagent_type: ork:git-operations-engineer for steps 1–5 to keep main context lean. The coordinator only reads the ledger.
Phase 4 — Wave gate
After every wave, check the ledger:
- All
green→ release the next wave. - Any
pending CI→ keep polling. - Any
red CI→ consultci_gate.on_failure:pause→ halt the swarm, write a summary to.swarm-state.json, surface the failing logs, ask the user.skip→ mark repofailed-ci, continue with siblings (but block downstream unless they explicitly don't depend on this repo).abort→ terminate the swarm, leave open PRs as-is, never merge.
Phase 5 — Auto-rebase on conflicts
If a downstream repo's worker hits a merge conflict on rebase (because an upstream merged), the worker:
- Re-fetches the upstream's merge commit SHA.
- Attempts
git rebase origin/<base>. If clean → push, ledger update. - If conflicts → mark the conflict files in the ledger, do NOT auto-resolve, surface to the coordinator. Conflicts are the most common place auto-fixers ship broken code.
Phase 6 — Final report
When all waves complete (or the swarm pauses/aborts), emit a single markdown report under .swarm-logs/<spec-name>-report.md:
# Swarm report: bump-actions-checkout-v4
Completed: 12/14 repos · paused: 2 · duration: 47 min
| repo | status | PR | CI | duration |
|-----------------|---------|-------|--------|----------|
| platform | merged | #3456 | green | 8 min |
| jobscraper | merged | #281 | green | 6 min |
| ... |
| dormant-repo-1 | skipped | — | — | (no CI runner configured) |
| trading-ai | paused | #99 | red | (novel failure — see logs) |
## Novel failures (escalated)
- trading-ai #99: pyproject lockfile mismatch — see .swarm-logs/trading-ai-ci.log
Finish line. Done means: every repo in the spec has a PR open and green (never merged by the swarm), or is skipped with a reason, or paused with its novel failure logged, and the final report is written. Follow Read("../../shared/rules/long-run-protocol.md"): keep going when a step needs no input from the user, stop and ask only when you can't continue without them or before anything destructive, check each subagent's evidence before accepting it, and mark anything you couldn't confirm with where you looked.
Hard rules
- Never merge a PR. The swarm opens PRs; humans merge them. Auto-merge can be armed by the user with
gh pr merge --autopost-swarm if they want. - Never force-push. If a worker can't fast-forward, it pauses.
- Never roam outside the spec's declared
repos[]. Even if a transformation seems like it'd help elsewhere. - Always quarantine credentials. Workers run with the user's gh auth; the coordinator never logs tokens, just the URLs.
- Always respect existing branch protections. If
gh pr createfails because of required reviewers or other rules, that's a feature, not a bug to work around.
Failure modes you'll actually hit
| Mode | What it looks like | Mitigation |
|---|---|---|
| Stale lockfile | CI red on npm ci after dependency bump | Spec includes a post_transform.command: npm install step |
| Branch protection blocks PR creation | gh pr create exits non-zero | Coordinator marks repo blocked-by-protection, surfaces to user |
| Topology cycle | Phase 2 abort | Re-spec the upstream edges |
| Coordinator crash mid-flight | .swarm-state.json half-written | Skill is resumable: re-run with same spec, it reads the ledger and skips merged/green repos |
| Worker subagent hangs | No ledger update for >5 min | Coordinator times out the agent, marks repo worker-timeout, surfaces logs |
Related Skills
- Upstream —
brainstormto design the spec,visualize-planto ASCII-preview the DAG before dispatch. - Downstream —
verifyper repo after merge,/statusfor org-wide sweep,/ci-debugif a worker hits a CI red. - Composes with —
create-pr(each worker calls into it),github-operations(bulk-update labels/milestones post-swarm).
What this skill does NOT do
- Does not invent the spec. You write the spec; the skill executes it.
- Does not perform schema migrations across DBs (use a single-repo skill plus
database-patterns). - Does not orchestrate production deploys — open PRs only; deploy is a separate gate (the platform's deploy-operator).
- Does not bypass
create-pr's playground-gate rule — each PR body must include a playground reference if the repo enforces it.
Example invocation
# Dry-run: build the DAG, verify spec, do NOT push or open PRs
swarm-migrate swarm-specs/bump-actions-checkout-v4.yaml --dry-run
# Live: dispatch up to 4 workers in parallel
swarm-migrate swarm-specs/bump-actions-checkout-v4.yaml --max-parallel=4
# Resume after pause: same command, the ledger remembers
swarm-migrate swarm-specs/bump-actions-checkout-v4.yaml
Why this exists (one paragraph)
You ran 25 sessions in a single month coordinating cross-repo PRs by hand. The 14-repo @v1 workflow rollout, the M17 yg-mcp-core extraction, the M164 deploy-migration. Every one of those sessions had the same shape: a coordinator (you) holding the DAG in your head, dispatching workers (you, sequentially) in different terminal tabs, hand-rolling a status table in your notes. This skill makes the coordinator a YAML file and the workers parallel subagents. The DAG, the ledger, the auto-rebase, the wave gating — all the bookkeeping you were doing manually — get codified once. You write the spec, you walk away, you come back to a report.
UI Components
Patterns for building accessible UI component libraries with shadcn/ui and Radix Primitives, as a thin wrap over the first-party docs: quick-start recipes, key decisions, anti-patterns, and the house delta. Vendor mechanics (CVA variants, cn() utility, component extension, asChild composition, dialog/menu patterns, data-attribute styling) are upstream's job; see Upstream coverage (do not restate). Each remaining category has individual rule files in rules/ loaded on-demand.
Quick Reference
| Category | Rules | Impact | When to Use |
|---|---|---|---|
| shadcn/ui | 1 | HIGH | v4 styles, preset codes, style detection |
| Design System | 4 | HIGH | W3C tokens, OKLCH theming, spacing scales, typography, component states, animation |
| Design System Components | 1 | HIGH | Atomic design, CVA variants, accessibility, Storybook |
| Forms | 2 | HIGH | React Hook Form v7, Zod validation, Server Actions |
| Modern CSS & Tooling | 3 | HIGH | CSS cascade layers, Tailwind v4, Storybook CSF3 |
| UX Foundations | 4 | HIGH | Visual hierarchy, typography thresholds, color system, empty states |
Total: 15 rules across 6 categories. Radix primitive mechanics and shadcn customization tutorials are first-party documented; see Upstream coverage (do not restate) and references/ork-delta.md for what stays ours.
Quick Start
// CVA variant system with cn() utility
import { cva, type VariantProps } from 'class-variance-authority'
import { cn } from '@/lib/utils'
const buttonVariants = cva(
'inline-flex items-center justify-center rounded-md font-medium transition-colors',
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground hover:bg-primary/90',
destructive: 'bg-destructive text-destructive-foreground',
outline: 'border border-input bg-background hover:bg-accent',
ghost: 'hover:bg-accent hover:text-accent-foreground',
},
size: {
default: 'h-10 px-4 py-2',
sm: 'h-9 px-3',
lg: 'h-11 px-8',
},
},
defaultVariants: { variant: 'default', size: 'default' },
}
)
// Radix Dialog with asChild composition
import { Dialog } from 'radix-ui'
<Dialog.Root>
<Dialog.Trigger asChild>
<Button>Open</Button>
</Dialog.Trigger>
<Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 bg-black/50" />
<Dialog.Content className="data-[state=open]:animate-in">
<Dialog.Title>Title</Dialog.Title>
<Dialog.Description>Description</Dialog.Description>
<Dialog.Close>Close</Dialog.Close>
</Dialog.Content>
</Dialog.Portal>
</Dialog.Root>
shadcn/ui
Beautifully designed, accessible components built on CVA variants, cn() utility, and OKLCH theming.
| Rule | File | Key Pattern |
|---|---|---|
| v4 Styles | rules/shadcn-v4-styles.md | 6 styles (Vega→Luma), preset codes, style detection, class mapping |
Customization, form, and data-table walkthroughs are upstream's job now; see Upstream coverage (do not restate). Our conventions on top of them live in references/ork-delta.md.
v4 Style System
shadcn CLI v4 ships 6 visual styles. Each rewrites component class names — not just CSS variables.
| Style | Character | Best For |
|---|---|---|
| Vega | Balanced radius, clean lines | General purpose (successor to New York) |
| Nova | Compact padding, reduced margins | Dense dashboards, admin panels |
| Maia | Soft, rounded, generous spacing | Consumer-facing, friendly apps |
| Lyra | Sharp, zero radius, monospace pairs | Editorial, developer tools |
| Mira | Ultra-compact, minimal chrome | Spreadsheets, data-heavy interfaces |
| Luma | Extreme rounding (rounded-4xl), soft elevation (shadow-md + ring), breathable layouts | Polished native-app feel, macOS Tahoe-inspired |
Configure visually at ui.shadcn.com/create → pick style, theme, fonts, icons, then copy the generated command. Do not hardcode preset codes in docs — they're tied to a specific style snapshot and can drift.
shadcn CLI v4 (Apr 2026) — new commands
| Command | Purpose |
|---|---|
npx shadcn@latest apply <style> | Apply a published style (e.g. luma, nova, lyra) to the current project — re-skins existing components without re-adding them |
npx shadcn@latest info | Show resolved config: registry, style, tokens, components present, Tailwind version |
npx shadcn@latest skills | List the shadcn/skills registry — Claude Code- and Cursor-ready skill packs that bundle CLI commands with agent guidance |
npx shadcn@latest build | Build a custom registry (already-documented) — pair with apply to ship a private style |
Detection: Read components.json → "style" field (e.g., "radix-luma", "base-nova"). Old "new-york" and "default" styles are superseded by Vega.
Key Decisions
| Decision | Recommendation |
|---|---|
| Color format | OKLCH for perceptually uniform theming |
| Class merging | Always use cn() for Tailwind conflicts |
| Extending components | Wrap, don't modify source files |
| Variants | Use CVA for type-safe multi-axis variants |
| Styling approach | Data attributes + Tailwind arbitrary variants |
| Composition | Use asChild to avoid wrapper divs |
| Animation | CSS-only with data-state selectors |
| Form components | Combine with react-hook-form |
| Destructive confirmations | AlertDialog, never plain Dialog (see references/ork-delta.md) |
Anti-Patterns (FORBIDDEN)
- Modifying shadcn source: Wrap and extend instead of editing generated files
- Skipping cn(): Direct string concatenation causes Tailwind class conflicts
- Inline styles over CVA: Use CVA for type-safe, reusable variants
- Wrapper divs: Use
asChildto avoid extra DOM elements - Missing Dialog.Title: Every dialog must have an accessible title
- Positive tabindex: Using
tabindex > 0disrupts natural tab order - Color-only states: Use data attributes + multiple indicators
- Manual focus management: Use Radix built-in focus trapping
Upstream coverage (do not restate)
These topics were removed from this skill on 2026-07-31 because a first-party source owns them. Point sessions at the source; keep only floors, scars, and house decisions here (they live in references/ork-delta.md).
| Topic | First-party source |
|---|---|
| shadcn setup, init checklist, adding components | vercel:shadcn (marketplace skill), https://ui.shadcn.com/docs/installation |
| shadcn customization, CVA variants, cn() utility, component extension | vercel:shadcn (marketplace skill), https://ui.shadcn.com/docs and https://cva.style/docs |
| OKLCH theming variables, light/dark CSS variable sets | https://ui.shadcn.com/docs/theming |
| Dark mode toggle with next-themes | https://ui.shadcn.com/docs/dark-mode and https://github.com/pacocoursey/next-themes |
| Data table with TanStack Table | https://ui.shadcn.com/docs/components/data-table and https://tanstack.com/table |
| Form field wrappers and validation states | https://ui.shadcn.com/docs/components/form |
| Radix Dialog and AlertDialog patterns | https://www.radix-ui.com/primitives/docs/components/dialog and .../components/alert-dialog |
| Radix asChild / Slot composition | https://www.radix-ui.com/primitives/docs/guides/composition |
| Radix data-attribute styling and focus management | https://www.radix-ui.com/primitives/docs/guides/styling |
| Dropdown menu, popover, tooltip, hover card | https://www.radix-ui.com/primitives/docs/components/dropdown-menu (and sibling component pages) |
| Radix accessibility audit checklist | https://www.radix-ui.com/primitives/docs/overview/accessibility plus ork-extras:accessibility |
Detailed Documentation
| Resource | Description |
|---|---|
| scripts/ | Templates: CVA component, extended button, dialog, dropdown, theme CSS |
| references/ork-delta.md | Ork floors, scars, and house decisions kept out of upstream docs |
Design System
Design token architecture, spacing, typography, and interactive component states.
| Rule | File | Key Pattern |
|---|---|---|
| Token Architecture | rules/design-system-tokens.md | W3C tokens, OKLCH colors, Tailwind @theme |
| Spacing Scale | rules/design-system-spacing.md | 8px grid, Tailwind space-1 to space-12 |
| Typography Scale | rules/design-system-typography.md | Font sizes, weights, line heights |
| Component States | rules/design-system-states.md | Hover, focus, active, disabled, loading, animation presets |
Design System Components
Component architecture patterns with atomic design and accessibility.
| Rule | File | Key Pattern |
|---|---|---|
| Component Architecture | rules/design-system-components.md | Atomic design, CVA variants, WCAG 2.1 AA, Storybook |
Forms
React Hook Form v7 with Zod validation and React 19 Server Actions.
| Rule | File | Key Pattern |
|---|---|---|
| React Hook Form | rules/forms-react-hook-form.md | useForm, field arrays, Controller, wizards, file uploads |
| Zod & Server Actions | rules/forms-validation-zod.md | Zod schemas, Server Actions, useActionState, async validation |
Modern CSS & Tooling
Modern CSS patterns, Tailwind v4, and component documentation tooling for 2026.
| Rule | File | Key Pattern |
|---|---|---|
| CSS Cascade Layers | rules/css-cascade-layers.md | @layer ordering, specificity-free overrides, third-party isolation |
| Tailwind v4 | rules/tailwind-v4-patterns.md | CSS-first @theme, native container queries, @max-* variants |
| Storybook Docs | rules/storybook-component-docs.md | CSF3 stories, play() interaction tests, Chromatic visual regression |
UX Foundations
Cognitive-science-grounded UI/UX principles with specific numeric thresholds for production-quality interfaces.
| Rule | File | Key Pattern |
|---|---|---|
| Visual Hierarchy | rules/visual-hierarchy.md | Button tiers, de-emphasis, F/Z scan, Von Restorff, proximity, max-width |
| Typography Thresholds | rules/typography-thresholds.md | 65ch line length, 1.4–1.6 line height, rem units, modular type scale |
| Color System | rules/color-system.md | OKLCH 9-shade scales, semantic categories, no true black, brand-tinted neutrals |
| Empty States | rules/empty-states.md | Skeleton-first, icon + headline + description + CTA, cause-specific tone |
Related Skills
ork-extras:accessibility- WCAG compliance and React Aria patternsork:testing-unit- Component testing patterns
Vite Advanced Patterns
A wrapper around Vite 8 (Rolldown-powered), not a copy of its documentation. Vite's own docs are the source of truth for config keys, API surface, and migration mechanics. This skill carries the house delta plus four enforceable rules.
Vite 8 replaces the esbuild+Rollup pipeline with Rolldown (Rust-based unified
bundler) and is the default for new projects. advancedChunks supersedes
manualChunks; build.rollupOptions becomes build.rolldownOptions.
Upstream coverage (do not restate)
Fetch these from Vite rather than expecting them here. Rows marked with a rule keep a narrower, enforceable house subset in that rule file: read the rule for the house position, fetch the doc for the full API.
| Topic | Fetch from |
|---|---|
Vite 7 to 8 migration: rolldownOptions, transformWithOxc, moduleType: 'js', removed hooks and output formats, browser target bumps | https://vite.dev/guide/migration |
Rolldown adoption path, rolldown-vite, Oxc, advancedChunks group syntax (house subset stays in rules/vite-advanced-chunks.md) | https://vite.dev/guide/rolldown |
Build options: target, minify, sourcemap, cssCodeSplit, cssMinify, assetsInlineLimit, chunkSizeWarningLimit | https://vite.dev/config/build-options |
Dependency pre-bundling and optimizeDeps include/exclude/force | https://vite.dev/guide/dep-pre-bundling |
| SSR: client and server entry points, middleware-mode dev server, production server wiring, streaming | https://vite.dev/guide/ssr |
Environment API config and per-environment build output (house subset stays in rules/vite-environments.md) | https://vite.dev/guide/api-environment |
Environment API for plugins: this.environment, perEnvironmentPlugin, applyToEnvironment | https://vite.dev/guide/api-environment-plugins |
Environment API for frameworks: createBuilder, buildApp, ModuleRunner | https://vite.dev/guide/api-environment-frameworks |
Plugin hook reference, virtual modules, enforce/apply, handleHotUpdate (house subset stays in rules/vite-plugin-hooks.md) | https://vite.dev/guide/api-plugin |
Env variables and modes, .env files, the VITE_ prefix | https://vite.dev/guide/env-and-mode |
Deploying a static site and verifying with vite preview | https://vite.dev/guide/static-deploy |
Library mode is not in the table: references/library-mode.md and
rules/vite-lib-config.md still carry it in full.
House delta
Read references/ork-delta.md for the rules Vite's docs do not
state: the Vite 8 adoption path for existing production apps, the VITE_ secrets
rule, the production sourcemap setting, the house build budget, the vite preview
gate, chunk-name stability across the advancedChunks migration, the visualizer
diff requirement, and the node_modules/.vite cache-clearing step.
House config
Not a Vite tutorial: these are the settings the delta above makes non-negotiable, in the shape we actually ship them.
// vite.config.ts
import { defineConfig } from 'vite';
export default defineConfig({
build: {
// 'hidden' emits maps for the error reporter without publishing source.
// Never true (publishes source) and never 'inline' (inflates every JS file).
sourcemap: 'hidden',
rollupOptions: {
output: {
// Carry existing chunk NAMES across the manualChunks to advancedChunks
// migration. A renamed group changes its filename and invalidates that
// chunk for every returning visitor, even with identical contents.
advancedChunks: {
groups: [
{ name: 'vendor', test: /node_modules/, priority: 10 },
{ name: 'app', priority: 0 },
],
},
},
},
},
});
# Prove the build. `vite build` exiting 0 means the bundler finished, not that the
# app runs: base-path mistakes and dev-only env vars survive a green build.
vite build && vite preview # then walk the routes, console must be clean
# Diff the chunk graph before and after any chunk-config change.
npx vite-bundle-visualizer
# Stale pre-bundle cache mimics a broken plugin. Clear it BEFORE editing plugin code.
rm -rf node_modules/.vite && vite --force
VITE_-prefixed variables are inlined into the client bundle at build time. They are public bundle content, never secrets. Audit.env.productionbefore deploy.
Rules
| Rule | Covers |
|---|---|
rules/vite-advanced-chunks.md | Chunk splitting: advancedChunks groups, priority, maxSize, minShareCount |
rules/vite-environments.md | environments config for client, SSR, and edge; per-environment outDir |
rules/vite-lib-config.md | Library mode externals, dual ESM/CJS output, exports map, type declarations |
rules/vite-plugin-hooks.md | Hook order, virtual modules via resolveId + load, enforce and apply |
Key Decisions
| Decision | Recommendation |
|---|---|
| New projects | Vite 8 (default) |
| Existing production apps | Stage the upgrade through rolldown-vite before committing |
| Multi-env builds | Environment API (environments config) |
| Plugin scope | Use this.environment for env-aware plugins |
| SSR | Middleware mode for dev, separate builds for prod |
| Chunks | advancedChunks for Vite 8, manualChunks for Vite 7 compat |
Related Skills
ork:react-server-components-framework- SSR integrationork-extras:storybook-testing- Component testing with Vitestork:performance- Core Web Vitals targets behind the build budget
References
Load on demand with Read("references/<file>"):
| File | Content |
|---|---|
ork-delta.md | House rules that Vite's docs do not state |
library-mode.md | Building publishable npm packages |
Zustand Patterns
Modern state management with Zustand 5.x - lightweight, TypeScript-first, no boilerplate.
Overview
- Global state without Redux complexity
- Shared state across components without prop drilling
- Persisted state with localStorage/sessionStorage
- Computed/derived state with selectors
- State that needs middleware (logging, devtools, persistence)
Upstream coverage (do not restate)
Zustand's own docs are the source for the mechanics. This skill carries only the OrchestKit delta
on top of them, in references/ork-delta.md, the rules/ files, and the checklist.
Quick Reference
// ✅ Create typed store with double-call pattern
const useStore = create<State>()((set, get) => ({ ... }));
// ✅ Use selectors for all state access
const count = useStore((s) => s.count);
// ✅ Use useShallow for multiple values (Zustand 5.x)
const { a, b } = useStore(useShallow((s) => ({ a: s.a, b: s.b })));
// ✅ Middleware order: immer → subscribeWithSelector → devtools → persist
create(persist(devtools(immer((set) => ({ ... })))))
// ❌ Never destructure entire store
const store = useStore(); // Re-renders on ANY change
// ❌ Never store server state (use TanStack Query instead)
const useStore = create((set) => ({ users: [], fetchUsers: async () => ... }));
Key Decisions
| Decision | Option A | Option B | Recommendation |
|---|---|---|---|
| State structure | Single store | Multiple stores | Slices in single store - easier cross-slice access |
| Nested updates | Spread operator | Immer middleware | Immer for deeply nested state (3+ levels) |
| Persistence | Manual localStorage | persist middleware | persist middleware with partialize |
| Multiple values | Multiple selectors | useShallow | useShallow for 2-5 related values |
| Server state | Zustand | TanStack Query | TanStack Query - Zustand for client-only state |
| DevTools | Always on | Conditional | Conditional - enabled: process.env.NODE_ENV === 'development' |
Anti-Patterns & Integration
Forbidden patterns (store destructuring, derived state, server state, direct mutation) and React Query integration guidance.
Load Read("references/anti-patterns-and-integration.md") for anti-pattern examples and TanStack Query separation patterns.
Related Skills
react-server-components-framework- RSC hydration considerations with Zustand- Server state: https://tanstack.com/query/latest/docs/framework/react/guides/does-this-replace-client-state
- Form state: https://react-hook-form.com/docs/useform
Capability Details
store-creation
Keywords: zustand, create, store, typescript, state Solves: Setting up type-safe Zustand stores with proper TypeScript inference
slices-pattern
Keywords: slices, modular, split, combine, StateCreator Solves: Organizing large stores into maintainable, domain-specific slices
middleware-stack
Keywords: immer, persist, devtools, middleware, compose Solves: Combining middleware in correct order for immutability, persistence, and debugging
selector-optimization
Keywords: selector, useShallow, re-render, performance, memoization Solves: Preventing unnecessary re-renders with proper selector patterns
persistence-migration
Keywords: persist, localStorage, sessionStorage, migrate, version Solves: Persisting state with schema migrations between versions
References
Load on demand with Read("references/<file>"):
| File | Content |
|---|---|
ork-delta.md | OrchestKit-specific rules: the corrected zustand/shallow label, the v5 floor, secret handling, graded slice typing |
anti-patterns-and-integration.md | Forbidden patterns and React Query integration |
Other resources:
- Load:
Read("scripts/store-template.ts")- Production-ready store template - Load:
Read("checklists/zustand-checklist.md")- Implementation checklist
Sponsors
Details
- Marketplace
- yonatangross/orchestkit
- Source
- plugins/ork-extras
- Author
- Yonatan Gross
- Category
- Development