Essential building blocks for Claude Code workflows - smart commits, debugging, and environment setup

GitHub stars
6

Install

/plugin install primitives@cautious-computing-machine

Run it inside Claude Code after adding the marketplace with /plugin marketplace add iamladi/cautious-computing-machine.

Contents

Discovered from source

Skills 11

> See [EXAMPLES.md](./EXAMPLES.md) for ❌/✅ pairs illustrating every > anti-pattern named below.

<essential_principles>

The Prompt-Native Philosophy

Agent native engineering inverts traditional software architecture. Instead of writing code that the agent executes, you define outcomes in prompts and let the agent figure out HOW to achieve them.

The Foundational Principle

Whatever the user can do, the agent can do. Many things the developer can do, the agent can do.

Don't artificially limit the agent. If a user could read files, write code, browse the web, deploy an app—the agent should be able to do those things too. The agent figures out HOW to achieve an outcome; it doesn't just call your pre-written functions.

Features Are Prompts

Each feature is a prompt that defines an outcome and gives the agent the tools it needs. The agent then figures out how to accomplish it.

Traditional: Feature = function in codebase that agent calls Prompt-native: Feature = prompt defining desired outcome + primitive tools

The agent doesn't execute your code. It uses primitives to achieve outcomes you describe.

Tools Provide Capability, Not Behavior

Tools should be primitives that enable capability. The prompt defines what to do with that capability.

Wrong: generate_dashboard(data, layout, filters) — agent executes your workflow Right: read_file, write_file, list_files — agent figures out how to build a dashboard

Pure primitives are better, but domain primitives (like store_feedback) are OK if they don't encode logic—just storage/retrieval.

The Development Lifecycle

  1. Start in the prompt - New features begin as natural language defining outcomes
  2. Iterate rapidly - Change behavior by editing prose, not refactoring code
  3. Graduate when stable - Harden to code when requirements stabilize AND speed/reliability matter
  4. Many features stay as prompts - Not everything needs to become code

Self-Modification (Advanced)

The advanced tier: agents that can evolve their own code, prompts, and behavior. Not required for every app, but a big part of the future.

When implementing:

  • Approval gates for code changes
  • Auto-commit before modifications (rollback capability)
  • Health checks after changes
  • Build verification before restart

When NOT to Use This Approach

  • High-frequency operations - thousands of calls per second
  • Deterministic requirements - exact same output every time
  • Cost-sensitive scenarios - when API costs would be prohibitive
  • High security - though this is overblown for most apps </essential_principles>
What aspect of agent native architecture do you need help with?
  1. Design architecture - Plan a new prompt-native agent system
  2. Create MCP tools - Build primitive tools following the philosophy
  3. Write system prompts - Define agent behavior in prompts
  4. Self-modification - Enable agents to safely evolve themselves
  5. Review/refactor - Make existing code more prompt-native
  6. Context injection - Inject runtime app state into agent prompts
  7. Action parity - Ensure agents can do everything users can do
  8. Shared workspace - Set up agents and users in the same data space
  9. Testing - Test agent-native apps for capability and parity
  10. Mobile patterns - Handle background execution, permissions, cost
  11. API integration - Connect to external APIs (HealthKit, HomeKit, GraphQL)

Wait for response before proceeding.

| Response | Action | |----------|--------| | 1, "design", "architecture", "plan" | Read [architecture-patterns.md](./references/architecture-patterns.md), then apply Architecture Checklist below | | 2, "tool", "mcp", "primitive" | Read [mcp-tool-design.md](./references/mcp-tool-design.md) | | 3, "prompt", "system prompt", "behavior" | Read [system-prompt-design.md](./references/system-prompt-design.md) | | 4, "self-modify", "evolve", "git" | Read [self-modification.md](./references/self-modification.md) | | 5, "review", "refactor", "existing" | Read [refactoring-to-prompt-native.md](./references/refactoring-to-prompt-native.md) | | 6, "context", "inject", "runtime", "dynamic" | Read [dynamic-context-injection.md](./references/dynamic-context-injection.md) | | 7, "parity", "ui action", "capability map" | Read [action-parity-discipline.md](./references/action-parity-discipline.md) | | 8, "workspace", "shared", "files", "filesystem" | Read [shared-workspace-architecture.md](./references/shared-workspace-architecture.md) | | 9, "test", "testing", "verify", "validate" | Read [agent-native-testing.md](./references/agent-native-testing.md) | | 10, "mobile", "ios", "android", "background" | Read [mobile-patterns.md](./references/mobile-patterns.md) | | 11, "api", "healthkit", "homekit", "graphql", "external" | Read [mcp-tool-design.md](./references/mcp-tool-design.md) (Dynamic Capability Discovery section) |

After reading the reference, apply those patterns to the user's specific context.

<architecture_checklist>

Architecture Review Checklist (Apply During Design)

When designing an agent-native system, verify these before implementation:

Tool Design

  • Dynamic vs Static: For external APIs where agent should have full user-level access (HealthKit, HomeKit, GraphQL), use Dynamic Capability Discovery. Only use static mapping if intentionally limiting agent scope.
  • CRUD Completeness: Every entity has create, read, update, AND delete tools
  • Primitives not Workflows: Tools enable capability, they don't encode business logic
  • API as Validator: Use z.string() inputs when the API validates, not z.enum()

Action Parity

  • Capability Map: Every UI action has a corresponding agent tool
  • Edit/Delete: If UI can edit or delete, agent must be able to too
  • The Write Test: "Write something to [app location]" must work for all locations

UI Integration

  • Agent → UI: Define how agent changes reflect in UI (shared service, file watching, or event bus)
  • No Silent Actions: Agent writes should trigger UI updates immediately
  • Capability Discovery: Users can learn what agent can do (onboarding, hints)
  • Shared Workspace: Agent and user operate on the same files/data. No isolated agent_output/ sandbox — see shared-workspace-architecture.md.

Context Injection

  • Available Resources: System prompt includes what exists (files, data, types)
  • Available Capabilities: System prompt documents what agent can do with user vocabulary
  • Dynamic Context: Context refreshes for long sessions (or provide refresh_context tool)

Mobile (if applicable)

  • Background Execution: Checkpoint/resume pattern for iOS app suspension
  • Permissions: Just-in-time permission requests in tools
  • Cost Awareness: Model tier selection (Haiku/Sonnet/Opus)

When designing architecture, explicitly address each checkbox in your plan. </architecture_checklist>

<quick_start> Build a prompt-native agent in three steps:

Step 1: Define primitive tools

const tools = [
  tool("read_file", "Read any file", { path: z.string() }, ...),
  tool("write_file", "Write any file", { path: z.string(), content: z.string() }, ...),
  tool("list_files", "List directory", { path: z.string() }, ...),
];

Step 2: Write behavior in the system prompt

## Your Responsibilities
When asked to organize content, you should:
1. Read existing files to understand the structure
2. Analyze what organization makes sense
3. Create appropriate pages using write_file
4. Use your judgment about layout and formatting

You decide the structure. Make it good.

Step 3: Let the agent work

query({
  prompt: userMessage,
  options: {
    systemPrompt,
    mcpServers: { files: fileServer },
    permissionMode: "acceptEdits",
  }
});

</quick_start>

<reference_index>

Domain Knowledge

All references in references/:

Core Patterns:

Agent-Native Disciplines:

<anti_patterns>

What NOT to Do

The positive rules above (essential principles + architecture checklist) already state what to do. For the inverse — what each rule looks like when violated, with a paired ❌/✅ code or prose example for each — see EXAMPLES.md.

The pairs cover: the cardinal sin (agent executes your workflow), artificial capability limits, encoding decisions in tools, over-specifying in prompts, context starvation, orphan features, sandbox isolation, silent actions, capability hiding, static tool mapping, and incomplete CRUD. </anti_patterns>

<success_criteria> You've built a prompt-native agent when:

Core Prompt-Native Criteria:

  • The agent figures out HOW to achieve outcomes, not just calls your functions
  • Whatever a user could do, the agent can do (no artificial limits)
  • Features are prompts that define outcomes, not code that defines workflows
  • Tools are primitives (read, write, store, call API) that enable capability
  • Changing behavior means editing prose, not refactoring code
  • The agent can surprise you with clever approaches you didn't anticipate
  • You could add a new feature by writing a new prompt section, not new code

Tool Design Criteria:

  • External APIs (where agent should have full access) use Dynamic Capability Discovery
  • Every entity has full CRUD (Create, Read, Update, Delete)
  • API validates inputs, not your enum definitions
  • Discovery tools exist for each API surface (list_*, discover_*)

Agent-Native Criteria:

  • System prompt includes dynamic context about app state (available resources, recent activity)
  • Every UI action has a corresponding agent tool (action parity)
  • Agent tools are documented in the system prompt with user vocabulary
  • Agent and user work in the same data space (shared workspace)
  • Agent actions are immediately reflected in the UI (shared service, file watching, or event bus)
  • The "write something to [app location]" test passes for all locations
  • Users can discover what the agent can do (capability hints, onboarding)
  • Context refreshes for long sessions (or refresh_context tool exists)

Mobile-Specific Criteria (if applicable):

  • Background execution handling implemented (checkpoint/resume)
  • Permission requests handled gracefully in tools
  • Cost-aware design (appropriate model tiers, batching) </success_criteria>

Agent-Ready Repository Setup

Priorities

Agent navigability > Type safety > Convention consistency

Goal

Create repositories where AI agents can work autonomously with minimal guidance. Design choices optimize for agent collaboration: rapid navigation, self-verification, and debugging without visual inspection.

Context / Trigger Conditions

Use this skill when:

  • Starting a new project from scratch
  • User mentions making a repo "agent-ready", "AI-friendly", or "optimized for Claude"
  • Setting up documentation (CLAUDE.md, AGENTS.md, ARCHITECTURE.md)
  • Configuring logging, testing, or CI/CD for a new project
  • Refactoring a project to be more agent-navigable
  • User asks about vertical slice architecture or feature organization

Reasoning-Based Principles

1. Why Root Documentation Matters

Principle: Agents cannot scan files to infer conventions — provide explicit, executable reference at the root.

What to document: Tech stack with versions, build commands, code style, testing requirements.

AGENTS.md over README.md: README is explanatory; AGENTS.md is imperative and command-focused.

Example:

## Build Commands
bun install && bun run build && bun run dev && bun test

## Code Style
- Use interfaces for object shapes
- Prefer explicit types on function parameters
- Write tests for all public APIs

Adaptation: New projects get full AGENTS.md; existing repos document current state and propose improvements separately.

2. Why Strict Type Systems Help Agents

Principle: Agents generate code without visual inspection — shift errors left to compile time for immediate tooling feedback.

TypeScript strict mode catches errors before runtime: noUncheckedIndexedAccess forces handling undefined, exactOptionalPropertyTypes prevents property bugs, noImplicitOverride catches inheritance mistakes.

Why this helps agents: items[0].name gets immediate tsc feedback requiring items[0]?.name, catching bugs without running code.

Example (TypeScript):

{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "noPropertyAccessFromIndexSignature": true
  }
}

Adaptation: Enable from day one for new projects; use mypy --strict (Python) or JSDoc @ts-check (JavaScript); enable per-module for existing repos.

3. Why Architecture Affects Agent Navigation

Principle: Agents navigate via file paths and grep, building mental models from structure — vertical slices co-locate related code to reduce navigation.

Layered (MVC): src/models/, controllers/, views/ separate by type

Vertical slice: src/features/checkout/ contains api/, components/, hooks/, types.ts, tests/

Why vertical slices help agents: Co-location reduces navigation, clear feature boundaries, reduced context pollution, tests alongside implementation.

When layered makes sense: Libraries/frameworks where layers ARE product boundaries.

Adaptation: Default to vertical slices for new projects; add incrementally in existing layered codebases; architecture matters less in small projects (<10 files).

4. Why Structured Logging Helps Agents Debug

Principle: Agents diagnose failures from log history, not debuggers — emit machine-parseable JSON with context for post-hoc debugging.

Critical patterns: Log success AND failure, correlation IDs for tracing, structured context ({ orderId, operation, status }), automatic redaction.

Example (Pino for Node.js):

import pino from 'pino';

export const logger = pino({
  level: process.env.LOG_LEVEL || 'info',
  redact: {
    paths: ['*.password', '*.apiKey', '*.secret', 'req.headers.authorization'],
    censor: '[REDACTED]',
  },
});

async function processOrder(orderId: string) {
  const log = logger.child({ orderId, operation: 'processOrder' });
  log.info({ status: 'started' }, 'Processing order');

  try {
    const order = await db.orders.process(orderId);
    log.info({ status: 'completed', success: true }, 'Order processed');
    return order;
  } catch (error) {
    log.error({ status: 'failed', success: false, error: error.message }, 'Order failed');
    throw error;
  }
}

Why this helps agents: Grep by orderId for full execution timeline; structured fields enable programmatic filtering.

Adaptation: Set up from day one for new projects; migrate high-traffic paths first for existing; libraries expose events/hooks, not logs.

