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@orchestkit

Run it inside Claude Code after adding the marketplace with /plugin marketplace add yonatangross/orchestkit.

Contents

Discovered from source

Skills 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

CategoryRulesImpactWhen to Use
WCAG Compliance3CRITICALColor contrast, semantic HTML, automated testing
POUR Exit Criteria1CRITICALFalsifiable pass/fail thresholds for each WCAG 2.2 AA criterion
Static Anti-Patterns1HIGHGrep-able patterns detectable without a browser
Focus Management1HIGHKeyboard navigation; trap/restoration mechanics live upstream
React Aria2HIGHAccessible components and form hooks; overlay APIs live upstream
Modern Web Accessibility2CRITICAL/HIGHNative 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.

RuleFileKey Pattern
Color Contrastrules/wcag-color-contrast.md4.5:1 text, 3:1 UI components, focus indicators
Semantic HTMLrules/wcag-semantic-html.mdLandmarks, headings, ARIA labels, form structure
Testingrules/wcag-testing.mdaxe-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.

RuleFileKey Pattern
POUR Exit Criteriarules/pour-exit-criteria.mdFalsifiable 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.

RuleFileKey Pattern
A11y Anti-Patterns (Static)rules/a11y-antipatterns-static.mdFocus removal, missing labels, autoplay, icon-only buttons, div-click handlers

Focus Management

Keyboard focus management patterns for accessible interactive widgets.

RuleFileKey Pattern
Keyboard Navigationrules/focus-keyboard-nav.mdRoving 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.

RuleFileKey Pattern
Componentsrules/aria-components.mduseButton, useDialog, useMenu, FocusScope
Formsrules/aria-forms.mduseComboBox, 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.

RuleFileKey Pattern
Native HTML Firstrules/wcag-native-html-first.md<dialog>, <details>, native over custom ARIA
User Preferencesrules/wcag-user-preferences.mdprefers-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

DecisionRecommendation
Conformance levelWCAG 2.2 AA (legal standard: ADA, Section 508)
Contrast ratio4.5:1 normal text, 3:1 large text and UI components
Target size24px min (WCAG 2.5.8), 44px for touch
Focus indicator3px solid outline, 3:1 contrast
Component libraryReact Aria hooks for control, react-aria-components for speed
State managementreact-stately hooks (designed for a11y)
Focus managementFocusScope for modals, roving tabindex for widgets
Testingjest-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> or aria-label
  • Keyboard traps: Focus that cannot escape without Escape key
  • Removing focus outline: outline: none without replacement indicator
  • Positive tabindex: Using tabindex > 0 (disrupts natural order)
  • Div with onClick: Using <div onClick> instead of <button> or useButton
  • Manual focus in modals: Using useEffect + ref.focus() instead of FocusScope
  • 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.

TopicFirst-party source
WCAG 2.2 success-criterion walkthroughs and audit checklistsWCAG 2.2 quick reference and WCAG 2.2 spec
ARIA widget patterns and keyboard interaction modelsWAI-ARIA Authoring Practices Guide
React Aria hook APIs (useButton, useMenu, useComboBox, useModalOverlay, useTooltip, usePopover), component checklists, worked examplesReact Aria docs
Focus trap, focus restoration, roving tabindex, and skip-link algorithmsReact 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

ResourceDescription
scripts/Templates: accessible form, focus trap, React Aria components
references/ork-delta.mdOrk-specific floors, scars, and house decisions (cognitive ceilings, overlay recipe, canonical focus-trap selector)
references/ux-thresholds-quick.mdUI/UX thresholds quick reference: contrast, touch targets, cognitive load, typography, forms
examples/wcag-examples.mdComplete accessible form, modal, and navigation examples

Related Skills

  • ork:testing-e2e - E2E testing patterns including accessibility testing
  • design-system-starter - Accessible component library patterns
  • ork-extras:i18n-date-patterns - RTL layout and locale-aware formatting
  • motion-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 /workflows for 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 AskUserQuestion the 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

CategoryRulesImpactWhen to Use
Agent LoopsupstreamHIGHReAct reasoning, plan-and-execute, self-correction
Multi-Agent Coordination2CRITICALSupervisor routing, agent debate, result synthesis
Alternative FrameworksupstreamHIGHCrewAI crews, AutoGen teams, framework comparison
Multi-Scenario2MEDIUMParallel 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.