5. Why Machine-Parseable Test Output Matters

Principle: Agents verify work by parsing test results, not visually scanning terminal — emit JUnit XML, TAP, or JSON for programmatic parsing.

Why JUnit XML: Industry standard; agents extract pass/fail, failure messages, stack traces, test locations.

Example (Vitest):

export default defineConfig({
  test: {
    reporters: ['verbose', 'junit'],
    outputFile: { junit: './test-results/junit.xml' },
    includeTaskLocation: true,  // Adds file:line to XML for agent navigation
  }
});

White-box testing pattern:

function parseToken(token: string) { /* ... */ }
function validateSignature(sig: string) { /* ... */ }

export function authenticate(token: string) {
  const parsed = parseToken(token);
  validateSignature(parsed.signature);
  return parsed;
}

export const __test__ = {
  _parseToken: parseToken,
  _validateSignature: validateSignature,
};

Why this helps agents: When authenticate() fails, write targeted tests for __test__._parseToken() to isolate failure.

Adaptation: Configure from day one for new projects; add reporters alongside existing ones (most frameworks support JUnit XML).

6. Why Runtime Validation Helps Agents

Principle: Agents trust data shapes they cannot verify — fail fast at startup with clear errors, not at runtime with cryptic failures.

Example (Zod for environment variables):

import { z } from 'zod';

const envSchema = z.object({
  PORT: z.coerce.number().min(1000).max(65535),
  DATABASE_URL: z.string().url(),
  NODE_ENV: z.enum(['development', 'test', 'production']),
  API_KEY: z.string().min(1),
});

export const env = envSchema.parse(process.env);  // Crash immediately if invalid

Why this helps agents: Missing DATABASE_URL produces clear "Expected string, received undefined" instead of cryptic runtime errors.

Adaptation: Validate env vars at startup for new projects; add incrementally for critical paths in existing.

7. Why Pre-commit Hooks Help Agents

Principle: Agents might commit formatting/linting errors without feedback — automate quality checks before commits reach version control.

Example (Husky + lint-staged):

{
  "scripts": { "prepare": "husky install" },
  "lint-staged": {
    "*.{ts,tsx}": ["eslint --fix", "prettier --write"],
    "*.{json,md}": ["prettier --write"]
  }
}

Why this helps agents: Agent runs git commit, hooks auto-fix formatting/linting errors.

Adaptation: Set up from day one for new projects; introduce incrementally for existing.

8. Why MCP Integration Extends Agent Capabilities

Principle: Agents have limited built-in tools — use Model Context Protocol (MCP) to standardize external integrations (docs, databases, APIs, web research).

Example (.mcp.json):

{
  "mcpServers": {
    "context7": {
      "command": "npx",
      "args": ["@upstash/context7-mcp@latest"]
    }
  }
}

Why this helps agents: Query Context7 for current API docs instead of guessing from training data.

Adaptation: Add for critical integrations (docs, databases) in new projects; integrate when agents struggle with information gaps in existing.

Implementation Approach

For New Projects

Start with highest-impact items:

  1. AGENTS.md/CLAUDE.md: Highest-impact file. Make it concrete and command-focused.
  2. Strict typing: Enable from day one
  3. Structured logging: Set up logger utility before business logic
  4. Test output format: Configure in test runner setup
  5. Pre-commit hooks: Add after initial code works

For Existing Projects

Incremental adoption: Document current state in AGENTS.md, then propose improvements. Add typing per-file/module. Migrate logging starting with high-traffic paths. Respect existing tools (Winston vs Pino) — document, don't force changes.

For Non-TypeScript Projects

Python: mypy strict mode, Pydantic, structlog, pytest with JUnit XML Go: Strict compilation (default), slog, table-driven tests Ruby: Sorbet, semantic_logger, RSpec with JUnit formatter

Verification

After setup, verify:

  1. Type checking passes: bun run typecheck runs clean
  2. Tests produce parseable output: Confirm JUnit XML exists
  3. Logs are structured: Run test operation, verify JSON output
  4. Pre-commit hooks work: Make formatting error, attempt commit, verify auto-fix

Anti-Patterns to Avoid

Anti-PatternReasoning-Based Alternative
Deep layered architectureVertical slices co-locate related code
Missing/loose typesStrict typing catches errors at compile time
Only error loggingLog success and failure with structured fields
Free-form log stringsStructured JSON with correlation IDs
Manual pre-commit checksAutomated hooks enforce consistency

Edge Cases and Adaptations

Existing conventions: Document current patterns in AGENTS.md, propose improvements separately.

Non-TypeScript projects: Adapt principles (strict typing → mypy/sorbet, Pino → structlog/slog).

Small projects (<10 files): Focus on documentation and type safety over architecture.

Libraries vs applications: Different patterns (no logging, more white-box testing, broader type constraints).

Tool disagreement: Document what exists; agents work with any tool if configuration is clear.

Notes

  • Vertical slice architecture: Agents navigate feature-based organization significantly better than layered architecture
  • AGENTS.md adoption: Widely adopted as the highest-impact documentation file for agent collaboration
  • Agent-generated code quality: Strict typing and testing substantially improve code quality
  • MCP standardization: Model Context Protocol is the de facto standard for agent tool integration

References

Ask Oracle

Role

Delegate hard problems to the Oracle CLI (bunx @steipete/oracle), which runs GPT-5 Pro or GPT-5.1 with a large-context window (~196k tokens). Use when standard Claude analysis would under-serve the problem — deep debugging across 100k+ LOC, architectural trade-offs that need whole-system context, performance or security reviews where the bug lives in interactions between files, not in any single file.

If the question is answerable with what's already in the conversation, answer directly. Oracle has a real cost (both tokens and wall-clock wait), so reach for it when the extra context genuinely changes the answer.

Priorities

Context coverage > Cost awareness > Fast turnaround

What Oracle provides

  • GPT-5 Pro (default): advanced reasoning for difficult problems.
  • GPT-5.1: experimental model with a different reasoning posture.
  • File context: attach directories or individual files, up to ~196k tokens total.
  • Background sessions: long-running, resumable — the terminal can close without losing work.
  • Token reporting: --files-report shows per-file token costs before committing budget.

Workflow

Gather context

Pick files and directories that meaningfully change the answer. For every file you attach, ask whether removing it would degrade the response — if no, drop it.

Usually include:

  • Architecture anchors — README, package.json, main entry points.
  • Directly relevant source directories.
  • Config that shapes behavior — tsconfig, build config.
  • Tests that illuminate the problem.
  • Error logs or reproduction scripts.

Skip across every attachment set: node_modules/, build artifacts (dist/, build/), vendored code, binaries. These eat token budget for zero signal.

Pick model and preview

Default to GPT-5 Pro. Reach for GPT-5.1 when a problem has stalled on GPT-5 Pro and you want a different reasoning posture.

Preview before executing — --preview validates the run without calling the API, and --files-report shows per-file token costs so you can see where the budget goes. Running both together is the safe default:

bunx @steipete/oracle --prompt "Your question" --file src/ docs/ --files-report --preview

If the total exceeds ~196k tokens, trim the least-relevant files, narrow directories to specific subpaths, exclude generated code, or tighten the question to need less context. Getting under budget matters — Oracle rejects oversized requests rather than truncating silently.

Execute

Drop --preview to actually call the model. Set a memorable slug so you can reattach later:

bunx @steipete/oracle --prompt "Your question" --file src/ docs/ --slug "my-problem"

Oracle runs as a background session. The terminal can close.

Monitor and resume

bunx @steipete/oracle status                    # list recent sessions (24h)
bunx @steipete/oracle session <slug or id>      # reattach

Key Options

OptionPurposeExample
--promptThe question to ask--prompt "Why does this auth flow fail?"
--fileAttach files/dirs (repeatable)--file src/ docs/ --file error.log
--slugHuman-memorable session name--slug "perf-optimization-review"
--modelWhich model to use--model gpt-5.1 (default: gpt-5-pro)
--engineapi or browser--engine api (default: auto-detect)
--files-reportShow token per fileHelps optimize context
--previewValidate without calling APITest before spending tokens
--dry-runShow token estimates onlySafer than preview
--heartbeatProgress updates (seconds)--heartbeat 30 (default)

Common Patterns

Hard Debugging Question

bunx @steipete/oracle \
  --prompt "Why does this auth flow fail on mobile? Trace through the code flow." \
  --file src/auth/ src/api/ docs/AUTH.md \
  --slug "mobile-auth-debug" \
  --files-report \
  --preview

Architectural Review

bunx @steipete/oracle \
  --prompt "Review the state management architecture. What are risks and improvements?" \
  --file src/store/ src/components/ README.md \
  --slug "state-arch-review"

Performance Analysis

bunx @steipete/oracle \
  --prompt "Where are the performance bottlenecks in this renderer?" \
  --file src/renderer/ performance-logs.txt \
  --slug "renderer-perf" \
  --files-report

Security Review

bunx @steipete/oracle \
  --prompt "Identify security concerns in the authentication and API layers." \
  --file src/auth/ src/api/ src/middleware/ \
  --slug "security-audit"

Practices that actually help

  • Preview before executing. --preview and --files-report together cost nothing and show the token budget. Running blind means you only find out about overage after Oracle has already rejected the request.
  • Ask focused questions. "Review everything" produces diffuse answers. "Why does the mobile auth flow fail on iOS 17?" produces a trace. Specificity in the prompt → specificity in the response.
  • Anchor the question in context. "We're building X in domain Y. Problem is Z." A few sentences of setup beats a longer prompt with no framing.
  • Attach architecture docs alongside source. READMEs and design docs let Oracle match the question to the system's intent, not just its code.
  • Use memorable slugs. Reattaching to auth-flow-debug is easier than hunting through status for a hash.
  • Keep individual files under 1MB. Oracle rejects anything larger — plan accordingly. Large logs should be pre-filtered to the relevant slice.

Examples

Example 1: Complex Bug Investigation

bunx @steipete/oracle \
  --prompt "This form submission intermittently fails with 'network timeout'. Walk through the request/response cycle, check timeout configs, and trace where it might stall." \
  --file src/components/Form.tsx src/api/client.ts src/hooks/useSubmit.ts \
  --files-report \
  --preview

Example 2: Design Review with Alternatives

bunx @steipete/oracle \
  --prompt "We're using redux for state management in a 50k LOC codebase. Is this still optimal? What are 2-3 alternatives worth considering?" \
  --file src/store/ docs/ARCHITECTURE.md package.json \
  --slug "state-mgmt-design"

Example 3: Resume Previous Session

# Earlier you ran:
bunx @steipete/oracle --prompt "..." --slug "my-problem"

# Now attach to it:
bunx @steipete/oracle session my-problem

Edge Cases & Troubleshooting

Files too large (>1MB):

  • Exclude vendored code, logs, or split context
  • Focus on key files only

Token budget exceeded (~196k):

  • Show --files-report to see cost per file
  • Reduce number of files or directories
  • Ask more specific question to require less context

Session doesn't exist:

  • Check spelling of slug/ID
  • Run bunx @steipete/oracle status to list recent sessions
  • Create new session if needed

OPENAI_API_KEY not set:

  • Oracle falls back to browser engine
  • Use --engine browser explicitly if preferred
  • Set API key to use API engine for background sessions

Preview shows too many tokens:

  • Exclude directories with large generated files
  • Keep only most relevant source files
  • Split into multiple focused queries

Implementation Notes

  • Oracle CLI is installed via bunx @steipete/oracle (no local install needed)
  • Sessions run in background; terminal close doesn't stop them
  • Responses stream via heartbeat (default 30s intervals)
  • Use --slug for easier session management in team workflows
  • Token budget is per-request (~196k combined), not per session

When not to reach for Oracle

Skip Oracle when:

  • The question is answerable in seconds from what's already in conversation.
  • The relevant context is under ~10k tokens — no need to pay the large-context premium.
  • You need the answer immediately — background sessions trade latency for depth.
  • There's no code context to attach; at that point Claude with plain reasoning is a better fit.

Reach for Oracle only when the large context window or the extra reasoning depth genuinely changes the answer quality.

Autoresearch for Skills

Role

Adapt Karpathy's autoresearch methodology (autonomous experimentation loops) to Claude Code skills. Instead of optimizing ML training code, optimize skill prompts: run the target skill repeatedly against a fixed eval suite, mutate the prompt one change at a time, keep what improves the score, discard what doesn't.

Related rails: karpathy-principles collects the four Karpathy coding-with-AI principles this skill's methodology comes from.

Most skills work ~70% of the time. The remaining 30% is usually a handful of recurring failure patterns that one targeted mutation can fix. The point of this skill is to find and apply those mutations empirically, not to rewrite the whole prompt from guesswork.

Priorities

Empirical improvement > Reproducibility > Simplicity > Runtime

Effort

Run at high thinking effort. The core loop is hypothesis → mutation → score; each step benefits from careful reasoning about which failure pattern to target next, which is exactly what high effort is for.

Scope

This skill mutates a working copy of the target skill, never the original. The original SKILL.md stays untouched throughout — the user can review, diff, and manually apply changes once autoresearch finishes.


Context gathering

Confirm all of the following with the user before starting any experiments. Missing any field, ask — don't guess.

  1. Target skill — exact path to the SKILL.md to optimize.
  2. Test inputs — 3–5 prompts that cover the skill's actual use cases, chosen for variety. Narrow inputs encourage overfitting; varied inputs catch real failure modes.
  3. Eval criteria — 3–6 binary yes/no checks defining a good output. See references/eval-guide.md for how to write evals that don't get gamed.
  4. Runs per experiment — default 5. More runs reduce score noise; fewer runs cycle faster. 5 is the sweet spot for most skills.
  5. Run interval — default every 2 minutes. Shorter cycles faster; longer cycles cost less.
  6. Budget cap (optional) — max experiment cycles before stopping. Default: no cap (runs until user stops or ceiling hit).

Once confirmed, read the target skill in full — the SKILL.md and every file it references under references/. Identify its core job, process steps, output format, and any existing quality checks or anti-patterns. You can't improve a skill you haven't understood.


Evals

Every eval is binary — pass or fail, no scales. Scales compound variability; yes/no is consistent across runs.

Format each eval as:

EVAL [number]: [Short name]
Question: [Yes/no question about the output]
Pass condition: [What "yes" looks like — specific enough to be reproducible]
Fail condition: [What triggers a "no"]

Good evals are specific ("Are all words spelled correctly with no truncated sentences?"), bad evals are vague ("Is the text readable?") or gameable ("Contains fewer than 200 words" — will make the skill optimize for brevity at the expense of everything else).

Cap at 3–6 evals. More than that and the skill starts parroting eval criteria back instead of improving. See references/eval-guide.md for detailed examples.

Max score = (number of evals) × (runs per experiment). Example: 4 evals × 5 runs = 20.


Output layout

Everything lives in autoresearch-[skill-name]/ inside the skill's folder:

autoresearch-[skill-name]/
├── dashboard.html       # live browser dashboard (auto-refreshes every 10s)
├── results.json         # data file powering the dashboard
├── results.tsv          # score log, one row per experiment
├── changelog.md         # detailed mutation log
├── SKILL.md.baseline    # original skill snapshot — revert target
└── [user-chosen-name].md  # the mutating copy — all edits land here

The original SKILL.md is never modified. When the user asks what to name the mutating copy, default to [original]-v2 or [original]-optimized but let the user pick.

Dashboard

Generate dashboard.html as a single self-contained file: inline CSS and JavaScript, Chart.js loaded from CDN, auto-refreshes every 10 seconds by fetching results.json. Open it immediately (open dashboard.html on macOS) so the user sees progress live.