TopicFirst-party source
ReAct / plan-and-execute / self-correction loop implementationsOpenAI 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 checklistPython 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 integrationsOpenAI model docs (https://platform.openai.com/docs/models)
Multi-scenario state machine, architecture and skill-agnostic template deep-divesSuperseded 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 tutorials
  • references/framework-comparison.md - Condensed framework decision matrix and use-case table
  • references/langgraph-implementation.md - LangGraph 1.2+ implementation of the multi-scenario orchestrator
  • references/claude-code-instance-management.md - Running 3 parallel Claude Code instances for scenario demos

Key Decisions

DecisionRecommendation
Single vs multi-agentSingle for focused tasks, multi for decomposable work
Max loop steps5-15 (prevent infinite loops)
Agent count3-8 specialists per workflow
FrameworkMatch to team expertise + use case
TopologyAgent tool (star) for simple; Agent Teams (mesh) for complex; Workflow for large background fan-out
Scenario countAlways 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 agents rows now show done/total for fanned-out work.
    • Note (CC 2.1.157): claude agents honors the agent field in settings.json for dispatched sessions; --agent <name> overrides it — pin the agent type explicitly when dispatching.
  • 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 execution
  • ork: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

CategoryRulesImpactWhen to Use
json-render Integration1HIGHMulti-surface output, MCP visual output, type-safe catalogs
Prompt Engineering2HIGHWriting prompts for component generation
Quality Assurance2CRITICAL/HIGHReviewing and gating AI-generated code
Design System Integration2HIGHInjecting tokens, refactoring for conformance
Tool Selection & Workflow2MEDIUMChoosing 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

ScenarioToolWhy
Multi-surface / MCP visual outputjson-renderSingle catalog renders to any surface — FIRST CHOICE
Type-safe component catalogjson-renderSchema-driven specs with per-platform registries
Streaming UI from AI agentsjson-renderStructured JSON specs render progressively
New component from scratchv0.appFull scaffold with shadcn/ui, Tailwind, a11y. Pair with shadcn apply <style> for style consistency
Full-stack app with deployv0.appJan 2026 expansion — routes, DB, auth, Vercel/Cloudflare deploy in one generation
Design-driven (screenshot/URL/DESIGN.md)Google Stitchgenerate_screen_from_text (once; no retry) + get_screen(name="projects/{project}/screens/{screen}")
Multi-screen flow from a visual sourceGoogle StitchStrongest when grounded in an existing design
Full-stack prototype with persistent backendBolt CloudCloud dev env, GitHub integration, databases
Incremental change in existing codebaseCursorUnderstands project context, imports, tokens
Refactor existing componentCursorReads surrounding code, respects conventions
Explore visual design variationsv0.app or Stitchv0.app for freeform, Stitch when grounded in a reference
Add feature to running appBolt CloudCloud preview, full environment, persists between sessions
Fix bug in existing componentCursorInline 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.

RuleFileKey Pattern
json-render Patternsrules/json-render-patterns.mdCatalog-first: define once, render anywhere via per-platform registries

Prompt Engineering

Structured prompts that specify framework, tokens, a11y, and states upfront.

RuleFileKey Pattern
Prompt Patternsrules/ai-prompt-patterns.mdConstraint-first prompts with framework, tokens, a11y
Iteration Patternsrules/ai-iteration-patterns.mdMulti-pass prompts for complex interactive states

Quality Assurance

Systematic review and CI gating for AI-generated components.

RuleFileKey Pattern
Review Checklistrules/ai-review-checklist.md10-point checklist for every AI-generated component
CI Gaterules/ai-ci-gate.mdAutomated quality gates before merge

Design System Integration

Ensuring AI output uses design tokens and conforms to the design system.

RuleFileKey Pattern
Token Injectionrules/ai-token-injection.mdPass token names in prompts, reject hardcoded values
Refactoring Conformancerules/ai-refactoring-conformance.mdSteps to refactor raw AI output for design system

Tool Selection & Workflow

Choosing the right AI tool and iterating effectively.

RuleFileKey Pattern
Tool Selectionrules/ai-tool-selection.mdMatch tool to use case: v0, Bolt, Cursor
Iteration Patternsrules/ai-iteration-patterns.mdIterative refinement for complex states

Key Principles

  1. Own the output — AI generates a draft; the engineer reviews, refactors, and is accountable for what ships.
  2. Tokens over literals — Never accept hardcoded colors, spacing, or typography values. Always map to design tokens.
  3. Constraint-first prompts — Specify framework, tokens, shadcn style (Luma/Nova/etc.), a11y, and states upfront. Vague prompts produce vague output.
  4. Iterative refinement — Complex components need 2-3 prompt passes: structure first, states second, polish third.
  5. CI is non-negotiable — Every AI-generated component goes through the same CI pipeline as hand-written code.
  6. 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

ResourceDescription
references/ai-ui-tool-comparison.mdjson-render vs v0 vs Bolt vs Cursor vs Copilot comparison
references/prompt-templates-library.mdCopy-paste prompt templates for common components
references/ai-ui-failure-modes.mdTop 10 failure modes and fixes

Related Skills

  • ork:json-render-catalog — json-render catalog authoring, schema validation, and registry patterns
  • ork:mcp-visual-output — MCP visual output rendering with json-render specs
  • ork:multi-surface-render — Cross-platform rendering from a single component catalog
  • ork-extras:ui-components — shadcn/ui component patterns and CVA variants
  • ork-extras:accessibility — WCAG compliance, ARIA patterns, screen reader support
  • ork-extras:animation-motion-design — Motion library animation patterns
  • ork-extras:responsive-patterns — Responsive layout and container query patterns
  • ork: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

RuleFileImpactWhen to Use
Layout Animationsrules/motion-layout.mdHIGHShared layout transitions, FLIP animations, layoutId
Gesture Interactionsrules/motion-gestures.mdHIGHDrag, hover, tap with spring physics
Exit Animationsrules/motion-exit.mdHIGHAnimatePresence, unmount transitions
View Transitions APIrules/view-transitions-api.mdHIGHPage navigation, cross-document transitions
Motion Accessibilityrules/motion-accessibility.mdCRITICALprefers-reduced-motion, cognitive load
Motion Performancerules/motion-performance.mdHIGH60fps, GPU compositing, layout thrash

Total: 6 rules across 3 categories

Decision Table — Motion vs View Transitions API

ScenarioRecommendationWhy
Component mount/unmountMotionAnimatePresence handles lifecycle
Page navigation transitionsView Transitions APIBuilt-in browser support, works with any router
Complex interruptible animationsMotionSpring physics, gesture interruption
Simple crossfade between pagesView Transitions APIZero JS bundle cost
Drag/reorder interactionsMotiondrag prop with layout animations
Shared element across routesView Transitions APIviewTransitionName CSS property
Scroll-triggered animationsMotionuseInView, useScroll hooks
Multi-step orchestrated sequencesMotionstaggerChildren, 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

  1. 60fps or nothing — Only animate transform and opacity (composite properties). Never animate width, height, top, or left.
  2. Centralized presets — Define animation variants in a shared file, not inline on every component.
  3. AnimatePresence for exits — React unmounts instantly; wrap with AnimatePresence to animate out.
  4. Spring over duration — Springs feel natural and are interruptible. Use stiffness/damping, not duration.
  5. Respect user preferences — Always check prefers-reduced-motion and provide instant alternatives.

Performance Budget

MetricTargetMeasurement
Transition duration< 400msUser perception threshold
Animation propertiestransform, opacity onlyDevTools > Rendering > Paint flashing
JS bundle (Motion)~16KB gzippedImport only what you use
First paint delay0msAnimations must not block render
Frame drops< 5% of framesPerformance API: PerformanceObserver

Anti-Patterns (FORBIDDEN)

  • Animating layout properties — Never animate width, height, margin, padding directly. Use transform: 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, not duration. Mixing causes unexpected behavior.
  • Synchronous startViewTransition — Always await or handle the promise from document.startViewTransition().

Detailed Documentation

ResourceDescription
references/motion-vs-view-transitions.mdComparison table, browser support, limitations
references/animation-presets-library.mdCopy-paste preset variants for common patterns
references/micro-interactions-catalog.mdButton press, toggle, checkbox, loading, success/error

Related Skills

  • ork-extras:ui-components — shadcn/ui component patterns and CVA variants
  • ork-extras:responsive-patterns — Responsive layout and container query patterns
  • ork:performance — Core Web Vitals and runtime performance optimization
  • ork-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

TopicWhere our part lives
Configurationreferences/celery-config.md, rules/jobs-task-queue.md
Task Routingreferences/ork-delta.md (queue taxonomy, prefetch tiers, Redis priority)
Canvas Workflowsrules/celery-canvas.md
Retry Strategiesreferences/ork-delta.md (backoff cap, idempotency layers, lock TTLs)
Schedulingrules/jobs-scheduling.md, references/ork-delta.md (beat process model)
Monitoringreferences/ork-delta.md (alert thresholds, histogram buckets)
Result Backendsrules/jobs-monitoring.md, references/ork-delta.md (return contract)
ARQ Patternsrules/jobs-task-queue.md, references/ork-delta.md (budgets, pool ownership)
Temporal Workflowsrules/temporal-workflows.md
Temporal Activitiesrules/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.

TopicFirst-party sourceHouse subset stays in
Celery settings, serializers, time limits, worker flagshttps://docs.celeryq.dev/en/stable/userguide/configuration.html and .../optimizing.htmlreferences/celery-config.md, rules/jobs-task-queue.md
Queue declarations, router classes, Redis priority mechanicshttps://docs.celeryq.dev/en/stable/userguide/routing.htmlreferences/ork-delta.md
chain / group / chord / signature semanticshttps://docs.celeryq.dev/en/stable/userguide/canvas.htmlrules/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 classeshttps://docs.celeryq.dev/en/stable/userguide/tasks.htmlreferences/ork-delta.md, rules/jobs-task-queue.md
Beat schedules, crontab syntax, DatabaseSchedulerhttps://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 nameshttps://docs.celeryq.dev/en/stable/userguide/monitoring.html, https://docs.celeryq.dev/en/stable/userguide/signals.html, https://flower.readthedocs.io/en/latest/config.htmlreferences/ork-delta.md
Result backend, AsyncResult, custom stateshttps://docs.celeryq.dev/en/stable/userguide/configuration.htmlrules/jobs-monitoring.md keeps our status endpoints and update_state() usage
Per-task rate_limit, control.rate_limit, Redis Luahttps://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 statushttps://arq-docs.helpmanual.io/rules/jobs-task-queue.md keeps the worker skeleton; references/ork-delta.md keeps the budgets
FastAPI lifespan and dependency wiringhttps://fastapi.tiangolo.com/advanced/events/references/ork-delta.md
Distributed locks with SET NX EXhttps://redis.io/docs/latest/commands/set/references/ork-delta.md

Configuration

Load: Read("references/celery-config.md").

DecisionRecommendation
SerializerJSON (never pickle)
Ack modeLate ack (task_acks_late=True)
Prefetch1 for fair, 4-8 for throughput
Time limitsoft < hard (540 / 600)
TimezoneUTC always

Task Routing

DecisionRecommendation
Queue count5: critical / high / default / low / bulk
Priority levels0-9, with all four Redis priority switches set together
Worker assignmentDedicated worker per queue
Prefetch1 critical, 2 high, 4 default, 8 low/bulk
RoutingRouter class once past 5 routing rules

Canvas Workflows

Load: Read("rules/celery-canvas.md").

DecisionRecommendation
SequentialChain with s()
ParallelGroup for independent tasks
Fan-inChord (all header tasks must succeed for the body to run)
Ignore inputUse si() immutable signature
Error in chainReject stops the chain, retry continues it
Partial failuresReturn an error dict from chord header tasks

Retry Strategies

DecisionRecommendation
Retry delayExponential backoff, jitter on, capped at 600s
Max retries3-5 for transient, 0 for permanent
IdempotencyRedis marker (86400s TTL) plus the vendor idempotency key
Failed tasksDLQ for manual review
SingletonRedis lock with a TTL longer than the hard time limit

Scheduling

Load: Read("rules/jobs-scheduling.md").

DecisionRecommendation
Schedule typeCrontab for time-based, float interval for frequency
DynamicDatabaseScheduler (django-celery-beat)
OverlapRedis lock, 3600s default and 7200s for long jobs
Beat processSeparate process; embedded --beat is development only
TimezoneUTC always

Monitoring

DecisionRecommendation
DashboardFlower with persistent storage
MetricsPrometheus wired to task_prerun / task_postrun / task_failure
HealthBroker reachable, at least one worker, queue depths
Alertingcritical > 100, default > 5000, workers < 1
AutoscaleQueue depth > 500

Result Backends

Load: Read("rules/jobs-monitoring.md").

DecisionRecommendation
Status storageRedis result backend, status and small JSON only
Large resultsS3 or database, task returns a reference dict
ProgressCustom states with update_state()
Result queryAsyncResult with state checks

ARQ Patterns

Load: Read("rules/jobs-task-queue.md").

DecisionRecommendation
Simple asyncARQ (native async), max_jobs=10, job_timeout=300
Pool ownershipFastAPI lifespan, never a per-request create_pool
Complex workflowsCelery (chains, chords, DLQ, per-task rate limits)
In-process quickFastAPI BackgroundTasks, under 30s, non-critical only
LLM workflowsLangGraph, 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").

DecisionRecommendation
Workflow IDBusiness-meaningful, idempotent
DeterminismUse workflow.random(), workflow.now()
I/OAlways via activities, never directly

Temporal Activities

Load: Read("rules/temporal-activities.md").

DecisionRecommendation
Activity timeoutstart_to_close for most cases
Error handlingNon-retryable for business errors
TestingWorkflowEnvironment.start_local() for integration tests

Related Skills

  • ork:python-backend - FastAPI, asyncio, SQLAlchemy patterns
  • ork-extras:langgraph - LangGraph workflow patterns (use for LLM workflows, not Celery)
  • ork-extras:distributed-systems - Resilience patterns, circuit breakers
  • ork-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. See docs/feat--activation-audit/.

Quick Reference

CategoryFileImpactWhen to Use
Activation Checksrules/activation-checks.mdHIGHWhat to compute per agent
Classificationrules/activation-status.mdHIGHfires / mis-triggered / niche / dead buckets
Output Formatreferences/output-format.mdMEDIUMReport 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

  1. 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 --json
    

    It 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.

  2. 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's agents/ next to it, and --catalog-root overrides). Do not point it at a consumer project's agent directory.

  3. Read telemetry — .claude/logs/subagent-spawns.jsonl carries pretool intent and start events. Triangulate it with the restored global ~/.claude/analytics/agent-usage.jsonl stop feed when available. The streams have no stable common event ID, so never add them together or infer unique spawns.

  4. Compute — all checks from Read("rules/activation-checks.md"); the Report Contract below lists the mandatory ones.

  5. Classify — bucket every agent using the Four Buckets below (full procedure: Read("rules/activation-status.md")).

  6. Render — output per Read("references/output-format.md"), satisfying the Report Contract.

Report Contract (every audit MUST include all six)

  1. Data-source line (first line of the report) — name scripts/run-activation-audit.sh, every explicit consumer .claude/logs/subagent-spawns.jsonl root, the UTC window, and the spawn coverage state (observed, missing, empty, or partial). State whether ~/.claude/analytics/agent-usage.jsonl was supplied as a stop feed. A report that presents numbers without these coverage facts is invalid.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.

BucketConditionAction
ACTIVEfired ≥1× in the telemetry windownone — it works
MIS-TRIGGEREDobserved zero starts, has references but no real subagent_type= spawn from a busy skillwire a spawn from a high-traffic skill
NICHEobserved zero starts, rare-by-nature domain (design, multimodal, perf, IaC, security-LLM) AND wired somewherekeep - low use expected
DEADobserved zero starts AND zero references in ANY skill or agentprune 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:start is started activation, and agent-usage.jsonl is 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 from
  • analytics — raw usage queries across projects
  • doctor — 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: max for 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 is medium (one level below Opus 5's high), and CC 2.1.280+ starts a newly released model at its default rather than an older saved /effort level. Run audits at high; use xhigh for one additional cross-file pattern sweep on the hardest codebases.

1M Context Required: If CLAUDE_CODE_DISABLE_1M_CONTEXT is 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 use verify for chunked analysis instead.

Effort (CC 2.1.111+): xhigh adds a second pass that re-reads cross-module boundaries specifically looking for patterns the first pass normalized over. Reserve xhigh for the hardest codebases (see the Opus 5.5 note above for the default). Silently falls back to high on other models; doctor warns on mismatch.

Switching to Opus (CC 2.1.144+): /model now affects the current session only — pick Opus for this audit without it persisting. Press d in 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 budgetTierPath
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 budgetMap-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:

  1. Data flow tracing: Track user input from entry point → processing → storage
  2. Auth boundary verification: Ensure all protected routes check auth
  3. Secret detection: Scan for hardcoded credentials, API keys, tokens
  4. Injection surfaces: SQL, command, template injection across file boundaries
  5. 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:

  1. Dependency direction: Verify imports flow inward (clean architecture)
  2. Circular dependencies: Detect import cycles across modules
  3. Layer violations: Business logic in controllers, DB in routes, etc.
  4. Pattern consistency: Same problem solved differently across codebase
  5. 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:

  1. Known CVEs: Check versions against known vulnerabilities
  2. License compliance: Identify copyleft licenses in proprietary code
  3. Version currency: Flag significantly outdated dependencies
  4. Transitive risk: Identify deep dependency chains
  5. 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:

  1. Security findings first — show critical/high vulnerabilities immediately, don't wait for architecture review
  2. Architecture findings — show dependency direction violations, circular deps as they surface
  3. 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

SituationUse Instead
Small targeted check (1-5 files)Direct Read + analysis
CI/CD automated scanningsecurity-scanning skill
Multi-agent graded verificationverify
Exploring unfamiliar codebaseexplore
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 explicit offset/limit to 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 classification
  • ork:architecture-patterns — Architectural pattern reference
  • ork:quality-gates — Quality assessment criteria
  • ork:verify — Multi-agent verification (fallback for codebases exceeding 1M context)

References

Load on demand with Read("references/<file>"):

FileContent
references/security-audit-guide.mdCross-file vulnerability patterns
references/architecture-review-guide.mdPattern and coupling analysis
references/dependency-audit-guide.mdCVE, license, currency checks
references/adversarial-refutation.mdBlind-refuter bindings (STEP 3.5), loads the engine copy below
references/adversarial-refutation-engine.mdByte copy of core's shared refutation engine, so the skill runs from ork-extras (a test keeps it equal)
references/push-notification-on-completion.mdByte copy of core's push-notification rule, same reason
references/token-estimation.mdFile type ratios and budget planning
assets/audit-report-template.mdStructured output format
assets/severity-matrix.mdFinding classification criteria
checklists/audit-completion.mdPre-report verification
scripts/estimate-tokens.shAutomated LOC to token estimation
workflows/audit-full-mapreduce.jsScale 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 -p call 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 TypeCommand Pattern
Gradingclaude -p "$prompt" --bare --max-turns 1 --output-format text
Triggerclaude -p "$prompt" --bare --json-schema "$schema" --output-format json
Streaming gradeclaude -p "$prompt" --bare --max-turns 1 --output-format stream-json
Optimizeecho "$prompt" | claude -p --bare --max-turns 1 --output-format text
Force-skillclaude -p "$prompt" --bare --print --append-system-prompt "$content"
@-file in promptclaude -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=1 for unattended eval batches: it raises the default retry count for non-capacity transient errors to 300 and lifts the cap of 15 on CLAUDE_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) and CLAUDE_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:

ConsequenceAction
Eval graders that relied on unrestricted tool access may now failAudit grader prompts for tools they actually need; whitelist explicitly via the agent's tools: frontmatter
Eval results match interactive runsReproducibility improves — grading what the model can actually do, not what it could do in an unsandboxed --print
--agent <name> also honors permissionMode in --printPermission-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:

InheritedSymptom
memory MCP query cachegrader sees stale hit from previous run; same fixture grades differently
.claude/chain/*.json on diskgrader for "implement" thinks "explore" already ran (file is from previous test)
ToolSearch deferred-tool cachefirst grader's MCP loads bleed into next grader's tool registry
model picker prefgrader 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

ScenarioWithout --bareWith --bareSavings
Single grading call~3-5s startup~0.5-1s2-4x
Trigger (per prompt)~3-5s~0.5-1s2-4x
Full eval (50 calls)~150-250s overhead~25-50s3-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:skill npm script — unified skill evaluation runner
  • eval:trigger — trigger accuracy testing
  • eval:quality — A/B quality comparison
  • optimize-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

RuleBlocksStill allowed
rm-rfrm 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-forcegit push --force, -f (also inside -uf), --force-with-lease[=...], a +branch refspec, to any branchgit push, git push -u origin <branch>
git-push-deletegit push origin --delete <b>, -d <b>, :<b>git push origin <b>:<b>
git-reset-hardgit reset --hardgit reset --soft, git reset HEAD <file>
sql-dropDROP TABLE, DROP DATABASE, DROP SCHEMA anywhere in the command, heredocs includeda SELECT that mentions drop
sql-truncateTRUNCATE TABLE, or a TRUNCATE <name> statement sent to a SQL clienttruncate -s 0 file.log
kubectl-deletekubectl ... deletekubectl get, kubectl logs
terraform-destroyterraform destroy, terraform apply -destroy, the same with tofuterraform 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', then nuke src);

  • scripts, Makefiles, npm scripts or binaries that run these commands inside (./deploy.sh, make clean, npm run reset-db);

  • eval or bash -c built 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 plain ssh 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 /usr is denied), but one made by the command itself is out of reach for a text check, like python -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.

RecipeUse when
elevation/sm md lgLayered neutral shadows — compact controls / cards / hero surfaces
glass/darkFrosted glass panel on a dark backdrop
border/gradient1px gradient border without a wrapper hack
background/mesh2–3 hue radial mesh page background
type/editorialDisplay + body + mono role split with tracking values
motion/budgetThe 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:

  1. Use when — one line, concrete surfaces ("cards, panels, popovers"), not adjectives.
  2. Values — copy-paste-ready code. Numbers, not descriptions.
  3. 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 apps
  • ork:design-system-tokens — where recipes graduate into project token architecture
  • ork: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

CategoryRulesImpactWhen to Use
Distributed Locks1CRITICALFencing tokens, owner validation; Redis/Redlock and Postgres advisory via upstream docs
Resilience3CRITICALCircuit breakers, retry with backoff, bulkhead isolation
Idempotency1HIGHIdempotency keys; dedup and database-backed storage via upstream docs
Rate Limiting2HIGHToken bucket, sliding window; SlowAPI integration via upstream docs
Edge Computing2HIGHEdge workers, V8 isolates, CDN caching, geo-routing
Event-Driven2HIGHEvent 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.

RuleFileKey Pattern
Fencing Tokensrules/locks-fencing-tokens.mdOwner 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.

RuleFileKey Pattern
Circuit Breakerrules/resilience-circuit-breaker.mdCLOSED/OPEN/HALF_OPEN states, sliding window
Retry & Backoffrules/resilience-retry-backoff.mdExponential backoff, jitter, error classification
Bulkhead Isolationrules/resilience-bulkhead.mdSemaphore tiers, rejection policies, queue depth

Idempotency

Ensure operations can be safely retried without unintended side effects.

RuleFileKey Pattern
Idempotency Keysrules/idempotency-keys.mdDeterministic 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.

RuleFileKey Pattern
Token Bucketrules/ratelimit-token-bucket.mdRedis Lua scripts, burst capacity, refill rate
Sliding Windowrules/ratelimit-sliding-window.mdSorted 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.

RuleFileKey Pattern
Edge Workersrules/edge-workers.mdV8 isolate constraints, Web APIs, geo-routing, auth at edge
Edge Cachingrules/edge-caching.mdCache-aside at edge, CDN headers, KV storage, stale-while-revalidate

Event-Driven

Event sourcing, CQRS, saga orchestration, and reliable messaging patterns.

RuleFileKey Pattern
Event Sourcingrules/event-sourcing.mdEvent-sourced aggregates, CQRS read models, optimistic concurrency
Event Messagingrules/event-messaging.mdTransactional 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.

TopicFirst-party source
Redis single-node locks, Redlock algorithm and quorumhttps://redis.io/docs/latest/develop/use/patterns/distributed-locks/
PostgreSQL advisory locks (session and transaction level)https://www.postgresql.org/docs/current/explicit-locking.html#ADVISORY-LOCKS
Circuit breaker pattern, thresholds, setup and rollout guideshttps://learn.microsoft.com/azure/architecture/patterns/circuit-breaker
Bulkhead pattern deep dive (thread pool, semaphore, tiers)https://learn.microsoft.com/azure/architecture/patterns/bulkhead
Retry strategies, exponential backoff, jitter, retry budgetshttps://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ and https://tenacity.readthedocs.io
HTTP and LLM provider error classification (retryable vs not)https://docs.claude.com/en/api/errors and https://platform.openai.com/docs/guides/error-codes
Idempotency keys, request dedup, database-backed idempotencyhttps://docs.stripe.com/api/idempotent_requests
Token bucket algorithm and Redis rate-limiting patternshttps://redis.io/glossary/rate-limiting/
FastAPI distributed rate limiting (SlowAPI middleware, tiers)https://slowapi.readthedocs.io/
LLM fallback chains, provider failover, cost trackinghttps://vercel.com/docs/ai-gateway; model ids and pricing at https://docs.claude.com/en/docs/about-claude/pricing

Key Decisions

DecisionRecommendation
Lock backendRedis for speed, PostgreSQL if already using it, Redlock for HA
Lock TTL2-3x expected operation time
Circuit breaker recoveryHalf-open probe with sliding window
Retry algorithmExponential backoff + full jitter
Bulkhead isolationSemaphore-based tiers (Critical/Standard/Optional)
Idempotency storageRedis (speed) + DB (durability), 24-72h TTL
Rate limit algorithmToken bucket for most APIs, sliding window for strict quotas
Rate limit storageRedis (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.

PatternInterviewHackathonMVPGrowthEnterpriseSimpler Alternative
Event sourcingOVERKILLOVERKILLOVERKILLOVERKILLWHEN JUSTIFIEDAppend-only table with status column
Saga orchestrationOVERKILLOVERKILLOVERKILLSELECTIVEAPPROPRIATESequential service calls with manual rollback
Circuit breakerOVERKILLOVERKILLBORDERLINEAPPROPRIATEREQUIREDTry/except with timeout
Distributed locksOVERKILLOVERKILLBORDERLINEAPPROPRIATEREQUIREDDatabase row-level lock (SELECT FOR UPDATE)
CQRSOVERKILLOVERKILLOVERKILLOVERKILLWHEN JUSTIFIEDSingle model for read/write
Transactional outboxOVERKILLOVERKILLOVERKILLSELECTIVEAPPROPRIATEDirect publish after commit
Rate limitingOVERKILLOVERKILLSIMPLE ONLYAPPROPRIATEREQUIREDNginx 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

ResourceDescription
scripts/Templates: lock implementations, circuit breaker, rate limiter
references/ork-delta.mdOrk-specific scars and house decisions kept after the wrap-plus-delta thinning

Related Skills

  • caching - Redis caching patterns, cache as fallback
  • background-jobs - Job deduplication, async processing with retry
  • observability-monitoring - Metrics and alerting for circuit breaker state changes
  • error-handling-rfc9457 - Structured error responses for resilience failures
  • auth-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

CategoryRuleImpactWhen to Use
README1HIGHStarting a project, onboarding contributors
ADR1HIGHRecording architecture decisions
API Docs1HIGHDocumenting REST APIs with OpenAPI 3.1
Changelog1MEDIUMMaintaining release history
Writing Style1MEDIUMAny 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 lifecycle
  • ork-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

DecisionRecommendation
Entity vs VOHas unique ID + lifecycle? Entity. Otherwise VO
Entity equalityBy ID, not attributes
Value object mutabilityAlways immutable (frozen=True)
Repository scopeOne per aggregate root
Domain eventsCollect in entity, publish after persist
Context boundariesBy business capability, not technical

Rules Quick Reference

RuleImpactWhat It Covers
aggregate-boundaries (load rules/aggregate-boundaries.md)HIGHAggregate root design, reference by ID, one-per-transaction
aggregate-invariants (load rules/aggregate-invariants.md)HIGHBusiness rule enforcement, specification pattern
aggregate-sizing (load rules/aggregate-sizing.md)HIGHRight-sizing, when to split, eventual consistency

When NOT to Use

Under 5 entities? Skip DDD entirely. The ceremony costs more than the benefit.

PatternInterviewHackathonMVPGrowthEnterpriseSimpler Alternative
AggregatesOVERKILLOVERKILLOVERKILLSELECTIVEAPPROPRIATEPlain dataclasses with validation
Bounded contextsOVERKILLOVERKILLOVERKILLBORDERLINEAPPROPRIATEPython packages with clear imports
CQRSOVERKILLOVERKILLOVERKILLOVERKILLWHEN JUSTIFIEDSingle model for read/write
Value objectsOVERKILLOVERKILLBORDERLINEAPPROPRIATEREQUIREDTyped fields on the entity
Domain eventsOVERKILLOVERKILLOVERKILLSELECTIVEAPPROPRIATEDirect method calls between services
Repository patternOVERKILLOVERKILLBORDERLINEAPPROPRIATEREQUIREDDirect 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.

TopicSource
Entity / value-object dataclass mechanics: frozen, __post_init__, inherited field ordering, kw_onlyhttps://docs.python.org/3/library/dataclasses.html
Domain event definition, deferred dispatch, handler wiring, dispatch before vs after commithttps://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 costshttps://learn.microsoft.com/en-us/azure/architecture/patterns/anti-corruption-layer
UUIDv7 generation, server side and in Pythonhttps://www.postgresql.org/docs/18/functions-uuid.html and https://github.com/aminalaee/uuid-utils
Payment amounts in minor units, zero-decimal currencieshttps://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 standardsthe 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 skill
  • ork:architecture-patterns - Layer boundaries and project structure validation
  • ork-extras:distributed-systems - Cross-aggregate coordination
  • ork:database-patterns - Schema design for DDD

References

Load on demand with Read("references/<file>"):

FileContent
ork-delta.mdHouse rules: UUIDv7, event drain ordering, ACL boundary, source layout
repositories.mdRepository 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

RuleFileImpactWhen to Use
Figma Variables & Tokensrules/figma-variables-tokens.mdCRITICALConverting Figma Variables to W3C design tokens JSON
Component Specsrules/figma-component-specs.mdHIGHExtracting component props, variants, states from Figma
Dev Mode Inspectionrules/figma-dev-mode.mdHIGHMeasurements, spacing, typography, asset export
Auto Layout → CSSrules/figma-auto-layout.mdHIGHMapping Auto Layout to Flexbox/Grid
Visual Regressionrules/figma-visual-regression.mdMEDIUMComparing 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):

ToolReturnsUse for
get_design_contextComponent tree + layout + typography + spacingFirst call on any Figma node → grounds every other tool
get_variable_defsToken collections (variables + modes + aliases)Straight export to W3C DTCG JSON — skip the REST pipeline
get_code_connect_mapFigma node → codebase component mappingLinking generated code to existing repo components
get_screenshotPNG of a node or frameScreenshot for visual diffing / embed in chat
search_design_systemToken/component search across librariesFinding existing tokens before generating new ones
use_figma (beta)Writes back to the Figma canvasCode-to-design round-trip (write-to-canvas)
generate_figma_design (beta)Creates a design frame from a promptAI-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:

  1. Design in Figma — Designer creates components with Variables, Auto Layout, and proper naming
  2. Extract Specs — Use Dev Mode to inspect spacing, typography, colors, and export assets
  3. Export Tokens — Figma Variables → W3C tokens JSON via REST API or plugin
  4. Build Components — Map Auto Layout to CSS Flexbox/Grid, apply tokens, implement variants
  5. 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 LayoutCSS EquivalentTailwind Class
Direction: Horizontalflex-direction: rowflex-row
Direction: Verticalflex-direction: columnflex-col
Gap: 16gap: 16pxgap-4
Padding: 16padding: 16pxp-4
Padding: 16, 24padding: 16px 24pxpy-4 px-6
Align: Centeralign-items: centeritems-center
Justify: Space betweenjustify-content: space-betweenjustify-between
Fill containerflex: 1 1 0%flex-1
Hug contentswidth: fit-contentw-fit
Fixed width: 200width: 200pxw-[200px]
Min width: 100min-width: 100pxmin-w-[100px]
Max width: 400max-width: 400pxmax-w-[400px]
Wrapflex-wrap: wrapflex-wrap
Absolute positionposition: absoluteabsolute

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

DecisionRecommendation
Token formatW3C Design Tokens Community Group (DTCG) JSON
Token pipelineFigma REST API → Style Dictionary → CSS/Tailwind
Color formatOKLCH for perceptually uniform theming
Layout mappingAuto Layout → CSS Flexbox (Grid for 2D layouts)
Visual QA toolApplitools Eyes + Figma Plugin for design-dev diff
Spec formatTypeScript interfaces matching Figma component props
Mode handlingFigma 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

ResourceDescription
references/figma-to-code-workflow.mdEnd-to-end workflow, toolchain options
references/design-dev-communication.mdPR templates, component status tracking
references/applitools-figma-plugin.mdSetup, CI integration, comparison config

Related Skills

  • ork:design-system-tokens — W3C token architecture and Style Dictionary transforms
  • ork-extras:ui-components — shadcn/ui and Radix component patterns
  • ork-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:

TargetVerdict
<frozen>/a.ts, or a new file in a new subdir of <frozen>allowed
<frozen>/../other/b.tsdenied
<frozen>-evil/x.ts (a prefix sibling)denied
<frozen>/link/b.ts where link points outsidedenied, symlinks are followed
<frozen>/dangling.ts, a link to a missing file outsidedenied, the link is chased
an edit call with no pathdenied

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

CategoryRulesImpactWhen to Use
Curation2HIGHContent collection, annotation pipelines
Management2HIGHVersioning, backup/restore
Validation1CRITICALRegression testing
Add Workflow1HIGH9-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.

RuleFileKey Pattern
Collectionrules/curation-collection.mdContent type classification, quality thresholds, duplicate prevention
Annotationrules/curation-annotation.mdMulti-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.

RuleFileKey Pattern
Versioningrules/management-versioning.mdJSON backup format, embedding regeneration, disaster recovery
Storagerules/management-storage.mdBackup 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.

RuleFileKey Pattern
Regressionrules/validation-regression.mdDifficulty 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.

RuleFileKey Pattern
Add Documentrules/curation-add-workflow.md9-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

DecisionRecommendation
Backup formatJSON (version controlled, portable)
Embedding storageExclude 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 entry2 domain tags
Min test queries3 per document
Difficulty balanceTrivial 3, Easy 3, Medium 5, Hard 3 minimum
CI frequencyWeekly automated backup (Sunday 2am UTC)

Common Mistakes

  1. Using placeholder URLs instead of canonical source URLs
  2. Skipping embedding regeneration after restore
  3. Not validating referential integrity between documents and queries
  4. Over-indexing on articles (neglecting tutorials, research papers)
  5. Missing difficulty distribution balance in test queries
  6. Not running verification after backup/restore operations
  7. Testing restore procedures in production instead of staging
  8. 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[]>
});
TypeScoresUse for
Evaluatorone itemPer-example quality (faithfulness, relevance)
RunEvaluatorthe whole runAggregate 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)

TopicFirst-party source
Dataset schema validation (JSON Schema, field constraints)https://json-schema.org and https://zod.dev
Duplicate detection via embeddings, cosine similarityhttps://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 queueshttps://langfuse.com/docs/datasets
Backup and restore mechanics for postgres datasetshttps://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 dataset
  • ork-extras:monitoring-observability - Langfuse tracing patterns for curation workflows
  • ork:testing-llm - Evaluation harnesses that consume golden datasets
  • ork: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 reference
  • references/ork-delta.md - House decisions and working config that upstream docs do not carry
  • checklists/i18n-checklist.md - Implementation and review checklist
  • examples/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.

TopicFirst-party sourceHouse subset kept here
ICU plural, select, selectordinal, offset and nested message grammarhttps://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 hashttps://cldr.unicode.org/index/cldr-spec/plural-rulesnone, read upstream
ICU number skeletons inside a message (::currency/ILS)https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.htmlreferences/ork-delta.md keeps only the ILS skeleton decision
In-message date and time forms ({date, date, medium}) and offset: pluralshttps://unicode-org.github.io/icu/userguide/format_parse/messages/nothing; fetch it upstream
<Trans> API: named vs indexed tags, self-closing tags, TransProps typinghttps://react.i18next.com/latest/trans-componentrules/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 i18nexthttps://github.com/i18next/i18next-icureferences/ork-delta.md keeps the decision and why suffix keys are not enough
Intl.ListFormat primitive behind useFormattinghttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormatreferences/formatting-utilities.md keeps the house hook API
Intl.NumberFormat primitive behind useFormattinghttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormatreferences/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

NeedSolution
UI textt('namespace:key') from useTranslation
CurrencyformatILS(amount) from useFormatting
ListsformatList(items) from useFormatting
OrdinalsformatOrdinal(n) from useFormatting
DatesformatDate(date) from @/lib/dates
PluralsICU MessageFormat in translation files
Rich text<Trans> component
RTL checkisRTL 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 i18n
  • ork:react-server-components-framework - Server-side locale detection and RSC i18n patterns
  • ork-extras:accessibility - RTL-aware focus management for bidirectional UI navigation

Key Decisions

DecisionChoiceRationale
Translation Libraryreact-i18nextReact-native hooks, namespace support, ICU format
Date LibrarydayjsLightweight, locale plugins, immutable API
Message FormatICU MessageFormatIndustry standard, complex plural/select support
Locale StoragePer-namespace JSONCode-splitting, lazy loading per feature
RTL DetectionCSS logical propertiesNative 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

RuleFileImpactWhen to Use
Skeleton Loadingrules/interaction-skeleton-loading.mdHIGHContent-shaped placeholders for async data
Infinite Scrollrules/interaction-infinite-scroll.mdCRITICALPaginated content with a11y and keyboard support
Progressive Disclosurerules/interaction-progressive-disclosure.mdHIGHRevealing complexity based on user need
Modal / Drawer / Inlinerules/interaction-modal-drawer-inline.mdHIGHChoosing overlay vs inline display patterns
Drag & Droprules/interaction-drag-drop.mdCRITICALReorderable lists with keyboard alternatives
Tabs Overflowrules/interaction-tabs-overflow.mdMEDIUMTab bars with 7+ items or dynamic tabs
Toast Notificationsrules/interaction-toast-notifications.mdHIGHSuccess/error feedback and notification stacking
Cognitive Load Thresholdsrules/interaction-cognitive-load-thresholds.mdHIGHEnforcing Miller's Law, Hick's Law, and Doherty Threshold with numeric limits
Form UXrules/interaction-form-ux.mdHIGHTarget sizing, label placement, error prevention, and smart defaults
Persuasion Ethicsrules/interaction-persuasion-ethics.mdHIGHDetecting dark patterns and applying ethical engagement principles

Total: 10 rules across 6 categories

Decision Table — Loading States

ScenarioPatternWhy
List/card content loadingSkeletonMatches content shape, reduces perceived latency
Form submissionSpinnerIndeterminate, short-lived action
File uploadProgress barMeasurable operation with known total
Image loadingBlur placeholderPrevents layout shift, progressive reveal
Route transitionSkeletonPreserves layout while data loads
Background syncNone / subtle indicatorNon-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

  1. Keyboard parity — Every mouse interaction MUST have a keyboard equivalent. No drag-only, no hover-only.
  2. Skeleton over spinner — Use content-shaped placeholders for data loading; reserve spinners for indeterminate actions.
  3. Native HTML first — Prefer <dialog>, <details>, role="feed" over custom implementations.
  4. Progressive enhancement — Features should work without JS where possible, then enhance with interaction.
  5. Announce state changes — Use aria-live regions to announce dynamic content changes to screen readers.
  6. 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

ResourceDescription
references/loading-states-decision-tree.mdDecision tree for skeleton vs spinner vs progress bar
references/interaction-pattern-catalog.mdCatalog of 15+ interaction patterns with when-to-use guidance
references/keyboard-interaction-matrix.mdKeyboard shortcuts matrix for all interactive patterns (WAI-ARIA APG)

Related Skills

  • ork-extras:ui-components — shadcn/ui component patterns and CVA variants
  • ork-extras:animation-motion-design — Motion library and View Transitions API
  • ork-extras:accessibility — WCAG compliance, ARIA patterns, screen reader support
  • ork-extras:responsive-patterns — Responsive layout and container query patterns
  • ork: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= accepts float | 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 raises NodeTimeoutError (carrying kind="idle"|"run" and elapsed), 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. See rules/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 typed NodeError (fields node, error) and returns a Command to update state and reroute. See rules/resilience-error-handlers.md.
  • RunControl (langgraph.runtime) — cooperative graceful shutdown. request_drain(reason) from any thread; nodes poll runtime.drain_requested and stop at a checkpoint boundary, leaving a resumable thread instead of a half-applied superstep. See rules/resilience-graceful-drain.md.
  • DeltaChannel (langgraph.channels.delta, beta) — checkpoints store only incremental writes and replay them through a batch reducer, with a snapshot every snapshot_frequency updates. Fixes checkpoint cost growing with thread length. Its reducer takes a batch and must be batching-invariant. See rules/state-delta-channel.md.
  • runtime.heartbeat() — explicit progress signal, the only one that refreshes an idle timeout under refresh_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) on create_agent.

Quick Reference

CategoryRulesImpactWhen to Use
State Management5CRITICALDesigning workflow state schemas, accumulators, reducers, delta channels
Resilience3CRITICALNode timeouts, error handlers, graceful drain (1.2+)
Routing & Branching4HIGHDynamic routing, retry loops, semantic routing, cross-graph
Parallel Execution3HIGHFan-out/fan-in, map-reduce, concurrent agents
Supervisor Patterns3HIGHCentral coordinators, round-robin, priority dispatch
Tool Calling4CRITICALBinding tools, ToolNode, dynamic selection, approvals
Checkpointing3HIGHPersistence, recovery, cross-thread Store memory
Human-in-Loop3MEDIUMApproval gates, feedback loops, interrupt/resume
Streaming3MEDIUMReal-time updates, token streaming, custom events
Subgraphs3MEDIUMModular composition, nested graphs, state mapping
Functional API3MEDIUM@entrypoint/@task decorators, migration from StateGraph
Platform3HIGHDeployment, 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.

RuleFileKey Pattern
TypedDict Staterules/state-typeddict.mdTypedDict + Annotated[list, add] for accumulators
Pydantic Validationrules/state-pydantic.mdBaseModel at boundaries, TypedDict internally
MessagesStaterules/state-messages.mdMessagesState or add_messages reducer
Custom Reducersrules/state-reducers.mdAnnotated[T, reducer_fn] for merge/overwrite
Delta Channels (1.2, beta)rules/state-delta-channel.mdDeltaChannel(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.

RuleFileKey Pattern
Node Timeoutsrules/resilience-node-timeouts.mdadd_node(..., timeout=TimeoutPolicy(run_timeout=, idle_timeout=))
Error Handlersrules/resilience-error-handlers.mdadd_node(..., error_handler=) + param typed NodeError → Command
Graceful Drainrules/resilience-graceful-drain.mdRunControl().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.

RuleFileKey Pattern
Conditional Edgesrules/routing-conditional.mdadd_conditional_edges with explicit mapping
Retry Loopsrules/routing-retry-loops.mdLoop-back edges with max retry counter
Semantic Routingrules/routing-semantic.mdEmbedding similarity or Command API routing
Cross-Graph Navigationrules/routing-cross-graph.mdCommand(graph=Command.PARENT) for parent/sibling routing

Parallel Execution

Run independent nodes concurrently. Use Annotated[list, add] to accumulate results.

RuleFileKey Pattern
Fan-Out/Fan-Inrules/parallel-fanout-fanin.mdSend API for dynamic parallel branches
Map-Reducerules/parallel-map-reduce.mdasyncio.gather + result aggregation
Error Isolationrules/parallel-error-isolation.mdreturn_exceptions=True + per-branch timeout

Supervisor Patterns

Central coordinator routes to specialized workers. Workers return to supervisor.

RuleFileKey Pattern
Basic Supervisorrules/supervisor-basic.mdCommand API for state update + routing
Priority Routingrules/supervisor-priority.mdPriority dict ordering agent execution
Round-Robinrules/supervisor-round-robin.mdCompletion tracking with agents_completed

Tool Calling

Integrate function calling into LangGraph agents. Keep tools under 10 per agent.

RuleFileKey Pattern
Tool Bindingrules/tools-bind.mdmodel.bind_tools(tools) + tool_choice
ToolNode Executionrules/tools-toolnode.mdToolNode(tools) prebuilt parallel executor
Dynamic Selectionrules/tools-dynamic.mdEmbedding-based tool relevance filtering
Tool Interruptsrules/tools-interrupts.mdinterrupt() for approval gates on tools

Checkpointing

Persist workflow state for recovery and debugging.

RuleFileKey Pattern
Checkpointer Setuprules/checkpoints-setup.mdMemorySaver dev / PostgresSaver prod
State Recoveryrules/checkpoints-recovery.mdthread_id resume + get_state_history
Cross-Thread Storerules/checkpoints-store.mdStore 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.

RuleFileKey Pattern
Interrupt/Resumerules/human-in-loop-interrupt.mdinterrupt() function + Command(resume=)
Approval Gaterules/human-in-loop-approval.mdinterrupt_before + state update + resume
Feedback Looprules/human-in-loop-feedback.mdIterative 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().

RuleFileKey Pattern
Stream Modesrules/streaming-modes.md5 modes: values, updates, messages, custom, debug
Token Streamingrules/streaming-tokens.mdmessages mode with node/tag filtering
Custom Eventsrules/streaming-custom-events.mdget_stream_writer() for progress events
Streaming v2rules/streaming-v2-format.mdversion="v2" for typed streaming (LG 1.1+)

Subgraphs

Compose modular, reusable workflow components with nested graphs.

RuleFileKey Pattern
Invoke from Noderules/subgraphs-invoke.mdDifferent schemas, explicit state mapping
Add as Noderules/subgraphs-add-as-node.mdShared state, add_node(name, compiled_graph)
State Mappingrules/subgraphs-state-mapping.mdBoundary transforms between parent/child

Functional API

Build workflows using @entrypoint and @task decorators instead of explicit graph construction.

RuleFileKey Pattern
@entrypointrules/functional-entrypoint.mdWorkflow entry point with optional checkpointer
@taskrules/functional-task.mdReturns futures, .result() to block
Migrationrules/functional-migration.mdStateGraph to Functional API conversion

Platform

Deploy graphs as managed APIs with persistence, streaming, and multi-tenancy.

RuleFileKey Pattern
Deploymentrules/platform-deployment.mdlanggraph.json + CLI + Assistants API
RemoteGraphrules/platform-remote-graph.mdRemoteGraph for calling deployed graphs
Double Textingrules/platform-double-texting.md4 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 typed stream() and astream() 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) or InMemoryCache from langgraph.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_before for 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

DecisionRecommendation
State typeTypedDict internally, Pydantic at boundaries
Entry pointadd_edge(START, node) not set_entry_point()
Routing + state updateCommand API
Routing onlyConditional edges
AccumulatorsAnnotated[list[T], add] always
Dev checkpointerMemorySaver
Prod checkpointerPostgresSaver
Short-term memoryCheckpointer (thread-scoped)
Long-term memoryStore (cross-thread, namespaced)
Max parallel branches5-10 concurrent
Tools per agent5-10 max (dynamic selection for more)
Approval gatesinterrupt() for high-risk operations
Stream modes["updates", "custom"] for most UIs
Subgraph patternInvoke for isolation, Add-as-Node for shared state
Functional vs GraphFunctional for simple flows, Graph for complex topology

Common Mistakes

  1. Forgetting add reducer (overwrites instead of accumulates)
  2. Mutating state in place (breaks checkpointing)
  3. No END fallback in routing (workflow hangs)
  4. Infinite retry loops (no max counter)
  5. Side effects in router functions
  6. Too many tools per agent (context overflow)
  7. Raising exceptions in tools (crashes agent loop)
  8. No checkpointer in production (lose progress on crash)
  9. Wrapping interrupt() in try/except (breaks the mechanism)
  10. Not transforming state at subgraph boundaries
  11. Forgetting .result() on Functional API tasks
  12. Using set_entry_point() (deprecated, use add_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 comparisons
  • temporal-io - Durable execution alternative
  • ork-extras:llm-integration - General LLM function calling
  • type-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

CategoryRulesImpactWhen to Use
Function Calling3CRITICALTool definitions, parallel execution, input validation
Streaming3HIGHSSE endpoints, structured streaming, backpressure handling
Local Inference3HIGHOllama setup, model selection, GPU optimization
Fine-Tuning3HIGHLoRA/QLoRA training, dataset preparation, evaluation
Context Optimization2HIGHWindow management, compression, caching, budget scaling
Evaluation2HIGHLLM-as-judge, RAGAS metrics, quality gates, benchmarks
Prompt Engineering4HIGHCoT, 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 binding
  • calling-parallel.md -- Parallel tool execution, asyncio.gather, strict mode constraints
  • calling-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 iterators
  • streaming-structured.md -- Streaming with tool calls, partial JSON parsing, chunk accumulation
  • streaming-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 configuration
  • local-model-selection.md -- Model comparison by task, hardware profiles, quantization
  • local-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 merging
  • tuning-dataset-prep.md -- Synthetic data generation, quality validation, deduplication
  • tuning-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 triggers
  • context-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 detection
  • evaluation-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 guide
  • prompt-testing.md -- Langfuse versioning, DSPy optimization, A/B testing, self-consistency
  • prompt-react-pattern.md -- ReAct loop for tool-using agents, thought-action-observation format
  • prompt-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.

TopicFirst-party source
Strict-mode tool schemas, structured outputshttps://platform.openai.com/docs/guides/function-calling
Anthropic input_schema / tool_usehttps://docs.claude.com/en/docs/agents-and-tools/tool-use/overview
SSE client mechanics, reconnection, cancellationhttps://developer.mozilla.org/en-US/docs/Web/API/EventSource
LoRA / QLoRA config, target modules, adapter merginghttps://huggingface.co/docs/peft/developer_guides/lora
Unsloth training loop, 4-bit loadinghttps://docs.unsloth.ai/get-started/fine-tuning-llms-guide
DPO, preference pairs, beta tuning, RLHF comparisonhttps://huggingface.co/docs/trl/dpo_trainer
SFT dataset formats (Alpaca, ChatML)https://huggingface.co/docs/trl/sft_trainer
Embedding similarity for dataset deduphttps://sbert.net/
Fine-tune vs prompt vs RAG decision frameworkhttps://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 provenance
  • references/model-selection.md -- local model comparison by task and hardware
  • scripts/create-lora-config.md -- LoRA config scaffold with auto-detected model type

Key Decisions

DecisionRecommendation
Tool schema modestrict: true (2026 best practice)
Tool countLoad roughly 5-15 up front; defer the rest behind a non-deferred tool search tool
Streaming protocolSSE for web, WebSocket for bidirectional
Buffer size50-200 tokens
Local model (reasoning)deepseek-r1:70b
Local model (coding)qwen2.5-coder:32b
Fine-tuning approachLoRA/QLoRA (try prompting first)
LoRA rank16-64 typical
Training epochs1-3 (more risks overfitting)
Context compressionAnchored iterative (60-80%)
Compress trigger70% utilization, target 50%
Judge modelclaude-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 threshold0.7 production, 0.6 drafts
Few-shot examples3-5 diverse, representative
Prompt versioningLangfuse with labels
Auto-optimizationDSPy MIPROv2

Related Skills

  • ork-extras:rag-retrieval -- Embedding patterns, when RAG is better than fine-tuning
  • agent-loops -- Multi-step tool use with reasoning
  • llm-evaluation -- Evaluate fine-tuned and local models
  • langfuse-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-builder skill (from the anthropics/skills marketplace: /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-cloudflare skill for Workers-specific deployment patterns.

Pin mcp<2 until 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 mcp now resolves to it, and upstream's own README says to keep a <2 upper bound on your requirement until you have migrated. FastMCP does 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

CategoryRuleImpactKey Pattern
Serverserver-setup.mdHIGHFastMCP lifespan, Tool/Resource/Prompt primitives
Serverserver-transport.mdHIGHstdio for CLI, Streamable HTTP for production
Authauth-oauth21.mdHIGHPKCE, RFC 8707 resource indicators, token validation
Advancedadvanced-composition.mdMEDIUMPipeline, parallel, and branching tool composition
Advancedadvanced-resources.mdMEDIUMResource caching with TTL, LRU eviction, lifecycle
Advancedelicitation.mdMEDIUMServer-initiated structured input from users
Advancedsampling-tools.mdMEDIUMServer-side agent loops with tool calling
Advancedapps-ui.mdMEDIUMInteractive UI via MCP Apps + @mcp-ui/* SDK
Clientclient-patterns.mdMEDIUMTypeScript/Python MCP client connection patterns
Securitysecurity-injection.mdHIGHDescription sanitization, encoding normalization
Securitysecurity-hardening.mdHIGHZero-trust allowlist, hash verification, rug pull detection
Qualitytesting-debugging.mdMEDIUMMCP Inspector, unit tests, transport debugging
Ecosystemregistry-discovery.mdLOWOfficial registry API, server metadata
Ecosystemwebmcp-browser.mdLOWW3C browser-native agent tools (complementary)

Total: 14 rules across 6 categories

Key Decisions

DecisionRecommendation
Transportstdio for CLI/Desktop, Streamable HTTP for production (SSE deprecated)
LanguageTypeScript for production (better SDK support, type safety)
AuthOAuth 2.1 with PKCE (S256) + RFC 8707 resource indicators
Server lifecycleAlways use FastMCP lifespan for resource management
Error handlingReturn errors as text content (Claude can interpret and retry)
Tool compositionPipeline for sequential, asyncio.gather for parallel
Resource cachingTTL + LRU eviction with memory cap
Tool trust modelZero-trust: explicit allowlist + hash verification
User inputElicitation for runtime input; never request PII via elicitation
Interactive UIMCP Apps with @mcp-ui/* SDK; sandbox all iframes
Token handlingNever pass through client tokens to downstream services
Large resultsUse _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

FeatureSpec VersionStatus
Tools, Resources, Prompts2024-11-05Stable
Streamable HTTP transport2025-03-26Stable (replaces SSE)
OAuth 2.1 + Elicitation (form)2025-06-18Stable
Sampling with tool calling2025-11-25Stable
Elicitation URL mode2025-11-25Stable
MCP Apps (UI extension)2026-01-26Extension (ext-apps)
WebMCP (browser-native)2026-02-14W3C Community Draft

SDK landscape (2026-Q2)

PackageWhat it isWhen to use
mcp (PyPI) >=1.27Official Python SDK — includes the FastMCP helper, transport adapters, InspectorNew Python servers. This is the canonical package.
@modelcontextprotocol/sdk (npm) >=1.29Official TypeScript SDKNew TS servers
fastmcp (PyPI)Standalone fork by jlowin — predates mcp; API-compatible but diverges on lifespan and middlewareExisting projects pinned to it. New projects should prefer mcp.

The fastmcp fork and the mcp.server.fastmcp module are not the same package. Imports and pyproject.toml entries 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. See references/mcp-audit-runbook.md for 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_CERTS config that already routes MCP transport now also routes auth. See configure/references/cc-version-settings.md (CC 2.1.133 section) for the env-var example. The companion deployment skill building-mcp-server-on-cloudflare can drop any prior "proxy-aware OAuth requires manual handling" caveat at this floor.

CC 2.1.169 — managed MCP policies enforced everywhere: enterprise allowedMcpServers/deniedMcpServers now apply on reconnect, IDE-typed configs, --mcp-config servers 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 same CLAUDE_CODE_SESSION_ID env 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

  1. No lifecycle management (connection/resource leaks on shutdown)
  2. Missing input validation on tool arguments
  3. Returning secrets in tool output (API keys, credentials)
    • CC 2.1.161 mitigates this at the CLI layer: claude mcp list/get/add no 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. /mcp also 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-browser to 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.
  4. Unbounded response sizes without _meta annotation — use _meta["anthropic/maxResultSizeChars"] to declare intentionally large results (DB schemas, API specs) so clients/hooks don't truncate them
  5. Trusting tool descriptions without sanitization (injection risk)
  6. No hash verification on tool invocations (rug pull vulnerability)
  7. Storing auth tokens in session IDs (credential leak)
  8. Blocking synchronous code in async server (use asyncio.to_thread())
  9. Using SSE transport instead of Streamable HTTP (deprecated since March 2025)
  10. Passing through client tokens to downstream services (confused deputy)

Ecosystem

ResourceWhat For
mcp-builder skill (anthropics/skills)Scaffold new MCP servers + create evals
building-mcp-server-on-cloudflare skillDeploy MCP servers on Cloudflare Workers
@mcp-ui/* packages (npm)Implement MCP Apps UI standard
MCP RegistryDiscover servers: https://registry.modelcontextprotocol.io/
MCP InspectorDebug and test servers interactively

Related Skills

  • ork-extras:llm-integration — LLM function calling patterns
  • ork:security-patterns — General input sanitization and layered security
  • ork: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.

TopicFirst-party source
Prometheus metric types, RED method, cardinality, PromQLhttps://prometheus.io/docs/practices/
Alertmanager grouping, inhibition, escalation, runbookshttps://prometheus.io/docs/alerting/latest/configuration/
Grafana dashboards, Loki and LogQL, Promtailhttps://grafana.com/docs/
OpenTelemetry spans, sampling, context propagationhttps://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 pathshttps://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 v2https://langfuse.com/docs/model-usage-and-cost
Langfuse scores, online evaluators, annotation queues, prompt managementhttps://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 callshttps://langfuse.com/docs/tracing-features/agent-graphs
PSI, KS test, KL and JS divergence, Wasserstein, embedding drifthttps://www.evidentlyai.com/blog/data-drift-detection-large-datasets
EWMA control chartshttps://www.itl.nist.gov/div898/handbook/pmc/section3/pmc324.htm
structlog, Winston, correlation IDs, log samplinghttps://www.structlog.org/en/stable/

Quick Reference

CategoryRulesImpactWhen to Use
Infrastructure Monitoring1CRITICALGrafana dashboards, Golden Signals, SLO/SLI
LLM Observability1HIGHLangfuse tracing, observation types, agent graphs
Silent Failures3HIGHTool 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.

RuleFileKey Pattern
Grafana Dashboardsrules/monitoring-grafana.mdGolden Signals, SLO/SLI, health checks

CC 2.1.161 — OTEL resource attributes as metric labels: OTEL_RESOURCE_ATTRIBUTES values 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.

RuleFileKey Pattern
Langfuse Tracesrules/llm-langfuse-traces.md@observe decorator, OTEL spans, agent graphs

Silent Failures

Detection and alerting for silent failures in LLM agents.

RuleFileKey Pattern
Tool Skippingrules/silent-tool-skipping.mdExpected vs actual tool calls, Langfuse traces
Quality Degradationrules/silent-degraded-quality.mdHeuristics + LLM-as-judge, z-score baselines
Silent Alertingrules/silent-alerting.mdLoop 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

DecisionRecommendationRationale
Metric methodologyRED method (Rate, Errors, Duration)Industry standard, covers essential service health
Log formatStructured JSONMachine-parseable, supports log aggregation
TracingOpenTelemetryVendor-neutral, auto-instrumentation, broad ecosystem
LLM observabilityLangfuse (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 APIsObservations API v2 + Metrics API v2v4 (Mar 2026): faster querying, aggregations at scale
Hook telemetry transportJSONL under ~/.claude/analytics/, never an SDK in-processHooks are per-event processes; SDK init would be paid on every spawn (references/ork-delta.md)

Detailed Documentation

ResourceDescription
references/ork-delta.mdStart here. Floors, house decisions and scars that upstream docs do not carry
references/langfuse-js-v5.mdJS/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.mdLangfuse experiments and dataset runs as this repo uses them
references/evaluation-scores.mdScore shapes and scoring pipeline wiring
references/session-tracking.mdSession and user grouping across multi-step workflows
references/metrics-collection.mdClaude Code OTEL metric inventory and collector-side joins
references/dashboards.mdDashboard layout conventions
references/structured-logging.mdStructured log field conventions
references/dev-agent-lens.mdLiteLLM proxy layer (or Bifrost) for API-boundary observability
examples/orchestkit-monitoring-dashboard.mdWorked monitoring dashboard example
scripts/Templates: Prometheus, OpenTelemetry, health checks, Langfuse

Related Skills

  • defense-in-depth - Layer 8 observability as part of security architecture
  • devops-deployment - Observability integration with CI/CD and Kubernetes
  • resilience-patterns - Monitoring circuit breakers and failure scenarios
  • llm-evaluation - Evaluation patterns that integrate with Langfuse scoring
  • caching - 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):

ProviderModel IDs
Anthropicclaude-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-5 is 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 spend
OpenAIgpt-5.5 (current flagship)
Googlegemini-3.1-pro-preview (flagship), gemini-3.1-flash-lite (cost)
Veoveo-3.1-generate-preview / veo-3.1-lite-generate-preview / veo-3.1-fast-generate-preview
Klingkling-v3 (model_name field in Kling API)
Runwaygen4_turbo (product label: Gen-4.5)

Quick Reference

CategoryRulesImpactWhen to Use
Vision: Image Analysis1HIGHImage captioning, VQA, multi-image comparison, object detection
Vision: Document Understanding1HIGHOCR, chart/diagram analysis, PDF processing, table extraction
Vision: Model Selection1MEDIUMChoosing provider, cost optimization, image size limits
Audio: Speech-to-Text1HIGHTranscription, speaker diarization, long-form audio
Audio: Text-to-Speech1MEDIUMVoice synthesis, expressive TTS, multi-speaker dialogue
Audio: Model Selection1MEDIUMReal-time voice agents, provider comparison, pricing
Video: Model Selection1HIGHChoosing video gen provider (Kling, Sora, Veo, Runway)
Video: API Patterns1HIGHAsync task polling, SDK integration, webhook callbacks
Video: Multi-Shot1HIGHStoryboarding, 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.

RuleFileKey Pattern
Image Analysisrules/vision-image-analysis.mdBase64 encoding, multi-image, bounding boxes

Vision: Document Understanding

Extract structured data from documents, charts, and PDFs using vision models.

RuleFileKey Pattern
Document Visionrules/vision-document.mdPDF page ranges, detail levels, OCR strategies

Vision: Model Selection

Choose the right vision provider based on accuracy, cost, and context window needs.

RuleFileKey Pattern
Vision Modelsrules/vision-models.mdProvider comparison, token costs, image limits

Audio: Speech-to-Text

Convert audio to text with speaker diarization, timestamps, and sentiment analysis.

RuleFileKey Pattern
Speech-to-Textrules/audio-speech-to-text.mdGemini long-form, GPT-4o-Transcribe, AssemblyAI features

Audio: Text-to-Speech

Generate natural speech from text with voice selection and expressive cues.

RuleFileKey Pattern
Text-to-Speechrules/audio-text-to-speech.mdGemini TTS, voice config, auditory cues

Audio: Model Selection

Select the right audio/voice provider for real-time, transcription, or TTS use cases.

RuleFileKey Pattern
Audio Modelsrules/audio-models.mdReal-time voice comparison, STT benchmarks, pricing

Video: Model Selection

Choose the right video generation provider based on use case, duration, and budget.

RuleFileKey Pattern
Video Modelsrules/video-generation-models.mdKling vs Sora vs Veo vs Runway, pricing, capabilities

Video: API Patterns

Integrate video generation APIs with proper async polling, SDKs, and webhook callbacks.

RuleFileKey Pattern
API Integrationrules/video-generation-patterns.mdKling REST, fal.ai SDK, Vercel AI SDK, task polling

Video: Multi-Shot

Generate multi-scene videos with consistent characters using storyboarding and character elements.

RuleFileKey Pattern
Multi-Shotrules/video-multi-shot.mdKling v3 character elements, 6-shot storyboards, identity binding

Key Decisions

DecisionRecommendation
High accuracy visionclaude-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 documentsgemini-3.1-pro-preview (1M+ context)
Cost-efficient visiongemini-3.1-flash-lite (GA successor of the Flash-Lite preview, which was shut down 2026-05-25; shutdown scheduled 2027-05-07)
Video analysisgemini-3.1-pro-preview (native video, supersedes 2.5 Pro)
Voice assistantGrok Voice Agent on Grok 4.20 (fastest, <1s)
Emotional voice AIGemini Live API
Long audio transcriptiongemini-3.1-pro-preview (9.5hr)
Speaker diarizationAssemblyAI or Gemini
Self-hosted STTWhisper Large V3
Character-consistent videokling-v3 (Character Elements 3.0)
Narrative video / storytellingSora 2 (best cause-and-effect coherence)
Cinematic B-rollveo-3.1-generate-preview (camera control + polished motion)
Budget draftsveo-3.1-lite-generate-preview (~$0.05/s, 720/1080p)
Mid-tier fast rendersveo-3.1-fast-generate-preview
Professional VFXRunway gen4_turbo (Act-Two motion transfer)
High-volume social videokling-v3 Standard (~$0.20/video)
Open-source video genWan 2.6 or LTX-2
Lip-sync / avatar videokling-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

  1. Not setting max_tokens on vision requests (responses truncated)
  2. Sending oversized images without resizing (>2048px)
  3. Using high detail level for simple yes/no classification
  4. Using STT+LLM+TTS pipeline instead of native speech-to-speech
  5. Not leveraging barge-in support for natural voice conversations
  6. Using deprecated models (GPT-4V, Whisper-1)
  7. Ignoring rate limits on vision and audio endpoints
  8. Calling video generation APIs synchronously (they're async — poll or use callbacks)
  9. Generating separate clips without character elements (characters look different each time)
  10. Using Sora for high-volume social content (expensive, slow — use Kling Standard instead)

Related Skills

  • ork-extras:rag-retrieval - Multimodal RAG with image + text retrieval
  • ork-extras:llm-integration - General LLM function calling patterns
  • streaming-api-patterns - WebSocket patterns for real-time audio
  • ork: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 .localhost URL won't resolve.
  • HTTP/2 Host forwarding fix (0.15.0) — the proxy now forwards the HTTP/2 :authority as Host to HTTP/1.1 backends, fixing apps that read Host and previously saw 127.0.0.1 for browser traffic. --force takeover cleanup now removes only routes still owned by the exiting process, so a forced takeover no longer deregisters the new owner's route.
  • --ngrok flag (0.14.0) — share an app publicly via ngrok while local access keeps its .localhost URL. 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 .localhost URLs survive reboot reliably.
  • State directory moved to ~/.portless (0.11, BREAKING) — state relocated from scattered/temp locations to ~/.portless; override with PORTLESS_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 uninstall register a native startup service for the HTTPS proxy across macOS launchd, Linux systemd, and Windows Task Scheduler. .localhost URLs survive reboot without a manual portless proxy start. portless clean removes the service alongside CA + hosts cleanup.
  • Tailscale readiness preflight (0.13.0) — --tailscale and --funnel now validate Tailscale HTTPS + Funnel prerequisites before starting the child process, surfacing actionable errors instead of hanging during registration.
  • Tailscale integration (0.12.0) — --tailscale shares your app over your tailnet with automatic HTTPS on port 443; --funnel exposes it publicly via Tailscale Funnel. Apps receive PORTLESS_TAILSCALE_URL so they can reference their own public address. portless list now shows tailnet URLs.
  • Zero-config mode (0.11.0) — bare portless auto-discovers dev scripts from package.json. Multi-app monorepos get automatic subdomain assignment; Turborepo task-graph integration is wired in. portless.json config file supported. --script overrides 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-tls reverts.
  • NODE_EXTRA_CA_CERTS auto-injected (0.10.2) into child processes — node HTTPS calls trust portless CA with zero setup.
  • --wildcard subdomains — https://*.myapp.localhost for multi-tenant / preview routing.
  • portless alias <name> <port> — map a docker-compose / emulate port to a named URL without a long-running run process.
  • portless clean — full teardown: stops proxy, removes CA, wipes state, cleans /etc/hosts.
  • --lan mode — mDNS .local hostnames reachable across wifi (phone, tablet, other machines) without router config.
  • Fixed app ports — --app-port 3000 / PORTLESS_APP_PORT for 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 start gives 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.localhost to https://app.localhost on port 443. Use --no-tls to revert. NODE_EXTRA_CA_CERTS is injected into child processes automatically (0.10.2) — no manual cert setup. /etc/hosts is synced automatically for Safari; disable with PORTLESS_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:

FrameworkAuto-detected?Extra flags needed
Next.jsYesNone
Vite / AstroYesNone
Express / Fastify / HonoYesNone (reads PORT env var)
Ruby on RailsYesNone
FastAPI / uvicornNo--port $PORT --host $HOST
DjangoNo$HOST:$PORT positional arg

Why .localhost?

Feature.localhost (RFC 6761)127.0.0.1:PORT/etc/hosts hack
No /etc/hosts editingYesYesNo
HTTPS with valid certYesNoManual
Wildcard subdomainsYesNoNo
Works in all browsersYesYesVaries
Cookie isolation per serviceYesNoYes
No port conflictsYesNoYes

Key Environment Variables

When portless runs your command, it injects:

VariableValueUse in agents
PORTAssigned ephemeral port (4000-4999)Internal only
HOST127.0.0.1Internal only
PORTLESS_URLhttps://myapp.localhostUse this in agent prompts
NODE_EXTRA_CA_CERTSPath to portless CA (auto-injected 0.10.2)Child node processes trust portless certs without setup

Toggle env vars

VariableEffect
PORTLESS=0Bypass portless entirely (CI)
PORTLESS_SYNC_HOSTS=0Disable auto /etc/hosts sync (default: on in 0.10.1+)
PORTLESS_STATE_DIROverride 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'tDo Instead
Hardcode localhost:3000 in testsUse PORTLESS_URL or process.env.PORTLESS_URL
Run portless in CISet PORTLESS=0 in CI environments
Use numeric ports in AGENTS.mdDocument the portless URL

References

FileContent
references/upstream.mdFull portless CLI reference (synced from Vercel)
references/upstream-oauth.mdOAuth callback patterns with stable URLs
references/framework-integration.mdFramework recipes (FastAPI, Django, Docker, gotchas)
checklists/new-project-setup.mdStep-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

CommandWhat it doesOutput
scanread history, attribute, aggregateagg.json (counts only)
reportscan, then build the pagereport.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 replacesdaily.jsonl
demo [path]the same page from synthetic dataa shareable demo page
selftestsynthetic run with privacy assertsexit 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

  1. Run report, then open report.html for the user.
  2. Lead with the verdict line from the page: the top area, prompts per week, and the nudge and words-per-prompt trend.
  3. 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.
  4. 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_patterns is an agent's, not yours.
  • Counts only. agg.json, daily.jsonl and 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 (weeks in config).
  • Areas. Your project folder by default; add areas regexes in config.json to group by topic instead.

Common Mistakes

  • Sharing your real report.html publicly: it names your projects. Use demo for 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

CategoryRulesImpactWhen to Use
Core RAG4CRITICALBasic RAG, citations, hybrid search, context management
Embeddings3HIGHModel selection, chunking, batch/cache optimization
Contextual Retrieval3HIGHContext-prepending, hybrid BM25+vector, pipeline
HyDE3HIGHVocabulary mismatch, hypothetical document generation
Agentic RAG4HIGHSelf-RAG, CRAG, knowledge graphs, adaptive routing
Multimodal RAG3MEDIUMImage+text retrieval, PDF chunking, cross-modal search
Query Decomposition3MEDIUMMulti-concept queries, parallel retrieval, RRF fusion
Reranking3MEDIUMCross-encoder, LLM scoring, combined signals
PGVector4HIGHPostgreSQL hybrid search, HNSW indexes, schema design

Total: 30 rules across 9 categories

Core RAG

Fundamental patterns for retrieval, generation, and pipeline composition.

RuleFileKey Pattern
Basic RAGrules/core-basic-rag.mdRetrieve + context + generate with citations
Hybrid Searchrules/core-hybrid-search.mdRRF fusion (k=60) for semantic + keyword
Context Managementrules/core-context-management.mdToken budgeting + sufficiency check
Pipeline Compositionrules/core-pipeline-composition.mdComposable Decompose → HyDE → Retrieve → Rerank

Embeddings

Embedding models, chunking strategies, and production optimization.

RuleFileKey Pattern
Models & APIrules/embeddings-models.mdModel selection, batch API, similarity
Chunkingrules/embeddings-chunking.mdSemantic boundary splitting, 512 token sweet spot
Advancedrules/embeddings-advanced.mdRedis cache, Matryoshka dims, batch processing

Contextual Retrieval

Anthropic's context-prepending technique — 67% fewer retrieval failures.

RuleFileKey Pattern
Context Prependingrules/contextual-prepend.mdLLM-generated context + prompt caching
Hybrid Searchrules/contextual-hybrid.md40% BM25 / 60% vector weight split
Complete Pipelinerules/contextual-pipeline.mdEnd-to-end indexing + hybrid retrieval

HyDE

Hypothetical Document Embeddings for bridging vocabulary gaps.

RuleFileKey Pattern
Generationrules/hyde-generation.mdEmbed hypothetical doc, not query
Per-Conceptrules/hyde-per-concept.mdParallel HyDE for multi-topic queries
Fallbackrules/hyde-fallback.md2-3s timeout → direct embedding fallback

Agentic RAG

Self-correcting retrieval with LLM-driven decision making.

RuleFileKey Pattern
Self-RAGrules/agentic-self-rag.mdBinary document grading for relevance
Corrective RAGrules/agentic-corrective-rag.mdCRAG workflow with web fallback
Knowledge Graphrules/agentic-knowledge-graph.mdKG + vector hybrid for entity-rich domains
Adaptive Retrievalrules/agentic-adaptive-retrieval.mdQuery routing to optimal strategy

Multimodal RAG

Image + text retrieval with cross-modal search.

RuleFileKey Pattern
Embeddingsrules/multimodal-embeddings.mdCLIP, SigLIP 2, Voyage multimodal-3
Chunkingrules/multimodal-chunking.mdPDF extraction preserving images
Pipelinerules/multimodal-pipeline.mdDedup + hybrid retrieval + generation

Query Decomposition

Breaking complex queries into concepts for parallel retrieval.

RuleFileKey Pattern
Detectionrules/query-detection.mdHeuristic indicators (<1ms fast path)
Decompose + RRFrules/query-decompose.mdLLM concept extraction + parallel retrieval
HyDE Comborules/query-hyde-combo.mdDecompose + HyDE for maximum coverage

Reranking

Post-retrieval re-scoring for higher precision.

RuleFileKey Pattern
Cross-Encoderrules/reranking-cross-encoder.mdms-marco-MiniLM (~50ms, free)
LLM Rerankingrules/reranking-llm.mdBatch scoring + Cohere API
Combinedrules/reranking-combined.mdMulti-signal weighted scoring

PGVector

Production hybrid search with PostgreSQL.

RuleFileKey Pattern
Schemarules/pgvector-schema.mdHNSW index + pre-computed tsvector
Hybrid Searchrules/pgvector-hybrid-search.mdSQLAlchemy RRF with FULL OUTER JOIN
Indexingrules/pgvector-indexing.mdHNSW (17x faster) vs IVFFlat
Metadatarules/pgvector-metadata.mdFiltering, 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

DecisionRecommendation
Embedding modeltext-embedding-3-small (general), voyage-3.5 (production)
Chunk size256-1024 tokens (512 typical)
Hybrid weight40% BM25 / 60% vector
Top-k3-10 documents
Temperature0.1-0.3 (factual)
Context budget4K-8K tokens
RerankingRetrieve 50, rerank to 10
Vector indexHNSW (production), IVFFlat (high-volume)
HyDE timeout2-3 seconds with fallback
Query decompositionHeuristic 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.

TopicSource
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_cdhttps://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/ANALYZEhttps://www.postgresql.org/docs/current/using-explain.html
RRF mechanics: rank constant, rank window size, tie handlinghttps://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 concepthttps://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, pricinghttps://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 setork skill golden-dataset
Search endpoint shape, pagination, error bodiesork skill api-design
Tracing and dashboarding search callsork skill monitoring-observability
Writing the integration test that runs these assertionsork skill testing-integration

Common Mistakes

  1. No citation tracking (unverifiable answers)
  2. Context too large (dilutes relevance)
  3. Single retrieval method (misses keyword matches)
  4. Not chunking long documents (context gets lost)
  5. Embedding queries differently than documents
  6. No fallback path in agentic RAG (workflow hangs)
  7. Infinite rewrite loops (no retry limit)
  8. Using wrong similarity metric (cosine vs euclidean)
  9. Not caching embeddings (recomputing unchanged content)
  10. 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 quality
  • ork-extras:llm-integration - Local embeddings with nomic-embed-text
  • ork-extras:multimodal-llm - Image analysis for multimodal RAG
  • ork:database-patterns - Schema design for vector search
  • ork: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-run in CI before release-please opens its release PR; catches manifest drift early. See src/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

  1. Use semantic versioning - Communicate change impact
  2. Draft releases first - Review notes before publishing
  3. Generate notes from PRs - Accurate, automatic history
  4. Close milestone on release - Track completion
  5. Tag main only - Never tag feature branches
  6. Announce breaking changes - Prominent in release notes

Related Skills

  • ork:github-operations: Milestones, issues, and CLI reference
  • ork:github-operations: Branch management and git operations

References

Load on demand with Read("references/<file>"):

FileContent
semver.mdSemantic versioning rules and decision tree
release-workflows.mdStandard and hotfix release procedures
changelog-generation.mdAuto-generated, template, and manual changelog formats
release-automation.mdGitHub 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

FeatureMedia QueriesContainer Queries
Responds toViewport sizeContainer size
Component reuseContext-dependentTruly portable
Browser supportUniversalBaseline 2023+
Use casePage layoutsComponent 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

FeatureChromeSafariFirefoxEdge
Container Size Queries105+16+110+105+
Container Style Queries111+❌❌111+
Container Scroll-State126+❌❌126+
cqi/cqb units105+16+110+105+
clamp()79+13.1+75+79+
Subgrid117+16+71+117+

Rules

Each category has individual rule files in rules/ loaded on-demand:

CategoryRuleImpactKey Pattern
Modern CSS Layoutrules/css-subgrid.mdHIGHCSS Subgrid for nested grid alignment, card layouts
Modern CSS Layoutrules/css-intrinsic-responsive.mdHIGHIntrinsic responsive layouts, auto-fit/minmax, clamp(), zero breakpoints
Modern CSS Layoutrules/responsive-foldables.mdMEDIUMFoldable devices, safe area insets, viewport segments
CSSrules/css-patterns.mdHIGHContainer queries, cqi/cqb, fluid typography, grid, scroll-queries
Reactrules/react-patterns.mdHIGHContainer query components, Tailwind, useContainerQuery, responsive images
PWArules/pwa-service-worker.mdHIGHWorkbox caching strategies, VitePWA, update management
PWArules/pwa-offline.mdHIGHOffline hooks, background sync, install prompts
Animationrules/animation-motion.mdHIGHMotion presets, AnimatePresence, View Transitions
Animationrules/animation-scroll.mdMEDIUMCSS scroll-driven animations, parallax, progressive enhancement
Touch & Mobilerules/touch-interaction.mdHIGHTouch targets (44px min), thumb zones, pinch-to-zoom, safe areas, gestures

Total: 10 rules across 6 categories

Key Decisions

DecisionOption AOption BRecommendation
Query typeMedia queriesContainer queriesContainer for components, Media for layout
Container unitscqw/cqhcqi/cqbcqi/cqb (logical, i18n-ready)
Fluid type basevw onlyrem + vwrem + vw (accessibility)
Mobile-firstYesDesktop-firstMobile-first (less CSS, progressive)
Grid patternauto-fitauto-fillauto-fit for cards, auto-fill for icons

Related Skills

  • design-system-starter - Building responsive design systems
  • ork:performance - CLS, responsive images, and image optimization
  • ork-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>"):

FileContent
container-queries.mdContainer query patterns
fluid-typography.mdAccessible 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-test renamed to addon-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

RuleImpactDescription
storybook-csf3-factoriesHIGHTypesafe CSF3 story factories with satisfies Meta
storybook-play-functionsCRITICALInteraction testing with play() and @storybook/test
storybook-vitest-integrationHIGHRun stories as Vitest tests via @storybook/addon-vitest
storybook-chromatic-turbosnapHIGHTurboSnap reduces snapshot cost 60-90%
storybook-sb-mockHIGHStory-level module mocking with sb.mock
storybook-a11y-testingCRITICALAutomated axe-core accessibility scans in CI
storybook-autodocsMEDIUMAuto-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 + satisfies for type safety. Use satisfies 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 with mocked() in beforeEach. Never use vi.mock in story files. No factory functions — sb.mock is 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-PatternWhy It FailsUse Instead
CSF2 Template.bind({})Deprecated, no type inference, will be removed in SB 11CSF3 object stories with satisfies
@storybook/test-runner packageDeprecated since Storybook 9@storybook/addon-vitest
vi.mock() in story filesLeaks between stories, breaks isolationRegister sb.mock(import(...)) in preview.ts, configure with mocked() in beforeEach
Full Chromatic snapshots on every PRExpensive and slowTurboSnap with onlyChanged: true
Manual accessibility checkingMisses violations, not repeatable@storybook/addon-a11y in CI pipeline
Separate documentation siteDrifts from actual component behaviorAutodocs with tags: ['autodocs']
Testing implementation detailsBrittle, breaks on refactorsTest user-visible behavior via play()
CJS imports in storiesESM-only since SB 9/10Use 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

ToolPurpose
run-story-testsRun component + a11y tests via MCP, returns pass/fail + violation details
preview-storiesReturns preview URLs for visual verification in chat
get-storybook-story-instructionsGuidance 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 10
  • references/storybook-ci-strategy.md — CI pipeline configuration for visual, interaction, and a11y testing
  • references/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, previews
  • react-server-components-framework — React 19 + Next.js 16 patterns (component architecture)
  • accessibility — Broader accessibility patterns beyond Storybook
  • devops-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-migrate is 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 /workflows when you want large-scale fire-and-forget background fan-out; reach for swarm-migrate when 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 /workflows on 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 SendMessage to 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-session SendMessage / ListAgents also 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 -p processes use cross-session messaging (CC 2.1.224, see chain-patterns Pattern 10). A -p worker must run with crossSessionInbound: "accept" in --settings to 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[].path exists and is a git repo (use git -C <path> rev-parse checks).
  • The transform.command returns 0 in a dry-run mode (or transform.type: codemod resolves to a known codemod registered in swarm-specs/codemods/).
  • Every upstream reference points to a declared repo (no dangling deps).
  • pr.body_file exists 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):

  1. Worktree — create an isolated worktree at <repo>/../<repo>-swarm-<spec-name> off origin/<base>. Never mutate the live working tree.
  2. Branch — git checkout -b <branch_prefix>-<short-sha>.
  3. Transform — run transform.command (or apply codemod). Capture stdout to .swarm-logs/<repo>-transform.log.
  4. Verify — run each verify[].command, assert exit matches expect. On mismatch, mark repo skipped in ledger with reason, do not push.
  5. Push + PR — push branch, open PR via gh pr create. Update ledger with PR URL.
  6. Watch CI — poll gh pr checks <n> every 45s up to ci_gate.timeout_minutes. Update ci_state in 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 → consult ci_gate.on_failure:
    • pause → halt the swarm, write a summary to .swarm-state.json, surface the failing logs, ask the user.
    • skip → mark repo failed-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:

  1. Re-fetches the upstream's merge commit SHA.
  2. Attempts git rebase origin/<base>. If clean → push, ledger update.
  3. 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 --auto post-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 create fails because of required reviewers or other rules, that's a feature, not a bug to work around.

Failure modes you'll actually hit

ModeWhat it looks likeMitigation
Stale lockfileCI red on npm ci after dependency bumpSpec includes a post_transform.command: npm install step
Branch protection blocks PR creationgh pr create exits non-zeroCoordinator marks repo blocked-by-protection, surfaces to user
Topology cyclePhase 2 abortRe-spec the upstream edges
Coordinator crash mid-flight.swarm-state.json half-writtenSkill is resumable: re-run with same spec, it reads the ledger and skips merged/green repos
Worker subagent hangsNo ledger update for >5 minCoordinator times out the agent, marks repo worker-timeout, surfaces logs

Related Skills

  • Upstream — brainstorm to design the spec, visualize-plan to ASCII-preview the DAG before dispatch.
  • Downstream — verify per repo after merge, /status for org-wide sweep, /ci-debug if 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

CategoryRulesImpactWhen to Use
shadcn/ui1HIGHv4 styles, preset codes, style detection
Design System4HIGHW3C tokens, OKLCH theming, spacing scales, typography, component states, animation
Design System Components1HIGHAtomic design, CVA variants, accessibility, Storybook
Forms2HIGHReact Hook Form v7, Zod validation, Server Actions
Modern CSS & Tooling3HIGHCSS cascade layers, Tailwind v4, Storybook CSF3
UX Foundations4HIGHVisual 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.

RuleFileKey Pattern
v4 Stylesrules/shadcn-v4-styles.md6 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.

StyleCharacterBest For
VegaBalanced radius, clean linesGeneral purpose (successor to New York)
NovaCompact padding, reduced marginsDense dashboards, admin panels
MaiaSoft, rounded, generous spacingConsumer-facing, friendly apps
LyraSharp, zero radius, monospace pairsEditorial, developer tools
MiraUltra-compact, minimal chromeSpreadsheets, data-heavy interfaces
LumaExtreme rounding (rounded-4xl), soft elevation (shadow-md + ring), breathable layoutsPolished 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

CommandPurpose
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 infoShow resolved config: registry, style, tokens, components present, Tailwind version
npx shadcn@latest skillsList the shadcn/skills registry — Claude Code- and Cursor-ready skill packs that bundle CLI commands with agent guidance
npx shadcn@latest buildBuild 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

DecisionRecommendation
Color formatOKLCH for perceptually uniform theming
Class mergingAlways use cn() for Tailwind conflicts
Extending componentsWrap, don't modify source files
VariantsUse CVA for type-safe multi-axis variants
Styling approachData attributes + Tailwind arbitrary variants
CompositionUse asChild to avoid wrapper divs
AnimationCSS-only with data-state selectors
Form componentsCombine with react-hook-form
Destructive confirmationsAlertDialog, 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 asChild to avoid extra DOM elements
  • Missing Dialog.Title: Every dialog must have an accessible title
  • Positive tabindex: Using tabindex > 0 disrupts 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).

TopicFirst-party source
shadcn setup, init checklist, adding componentsvercel:shadcn (marketplace skill), https://ui.shadcn.com/docs/installation
shadcn customization, CVA variants, cn() utility, component extensionvercel:shadcn (marketplace skill), https://ui.shadcn.com/docs and https://cva.style/docs
OKLCH theming variables, light/dark CSS variable setshttps://ui.shadcn.com/docs/theming
Dark mode toggle with next-themeshttps://ui.shadcn.com/docs/dark-mode and https://github.com/pacocoursey/next-themes
Data table with TanStack Tablehttps://ui.shadcn.com/docs/components/data-table and https://tanstack.com/table
Form field wrappers and validation stateshttps://ui.shadcn.com/docs/components/form
Radix Dialog and AlertDialog patternshttps://www.radix-ui.com/primitives/docs/components/dialog and .../components/alert-dialog
Radix asChild / Slot compositionhttps://www.radix-ui.com/primitives/docs/guides/composition
Radix data-attribute styling and focus managementhttps://www.radix-ui.com/primitives/docs/guides/styling
Dropdown menu, popover, tooltip, hover cardhttps://www.radix-ui.com/primitives/docs/components/dropdown-menu (and sibling component pages)
Radix accessibility audit checklisthttps://www.radix-ui.com/primitives/docs/overview/accessibility plus ork-extras:accessibility

Detailed Documentation

ResourceDescription
scripts/Templates: CVA component, extended button, dialog, dropdown, theme CSS
references/ork-delta.mdOrk floors, scars, and house decisions kept out of upstream docs

Design System

Design token architecture, spacing, typography, and interactive component states.

RuleFileKey Pattern
Token Architecturerules/design-system-tokens.mdW3C tokens, OKLCH colors, Tailwind @theme
Spacing Scalerules/design-system-spacing.md8px grid, Tailwind space-1 to space-12
Typography Scalerules/design-system-typography.mdFont sizes, weights, line heights
Component Statesrules/design-system-states.mdHover, focus, active, disabled, loading, animation presets

Design System Components

Component architecture patterns with atomic design and accessibility.

RuleFileKey Pattern
Component Architecturerules/design-system-components.mdAtomic design, CVA variants, WCAG 2.1 AA, Storybook

Forms

React Hook Form v7 with Zod validation and React 19 Server Actions.

RuleFileKey Pattern
React Hook Formrules/forms-react-hook-form.mduseForm, field arrays, Controller, wizards, file uploads
Zod & Server Actionsrules/forms-validation-zod.mdZod schemas, Server Actions, useActionState, async validation

Modern CSS & Tooling

Modern CSS patterns, Tailwind v4, and component documentation tooling for 2026.

RuleFileKey Pattern
CSS Cascade Layersrules/css-cascade-layers.md@layer ordering, specificity-free overrides, third-party isolation
Tailwind v4rules/tailwind-v4-patterns.mdCSS-first @theme, native container queries, @max-* variants
Storybook Docsrules/storybook-component-docs.mdCSF3 stories, play() interaction tests, Chromatic visual regression

UX Foundations

Cognitive-science-grounded UI/UX principles with specific numeric thresholds for production-quality interfaces.

RuleFileKey Pattern
Visual Hierarchyrules/visual-hierarchy.mdButton tiers, de-emphasis, F/Z scan, Von Restorff, proximity, max-width
Typography Thresholdsrules/typography-thresholds.md65ch line length, 1.4–1.6 line height, rem units, modular type scale
Color Systemrules/color-system.mdOKLCH 9-shade scales, semantic categories, no true black, brand-tinted neutrals
Empty Statesrules/empty-states.mdSkeleton-first, icon + headline + description + CTA, cause-specific tone

Related Skills

  • ork-extras:accessibility - WCAG compliance and React Aria patterns
  • ork: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.

TopicFetch from
Vite 7 to 8 migration: rolldownOptions, transformWithOxc, moduleType: 'js', removed hooks and output formats, browser target bumpshttps://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, chunkSizeWarningLimithttps://vite.dev/config/build-options
Dependency pre-bundling and optimizeDeps include/exclude/forcehttps://vite.dev/guide/dep-pre-bundling
SSR: client and server entry points, middleware-mode dev server, production server wiring, streaminghttps://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, applyToEnvironmenthttps://vite.dev/guide/api-environment-plugins
Environment API for frameworks: createBuilder, buildApp, ModuleRunnerhttps://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_ prefixhttps://vite.dev/guide/env-and-mode
Deploying a static site and verifying with vite previewhttps://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.production before deploy.

Rules

RuleCovers
rules/vite-advanced-chunks.mdChunk splitting: advancedChunks groups, priority, maxSize, minShareCount
rules/vite-environments.mdenvironments config for client, SSR, and edge; per-environment outDir
rules/vite-lib-config.mdLibrary mode externals, dual ESM/CJS output, exports map, type declarations
rules/vite-plugin-hooks.mdHook order, virtual modules via resolveId + load, enforce and apply

Key Decisions

DecisionRecommendation
New projectsVite 8 (default)
Existing production appsStage the upgrade through rolldown-vite before committing
Multi-env buildsEnvironment API (environments config)
Plugin scopeUse this.environment for env-aware plugins
SSRMiddleware mode for dev, separate builds for prod
ChunksadvancedChunks for Vite 8, manualChunks for Vite 7 compat

Related Skills

  • ork:react-server-components-framework - SSR integration
  • ork-extras:storybook-testing - Component testing with Vitest
  • ork:performance - Core Web Vitals targets behind the build budget

References

Load on demand with Read("references/<file>"):

FileContent
ork-delta.mdHouse rules that Vite's docs do not state
library-mode.mdBuilding 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.

TopicFirst-party source
Basic store, create<State>()(), actions, async actionshttps://github.com/pmndrs/zustand/blob/main/docs/reference/apis/create.md
Slices pattern (splitting and combining stores)https://github.com/pmndrs/zustand/blob/main/docs/learn/guides/slices-pattern.md
Typing slices and middleware mutator tupleshttps://github.com/pmndrs/zustand/blob/main/docs/learn/guides/advanced-typescript.md
Immer middleware (draft mutations)https://github.com/pmndrs/zustand/blob/main/docs/reference/middlewares/immer.md
persist: partialize, version, migrate, onRehydrateStorage, storage adaptershttps://github.com/pmndrs/zustand/blob/main/docs/reference/middlewares/persist.md
devtools: action names, enabled, serialize, tracehttps://github.com/pmndrs/zustand/blob/main/docs/reference/middlewares/devtools.md
subscribeWithSelector and non-React subscriptionshttps://github.com/pmndrs/zustand/blob/main/docs/reference/middlewares/subscribe-with-selector.md
Selectors and useShallow re-render controlhttps://github.com/pmndrs/zustand/blob/main/docs/learn/guides/prevent-rerenders-with-use-shallow.md
v4 to v5 migration (createWithEqualityFn, React 18 floor)https://github.com/pmndrs/zustand/blob/main/docs/reference/migrations/migrating-to-v5.md
SSR and hydrationhttps://github.com/pmndrs/zustand/blob/main/docs/learn/guides/ssr-and-hydration.md
Store testing and resethttps://github.com/pmndrs/zustand/blob/main/docs/learn/guides/testing.md
Server-state ownership (use TanStack Query, not Zustand)https://tanstack.com/query/latest/docs/framework/react/guides/does-this-replace-client-state

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

DecisionOption AOption BRecommendation
State structureSingle storeMultiple storesSlices in single store - easier cross-slice access
Nested updatesSpread operatorImmer middlewareImmer for deeply nested state (3+ levels)
PersistenceManual localStoragepersist middlewarepersist middleware with partialize
Multiple valuesMultiple selectorsuseShallowuseShallow for 2-5 related values
Server stateZustandTanStack QueryTanStack Query - Zustand for client-only state
DevToolsAlways onConditionalConditional - 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

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>"):

FileContent
ork-delta.mdOrchestKit-specific rules: the corrected zustand/shallow label, the v5 floor, secret handling, graded slice typing
anti-patterns-and-integration.mdForbidden 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

More from yonatangross/orchestkit

All 7