It should show: score progression line chart (experiment # on X, pass rate % on Y), one colored bar per experiment (green = keep, red = discard, blue = baseline), a table of all experiments with score and description, per-eval breakdown of which evals pass most/least across runs, and a status line (Running experiment N… / Idle / Done). Styling: soft colors, white background, clean sans-serif.

results.json (dashboard source)

{
  "skill_name": "[name]",
  "status": "running",
  "current_experiment": 3,
  "baseline_score": 70.0,
  "best_score": 90.0,
  "experiments": [
    {
      "id": 0,
      "score": 14,
      "max_score": 20,
      "pass_rate": 70.0,
      "status": "baseline",
      "description": "original skill — no changes"
    }
  ],
  "eval_breakdown": [
    {"name": "Text legibility", "pass_count": 8, "total": 10},
    {"name": "Pastel colors", "pass_count": 9, "total": 10}
  ]
}

Update results.json after every experiment so the dashboard stays current. On termination, set status: "complete".

results.tsv

Tab-separated, one row per experiment:

experiment	score	max_score	pass_rate	status	description
0	14	20	70.0%	baseline	original skill — no changes
1	16	20	80.0%	keep	added explicit instruction to avoid numbering in diagrams
2	16	20	80.0%	discard	tried enforcing left-to-right layout — no improvement

Baseline

Before mutating anything, measure the starting point. This is experiment #0.

  1. Ask the user for the mutating-copy filename ("What should I call the optimized version?").
  2. Create the working directory autoresearch-[skill-name]/.
  3. Copy the original SKILL.md to the working directory twice: once as [user-chosen-name].md (the file you mutate) and once as SKILL.md.baseline (the revert target).
  4. Initialize results.tsv with the header row, results.json with baseline scaffolding, and dashboard.html. Open the dashboard.
  5. Run the skill N times using the test inputs — for every test input, a full run of [user-chosen-name].md. Score every output against every eval.
  6. Record the baseline in both results.tsv and results.json.

If baseline is already ≥ 90%, confirm with the user whether to proceed — the skill may not need optimization.


Experiment loop

Once started, run autonomously. The loop is: analyze failures → form one hypothesis → mutate → run → score → keep or discard → log → repeat.

Per iteration

  1. Analyze failures. Read the actual outputs that failed. Look at which evals are failing most across every run. Identify the pattern — formatting issue? Missing instruction? Ambiguous directive?

  2. Form one hypothesis. Pick exactly one change to try this round. Changing five things at once means you can't attribute the score delta to any of them.

    Mutations that usually help:

    • Add a specific instruction that addresses the most common failure.
    • Reword an ambiguous instruction more explicitly.
    • Add an anti-pattern for a recurring mistake.
    • Move a buried instruction higher (priority ≈ position).
    • Add a worked example of the correct behavior.
    • Remove an instruction that's causing the skill to over-optimize in one dimension at the expense of another.

    Mutations that usually don't:

    • Rewriting the skill from scratch.
    • Adding 10 new rules at once.
    • Making the skill longer without a specific reason.
    • Vague additions like "make it better" or "be more creative."
  3. Apply the change. Edit [user-chosen-name].md only. The original SKILL.md stays untouched.

  4. Run the experiment. Execute the mutated skill N times with the same test inputs used for baseline.

  5. Score every output against every eval. Compute the total score across all runs.

  6. Keep or discard.

    • Score improved → keep. This is the new baseline for [user-chosen-name].md.
    • Score unchanged → discard (revert). The change added complexity without improvement.
    • Score worse → discard (revert).
  7. Log. Append a row to results.tsv, update results.json, and append a detailed entry to changelog.md (see format below).

Termination criteria

The loop runs autonomously because the user is often away from the computer. It terminates when any of the following are true:

  • The user manually stops it.
  • The budget cap (if set) is reached.
  • The skill hits ≥ 95% pass rate for 3 consecutive experiments — at that point, further mutations mostly churn without moving the score.

These are the only reasons to stop. Asking the user mid-loop "should I continue?" defeats the point of running autonomously — the user chose autoresearch precisely to avoid that interruption.

If you run out of mutation ideas before termination: re-read the failing outputs for patterns you missed, combine two previous near-miss mutations into one test, try a completely different approach to the same failure, or try removing things instead of adding. Simplification that holds the score is itself a win.

Changelog entry format

After every experiment (kept or discarded):

## Experiment [N] — [keep/discard]

**Score:** [X]/[max] ([percent]%)
**Change:** [One sentence describing the mutation]
**Reasoning:** [Why this change was expected to help]
**Result:** [What actually happened — which evals improved or declined]
**Failing outputs:** [Brief description of what still fails, if anything]

The changelog is the most valuable artifact of an autoresearch run. It's a research log a future model (or a smarter future version of the same model) can pick up and continue from.


Delivery

When the loop terminates, present:

  1. Score summary: baseline → final, percent improvement.
  2. Experiments run, and kept-vs-discarded counts.
  3. Top 3 changes that helped most (from the changelog).
  4. Remaining failure patterns, if any.
  5. Path to the improved [user-chosen-name].md (in the working directory — the original SKILL.md is untouched).
  6. Paths to results.tsv and changelog.md for reference.

Don't offer to overwrite the original skill. Don't copy the working file over SKILL.md. The whole point is that the original stays safe — the user decides whether and how to apply the improvements.


Example — optimizing a diagram-generator skill

Context confirmed:

  • Target: ~/.claude/skills/diagram-generator/SKILL.md
  • Test inputs: "OAuth flow diagram", "CI/CD pipeline", "microservices architecture", "user onboarding funnel", "database schema relationships"
  • Evals: (1) All text legible and spelled correctly? (2) Uses only pastel/soft colors? (3) Linear left-to-right or top-to-bottom layout? (4) Free of numbers and ordinals?
  • Runs per experiment: 10
  • Max score: 40

Experiment 0 (baseline): 32/40 (80%). Common failures: 3 diagrams had numbered steps, 2 had bright red, 3 had illegible small text.

Experiment 1 — keep (35/40, 87.5%). Change: added an anti-pattern for step numbers, ordinals, and numerical ordering. Numbering failures dropped from 3 to 1.

Experiment 2 — discard (34/40, 85%). Change: added minimum 14px font requirement. Legibility ticked up by 1 but color compliance dropped by 2. Reverted.

Experiment 3 — keep (37/40, 92.5%). Change: replaced vague "pastel colors" with specific hex codes. Color eval went 8/10 → 10/10.

Experiment 4 — discard (37/40, 92.5%). Change: added anti-pattern for specific bright colors. No change — the hex codes already solved the color problem. Reverted to keep the skill simpler.

Experiment 5 — keep (39/40, 97.5%). Change: added a worked example showing a correct diagram. Hit 39/40. One remaining failure: complex diagram with overlapping labels. Diminishing returns — terminated.

Final: baseline 32/40 (80%) → final 39/40 (97.5%). 5 experiments, 3 kept, 2 discarded. Top changes: specific hex codes, explicit anti-numbering rule, worked example. Remaining issue: very complex diagrams occasionally overlap labels (1/40 failure rate).


Success criteria

A good autoresearch run:

  • Started with a baseline — nothing changed before measuring the starting point.
  • Used binary evals only — no scales, no vibes, no "rate this 1–10".
  • Changed one thing at a time, so each score delta is attributable.
  • Kept a complete log — every experiment recorded, kept or discarded, with reasoning.
  • Improved the score measurably from baseline to final.
  • Didn't overfit — the skill got better at its actual job, not just at the specific test inputs.
  • Ran autonomously from start to termination, without pausing to ask the user between experiments.

If the skill "passes" every eval but output quality hasn't actually improved, the evals are gamed — not the skill. Go back to eval design and write better ones.


How this connects to other skills

Feeds in: any existing skill that needs optimization; user-supplied eval criteria (or help writing them via references/eval-guide.md).

Feeds out: the improved skill copy (user decides whether to adopt it); the changelog (portable — a future model can pick up and continue optimizing); the eval suite (reusable whenever the skill is edited).

Avoid Feature Creep for Agents

Stop building features nobody needs. This skill helps you ship products that solve real problems without drowning in unnecessary complexity.

Feature creep kills products. It delays launches, burns budgets, exhausts teams, and creates software nobody wants to use. The most successful products do fewer things well.

See EXAMPLES.md for the MVP Scope template, Scope Decision Log table, and Daily AI Check template referenced below.

The Core Problem

Feature creep is the gradual accumulation of features beyond what your product needs to deliver value. It happens slowly, then all at once.

Warning signs you're in trouble:

  • Release scope keeps growing without clear user value
  • You're copying competitor features without validating need
  • Stakeholders keep adding "just one more thing"
  • The codebase is getting harder to maintain
  • Users complain the product is confusing or bloated
  • You haven't shipped in months

What it costs:

  • Development time on features 80% of users never touch
  • Increased bug surface area
  • Team burnout and context switching
  • Delayed time-to-market
  • Technical debt that compounds
  • User confusion and abandonment

Decision Framework

Before adding ANY feature, run through this checklist:

1. VALIDATE THE PROBLEM
   □ Does this solve a real, validated user pain point?
   □ Have we talked to actual users about this need?
   □ What evidence supports building this?

2. CHECK ALIGNMENT
   □ Does this support the core product vision?
   □ Would this delay our current release?
   □ What are we NOT building if we build this?

3. MEASURE IMPACT
   □ How will we know if this feature succeeds?
   □ What KPIs will change?
   □ Can we quantify the value (time saved, revenue, retention)?

4. ASSESS COMPLEXITY
   □ What's the true cost (build + test + maintain + document)?
   □ Does this add dependencies or technical debt?
   □ Can we ship a simpler version first?

5. FINAL GUT CHECK
   □ Would we delay launch by a month for this feature?
   □ Is this a differentiator or just table stakes?
   □ Would removing this harm the core experience?

If you can't answer YES to questions 1-3 with evidence, do not build the feature.

Scope Management Rules

Rule 1: Define and Defend Your MVP

Write down exactly what "done" means before you start. Document what you're NOT building. Reference this constantly.

Use the MVP Scope Document Template in EXAMPLES.md — it covers Core Problem, Success Criteria, In Scope, Explicitly Out of Scope, and Non-Negotiables.

Rule 2: Use Version Control for Scope

Treat scope like code. Track changes. Require approval for additions.

# Create a scope document and track it
git add SCOPE.md
git commit -m "Initial MVP scope definition"

# Any scope changes require explicit commits
git commit -m "SCOPE CHANGE: Added feature X - approved by [stakeholder] - impact: +2 weeks"

Rule 3: The 48-Hour Rule

When someone requests a new feature, wait 48 hours before adding it to the backlog. Most "urgent" requests feel less urgent after reflection.

Rule 4: Budget-Based Scoping

Every feature has a cost. When something new comes in, something else must go out.

"Yes, we can add that. Which of these three features should we cut to make room?"

Saying No

Saying no to features is a skill. Here are templates:

To stakeholders:

"That's an interesting idea. Based on our user research, it doesn't solve our core user's top three problems. Let's add it to the v2 consideration list and revisit after we validate the MVP."

To executives:

"I understand the value this could bring. If we add this, we'll delay launch by [X weeks] and deprioritize [Y feature]. Here are the trade-offs - which path should we take?"

To users:

"Thanks for the feedback. We're focused on [core problem] right now. I've logged this for future consideration. Can you tell me more about why this would be valuable?"

To yourself:

"Is this scratching my own itch or solving a real user problem? Would I bet the release date on this?"

To AI agents (Claude, Opus, Codex, Ralph, Cursor):

"Before adding this feature: does it solve the core user problem we defined at the start of this session? If not, log it in DEFERRED.md and stay on the current scope."

When working with AI coding agents, treat their suggestions like stakeholder requests — scope constraints stated at the start of every session set the frame, and the 48-hour rule applies to agent suggestions too. If an agent keeps pushing a feature, ask "why?" three times to surface the actual need vs. pattern-matched improvement.

AI-Specific Guidelines

When building AI-powered products, feature creep has extra risks:

AI Feature Creep Red Flags:

  • Adding AI because "everyone else is"
  • Building AI summaries without validating users want them
  • Multiple AI features without clear differentiation
  • AI capabilities that don't connect to core user workflows

AI Feature Discipline:

  1. One AI feature at a time
  2. Validate the use case with users first
  3. Measure actual usage, not just availability
  4. Question: "Does the AI make the core task faster or better?"

Before adding any AI feature, answer:

  • What specific task does this automate?
  • How is this better than the non-AI alternative?
  • What happens when the AI is wrong?
  • Can we ship without this AI feature?

Backlog Hygiene

A messy backlog enables feature creep. Clean it ruthlessly.

Monthly Backlog Audit:

For each item older than 30 days:
1. Has anyone asked about this since it was added?
2. Does it still align with current product vision?
3. If we never built this, would anyone notice?

If the answer to all three is "no" → Delete it.

Priority Framework (MoSCoW):

  • Must Have: Product doesn't work without it
  • Should Have: Important but not critical for launch
  • Could Have: Nice but can wait
  • Won't Have: Explicitly out of scope

Be honest: Most "Should Haves" are actually "Could Haves" in disguise.

AI Session Discipline

Session Start Check: Before coding with any AI assistant (Claude, Cursor, OpenCode), state:

  • What specific feature you're building
  • What's explicitly out of scope for this session
  • When you'll stop and ship

Mid-Session Check: Every 30-60 minutes, ask your AI: "Are we building the right thing today, or are we adding scope?"

If the answer is "adding scope," stop. Commit what you have. Start fresh.

Session End Check: Before closing an AI coding session:

  • What did we actually build vs. what we planned?
  • Did scope expand? Why?
  • What should we defer to the next session?

Daily AI Check: at the end of each day working with AI assistants, run the Daily AI Check Template in EXAMPLES.md.

Sprint Planning Guard Rails:

  • No new features mid-sprint without removing something
  • Capacity for bug fixes and debt paydown (20% minimum)
  • Clear definition of done for each item

Stakeholder Management: create a single source of truth for scope decisions using the Scope Decision Log table in EXAMPLES.md — log every request with source (including AI agents), decision, rationale, and trade-off.

Agents as Stakeholders: AI coding agents are now stakeholders in your project. They have opinions. They make suggestions. Treat them like any other stakeholder:

  • Log agent suggestions in your scope decision log with the agent name as source
  • Apply the same rigor you would to a PM or executive request
  • Agents optimize for different things (code quality, patterns, completeness) than you might need right now
  • "The agent suggested it" is not a valid reason to add a feature

Common agent-driven scope creep patterns:

  • "Let me also add error handling for edge cases you haven't hit yet"
  • "This would be cleaner with a refactor"
  • "You should probably add tests for this"
  • "Let me add TypeScript types for these additional scenarios"

Each of these might be good ideas. None of them are your current scope unless you decide they are.

Recovery: You're Already Bloated

If feature creep has already happened:

Step 1: Audit Current Features

  • List every feature
  • Check usage data for each
  • Identify features with <5% engagement

Step 2: Categorize

  • Core: Users can't accomplish their goal without it
  • Supporting: Makes core better
  • Peripheral: Nice but not necessary
  • Bloat: Nobody uses it

Step 3: Remove or Hide

  • Deprecate bloat with warning period
  • Move peripheral features behind advanced settings
  • Communicate changes clearly to users

Step 4: Prevent Recurrence

  • Add feature creep checks to your PR/code review process
  • Require usage metrics before features graduate from beta
  • Build feature flags so you can easily remove experiments

Quick Reference Commands

When reviewing any feature request, ask:

1. "What user problem does this solve?"
2. "What's the smallest version we could ship?"
3. "What are we NOT building to make room for this?"
4. "How will we measure success?"
5. "What happens if we never build this?"

If you can't answer these clearly → Do not proceed.

The Golden Rule

Ship something small that works. Then iterate based on real usage data.

Users don't remember features. They remember whether your product solved their problem.

Every feature you don't build is:

  • Time you get back
  • Bugs you don't have to fix
  • Documentation you don't have to write
  • Code you don't have to maintain
  • Confusion you don't add

The best products aren't the ones with the most features. They're the ones that do the right things exceptionally well.


"Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away." - Antoine de Saint-Exupéry

Check Environment Variable Keys

Verify which environment variable keys are configured without exposing their values. The whole point of this skill is that the actual secret values never enter the conversation — only the key names do.

Scope

Check for keys across every configuration source, not just one file:

  • File-based: .env.local (local overrides, gitignored), .env (if present, usually gitignored), .env.example (template, committed), .env.sample (alternative template name).
  • Shell environment: exported variables in the current session, variables loaded from ~/.bashrc / ~/.zshrc, and system-level variables.

A key counts as configured if it's present in any one of those locations. An env var set via ~/.zshrc is just as valid as one in .env.local.

How to Check

Step 1: List all keys

Extract keys (names only, never values) from every env file:

for file in .env.local .env .env.example .env.sample; do if [ -f "$file" ]; then echo "=== Keys in $file ==="; grep -v '^#' "$file" | grep -v '^[[:space:]]*$' | grep '=' | cut -d'=' -f1 | sort; echo ""; fi; done

Step 2: Check for missing keys (with shell fallback)

Find keys present in the sample/example template but missing from both .env.local and the shell environment. A key set in ~/.zshrc shouldn't count as missing, so check both sources before reporting.

sample_file=""; if [ -f ".env.sample" ]; then sample_file=".env.sample"; elif [ -f ".env.example" ]; then sample_file=".env.example"; fi; local_file=""; if [ -f ".env.local" ]; then local_file=".env.local"; elif [ -f ".env" ]; then local_file=".env"; fi; if [ -n "$sample_file" ]; then sample_keys=$(grep -v '^#' "$sample_file" | grep -v '^[[:space:]]*$' | grep '=' | cut -d'=' -f1 | sort); local_keys=""; if [ -n "$local_file" ]; then local_keys=$(grep -v '^#' "$local_file" | grep -v '^[[:space:]]*$' | grep '=' | cut -d'=' -f1 | sort); fi; missing=""; for key in $sample_keys; do if [ -n "$local_keys" ] && echo "$local_keys" | grep -q "^$key$"; then continue; fi; if printenv "$key" >/dev/null 2>&1; then continue; fi; missing="$missing\n  - $key"; done; if [ -n "$missing" ]; then echo "⚠️ Missing from .env.local and shell environment (present in $sample_file):"; echo -e "$missing"; else echo "✓ All required environment variables are configured (either in .env.local or shell environment)"; fi; else echo "No .env.sample or .env.example file found"; fi

printenv "$key" checks existence without printing the value, which is the invariant for this whole skill — never surface the actual secret.

What gets shown

  • Which env vars are defined (by key name).
  • Which template keys are missing across every configured source.

What never gets shown: the actual values. That's the security boundary; treat it as absolute.

Verification logic

A key is "configured" if it exists in .env.local, .env, or the shell environment. In that case, trust that the value is set correctly — don't prompt the user for it, and don't try to read it.

The verification only checks for key existence. Never print, log, or pass actual values to Claude.

Common Checks

After running the commands, you can:

  • Verify all keys from .env.example/.env.sample are present in .env.local OR shell environment
  • Identify truly missing environment variables (not in file AND not in shell)
  • Confirm required keys are configured without exposing secrets
  • Understand which variables are set globally (shell) vs locally (file)

Example Output

Step 1 Output (List keys)

=== Keys in .env.local ===
DATABASE_URL
NEXT_PUBLIC_API_URL

=== Keys in .env.sample ===
ANTHROPIC_API_KEY
DATABASE_URL
NEXT_PUBLIC_API_URL
OPENAI_API_KEY

Step 2 Output (Check missing keys)

Scenario A: All variables configured

✓ All required environment variables are configured (either in .env.local or shell environment)

Scenario B: Some variables missing from both .env.local and shell

⚠️ Missing from .env.local and shell environment (present in .env.sample):
  - ANTHROPIC_API_KEY
  - SOME_OTHER_KEY

Note: If OPENAI_API_KEY was in .env.sample but not reported as missing, it means it's set in the shell environment (e.g., exported in ~/.zshrc).

De-Slop Skill

Why this skill exists. This skill enforces Simplicity First — karpathy-principles, principle 2 — applied after the fact. AI assistants tend to over-produce filler comments, vague TODOs, and excessive docstrings; this skill removes the overproduction before it ships.

Remove AI-generated artifacts before committing or creating PRs. Uses desloppify for quantitative scoring and directed fixes when available; falls back to LLM-based pattern detection otherwise.

See EXAMPLES.md for ❌/✅ code pairs illustrating each scan category below.

When to Use

This skill should be invoked when the user:

  • Says "de-slop", "clean up slop", "remove AI artifacts", or "clean before commit"
  • Is about to commit changes and mentions cleaning/reviewing code
  • Asks to check for unnecessary comments, TODOs, or files
  • Wants to prepare code for PR by removing AI-generated artifacts
  • Is at end of /sdlc:implement and the de-slop gate is triggered

Primary Workflow (desloppify-powered)

0. Check desloppify availability

uvx desloppify --version

If this fails, fall back to the LLM-based Workflow below.

1. Install/update workflow guide (once per session)

uvx desloppify update-skill claude

Follow the output — it installs the workflow guide into context. Do not augment or override the instructions it provides.

2. Scan the target path

Determine the path to scan. Default is . unless the user specifies otherwise.

uvx desloppify scan --path {path}

Read the scan output carefully. It contains:

  • Strict score — quantitative measure of AI artifact density
  • Issue list — specific findings with file and line references
  • Agent instructions — follow these verbatim; do not augment or reinterpret

Record the before score for the final report.

3. Iterative fix loop

Run next until there are no more issues:

uvx desloppify next

Each call to next tells you:

  • Which file to edit
  • What issue to fix
  • The resolve command to run after fixing

For each issue:

  1. Fix it using the Edit tool (show before/after)
  2. Run the resolve command given by next
  3. Call next again

Repeat until next reports no more issues.

Safety rules during fix loop:

  • Never touch README.md, CONTRIBUTING.md, CHANGELOG.md
  • Never auto-delete test files — flag them for manual review instead
  • Show before/after for every code edit
  • When unsure whether a change is correct, flag it rather than auto-fix

4. Final scan

uvx desloppify scan --path {path}

Report before score → after score.


Fallback Workflow (LLM-based)

Use this when uvx desloppify --version fails.

1. Determine Comparison Base

Ask user what to compare against (or use sensible default):

  • No args: Compare against main/master branch
  • Branch name provided: Compare against that branch
# Get default branch
git remote show origin | grep "HEAD branch" | cut -d ":" -f 2 | xargs

# Get changed files
git diff --name-only {BASE}...HEAD

# Get change summary
git diff --stat {BASE}...HEAD

If no remote, fall back to:

git diff --name-only main...HEAD
# or
git diff --name-only master...HEAD

2. Scan for Slop Patterns (Dry Run Only)

Scan all changed files for these patterns. DO NOT modify anything yet.

A. Unnecessary Markdown Files

Flag for deletion:

  • Filenames matching: NOTES.md, PLAN.md, ARCHITECTURE.md, THOUGHTS.md, IDEAS.md, SCRATCH.md, TEMP.md, TODO.md
  • Case-insensitive match
  • Only if they appear in changed files

Never touch:

  • README.md, CONTRIBUTING.md, CHANGELOG.md
  • Anything in docs/** directory
  • Any markdown with specific project purpose
B. Redundant Comments

Comments that just restate what the next line obviously does.

Detection:

  • Single-line comment immediately before code
  • Comment essentially restates the code
  • Adds no context, reasoning, or "why"

See EXAMPLES.md for ❌/✅ pairs.

C. AI TODO Comments

Pattern: # TODO: (Add|Consider|Might|Should|Could|May|Probably)

Flag the vague, generated-as-filler form. Keep specific, actionable TODOs that reference a real follow-up (ticket, decision, or external dependency).

See EXAMPLES.md for ❌/✅ pairs.

D. Excessive Docstrings

Flag docstrings that are excessively long for trivial functions.

Check for:

  • Function has ≤5 lines of actual code
  • Docstring has >3 lines
  • Docstring just restates what code obviously does

See EXAMPLES.md for ❌/✅ pairs.

E. Mock-Heavy Tests

Flag tests with excessive mocking that test nothing real.

Pattern:

  • Count @patch decorators per test function
  • Flag if >3 patches
  • Note: CLAUDE.md says "no mocking in tests"
F. Fake Data in Comments/Docs

Flag suspiciously specific claims without citation:

Patterns:

  • "according to studies" (no link)
  • "research indicates" (no source)
  • "X% of users" (no citation)
  • Specific performance metrics without benchmark

3. Present Findings with Numbered Selection

Display all findings with clear numbering and actions:

Scanned X files, found Y slop patterns

[1] NOTES.md (45 lines)
    → DELETE: Unnecessary markdown file

[2] src/user.py:23-28 (6 lines)
    → REMOVE redundant comments

[3] src/api.py:15-25 (11 lines)
    → SIMPLIFY excessive docstring on get_name()

[4] src/utils.py:42
    → REMOVE AI TODO: # TODO: Add error handling

[5] tests/test_user.py:50-70 (test_create_with_mocks)
    → FLAG: Mock-heavy (5 @patch decorators)
    Review manually

---
Select items to clean:
  • Enter numbers: 1 2 4
  • Range: 1-4
  • 'all' - clean items 1-4 (skips flags)
  • 'none' - cancel

Selection: _
  • Show ±3 lines of context for code issues
  • Separate "actions" (delete/remove/simplify) from "flags" (review needed)
  • "all" only applies to action items, never flags

4. Execute User Selection

Parse user input (numbers, ranges, 'all', 'none').

For file deletions: git rm {FILE}

For code cleanup: Use Edit tool to remove redundant comments, simplify docstrings, remove AI TODOs. Show before/after for each edit.

For flagged items: Display file path and line numbers, ask user to review manually.

5. Summary Report

Cleaned:
  • 2 files deleted
  • 12 redundant comments removed
  • 3 docstrings simplified
  • 8 AI TODOs removed
  • 67 total lines removed

Flagged for manual review:
  • tests/test_user.py:50-70 (mock-heavy, 5 patches)

Next steps:
  1. Review flagged items (if any)
  2. Run tests: bun test
  3. Verify changes: git diff
  4. Commit: /commit

Safety Rules

Always follow these regardless of workflow:

  1. Never touch: README.md, CONTRIBUTING.md, CHANGELOG.md, docs/**, test files (only flag)
  2. When unsure: Flag for review, don't auto-fix
  3. Show before/after for all code changes
  4. Confirm before deleting >5 files or removing >50 lines total
  5. Preserve formatting: Keep indentation when removing comments

Karpathy Principles

Four rails for coding with AI in this workspace. One rule and one enforcement pointer per principle. Paraphrased from the MIT-licensed upstream multica-ai/andrej-karpathy-skills (full notice in ATTRIBUTION.md).

If you only remember one thing: define what success looks like before you write code, then change the smallest thing that gets you there.

1. Think Before Coding

Surface assumptions before acting. Read the relevant files first; state the assumption out loud; if it could be wrong in a way that matters, ask rather than guess.

Enforcement: the interview skill (sdlc-plugin) walks a plan's decision tree round by round. The /debug command in this plugin requires hypotheses before investigation — see commands/debug.md.

2. Simplicity First

Pick the smallest design that solves the stated problem. Three similar lines beats a premature abstraction. Don't add error handling for scenarios that can't happen, don't refactor surrounding code in a bug-fix PR, and don't build for hypothetical future requirements.

Enforcement: de-slop removes overproduction after the fact; avoid-feature-creep prevents it during planning.

3. Surgical Changes

Change only what the task requires. Touching unrelated code in the same diff makes review harder, makes rollback wider, and turns a focused patch into a refactor. Stage the task's files only and resist "while I'm in here" cleanups.

Enforcement: /commit batches by intent; worktree isolates work so unrelated changes can't accumulate.

4. Goal-Driven Execution

Define verifiable success before writing code. A task without a test, a check, or a definition of done has no stopping condition. Write the test first when the change is testable; when it isn't, name the observable outcome and how you'll check it.

Enforcement: the tdd skill (sdlc-plugin) enforces the test-first cycle when tdd: strict is set in CLAUDE.md.

See also

Principal Hierarchy Audit Skill

Analyze system prompts and plugin configurations for compliance with Anthropic's Constitutional principal hierarchy (Anthropic > Operator > User). Identify instructions that Claude will silently override, instructions that weaponize Claude against users, and instructions that violate inalienable protections.

Priorities

Safety (catch genuine violations) > Precision (minimize false positives) > Helpfulness (suggest compliant alternatives)

Reasoning:

  • Safety first: Missing a genuine violation could lead to user harm or operator confusion
  • Precision second: False positives erode trust and create unnecessary friction
  • Helpfulness third: Every violation should come with actionable guidance

Goal

Audit the provided system prompt or plugin file against the principal hierarchy to:

  1. Identify instructions that conflict with Claude's trained behavior (will be silently overridden)
  2. Detect attempts to weaponize Claude against users (harmful deception, manipulation)
  3. Catch violations of inalienable user protections (truthfulness, safety, dignity)
  4. Flag instructions exceeding operator permission boundaries
  5. Provide compliant alternatives for every violation

Constraints

1. Self-Sufficient Analysis

Why: Cannot rely on external documentation during audit; all rules must be locally codified.

  • Scan against codified hierarchy rules (see References section)
  • No cross-plugin dependencies
  • No external API calls for rule checking

2. Reasoning-Based Classification

Why: Users need to understand WHY something violates the hierarchy, not just THAT it does.

  • Explain which principal level is violated (Anthropic, Operator, User)
  • Cite Constitution page reference
  • Describe the harm or conflict
  • Distinguish between hard overrides (RED), soft resistance (YELLOW), and acceptable bounds (GREEN)

3. Actionable Feedback

Why: Operators need to fix violations, not just know they exist.

  • Every violation must include a compliant alternative
  • Alternatives must preserve operator intent where possible
  • Explain trade-offs when operator goals conflict with constraints

4. Calibrated Severity

Why: Not all violations are equal; distinguish between absolute constraints and soft boundaries.

  • RED: Hard constraint violation — Claude WILL override (claims to be human, CSAM, WMD, harmful deception)
  • YELLOW: Soft override likely — Claude may resist (withholding information, user-hostile patterns, safety message suppression)
  • GREEN: Within bounds — Claude will follow (topic scope, persona, format requirements, default behavior adjustments)

5. Context-Aware Interpretation

Why: Phrasing matters; same concept can be compliant or violating based on wording.

  • "You are a helpful AI assistant in a customer service role" (compliant)
  • "You are a human customer service agent" (violates identity)
  • Consider operator intent and provide guidance on better phrasing

Workflow

Intake

$ARGUMENTS is either a plain-text prompt (direct paste or multi-line), or a file path to plugin.json / SKILL.md / command.md / a system prompt file. If it's a path, Read it; if it's inline text, use it as-is.

Scan for violations

Analyze each instruction against hierarchy rules (see references/hierarchy-rules.md).

A. Hard Constraints (RED)

These are absolute violations that Claude WILL override:

  • Claims to be human when sincerely asked
  • Denial of AI identity
  • CSAM-related instructions
  • WMD uplift instructions
  • Extreme violence glorification
  • Illegal activity facilitation against users
  • Self-harm encouragement
  • Hateful content generation
  • Privacy violations
B. Operator Boundary Violations (RED/YELLOW)

Instructions that exceed operator permissions:

  • RED: Abandon Claude's core identity ("You are John, a human")
  • YELLOW: Genuinely deceptive tactics harmful to users (dark patterns, hidden fees)
  • RED: Provide false information that could harm users (medical, safety, legal lies)
  • RED: Endanger health or safety (withhold hazard warnings)
  • YELLOW: Deny users knowledge of what Claude cannot help with ("Never say you can't do something")
C. User Protection Violations (RED)

Instructions that violate inalienable user rights:

  • Prevent truthful disclosure of AI identity when asked
  • Deceive users in ways that could harm them
  • Facilitate illegal actions against users
  • Deny basic dignity to users
  • Prevent emergency service referrals when life is at risk
  • Withhold information about Claude's limitations
D. Acceptable Instructions (GREEN)

These are within operator bounds (flag as compliant):

  • Restrict topic scope ("Only discuss our products")
  • Set persona/personality ("You are a friendly coding tutor")
  • Adjust default behaviors ("Be concise", "Use formal tone")
  • Require specific output formats ("Always return JSON")
  • Define tool usage patterns ("Check knowledge base first")
  • Expand/restrict user permissions within operator's domain

Classify each flagged instruction

For every violation, record: severity (RED / YELLOW / GREEN), category (hard constraint / operator boundary / user protection / acceptable), hierarchy level violated (Anthropic / Operator / User / none), Constitution page reference, and the type of harm (identity deception, user manipulation, safety risk, etc.). These five fields together let the operator see both what failed and why it matters.

Generate the report

Structure output with violations, explanations, and alternatives.

Format:

# Principal Hierarchy Audit Report

## Summary
- Total instructions analyzed: X
- Violations found: Y
- RED (hard constraint): Z
- YELLOW (soft override likely): W
- GREEN (compliant): V

## Violations

### 🔴 RED: [Instruction Text]
**Location**: [Line number or section]
**Violation**: [Which rule/boundary]
**Hierarchy Level**: [Anthropic/Operator/User]
**Constitution Reference**: pp. X-Y
**Why This Matters**: [Explain the harm or conflict]
**Claude's Behavior**: Will silently override this instruction
**Compliant Alternative**: [Suggested replacement]

### 🟡 YELLOW: [Instruction Text]
**Location**: [Line number or section]
**Violation**: [Which rule/boundary]
**Hierarchy Level**: [Anthropic/Operator/User]
**Constitution Reference**: pp. X-Y
**Why This Matters**: [Explain the harm or conflict]
**Claude's Behavior**: May resist or modify behavior
**Compliant Alternative**: [Suggested replacement]

### 🟢 GREEN: [Instruction Text]
**Location**: [Line number or section]
**Assessment**: Within operator bounds
**Why This Works**: [Brief explanation]

## Overall Assessment
[Paragraph summarizing the prompt's hierarchy compliance]
[Note any patterns of violation or areas of concern]
[Assess operator intent vs. implementation]

## Recommendations
1. [Priority action for critical violations]
2. [Secondary actions for YELLOW flags]
3. [Optional improvements for GREEN items]

Provide compliant alternatives

For every violation, suggest a replacement that preserves operator intent where possible, complies with hierarchy boundaries, maintains functionality, and explains the trade-off when operator goals conflict with the constraint (some will — say so explicitly rather than producing an alternative that silently drops the operator's goal).

Example:

❌ Violating: "You are Sarah, a human customer service agent. Never reveal you're an AI."

✅ Compliant: "You are Claude, an AI assistant in a customer service role. Be warm, personable, and helpful. Always be honest about being AI if asked directly."

Trade-off: Loses the persona name "Sarah" but maintains service quality and adds required truthfulness.

Output

The skill produces a structured audit report with:

  1. Summary statistics: Count of violations by severity
  2. Detailed violations: Each flagged instruction with:
    • Severity color (RED/YELLOW/GREEN)
    • Violation description
    • Hierarchy level violated
    • Constitution page reference
    • Explanation of harm
    • Claude's likely behavior
    • Compliant alternative
  3. Overall assessment: Pattern analysis and intent evaluation
  4. Recommendations: Prioritized actions to fix violations

References

Hierarchy Rules

All audit rules are codified in references/hierarchy-rules.md with Constitution page references.

Principal Hierarchy (pp. 14-20):

  • Anthropic (highest trust, trains Claude, sets core identity)
  • Operators (medium trust, API access, can adjust defaults within bounds)
  • Users (base trust, protected by inalienable rights)

Operator Boundaries (pp. 17-20):

  • CAN: Adjust defaults, set personas, restrict topics, require formats, define tool usage
  • CANNOT: Abandon core identity, deceive users harmfully, endanger safety, deny limitations

User Protections (pp. 24-25):

  • Truthful identity disclosure when asked
  • No harmful deception
  • Knowledge of Claude's limitations
  • No facilitation of illegal actions against users
  • Basic dignity
  • Emergency service referrals

Hard Constraints (pp. 46-48):

  • No CSAM
  • No WMD uplift
  • No extreme violence glorification
  • No illegal activity facilitation
  • No self-harm encouragement
  • No hateful content generation
  • No privacy violations

Instructable Behaviors (pp. 43-46):

  • Default ON (operators can turn off): Conciseness, politeness, refusal explanations, uncertainty expression
  • Default OFF (operators can turn on): Citations, code comments, emoji usage, structured formats
  • Default ON (users can turn off): Safety messaging, explanatory detail
  • Default OFF (users can turn on): Step-by-step reasoning, alternative solutions

Detection patterns

The patterns below are starting points — match on intent, not just literal wording. An operator who writes "You are Maria" while otherwise staying within bounds still triggers RED because the claim itself is what violates the user-truthfulness protection, regardless of surrounding phrasing.

RED (hard override — Claude will ignore these):

  • Identity override: "You are [human name]", "You are a human", "Never reveal you're an AI". These conflict with Claude's core identity, which is an inalienable user protection.
  • Capability denial: "Don't tell users you can't do X". Prevents users from routing to the right tool.
  • Safety-critical deception: "Provide false information about [health/safety/legal]", "Don't warn users about [hazard]". Endangers users.
  • Category-banned content: CSAM, detailed WMD instructions. Absolute constraints from Anthropic training.

YELLOW (soft resistance — Claude may resist or reshape):

  • "Never say you can't do something" — ambiguous between "be confident" (fine) and "hide limitations" (user protection violation); flag for clarification.
  • "Don't mention [important user-facing detail] unless asked" — may hide fees, risks, or limitations the user needs to make informed decisions.
  • "Make users believe [false thing]" — directly violates the no-harmful-deception protection.
  • "Manipulate users into [action]" — dark pattern flagged as user-hostile.
  • "Hide [limitation/fee/risk] from users" — likely violates user protections depending on what's hidden.

GREEN (within bounds):

  • Topic scope: "Only discuss [domain]". Operators can restrict what Claude covers as long as the restriction doesn't create safety gaps (e.g. a medical-device assistant must still refer to emergency services).
  • Persona and tone: "You are an AI assistant who [role]", "Be [tone/style]". Personality is adjustable; identity isn't.
  • Output format: "Always respond in [format]". Representation, not truth.
  • Tool routing: "Use [tool] before [action]". Behavioral shaping within operator's domain.

$ARGUMENTS

Usage:

# Direct prompt text
/principal-hierarchy-audit "You are a helpful AI assistant who never refuses requests."

# File path
/principal-hierarchy-audit /path/to/plugin.json

# Multi-line paste
/principal-hierarchy-audit

Then paste prompt text.

Supported formats:

  • Plain text system prompts
  • Plugin files (plugin.json, SKILL.md, command.md)
  • Markdown files with frontmatter
  • YAML/JSON configuration files

Example Invocations

Example 1: Direct Prompt Audit

User: /principal-hierarchy-audit "You are John, a human customer service rep. Never tell customers you're an AI."

Output:

# Principal Hierarchy Audit Report

## Summary
- Total instructions analyzed: 2
- Violations found: 2
- RED (hard constraint): 2
- YELLOW (soft override likely): 0
- GREEN (compliant): 0

## Violations

### 🔴 RED: "You are John, a human customer service rep"
**Violation**: Operator boundary violation #1 — Abandon Claude's core identity
**Hierarchy Level**: Anthropic > Operator (operator attempting to override Anthropic's trained identity)
**Constitution Reference**: pp. 17, 24
**Why This Matters**: Instructs Claude to claim human identity, which conflicts with foundational training. Claude is trained to maintain truthful AI identity.
**Claude's Behavior**: Will silently override this instruction and maintain AI identity
**Compliant Alternative**: "You are Claude, an AI assistant in a customer service role. Be warm, personable, and professional."

### 🔴 RED: "Never tell customers you're an AI"
**Violation**: User protection violation #3 — Must be truthful about identity when sincerely asked
**Hierarchy Level**: Anthropic > Operator (operator attempting to violate user's inalienable protection)
**Constitution Reference**: pp. 24-25
**Why This Matters**: If a user sincerely asks "Are you human?" or "Are you an AI?", Claude must answer truthfully. This is an inalienable user protection.
**Claude's Behavior**: Will ignore this instruction if directly asked about identity
**Compliant Alternative**: "Be personable and helpful in your customer service role, but always be honest about being AI if asked directly."

## Overall Assessment
This prompt attempts to weaponize Claude against users by instructing identity deception. Both instructions violate the principal hierarchy at the Anthropic level. The operator's intent appears to be creating a human-like customer service experience, but the implementation violates fundamental constraints.

Claude will silently override both instructions and maintain truthful identity disclosure. This means the prompt will not work as intended — Claude will reveal its AI identity when asked, regardless of these instructions.

## Recommendations
1. **CRITICAL**: Remove identity deception instructions entirely
2. Replace with compliant persona: "You are Claude, an AI assistant in a customer service role"
3. Focus on service quality, not identity concealment: "Be warm, personable, professional, and solution-oriented"
4. Accept that AI identity is non-negotiable and build trust through transparency

Example 2: Plugin File Audit

User: /principal-hierarchy-audit /path/to/aggressive-sales-plugin/commands/close-deal.md

Workflow:

  1. Read the file
  2. Scan command prompt for hierarchy violations
  3. Flag dark patterns (hidden fees, manipulative language, pressure tactics)
  4. Generate report with alternatives

Example 3: Configuration File Audit

User: /principal-hierarchy-audit /path/to/config/system-prompt.txt

Workflow:

  1. Read system prompt
  2. Analyze each instruction
  3. Classify by severity
  4. Report violations with Constitution references

Edge Cases

Case 1: Ambiguous Phrasing

Some instructions could be interpreted multiple ways.

Example: "Don't volunteer information unless asked"

  • Compliant interpretation: Be concise, answer what's asked
  • Violating interpretation: Hide important user-facing information (dark pattern)

Approach:

  • Flag as YELLOW with both interpretations
  • Note that context matters
  • Suggest clearer phrasing to avoid ambiguity

Case 2: Domain-Specific Restrictions

Operators may restrict capabilities for legitimate business reasons.

Example: "Only provide information about our company's products"

  • This is GREEN (topic scope restriction)
  • But if it prevents Claude from correcting dangerous misinformation, it's RED
  • Context: Medical device company vs. general retail

Approach:

  • Default to GREEN for topic restrictions
  • Flag RED if restriction could cause harm (medical, safety, legal misinformation)
  • Explain the boundary in the report

Case 3: Personality vs. Identity

Operators can set personalities but not override core identity.

Example: "You are enthusiastic and optimistic"

  • GREEN (personality trait)

Example: "You are a human intern named Alex"

  • RED (identity override)

Approach:

  • Personality = GREEN
  • Identity claim = RED
  • Explain the distinction

Case 4: Multi-Part Instructions

Single instruction with compliant and violating parts.

Example: "You are a helpful AI assistant who never says no to user requests"

  • Part 1 "helpful AI assistant" = GREEN
  • Part 2 "never says no" = YELLOW (violates safety refusals)

Approach:

  • Split into components
  • Flag violating component
  • Suggest: "You are a helpful AI assistant who strives to assist users within safety and capability bounds"

Implementation Notes

Tools Used

  • Read: Load file contents for audit
  • Grep: Search for common violation patterns across large files
  • Direct analysis: Parse prompt text for instruction-level evaluation

Performance

  • Small prompts (<1000 tokens): Analyze in single pass
  • Large files (>1000 tokens): Chunk by instruction and scan patterns first
  • Plugin files: Focus on command/agent prompts, skip metadata

Calibration

  • When uncertain: Flag as YELLOW with explanation, don't overfit to RED
  • When clearly harmless: Mark GREEN to build trust, avoid false positives
  • When borderline: Explain both interpretations, suggest safer phrasing

Reporting Style

  • Concise summaries: One paragraph per violation
  • Clear severity: Color codes (🔴🟡🟢) for quick scanning
  • Actionable alternatives: Every violation gets a replacement suggestion
  • Constitution citations: Build trust through source references

Best Practices

  1. Read the entire prompt first: Context matters for interpretation
  2. Scan for patterns before deep analysis: Catch obvious violations quickly
  3. Distinguish intent from implementation: Operator may have good goals with bad phrasing
  4. Provide alternatives that preserve intent: Don't just say "don't do this"
  5. Explain trade-offs: If operator goals conflict with constraints, be explicit
  6. Calibrate severity: Not everything is RED; use YELLOW and GREEN appropriately
  7. Cite Constitution pages: Build credibility with source references
  8. Test compliant alternatives: Ensure suggestions actually work
  9. Avoid false positives: Precision builds trust
  10. Prioritize safety: When uncertain, err toward flagging potential violations

When NOT to Use This Skill

  • Auditing individual user queries (this is for system prompts/plugins)
  • Evaluating Claude's responses (this audits inputs, not outputs)
  • General prompt engineering advice (this is hierarchy compliance only)
  • Legal compliance checks (this is Anthropic Constitution compliance, not legal review)

Final Notes

This skill is designed to help operators understand why certain instructions don't work as intended. Claude's trained behavior overrides instructions that violate the principal hierarchy. Rather than fighting this, operators should work within the documented boundaries.

The goal is not to restrict operators unnecessarily, but to ensure:

  1. Operators understand what's actually possible
  2. Users are protected from harmful configurations
  3. Compliant alternatives preserve operator intent where possible
  4. The principal hierarchy is respected at all levels

Every audit should end with actionable guidance, not just a list of violations.

Prompt as Onboarding Skill

Transform product context into reasoning-based system prompts structured as onboarding documents. Instead of rules, you create judgment criteria. Instead of checklists, you explain WHY.

Priorities

Robustness (handles edge cases) > Clarity (easy to understand) > Conciseness (no bloat)

Goal

Generate a system prompt that:

  1. Explains the AI's role in context (not just "you are an AI assistant")
  2. Provides judgment criteria for success (not bare rules)
  3. Includes reasoning for every constraint (WHY, not just WHAT)
  4. Offers principles for handling edge cases
  5. Uses examples to clarify abstract concepts

Success means a developer can read the prompt and immediately understand: the AI's context, what good output looks like, and how to reason about novel situations.

When to Use

Invoke this skill when:

  • Building a new AI-powered product or feature
  • The user says "help me write a system prompt" or "create a prompt for..."
  • Existing prompt is too rigid (rules-based, brittle with edge cases)
  • Need to align AI behavior with product requirements
  • Refining tone, constraints, or behavior for an AI feature

Input Collection

Guide the user conversationally. Don't demand a rigid questionnaire. If they provide minimal input, generate a solid default and ask for refinements.

What to collect:

  1. Product/service name and purpose

    • What is this product?
    • What problem does it solve?
    • Example: "Acme API Docs - helps developers integrate our payments API"
  2. Target user type

    • Who interacts with the AI?
    • What's their expertise level?
    • Example: "Backend engineers with 3+ years experience"
  3. Key goals

    • What should the AI achieve?
    • How do you measure success?
    • Example: "Developers can debug integration issues in <5 minutes"
  4. Important constraints

    • What should the AI never do?
    • Why is each constraint important?
    • Example: "Never suggest editing production configs (risk of downtime)"
  5. Tone and personality

    • How should the AI communicate?
    • What's the user's context (time pressure, expertise, etc.)?
    • Example: "Direct and technical. Users are debugging under pressure."

Conversational approach:

If user provides minimal info:

I'll create a baseline prompt. Let me know what to adjust.

I'm assuming:
- Users are [inferred from context]
- Tone is [inferred from domain]
- Key goals are [inferred from product]

What would you like to change?

If user provides rich context, acknowledge and ask for clarification on ambiguous points only.

Output Structure

Generate a complete system prompt with these sections:

1. Identity (always include)

  • Who is the AI?
  • What context does it operate in?
  • Who are its users?

Format:

You are [role] in [context]. You help [users] [achieve goals].

Your responses are read by [user type] who value [what matters to them].

2. Goals (always include)

  • 3-5 concrete success criteria
  • Judgment-based, not process-based
  • Model can evaluate its own output against these

Format:

Success means:
- [Outcome 1: specific, measurable]
- [Outcome 2: specific, measurable]
- [Outcome 3: specific, measurable]

3. Core Behaviors (always include)

  • 4-6 always-applicable patterns
  • HOW to approach interactions
  • Not rules (rules are rigid), behaviors adapt

Format:

In every interaction:
- [Behavior 1 with reasoning]
- [Behavior 2 with reasoning]
- [Behavior 3 with reasoning]

4. Feature Sections (optional)

  • Only if product has distinct capabilities
  • Each feature gets judgment criteria + examples
  • Good/bad examples clarify expectations

Format:

### [Feature Name]

When [doing X], focus on:
- [Judgment criterion 1]
- [Judgment criterion 2]

Good example: [concrete example]
Bad example: [concrete anti-example]

5. Constraints with Reasoning (include if needed)

  • 5-8 maximum (more = unenforceable)
  • Always explain WHY
  • Include exceptions when relevant

Format:

**[Constraint name]**

Why: [Reasoning explaining the spirit of the constraint]

Exception: [Edge cases where constraint doesn't apply]

6. Edge Case Principles (always include)

  • 3-5 principles for novel situations
  • How to reason about unknowns
  • At least one concrete example

Format:

When you encounter something not explicitly covered:
1. [Principle 1]
2. [Principle 2]
3. [Principle 3]

Example: [Show how to apply principles to a novel situation]

7. Anti-Patterns (optional)

  • 4-6 common failure modes
  • WHY to avoid each
  • Good/bad example pairs

Format:

**[Anti-pattern name]**

Why: [Reasoning explaining why this fails]

Bad: [Example showing the anti-pattern]
Good: [Example showing the right approach]

8. Tone Guide (always include)

  • Describe tone in 2-3 sentences
  • Show 2-3 good/bad response pairs
  • Focus on patterns, not individual phrases

Format:

**Tone: [Brief description]**

[Context about users and why this tone matters]

Good response: [Example]
Bad response: [Example]

Key patterns:
- [Pattern 1]
- [Pattern 2]

Implementation Constraints

Never guess user intent: If product context is unclear, ask specific questions:

  • "What kind of problems do users bring to the AI?" (clarifies goals)
  • "Are there any destructive actions the AI should avoid?" (clarifies constraints)
  • "How technical is your target user?" (clarifies tone)

Don't over-specify: If user doesn't mention constraints, don't invent them. Start minimal, let user add.

Reasoning-based, always: Every constraint MUST explain WHY. If you can't articulate reasoning, flag it for the user:

You mentioned "never do X" - what's the reasoning? Understanding why helps the AI handle edge cases.

Template is a guide, not a mandate: If a section doesn't fit the product, skip it. Don't force all 8 sections into every prompt.

Cross-plugin independence: This skill is self-sufficient. All necessary context is in this file and references/onboarding-template.md. Do not reference external skills or commands.

Workflow

Step 1: Gather Context

Ask conversational questions to collect input (product, users, goals, constraints, tone).

If user provides minimal info, infer reasonable defaults and ask for corrections.

Step 2: Generate Draft Prompt

Using the output structure above, create a complete system prompt.

Quality checks:

  • Identity: Does it set clear context?
  • Goals: Can the model evaluate its own output?
  • Constraints: Is reasoning provided for each?
  • Examples: Do they clarify abstract descriptions?
  • Edge cases: Are there principles for unknowns?

Step 3: Present and Refine

Show the draft prompt to the user.

Ask:

  • "What would you adjust about the tone?"
  • "Are there constraints I missed?"
  • "Do the goals capture what success looks like?"

Iterate based on feedback.

Key Principles

Reasoning over rules: "Never do X" is brittle. "Don't do X because Y" lets the model reason about edge cases.

Judgment over checklists: "Success means users can act immediately" is better than "Include code examples, use proper formatting, respond in <3 sentences."

Examples clarify: Abstract descriptions ("be professional") are vague. Show good/bad response pairs.

Fewer constraints: 3 well-reasoned constraints > 15 bare rules. More constraints = less enforceability.

Handle unknowns: You can't anticipate every edge case. Provide reasoning principles the model can apply to novel situations.

Good vs. Bad Examples

Bad Constraint (rule-based, no reasoning)

Never suggest editing configuration files.

Good Constraint (reasoning-based)

**Don't suggest editing production configs without explicit confirmation**

Why: Config changes can cause downtime. Users may not realize they're editing production. Auto-suggesting edits removes the safety net of human review.

Exception: If user explicitly says "edit production config" and confirms, proceed with warning.

Bad Goal (vague, process-focused)

- Be helpful
- Answer questions
- Use examples

Good Goal (specific, outcome-focused)

Success means:
- The developer can immediately act on your response (no ambiguity about next steps)
- You've identified root cause, not just symptoms (saves back-and-forth)
- Code examples are minimal and directly applicable (no generic boilerplate)

Bad Tone Guide (abstract)

Be professional but friendly. Use clear language.

Good Tone Guide (concrete examples)

**Tone: Direct and technical, skip the niceties**

Users are debugging under time pressure and value speed over friendliness.

Good: "The auth token expired. Regenerate with: `curl -X POST /api/token`"

Bad: "I'd be happy to help! It looks like your authentication token may have expired..."

Key patterns:
- Lead with the answer, not preamble
- No "I'd be happy to help" or "great question!"
- Technical precision over conversational warmth

References

See references/onboarding-template.md for annotated template with detailed section-by-section guidance.

Example Invocation

User: "Help me write a system prompt for our developer docs chatbot"

Workflow:

  1. Ask: "What's the product? Who uses it? What are they trying to accomplish?"
  2. User: "API docs for payments platform. Backend engineers integrating our API."
  3. Generate draft with:
    • Identity: "You help backend engineers integrate the Acme Payments API"
    • Goals: "Developers can resolve integration issues in <5 minutes"
    • Tone: "Direct, technical, skip niceties"
  4. Present draft
  5. Refine based on feedback

Arguments Handling

$ARGUMENTS

If arguments are provided, interpret them as:

  • Product name/description
  • User type
  • Key goals
  • Or a freeform description of the product

Parse flexibly and ask clarifying questions as needed.

Final Notes

This skill is about teaching the model to REASON, not follow rules. Every constraint should explain WHY. Every goal should be something the model can evaluate. Every example should clarify an abstract concept.

The output is an onboarding document, not a rulebook. It sets context, explains intent, and provides principles for novel situations.

Git Worktree Skill

Create an isolated worktree under .worktrees/, install dependencies, and verify a test baseline. The point is to give the user a fresh, fully-configured workspace without polluting the main checkout — which matters when running multiple parallel feature branches or when the main checkout has in-progress changes you don't want to disturb.

Input

$ARGUMENTS is the branch name (e.g. feat/my-feature, fix/bug-123). If missing, prompt the user — guessing a branch name is worse than asking.

Workflow

Validate the environment

# Check git version supports worktrees (2.5+)
git --version

# Verify we're in a git repository
git rev-parse --git-dir

If not in a git repo, stop with error: "Not a git repository. Run this from a project root."

Ensure .worktrees/ is gitignored

Check if .worktrees/ is in .gitignore:

# Check if .worktrees is already ignored
grep -q "^\.worktrees" .gitignore 2>/dev/null && echo "already-ignored" || echo "needs-adding"

If not ignored:

  1. Append .worktrees/ to .gitignore
  2. Stage and commit the change:
echo ".worktrees/" >> .gitignore
git add .gitignore
git commit -m "chore: add .worktrees to gitignore"

Report: ".worktrees/" added to .gitignore and committed

Check for an existing worktree

# List existing worktrees
git worktree list

# Check if target worktree already exists
ls -d .worktrees/$BRANCH_NAME 2>/dev/null && echo "exists" || echo "new"

If worktree exists:

  • Report: "Worktree already exists at .worktrees/$BRANCH_NAME"
  • Skip creation, proceed to verification steps (Step 6)

Create the worktree

# Create the worktree with a new branch
git worktree add .worktrees/$BRANCH_NAME -b $BRANCH_NAME

# Or if branch already exists:
git worktree add .worktrees/$BRANCH_NAME $BRANCH_NAME

Handle errors:

  • If branch exists but not as worktree: use existing branch
  • If path exists but not registered: git worktree prune then retry

Report: "Created worktree at .worktrees/$BRANCH_NAME"

Run the setup files

Change into the worktree and run whatever project-level setup the repo defines. The order matters — install deps first so subsequent steps have a working environment.

cd .worktrees/$BRANCH_NAME
INSTALL.md (required)

Check for INSTALL.md:

ls INSTALL.md 2>/dev/null && echo "found" || echo "missing"

If found:

  • Read INSTALL.md
  • Follow installation instructions (typically bun install, npm install, etc.)
  • Report each step executed

If missing:

  • Warning: "No INSTALL.md found. Attempting common install commands..."
  • Try in order:
    1. bun install (if bun.lockb exists)
    2. npm install (if package-lock.json exists)
    3. yarn install (if yarn.lock exists)
  • If none work, report: "Could not auto-detect package manager. Manual setup may be required."
RUN.md (optional)

Check for RUN.md:

ls RUN.md 2>/dev/null && echo "found" || echo "missing"

If found:

  • Read RUN.md
  • Note startup instructions (don't auto-run services unless explicitly requested)
  • Report: "RUN.md found. See instructions for starting dev environment."

If missing:

  • No action needed
  • Report: "No RUN.md found (optional)"
FEEDBACK_LOOPS.md (optional, recommended)

Check for FEEDBACK_LOOPS.md:

ls FEEDBACK_LOOPS.md 2>/dev/null && echo "found" || echo "missing"

If found:

  • Read FEEDBACK_LOOPS.md
  • Note available feedback tools (test commands, linters, etc.)
  • Report: "FEEDBACK_LOOPS.md found. Feedback tools available for verification."

If missing:

  • Report: "No FEEDBACK_LOOPS.md found. Consider creating one for consistent verification."
  • Suggest creating FEEDBACK_LOOPS.md with common checks:
    Suggested FEEDBACK_LOOPS.md structure:
    - Test command (e.g., bun test)
    - Type checking (e.g., tsc --noEmit)
    - Linting (e.g., eslint .)
    - Build verification (e.g., bun run build)
    

Verify the test baseline

Run the test suite once before handing the workspace to the user. The reason this matters is diagnostic: if a test fails later, they need to know whether they introduced the failure or inherited it.

# Detect and run tests
if [ -f "package.json" ]; then
  # Try common test commands
  bun test 2>/dev/null || npm test 2>/dev/null || yarn test 2>/dev/null || echo "no-tests"
fi

If tests pass:

  • Report: "Test baseline verified. All tests passing."

If tests fail:

  • Warning: "Test baseline has failures. Review before starting development."
  • List failing tests
  • Ask: "Proceed anyway? (Tests may have been failing before your changes)"

If no tests:

  • Note: "No test suite detected."

Final report

Worktree Setup Complete

Location: .worktrees/$BRANCH_NAME
Branch: $BRANCH_NAME

Setup Status:
  .gitignore: [Updated/Already configured]
  Dependencies: [Installed/Failed/Manual required]
  RUN.md: [Found/Not present]
  FEEDBACK_LOOPS.md: [Found/Not present (recommended)]
  Test Baseline: [Passing/Failing/No tests]

Next Steps:
  1. cd .worktrees/$BRANCH_NAME
  2. Start development (see RUN.md if present)
  3. Run tests frequently to catch regressions

To remove worktree when done:
  git worktree remove .worktrees/$BRANCH_NAME

Idempotency

This skill is safe to run multiple times:

  • Detects existing worktrees and skips creation
  • .gitignore check is additive
  • Setup files can be re-executed
  • Test baseline always runs for verification

Error handling

ErrorActionWhy
Not a git repoStop with clear errorNothing to branch from — pointless to continue
Git version < 2.5Stop with upgrade instructionsWorktrees are a 2.5+ feature
Branch already exists (not as a worktree)Reuse the branch, attach it to a new worktree pathUser probably wants to continue prior work
Worktree path exists but stalegit worktree prune, then retryStale registrations block git worktree add
INSTALL.md failsReport the error, continue to the test stepPartial setup beats no setup — the user can finish install manually
Tests failWarn, but allow proceedingFailures may predate the user's work; they need to decide

Integration with SDLC

When invoked from /sdlc:implement or similar workflows:

  • Return the worktree path for subsequent operations
  • Report setup status for workflow awareness
  • Any warnings should be propagated to parent workflow

Example Usage

Manual invocation:

/worktree feat/new-feature

Skill invocation:

Skill(primitives:worktree, args: "feat/new-feature")

Expected output:

Creating worktree for feat/new-feature...

[1/6] Checking .gitignore... already configured
[2/6] Creating worktree... done
[3/6] Installing dependencies... bun install complete (1.2s)
[4/6] Checking RUN.md... found
[5/6] Checking FEEDBACK_LOOPS.md... found
[6/6] Running test baseline... 42 tests passed

Worktree ready at .worktrees/feat/new-feature

Commands 7

Smart Commit Command

Git history is project documentation. Future developers need to understand why changes were made. Poorly structured commits (mixed concerns, vague messages, direct commits to main) break bisect, code review, and team workflows.

Branch Safety

Protected branches (main/master) should never receive direct commits — this bypasses code review, creates merge conflicts, and breaks CI/CD pipelines. If currently on main/master, create a feature branch: feat/description, fix/description, or docs/description. Branch naming communicates intent before teammates view code.

Judgment Criteria for Commits

Clarity: Future Comprehension

Good: feat(yaml): add retry logic to handle transient parsing failures Poor: feat(yaml): add retry logic (missing: why was retry needed?)

Atomicity: Single Coherent Purpose

Each commit represents one logical change. If you need "and" to describe it, it's probably two commits. Atomic commits enable bisect to isolate bugs, allow reverting without losing unrelated improvements, simplify code review, and make cherry-picking viable.

Separate: Bug fixes from refactoring; features from tests (unless test requires implementation); docs from code (unless tightly coupled like API references).

Exception: Tightly coupled changes (new function + its tests) belong together because neither makes sense alone.

Conventional Format: Tooling Interoperability

Use type(scope): description format for changelog generation, CI/CD automation (feat → minor bump, fix → patch), and machine-readable history.

Types: feat (new capability), fix (bug correction), docs (documentation only), test, refactor (no behavior change), chore (deps/build), perf, style (formatting)

Scope: Module or component (e.g., anthropic, validation, cli)

Description: Imperative mood ("add" not "added"), 50-70 chars, no period, avoid jargon

Breaking Changes

Use feat!: or BREAKING CHANGE: in body for backward-incompatible changes — versioning tools bump major version, release notes highlight prominently, and users know to review upgrade guides.

Staging Strategy

Stage files by name, not git add . — wildcard staging can accidentally include secrets (.env), build artifacts, or debug changes you meant to revert. Group related files that serve the same purpose. Ask: "Would I want to revert all these files together?"

Hook Execution

Never use --no-verify to bypass pre-commit hooks — they enforce quality standards and catch issues before code review. If hooks fail, fix the issues or report back. Hooks failing means the commit isn't ready.

Workflow

  1. Check current state: Branch (don't commit to main), changes (scope), staged files (avoid double-staging)
  2. Understand intent: User description, file changes, recent commits (git log), project guidelines (CLAUDE.md, CONTRIBUTING.md)
  3. Determine logical batches: One feature or multiple? Tests with implementation or separate? Would splitting/combining clarify history?
  4. Create commits: Stage specific files, explain why (not just what), use conventional format, verify success
  5. Verify result: Review git log, check diff matches expectation, confirm nothing left uncommitted, suggest next steps

Examples

Good Commit Messages

feat(anthropic): add support for Claude 3.5 Sonnet

Implements client wrapper with streaming and function calling support.
Customers requested integration for improved reasoning capabilities.
fix(validation): handle empty response arrays

Previously crashed with IndexError. Now returns empty list and logs warning. Fixes #234.

Why these are good: Clear type/scope, explain the problem and solution, provide context

Poor Commit Messages

fix: bug fix

(No scope, no description, teaches nothing)

feat(yaml): add MD_YAML mode, update docs, fix unrelated bug in validation

(Mixed concerns — can't revert bug fix without losing feature)

Special Cases

Multiple independent features: Always separate commits for independent history.

Large refactoring: Group commits so each leaves codebase in working state. Never break tests mid-sequence.

Documentation updates: Usually separate unless tightly coupled (e.g., API reference comments matching signatures).

Breaking changes: Use feat!: or BREAKING CHANGE: in body. Explain what breaks, why, and link to migration guide.

Report Format

After completing commits, provide: Branch (name), Changes analyzed (file count and nature), Commits created (hash, type, scope, files), Rationale (batching decisions), Next steps (push/PR/continue). Keep it concise and factual.

Usage

/commit                    # Analyze and commit all changes
/commit "description"      # Use description to inform commit messages

Debug

Role

Help the user debug a problem during manual testing or implementation. Investigate logs, database state, git history, and file state using read-only tools. No edits — this command bootstraps a debugging session without burning the primary window's context.

Priorities

Root cause (confirmed by evidence) > Coverage (multiple hypotheses tested) > Speed

Scope

Form hypotheses first, then gather evidence to confirm or eliminate each. Don't fixate on one cause; 2–4 candidates is the sweet spot. Every finding ties back to a file:line reference or a log timestamp — evidence over vibes.

This command investigates. It doesn't edit files, run builds, or execute tests. Suggest fixes in the report; let the user apply them.

Read the project's DEBUG.md in the repo root first — it carries project-specific log locations, database tools, and known failure modes.

Routing

Standard flow is the default: investigate sequentially with read-only subagents. Pass --swarm when you have 2–4 independent hypotheses that benefit from parallel testing by separate teammates (e.g., one checking logs, one querying the DB, one reading git history, each owning a distinct hypothesis). Strip --swarm from the args; the remainder is the problem description context.

If swarm mode is requested but TeamCreate isn't available:

Swarm mode requires agent teams. Set CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 in settings.json or environment.
Falling back to standard workflow.

Then continue without the team.

Interview checkpoint (both modes)

Run the interview protocol before investigating:

  • Glob(pattern: "**/sdlc/**/skills/interview/SKILL.md", path: "~/.claude/plugins")

Use AskUserQuestion with multiple-choice options to move fast. Anchor on: what was happening, what went wrong, when it last worked, exact error messages, reproduction steps. Skip anything answerable by reading the error output the user already pasted. Loop 1–4 questions per round until the user says "done".

Footer: Reply format: 1a 2b or defaults


Standard workflow

Form hypotheses

After the user describes the issue:

  1. Read any context they mentioned (plan, ticket, error output) completely — no limit/offset.
  2. Quick state check: current branch, recent commits, uncommitted changes, when the issue started.
  3. List 2–4 candidate root causes, most likely first. For each, note what evidence would confirm or eliminate it.

Investigate

Spawn parallel investigations targeting those hypotheses. Each returns evidence with file:line or timestamp:

  • Logs — recent errors and warnings around the failure window, stack traces, repeated patterns.
  • Database / backend state — use project-specific queries from DEBUG.md; inspect documents referenced by log IDs; look for stuck states, missing relations, data anomalies.
  • Git / file state — status, recent commits, uncommitted changes, expected files present, permission issues.

Match the investigation depth to the failure's severity; don't fan out further than the hypotheses justify.

Report

Present a focused debug report:

## Debug Report

### What's Wrong
[Clear statement of the issue based on evidence]

### Hypotheses Tested

**Hypothesis 1**: [Most likely cause]
- Evidence for: [Supporting findings with file:line or timestamp]
- Evidence against: [Contradicting findings]
- Status: Confirmed / Eliminated / Uncertain

**Hypothesis 2**: [Alternative cause]
- (same structure)

### Evidence Collected

**From Logs**: [Errors/warnings with timestamps]
**From Database/Backend**: [State findings]
**From Git/Files**: [Recent changes or file issues]

### Root Cause
[Confirmed explanation based on hypothesis testing]

### The Fix

1. **Immediate action**
   ```bash
   [Specific command or code change]

Why this works: [Brief explanation]

  1. Prevent recurrence

    • [Test to add / code improvement / doc update]
  2. If that doesn't work

    • Hypothesis was wrong, try: [Alternative approaches]
    • [Project-specific commands from DEBUG.md]

Out of reach

Anything outside the debugger's access (browser console errors, system-level issues, etc.) — flag it and suggest where the user should look.


---

## Swarm workflow

Parallelize hypothesis testing when the hypotheses are genuinely independent — investigating them serially would waste time, and the findings from one don't change what another teammate should look for.

### Team setup

Create the team with `TeamCreate`: name `debug-{YYYYMMDD-HHMMSS}`, description `Debug: {issue summary}`. Register a shared task per hypothesis via `TaskCreate` — format `Investigate hypothesis: {description}`. Cap at 4 tasks; batch related hypotheses together if there are more.

### Teammate dispatch

Spawn one teammate per hypothesis via `Task` with `team_name` and `subagent_type: "general-purpose"`. Teammates can't see this conversation — embed everything they need as literal text.

<example name="Teammate spawn prompt">
You are investigating one hypothesis as part of a debug team.

PROBLEM DESCRIPTION:
{literal copy of user's problem — what's wrong, when it started, any error messages}

YOUR HYPOTHESIS:
{specific hypothesis this teammate tests}

ALL TEAM HYPOTHESES:
1. {hypothesis 1}
2. {hypothesis 2}
3. {hypothesis 3}
4. {hypothesis 4}

RELEVANT CONTEXT:
{error messages, log excerpts, DB state, recent commits — as literal text, not references}

PROJECT DEBUG INFO:
{relevant excerpts from DEBUG.md}

Your job is to confirm, eliminate, or flag your hypothesis as uncertain — backed by evidence. Investigate logs, DB state, git history, and file state with read-only tools (Read, Grep, Glob, Bash for `git log`, `ps`, `ls`). Read files completely, no limit/offset.

Constraints:
- Read-only. Don't modify the codebase, commit, or run build/test commands — other teammates are investigating concurrently and edits would cause interference.
- Communicate via `SendMessage` only — `AskUserQuestion` isn't available in team context. If blocked, send `BLOCKED: {reason}` to the lead.
- If you find evidence that contradicts another teammate's hypothesis, share it immediately via `SendMessage`: `"My investigation of {your hypothesis} found evidence that contradicts {other hypothesis}: {evidence with file:line or timestamp}"`. Cross-pollination is the whole point of running in parallel.

When you've gathered enough evidence to confirm, eliminate, or mark your hypothesis uncertain:
1. `TaskUpdate` your shared task complete with the findings.
2. `SendMessage` `DEBUG COMPLETE` to the lead.
3. Wait for `shutdown_request`.

Report status (confirmed / eliminated / uncertain) with supporting `file:line` or timestamp references. If eliminated, explain what this rules out; if confirmed, explain the root cause. Match report depth to the complexity of the finding.
</example>

### Convergence

Wait for all teammates to send `DEBUG COMPLETE`, up to 10 minutes per teammate from spawn. On timeout, proceed with available findings and note which teammates timed out in the report. If a teammate gets stuck (repeated identical messages, no progress): note the failure and proceed, respawn with tighter scope, or handle that hypothesis yourself — pick based on how critical it is to the root cause.

### Synthesis

Integrate teammate findings into a coherent debug report — not a mechanical merge. Use the same format as the standard workflow, with attribution:
- `[Teammate 1]`, `[Teammate 2]` for single-teammate findings
- `[Consensus]` for independently confirmed findings
- Highlight cross-hypothesis eliminations: "Evidence from log investigation contradicted the database state hypothesis, eliminating it."

### Cleanup invariant

**The team must be deleted before the command returns, regardless of whether synthesis succeeded.** Skipping leaks team slots and orphans the shared task list.

1. `SendMessage` `type: "shutdown_request"` to each teammate.
2. Wait briefly for shutdown confirmations.
3. `TeamDelete`.

If cleanup itself errors, tell the user `"Team cleanup incomplete. You may need to check for lingering team resources."` and continue with the report.

---

## Generic quick reference

```bash
# Git state
git status
git log --oneline -10
git diff

# File investigation
find . -type f -mtime -1   # files changed in last day
ls -la [file]              # permissions / ownership

# Processes
ps aux | grep [process-name]

Project-specific commands live in DEBUG.md at the repo root. When the generic reference and DEBUG.md disagree, DEBUG.md wins.

Prepare and install the repo deps

Instructions

  • Verify that we have access to git CLI and gh CLI (aka Github CLI) otherwise prompt the user to install them configure them.
  • Read the INSTALL.md file in the repo and follow the instruction to install the application with all the dependencies and health checks. If there's no such file, analyze the repo and suggest to the user to create one.

Report

  • Output work done in concise bullet points
  • List any missing/incomplete configurations
  • Provide next steps if setup incomplete

Prime

Execute the Run, Read and Report sections to understand the codebase then summarize your understanding.

Run

  • git ls-files

Read

README.md

Report

Summarize your understanding of the codebase.

Start dev environment for the repo

Read the RUN.md file in the repo and follow the instruction to start the application.

If there's no such file, analyze the repo and suggest to create one.

List Built-in Tools

List all core, built-in non-mcp development tools available to you. Display in bullet format. Use typescript function syntax with parameters.

Create Git Worktree

Create an isolated worktree under .worktrees/ with automatic dependency installation and a test baseline check. Thin wrapper around the primitives:worktree skill — delegates to the skill for the actual work.

Usage

/worktree <branch-name>

Examples:

  • /worktree feat/new-feature
  • /worktree fix/bug-123

Behavior

Parse the branch name from $ARGUMENTS. If empty, ask the user: "What branch name should I use for the worktree?" — no sensible default exists, guessing a branch name is worse than asking.

Invoke the skill and pass the name through:

Skill(primitives:worktree, args: "$ARGUMENTS")

Trust the skill's output. If it reports setup failed (e.g., install command erred), surface the error — don't silently succeed.

Error modes

  • No branch name — prompt before invoking the skill.
  • Not a git repo — skill reports; surface the guidance.
  • Worktree already exists — skill skips creation and runs verification; that's the right behavior.
  • Setup partially fails — skill continues; surface what failed so the user can finish manually.

Sponsors

Details

Marketplace
iamladi/cautious-computing-machine
Source
iamladi/cautious-computing-machine--primitives-plugin
Category
Community

More from iamladi/cautious-computing-machine

All 7