Skills for thinking, file querying, image generation, and coding rules

version
8.2.1
GitHub stars
116

Install

/plugin install sc-skills@simpleclaude

Run it inside Claude Code after adding the marketplace with /plugin marketplace add kylesnowschwartz/SimpleClaude.

Contents

Discovered from source

Skills 8

External AI CLIs: Codex & Gemini

Run OpenAI Codex CLI or Google Gemini CLI for second opinions and external reviews.

Critical Rules

  1. Run CLIs directly via Bash. Subagents cannot approve Bash permissions interactively, so the command gets denied. run_in_background: true is fine for long runs.

  2. End every non-interactive codex call with </dev/null unless you pipe content in. When stdin is not a terminal, codex exec reads it and waits for end of file before it starts, so an inherited pipe that never closes hangs it with no output. Piping content in on purpose works: when stdin is piped and a prompt is also given, codex appends stdin to the prompt as a <stdin> block.

  3. Capture the final message and stderr. Pass -o <file> for the final message and redirect stderr to a file (2><file>). The session id: line you need to resume a run is printed on stderr, not stdout. Check that the -o file exists before reading it.

  4. Pair every read-only Codex call with -c 'approval_policy="never"'. The sandbox alone does not block writes: when the user's ~/.codex/config.toml sets approval_policy = "on-request", Codex can ask to run a command outside the sandbox, and an approved request writes files. With the policy set to never, Codex cannot escalate and writes fail with "operation not permitted". codex exec and codex exec resume have no -a flag, so -c is the only way to set it.

Prerequisites

ToolInstallConfig
Codexnpm install -g @openai/codexcodex login / ~/.codex/config.toml
Geminibrew install gemini-cliGoogle auth / ~/.gemini/settings.json

Check availability: codex --version / gemini --version

When to Use

  • User wants a second opinion from a different AI model
  • Code review from an external perspective
  • Verification of an approach or architecture
  • User explicitly requests codex or gemini

Models

Codex

Use the default model from ~/.codex/config.toml (model = "..."). Pass -m <model> only when the user names a model.

Codex uses stored OAuth tokens (~/.codex/auth.json) from codex login — no env var needed.

Gemini

ModelUse Case
gemini-3.1-pro-previewBest. Latest model (Feb 2026). Requires previewFeatures: true.
gemini-3-pro-previewPrevious generation preview.
gemini-3-flash-previewFaster, good for quick checks.
gemini-2.5-proStable GA fallback if preview models have capacity issues.
gemini-2.5-flashFast GA fallback.

Always pin the model with -m in non-interactive/headless calls. The user's ~/.gemini/settings.json may use auto-gemini-3 routing, which can select Flash for prompts it classifies as "simple" — not what you want for code reviews.

If you hit 429 MODEL_CAPACITY_EXHAUSTED on preview models, fall back to -m gemini-2.5-pro. This is a server capacity issue (not quota) and mostly affects oauth-personal auth. Enterprise API key (gemini-api-key auth with billing) has better capacity allocation.

Set default in ~/.gemini/settings.json:

{ "model": { "name": "gemini-3.1-pro-preview" } }

Codex CLI

Subcommands

CommandPurpose
codex reviewGit-aware code review (non-interactive)
codex execNon-interactive prompt execution
codex exec resume <id>Send a follow-up prompt to an earlier codex exec session
codex resumeResume previous interactive session
codex applyApply latest agent diff via git apply

Code Review (most common use)

codex review has no -s flag, so the examples set the sandbox and approval policy with -c.

Important: codex review treats --base, --uncommitted, --commit, and [PROMPT] as mutually exclusive modes. You cannot combine a custom prompt with --base or --uncommitted. To review with custom instructions, pipe the diff into codex exec, or save it to a file and name the file in the prompt.

# Review uncommitted changes (default instructions)
codex review -c 'sandbox_mode="read-only"' -c 'approval_policy="never"' --uncommitted </dev/null

# Review branch against main (default instructions)
codex review -c 'sandbox_mode="read-only"' -c 'approval_policy="never"' --base main </dev/null

# Review specific commit (default instructions)
codex review -c 'sandbox_mode="read-only"' -c 'approval_policy="never"' --commit <SHA> </dev/null

# Review with title context
codex review -c 'sandbox_mode="read-only"' -c 'approval_policy="never"' --uncommitted --title "Add user auth middleware" </dev/null

# Review with custom instructions: pipe the diff in; codex appends it as a <stdin> block
git diff main...HEAD | codex exec -s read-only -c 'approval_policy="never"' -o /tmp/codex-review.md "Review the diff in the stdin block for error handling and security" 2>/tmp/codex-review.err

# Or save the diff to a file and name it in the prompt
git diff main...HEAD > /tmp/review-diff.txt
codex exec -s read-only -c 'approval_policy="never"' -o /tmp/codex-review.md "Read /tmp/review-diff.txt and review it for error handling and security" </dev/null 2>/tmp/codex-review.err

Non-Interactive Execution

Use -s read-only together with -c 'approval_policy="never"' for reviews, questions, and analysis. Use -s workspace-write only when Codex must change files in the repository.

# Read-only analysis
codex exec -s read-only -c 'approval_policy="never"' -o /tmp/codex-out.md "Analyze the auth module for security issues" </dev/null 2>/tmp/codex-err.txt

# A model the user named (otherwise omit -m)
codex exec -s read-only -c 'approval_policy="never"' -m <model> -o /tmp/codex-out.md "Review this codebase architecture" </dev/null 2>/tmp/codex-err.txt

# Changes that need writes inside the repository
codex exec -s workspace-write -o /tmp/codex-out.md "Refactor the test helpers" </dev/null 2>/tmp/codex-err.txt

# JSONL event output on stdout
codex exec -s read-only -c 'approval_policy="never"' --json "List all TODO comments" </dev/null >/tmp/codex-events.jsonl 2>/tmp/codex-err.txt

# Outside a git repository
codex exec --skip-git-repo-check -C /path/to/dir -s read-only -c 'approval_policy="never"' -o /tmp/codex-out.md "Summarize the notes in this directory" </dev/null 2>/tmp/codex-err.txt

Follow-up questions

Resume the same session by its id, so Codex keeps the context of the first run. Take the id from the session id: line in the stderr file. Use the explicit id rather than --last when several Codex runs may be active.

A resumed session does not inherit the first run's sandbox or model: it falls back to ~/.codex/config.toml, which may allow writes and network access. Pass the sandbox with -c sandbox_mode=... (resume has no -s flag), set -c 'approval_policy="never"' so the resumed run cannot escalate out of the sandbox, and pass -m again if the first run used it.

SESSION_ID=$(sed -n 's/^session id: //p' /tmp/codex-err.txt)
codex exec resume -c 'sandbox_mode="read-only"' -c 'approval_policy="never"' -o /tmp/codex-followup.md "$SESSION_ID" "Expand on the second finding" </dev/null 2>/tmp/codex-followup.err

# The first run used a model the user named
codex exec resume -c 'sandbox_mode="read-only"' -c 'approval_policy="never"' -m <model> -o /tmp/codex-followup.md "$SESSION_ID" "Expand on the second finding" </dev/null 2>/tmp/codex-followup.err

The sandbox: line in the stderr file shows the sandbox the resumed run used. A resumed run that was not given approval_policy="never" can write outside a read-only sandbox when the user's config allows approval requests. codex exec resume accepts -o and --json. It has no -C flag. Outside a git repository, run it from the same directory as the first run and add --skip-git-repo-check.

Key Flags

FlagPurpose
-m, --model <MODEL>Model selection; omit it to use the config.toml default
-c key=valueOverride config (TOML format). Read-only calls set -c 'approval_policy="never"'; exec resume and review also set -c 'sandbox_mode="read-only"'
-s, --sandbox <MODE>read-only (reviews and analysis; pair with approval_policy="never"), workspace-write (edits inside the repository), danger-full-access
-C, --cd <DIR>Set the working root. Not needed when the shell is already in the repository. Outside a git repository, also pass --skip-git-repo-check
--skip-git-repo-checkAllow running outside a git repository
--jsonJSONL event output (exec only)
-o, --output-last-message <FILE>Write last message to file (exec and exec resume)

Gemini CLI

Non-Interactive (Headless)

# Non-interactive prompt (exits when done)
gemini -p "Review this codebase for architectural issues"

# Auto-approve all actions
gemini -y -p "Fix the failing tests"

# Structured output
gemini -o json -p "List the public API surface of src/auth/"

Interactive

# Interactive with initial prompt
gemini -i "Help me debug the auth flow"

# Resume last session
gemini -r latest

# Include additional directories
gemini --include-directories ../shared-lib "Review cross-repo dependencies"

Key Flags

FlagPurpose
-m, --model <MODEL>Model selection
-p, --prompt <TEXT>Non-interactive (headless) mode
-i, --prompt-interactive <TEXT>Run prompt then stay interactive
-y, --yoloAuto-approve all actions
--approval-mode <MODE>default, auto_edit, yolo
-r, --resume <ID>Resume session (latest or index)
--include-directories <DIRS>Additional workspace directories
-o, --output-format <FMT>text, json, stream-json

Usage Patterns

Get a Second Opinion on Changes

# Codex (git-aware, understands diffs natively)
codex review -c 'sandbox_mode="read-only"' -c 'approval_policy="never"' --uncommitted </dev/null

# Gemini (prompt-based)
gemini -p "Review the uncommitted changes in this repo for bugs and security issues"

Review a Design Decision

codex exec -s read-only -c 'approval_policy="never"' -o /tmp/codex-out.md "Evaluate the architecture in src/auth/. Is the token refresh approach sound?" </dev/null 2>/tmp/codex-err.txt

gemini -p "Analyze src/auth/ and critique the token refresh strategy"

Review a Branch Before PR

# Default review (no custom prompt needed)
codex review -c 'sandbox_mode="read-only"' -c 'approval_policy="never"' --base main </dev/null

# Custom review instructions: pipe the diff in
git diff main...HEAD | codex exec -s read-only -c 'approval_policy="never"' -o /tmp/codex-review.md "Review the diff in the stdin block for correctness, test coverage, and maintainability" 2>/tmp/codex-review.err

Troubleshooting

Gemini: GEMINI_API_KEY not found

Gemini with gemini-api-key auth reads GEMINI_API_KEY from the environment. If the key is managed by direnv, it's only available when direnv loads the .envrc that exports it. A child directory with its own .envrc shadows the parent without inheriting — so the key can be missing depending on which directory the session runs from.

Pre-flight check (run before any Gemini invocation):

echo "GEMINI_API_KEY: ${GEMINI_API_KEY:+set (${#GEMINI_API_KEY} chars)}"

If unset, tell the user and skip Gemini. Codex does not have this problem — it uses stored OAuth tokens from codex login.

Gemini: stdin bug

cat file | gemini -p "..." fails with "Cannot use both a positional prompt and the --prompt flag together." Gemini's arg parser treats cat-piped stdin as a positional argument conflicting with -p. Use < file redirection instead: gemini -m MODEL -p "prompt" < /path/to/file. This works correctly.

Gemini: headless tool trust bug

#18776: Gemini in -p headless mode cannot reliably use filesystem tools — the folder trust check fails. Feed content via stdin rather than expecting Gemini to read files itself.

Codex: hangs with no output

codex exec is waiting for end of file on an open stdin. Add </dev/null to the command, or pipe in content that ends.

Codex: unexpected argument '--full-auto'

Current Codex CLI releases have no --full-auto flag. Use -s read-only for reviews and analysis, or -s workspace-write when Codex must edit files.

Codex: read-only run still wrote a file

-s read-only limits the sandbox, but Codex can request escalation when the user's approval_policy permits requests, and an approved request runs outside the sandbox. Add -c 'approval_policy="never"' to every read-only call.

Codex: plan-confirmation instead of review

If codex output contains "Plan:" followed by "If you're happy with that approach", codex did not execute: it proposed a plan and waited for approval. This happens when the prompt says "review this" but names nothing codex can see. Pipe the content in, or save it to a file and name the file in the prompt.

Codex: -o creates no file

If Codex exhausts its turns without producing a final summary, -o creates no output file. Always check file existence, not just content.

General

  • Codex reads piped stdin and appends it to the prompt as a <stdin> block. Gemini reads stdin via < file redirection (not cat | gemini).
  • If a command fails with a syntax error, run <tool> --help to check current flags before retrying.
  • If an upgrade notice appears, inform the user. Do NOT auto-upgrade.
  • Codex config values use TOML format: -c model_reasoning_effort="high"

Codex Companion Script (codex-plugin-cc)

The codex-plugin-cc plugin provides a companion script that wraps codex review with structured JSON output, an app-server protocol, and job lifecycle management. Prefer it over raw codex review when available.

Discovery

The companion script resolves its own ROOT_DIR via import.meta.url, so it works from any cwd. Search known install locations:

CODEX_COMPANION=""
setopt NULL_GLOB 2>/dev/null  # zsh: suppress "no matches found" when globs miss
for d in ~/.claude/plugins/marketplaces/*/plugins/codex/scripts/codex-companion.mjs \
         ~/.claude/repos/*/plugins/codex/scripts/codex-companion.mjs; do
  [ -f "$d" ] && CODEX_COMPANION="$d" && break
done
unsetopt NULL_GLOB 2>/dev/null

Invocation

# Structured JSON review of branch vs main
node "$CODEX_COMPANION" adversarial-review -C "$PWD" --json --base main

# With user focus text
node "$CODEX_COMPANION" adversarial-review -C "$PWD" --json --base main "Check auth handling"

# Working tree (uncommitted changes)
node "$CODEX_COMPANION" adversarial-review -C "$PWD" --json --scope working-tree

Output envelope

The --json flag produces a structured payload:

{
  "result": {
    "verdict": "approve | needs-attention",
    "summary": "1-2 sentence assessment",
    "findings": [
      {
        "severity": "critical | high | medium | low",
        "title": "Short name",
        "body": "WHAT breaks, SCENARIO, IMPACT",
        "file": "path/to/file",
        "line_start": 10,
        "line_end": 25,
        "confidence": 0.85,
        "recommendation": "Concrete fix"
      }
    ],
    "next_steps": ["actionable step"]
  }
}

Requirements

  • Codex CLI must be authenticated: the companion script delegates to codex review internally, so codex login is required.
  • Node.js: the companion is an .mjs file, requires node in PATH.

If the companion isn't found, fall back to raw codex review (unstructured text output).

Core Principle

Use the codex-plugin-cc companion script for structured JSON reviews when available. Fall back to codex review for git-aware code reviews. Use codex exec -s read-only -c 'approval_policy="never"' for freeform analysis, with content piped in or named by file path, </dev/null when nothing is piped, and stderr captured for the session id. Use gemini -p with < file redirection for content analysis.

● main ↑3 │ build ✓ 2.1s ▁▂▂▃▄▅▆ │ tests 412/413 ✗ │ lint ✓ │ types ⚠2

That row is the skill. One line, six fields, no prompt, no dialog. You see system state through it, not at it. Lineage: Weiser (calm tech), Engelbart (IA), Tufte (data-ink, sparklines, small multiples).

Copilot vs. HUD

Copilot (anti-pattern)HUD (target)
You talk to itYou see through it
Demands attentionLives in periphery
Delegates judgmentExtends perception
Context-switch taxFlow-state preserving
"Do this for me""Now I notice more"

Reframing protocol

  1. Name the copilot reflex. What chat would you open? What prompt would you type?

  2. Extract the information need. What does the assistant need to know to answer? That is what you need to perceive.

  3. Compose from the primitive palette:

    • sparkline row — ▁▂▃▄▅▆▇█ in ≤8 cells, encoding a series (≤4 Hz)
    • gutter cell — column-1 marker per line: ! * ● ◐ · (event:save)
    • status-line field — key value pair, separated by │ on a single row (≤1 Hz)
    • dim/bold/inverse run — weight = salience; inverse = current/selected (event:focus)
    • badge glyph — single-cell state: ✓ ✗ · ⚠ ● ○ ◐ ↑ ↓ (event:state)
    • color-band column — fixed-width column, hue encodes category (event:classify)
    • box-drawing frame — ─ │ ┌ ┐ └ ┘ ├ ┤, only when a frame earns its cells (static)
    • prompt-line indicator — one trailing field appended to the shell prompt (≤30 Hz)
    • small-multiples / row-repeat — meta-primitive: layout, not glyph; does not consume the ≤3 budget. Same instrument repeats across N rows with shared column alignment and shared scales, so cross-row scan is structurally licensed.

    Budget: ≤3 primitives per row, ≤8 sparkline cells per primitive, one line per instrument. Beyond 3, the row is a dashboard, not a HUD.

    When you catch yourself wanting a GUI affordance, reach for the terminal substitute:

    • hover → inverse cursor row (j/k moves the highlight)
    • popover / tooltip → expand-on-key, or one appended status-line field
    • gradient → dim/normal/bold triplet, or a 3-step 256-color ramp via color-band
    • modal dialog → full-line takeover, single-key dismiss
    • animation → ≤4 Hz refresh on a single sparkline cell
    • drag → j/k to move, enter to commit
  4. Pass both terminal tests:

    • Spellcheck test — the marker appears in the line of work itself, not in a popup, dialog, side pane, or separate command. Pass: !43 │ if user.role == "admin":. Fail: a cx-review subcommand that prints a report.
    • Sparkline test (Tufte) — the signal renders with ▁▂▃▄▅▆▇█ (or a similar fixed-glyph row) in ≤8 cells inside an existing line; when sparklines stack, they share a labeled baseline. Pass: tests 412/413 ✗ ▁▂▃▇. Fail: a separate ASCII bar-chart screen, or four stacked sparklines each rescaling to their own min/max.

Worked example: test-runner HUD

PKG             STRIP                 N/N    LATENCY (▁=0 █=600ms)  TREND
auth/login      ✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓·  19/20  ▁▁▁▁▁▂▂▂   142ms
auth/oauth      ✓✓✓✓✓✓✗✓✓✓✓✓✓✓✓✓✓✓✓✓  19/20  ▁▂▂▂▂▃▃▃   211ms
billing/charge  ✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓  20/20  ▁▁▁▁▂▂▂▂    88ms
billing/refund  ✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓✓  20/20  ▃▄▅▅▆▆▇▇   503ms   ⚠

↑ small-multiples in action: each row applies the same gutter-strip + shared-baseline sparkline + badge instrument to one PKG, so the eye scans vertically. The strip is strict 3-state (✓ ✗ · = pass / fail / skip); trend warnings ride in their own badge column, so 20/20 still means 20/20. The flaky test (✗ in the strip) and the slow-creep (sparkline standing visibly taller than its neighbors, ⚠ in TREND) are legible without prose annotations — the data already speaks.

Copilot reflex: "summarize the test run." HUD instruments: gutter-strip + sparkline + badge, row-repeated across packages.

Same protocol, four domains

domaincopilot reflexHUD instrument (terminal-native)
code review"review this PR for bugs"!42 ● if x == True: ▆cx
inbox"summarize my email"▌ ●●● 02:14 CEO Re: Q3 review ▇▆▃▁
debugging"find the bug"i=37 arr[0..n) hits ▁▁▂▃▇▂▁ ✗ at i=23
writing"rewrite this paragraph"~/essay $ █ passive ▃ │ readab ▇▆ │ "just"×4 │ 318w

Inbox row leads with a ▌ color-band column (hue = folder); the writing row appends indicators to the shell prompt line. Each row picks ≤3 primitives and stays inside the existing line — the test-runner block above is the small-multiples form (one instrument, many parameters); this table is the protocol's transfer (one protocol, four instruments).

When copilot is fine

Routine, one-shot, you genuinely don't want to learn it (autopilot for straight-and-level). For expert work — judgment, debugging, prose — instrument, don't delegate.

Context-Efficient Extraction

Extract specific data from files using CLI tools instead of built-in Read/Grep. Saves 80-95% of context tokens on large files and enables features the built-in tools lack.

Route by Task

TaskToolWhen to use over built-in
JSON field extractionjqFile >50 lines, need specific fields
YAML field extractionyqFile >50 lines, need specific fields
Markdown element extractionmqNeed code blocks, links, headers, tables
Text search with advanced flagsrgNeed -F, -v, -w, -C, pipe composition

Fall back to Read when the file is small (<50 lines), the overall structure matters, or edits follow immediately. Fall back to built-in Grep for straightforward pattern matching (handles 95% of search needs).

jq: JSON Extraction

# Specific field
jq -r '.version' package.json
jq -r '.compilerOptions.target' tsconfig.json

# Nested field
jq -r '.dependencies.react' package.json

# All keys at a level
jq -r '.scripts | keys[]' package.json
jq -r '.dependencies | keys[]' package.json

# Multiple fields
jq '{name, version}' package.json

# Filter array by condition
jq '.items[] | select(.active == true)' data.json

# Count
jq '.dependencies | length' package.json

# Pluck from array
jq -r '.data[].name' response.json

# Filter with to_entries
jq -r '.dependencies | to_entries[] | select(.value | startswith("^")) | "\(.key): \(.value)"' package.json

Common files: package.json, tsconfig.json, package-lock.json, .eslintrc.json, API responses.

For detailed patterns (package.json, tsconfig, API responses), load jq reference.

yq: YAML Extraction

# Specific field
yq '.version' pubspec.yaml
yq '.services.web.image' docker-compose.yml

# All keys at a level
yq '.services | keys' docker-compose.yml

# Nested array element
yq '.jobs.build.steps[0].name' .github/workflows/ci.yml

# Filter by condition
yq '.services.[] | select(.ports)' docker-compose.yml

# Multiple fields
yq '.name, .version' pubspec.yaml

# Wildcard across siblings
yq '.services.*.image' docker-compose.yml

# Output as JSON
yq -o=json '.' config.yaml

Common files: docker-compose.yml, .github/workflows/*.yml, kubernetes manifests, Helm charts, pubspec.yaml.

For detailed patterns (Docker Compose, GitHub Actions, Kubernetes), load yq reference.

mq: Markdown Extraction

# Code blocks
mq '.code' README.md
mq '.code("python")' README.md

# Headers
mq '.h' README.md
mq '.h2' README.md

# Links
mq '.link.url' README.md

# Tables
mq '.[][]' README.md

# Lists
mq '.list' README.md

# YAML frontmatter
mq '.yaml.value' file.md

# Frontmatter parsed to JSON
mq '.yaml.value' file.md | yq -o json

# Filter by content
mq '.code | select(contains("import"))' file.md

# JSON output for further processing
mq -F json '.code' README.md | jq '.[0]'

Common files: README.md, CHANGELOG.md, documentation, API docs, specs.

For detailed patterns (selectors, filtering, output formats, frontmatter), load mq reference.

rg: Advanced Text Search

Use rg via Bash when the built-in Grep tool lacks the flag or composition needed.

# Fixed string (no regex interpretation)
rg -F 'console.log(' .

# Word boundaries
rg -w 'function' .

# Invert match
rg -v 'test' -t js .

# Context lines
rg -n -C 2 'pattern' .

# Specific file types
rg -t js 'import' .
rg -t py 'def ' .
rg -t go 'func ' .

# Exclude directories
rg --glob '!node_modules' 'pattern' .

# Count matches per file
rg -c 'TODO' .

# Files only (no content)
rg -l 'pattern' .

# Pipe composition
rg 'pattern' . | head -10
rg -l 'pattern' . | sort -u

For detailed patterns (function defs, imports, file types, pipe composition), load rg reference.

Cross-Tool Pipelines

# Parse markdown frontmatter as structured data
mq '.yaml.value' file.md | yq '.description'

# Markdown to JSON to jq
mq -F json '.link' README.md | jq '.[].url'

# Find files by content, extract structured data
rg -l 'apiVersion' -t yaml | xargs -I {} yq '.kind' {}

# Find markdown files, extract code blocks
fd -e md | xargs -I {} mq '.code("bash")' {}

# YAML to JSON conversion
yq -o=json '.' config.yaml | jq '.services | keys[]'

Core Principle

One command, exact data, minimal context. Built-in tools load everything; these tools load only what matters.

Project Memory File Improver

Audit and improve project memory files — primarily CLAUDE.md, but also AGENTS.md where present. The discipline is removal as much as addition: Chroma's 2025 Context Rot study (18 frontier models including Claude Opus 4 / Sonnet 4) showed every model degrades as input grows, and even a single distractor measurably reduces retrieval. Treat the file as hot-cache, not constitution.

This skill writes to memory files. After producing an audit report and getting user approval, it applies targeted edits — both additions and removals.

If multiple memory files exist in the codebase, ask the user whether to audit a single file or all of them.

AGENTS.md is a first-class concern alongside CLAUDE.md even though Claude Code does not currently read AGENTS.md natively (confirmed as of 2026-04). Other coding tools (GitHub Copilot, Codex) do read it, so projects often maintain both — and the two files are frequently symlinked together. Always check for symlinks before editing so you don't write the same content twice via two paths.

Workflow

Phase 1: Discovery

Find all memory files in the repository, then check whether any are symlinks:

# Find both CLAUDE.md and AGENTS.md, including dot-prefixed local variants
find . \( -name "CLAUDE.md" -o -name ".claude.md" -o -name ".claude.local.md" \
  -o -name "AGENTS.md" -o -name ".agents.md" \) 2>/dev/null | head -50

# Detect symlinks — if AGENTS.md and CLAUDE.md are linked, edit only the source
find . \( -name "CLAUDE.md" -o -name "AGENTS.md" \) -exec ls -la {} \; 2>/dev/null

File Types & Locations:

TypeLocationPurpose
Project root CLAUDE.md./CLAUDE.mdPrimary Claude Code context (checked into git)
Project root AGENTS.md./AGENTS.mdCross-tool agent context per agents.md spec; often symlinked to CLAUDE.md
Subdirectory CLAUDE.mdAny nested locationLoaded contextually when Claude works in that path — strongly recommended for monorepos and large codebases
Local overrides./.claude.local.mdPersonal/local settings (gitignored, not shared)
Global defaults~/.claude/CLAUDE.mdUser-wide defaults across all projects

Claude auto-discovers CLAUDE.md files in parent directories. Claude Code does not currently read AGENTS.md natively — projects depending on it should symlink (ln -s CLAUDE.md AGENTS.md).

If no memory files are found, surface that to the user and offer to scaffold one — point at references/templates.md (the pointer-style root template is the recommended starting point for monorepos and large codebases). Do not silently proceed with no audit target.

Phase 2: Quality Assessment

For each memory file, evaluate against quality criteria. See references/quality-criteria.md for the detailed rubric.

Quick Assessment Checklist:

CriterionWeightCheck
Attention economyHighCould each line be cut without harm? Is each one earning its share of finite attention budget?
Pointer disciplineHighAre long docs referenced via path, not embedded via @file?
Lint/test overlapHighDoes any rule duplicate what a linter, type-checker, or test already enforces?
Commands/workflowsHighAre build/test/deploy commands present and copy-pasteable with exact flags?
Non-obvious patternsMediumAre gotchas, ordering dependencies, and project-specific quirks documented?
UniversalityMediumAre rules universally applicable, or task-specific edge-cases that distract during other work?
CurrencyHighDo documented commands and paths still work?

Two strong anti-criteria (these lower the score):

  • High-level project description the model could derive from the codebase ("React project," "monorepo with packages/")
  • Auto-generated content that has not been curated (HumanLayer cites measured negative effect on benchmarks)

Phase 3: Audit Report Output

ALWAYS output the audit report BEFORE making any updates.

Format:

## Memory File Audit Report

### Summary
- Files found: X (with symlink relationships noted if any)
- Total lines across files: X
- Files needing changes: X

### File-by-File Assessment

#### 1. ./CLAUDE.md (Project Root)

| Criterion | Notes |
|-----------|-------|
| Attention economy | ... |
| Pointer discipline | ... |
| Lint/test overlap | ... |
| Commands/workflows | ... |
| Non-obvious patterns | ... |
| Universality | ... |
| Currency | ... |

**Lines to cut:**
- [Specific lines that fail one of the criteria or hit an anti-criterion]

**Lines to add:**
- [Specific additions, with reasoning]

**Lines to convert to pointers:**
- [Long content that should reference a path instead of embedding]

#### 2. ./AGENTS.md (symlink → ./CLAUDE.md)
[Note: edits to one apply to the other; report once.]

...

Phase 4: Targeted Updates

After outputting the audit report, ask the user for confirmation before applying changes. Both removals and additions are first-class — removals are often higher-yield.

If the user rejects all proposed diffs, acknowledge in one line and stop. Do not re-propose, soften, or iterate on the same audit; the user's call stands.

Propose targeted removals. The four highest-yield removal categories:

  1. Rules a linter, type-checker, or test already enforces. "Never send an LLM to do a linter's job." (HumanLayer.)
  2. Task-specific instructions not universally applicable. Instructions on (e.g.) how to scaffold a DB schema "won't matter and will distract the model when you're working on something else." (HumanLayer.)
  3. High-level project descriptions the model can derive from the codebase. (XDA Developers; GitHub blog's 2,500-repo analysis.)
  4. Brittle if-else logic and exhaustive edge-case lists. Diverse, canonical examples beat exhaustive enumeration. (Anthropic, Effective context engineering, Sept 2025.)

Propose targeted additions. Focus on genuinely useful, project-specific information:

  • Commands or workflows discovered during analysis
  • Gotchas or non-obvious patterns found in code
  • Package relationships not clear from imports
  • Configuration quirks (env vars, build-time vs runtime, IPv6 suffixes, etc.)
  • Pointers to deeper documentation (for X, see path/to/X.md)

Keep additions minimal. Avoid restating what is obvious from the code, generic best practices already covered by tooling, one-off fixes unlikely to recur, verbose explanations when one line will do, and embedding long files via @-references when a path pointer suffices.

Show diffs. For each change, show the file (and whether it's symlinked), the specific edit, and a brief reason — for additions, why the line earns its place; for removals, why it was costing more than it earned.

Diff Format:

### Update: ./CLAUDE.md

**Why:** Build command was missing; future sessions had to inspect package.json each time.

```diff
+ ## Quick Start
+
+ ```bash
+ npm install
+ npm run dev  # Start development server on port 3000
+ ```

### Phase 5: Apply Updates

After user approval, apply each accepted diff using the Edit tool, in the order they appeared in the report.

- **Symlinked files**: edit the symlink *source* — the link reflects the change automatically. Never edit through the link.
- **Partial acceptance**: if the user accepts only some diffs, skip the rest silently; do not re-propose.
- **Removals**: apply with Edit using the line(s) to cut as `old_string` and an empty (or replacement) `new_string`. Removals count as edits — track them the same way.
- **Multi-file**: when several files have accepted diffs, apply each file's edits as a contiguous batch before moving to the next file.

After applying, run a short verification: re-read each modified file, confirm the diffs landed, and report a one-line summary per file (`./CLAUDE.md: 3 cuts, 1 addition`).

## After the Audit

Three reminders that apply across the workflow:

- **Displacement test applies to existing lines, not just additions.** If a pre-existing line cannot defend its place, propose cutting it.
- **`#`-added lines are draft content.** The shortcut adds material on the fly without curation; HumanLayer cites measured *negative* effect on benchmarks. Treat any `#`-added line as draft and prune within the same session.
- **Subdirectory CLAUDE.md is preferred over root bloat.** Claude auto-loads them contextually — for monorepos and large codebases, push package- or domain-specific guidance down into the relevant directory rather than enlarging the root file.

Templates by project type — including the **pointer-style root** (~30 lines) the research most strongly endorses for monorepo roots — are in [references/templates.md](references/templates.md).

## Length Discipline

Specific line caps (30 / 60 / 150 / 200 / 300) circulating in community guides are folklore — no controlled study has settled on a threshold. The *direction* is empirically supported (Chroma's *Context Rot*; Liu et al., *Lost in the Middle*, TACL 2024): shorter is better, attention degrades with input length, and middle-of-file content is systematically under-attended.

**Working default: ≤200 lines for project root.** If exceeding, justify each section against the displacement test: *would the file work as well, or better, without this content?*

Gemini Image Generation

Generate and edit images using Google's Gemini API. The SDK reads GOOGLE_API_KEY by default (GEMINI_API_KEY as fallback). Or pass a key explicitly to genai.Client(api_key=...).

Models

ModelCodenameBest For
gemini-2.5-flash-imageNano BananaMost use cases, fast, good quality (default)
gemini-3-pro-image-previewNano Banana ProHigh-res (2K/4K), Google Search grounding, precise text
gemini-3.1-flash-image-previewNano Banana 2High volume, extended aspect ratios, 512 size

Start with gemini-2.5-flash-image. Upgrade to Pro for high-res output or search grounding.

Quick Reference

Default Settings

  • Model: gemini-2.5-flash-image
  • Resolution: 1K (default)
  • Aspect Ratio: 1:1 (default)

Available Aspect Ratios

All models: 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9

3.1 Flash only: 1:4, 4:1, 1:8, 8:1

Available Resolutions

All models: 1K (default), 2K, 4K

3.1 Flash only: 512

Core API Pattern

from google import genai
from google.genai import types

client = genai.Client()  # Reads GOOGLE_API_KEY (or GEMINI_API_KEY fallback)

response = client.models.generate_content(
    model="gemini-2.5-flash-image",
    contents="Your prompt here",
)

for part in response.parts:
    if part.text is not None:
        print(part.text)
    elif part.inline_data is not None:
        image = part.as_image()
        image.save("output.jpg")  # save() takes path only, writes raw bytes

Note: response_modalities is optional. Omit it to let the model decide. Set ['IMAGE'] for image-only output, or ['TEXT', 'IMAGE'] for interleaved text and images.

Custom Resolution & Aspect Ratio

response = client.models.generate_content(
    model="gemini-3-pro-image-preview",
    contents=prompt,
    config=types.GenerateContentConfig(
        image_config=types.ImageConfig(
            aspect_ratio="16:9",
            image_size="2K",
        ),
    ),
)

Editing Images (Chat Mode)

Chat mode is recommended for editing. The SDK handles thought signatures automatically across turns.

from PIL import Image

client = genai.Client()
image = Image.open("input.png")

chat = client.chats.create(model="gemini-2.5-flash-image")

# First edit
response = chat.send_message(["Add a sunset to this scene", image])

for i, part in enumerate(response.candidates[0].content.parts):
    if part.text is not None:
        print(part.text)
    elif part.inline_data is not None:
        image = part.as_image()
        image.save(f"edited_{i}.jpg")

# Continue refining
response = chat.send_message("Make the colors warmer")

PIL Image objects, base64 bytes, and file URIs (via client.files.upload()) all work as image inputs.

Google Search Grounding

Generate images informed by real-time data. Requires Pro model.

response = client.models.generate_content(
    model="gemini-3-pro-image-preview",
    contents="Visualize today's weather in Tokyo as an infographic",
    config=types.GenerateContentConfig(
        image_config=types.ImageConfig(
            aspect_ratio="16:9",
            image_size="1K",
        ),
        tools=[types.Tool(google_search=types.GoogleSearch())],
    ),
)

Image search grounding (searching for reference images) is only available on gemini-3.1-flash-image-preview.

Multiple Reference Images

Combine elements from multiple sources. Pass PIL Image objects directly in the contents list.

from PIL import Image

response = client.models.generate_content(
    model="gemini-2.5-flash-image",
    contents=[
        "Create a group photo of these people in an office",
        Image.open("person1.png"),
        Image.open("person2.png"),
        Image.open("person3.png"),
    ],
)

Limits differ by model:

  • 3.1 Flash: up to 10 object images + 4 character images (14 total)
  • 3 Pro: up to 6 object images + 5 character images (11 total)

Prompting Best Practices

Photorealistic Scenes

Include camera details: lens type, lighting, angle, mood.

"A photorealistic close-up portrait, 85mm lens, soft golden hour light, shallow depth of field"

Stylized Art

Specify style explicitly:

"A kawaii-style sticker of a happy red panda, bold outlines, cel-shading, white background"

Text in Images

Be explicit about font style and placement:

"Create a logo with text 'Daily Grind' in clean sans-serif, black and white, coffee bean motif"

Product Mockups

Describe lighting setup and surface:

"Studio-lit product photo on polished concrete, three-point softbox setup, 45-degree angle"

File Format & Saving

The API returns JPEG in practice. image.save(path) writes raw bytes from the API response. It takes only a path string (no format kwarg).

# Save as-is (JPEG bytes from the API)
image.save("output.jpg")

To convert formats, use PIL on the raw bytes:

from PIL import Image
import io

for part in response.parts:
    if part.inline_data is not None:
        pil_img = Image.open(io.BytesIO(part.inline_data.data))
        pil_img.save("output.png")  # PIL handles the conversion

Notes

  • All generated images include SynthID watermarks (not configurable for Gemini models)
  • save(path) writes raw bytes; no format kwarg exists. Use PIL for format conversion
  • response_modalities is optional; omit to let the model decide output format
  • Multi-turn chat handles thought signatures automatically via the SDK
  • Editing via chat mode doesn't support image_config (only modality config)
  • For editing, describe changes conversationally; the model understands semantic masking
  • Default to 1K for speed; use 2K/4K when quality matters
  • person_generation parameter exists on ImageConfig for controlling person depiction in outputs

Structured Reasoning (ADI Cycle)

Reason through problems by generating competing hypotheses, verifying them against constraints, gathering evidence, and presenting a comparison for the user to decide.

Based on the ADI reasoning cycle: Abduction (generate options) -> Deduction (verify logic) -> Induction (gather evidence) -> Decision (user picks).

When to Use This

  • Architectural decisions with long-term consequences
  • Multiple viable approaches that need systematic comparison
  • Decisions that benefit from an auditable reasoning trail
  • Problems where anchoring on the first idea is a risk

When NOT to Use This

  • Quick fixes with obvious solutions (just do the work)
  • Easily reversible decisions (just try it)
  • Open-ended uncertainty without clear options (use /sc-socratic instead)
  • Pure implementation tasks (implement directly)

Core Principle: Transformer Mandate

You generate options with evidence. The human decides.

Do not select winners autonomously. Present the comparison, surface the trade-offs, and wait for the user to choose.

The ADI Cycle

Each phase is a conversational turn. The user drives transitions — you don't auto-advance through all phases in one response.

Phase 1: Abduction (Generate Hypotheses)

Generate 3-5 competing approaches. Resist anchoring on the first idea that seems reasonable.

Requirements:

  • At least one conservative option (safe, proven, lower risk)
  • At least one radical option (novel, higher potential, less proven)
  • Each hypothesis states: what it is, key assumptions, and where it applies (scope)
  • Classify each as system (code/architecture) or process (methodology/workflow)

Anti-anchoring check: Before generating, ask yourself — am I just listing variations of the same idea? If yes, force at least one genuinely different approach.

Output format:

## Hypotheses

### H1: [Name] (conservative)
**Approach**: [What and how]
**Assumptions**: [What must be true]
**Scope**: [Where this applies]

### H2: [Name]
...

### H3: [Name] (radical)
...

After presenting hypotheses, ask the user:

  • Are any missing? Should we add one?
  • Should we kill any before going deeper?
  • Ready to verify?

Phase 2: Deduction (Verify Logic)

Check each surviving hypothesis against constraints. Kill the ones that don't hold up.

For each hypothesis, check:

  1. Logical consistency — Does the approach actually solve the stated problem?
  2. Constraint compatibility — Does it fit within known technical constraints (existing stack, team skills, timeline)?
  3. Type correctness — Does the solution shape match the problem shape? (e.g., proposing a caching solution for a data modeling problem)

Verdicts:

  • PASS — Logically sound, survives to evidence gathering
  • FAIL — Contradicts constraints or logic. Document why and drop it
  • REFINE — Has potential but needs adjustment. Modify and re-check

Output format:

## Verification Results

### H1: [Name] — PASS
**Logic**: [Why it holds up]
**Constraints**: [Compatible because...]

### H2: [Name] — FAIL
**Reason**: [Specific contradiction or logical flaw]

### H3: [Name] — REFINE
**Issue**: [What needs adjustment]
**Refined**: [Updated approach]

After verification, confirm with user: These hypotheses survived. Ready to gather evidence?

Phase 3: Induction (Gather Evidence)

Collect actual evidence for each surviving hypothesis. This is where you do real work — read code, run searches, check docs, analyze feasibility.

Evidence quality tiers:

TierSourceConfidence
Internal testRun code, benchmark, prototype in this projectHigh
Internal analysisRead this codebase, check compatibilityMedium-High
Similar contextEvidence from similar project/stackMedium
External docsLibrary docs, blog posts, general adviceLow-Medium

Weakest Link Principle (WLNK): A hypothesis is only as strong as its weakest piece of evidence. Don't average — report the floor.

For each hypothesis, gather:

  • Best available evidence (prefer internal over external)
  • The weakest link — what's the least certain thing?
  • Known unknowns — what couldn't you verify?

Use Agent tools to parallelize evidence gathering when hypotheses are independent.

Output format:

## Evidence

### H1: [Name]
**Evidence**: [What you found, with sources]
**Weakest link**: [Least certain element]
**Unknowns**: [What couldn't be verified]
**Confidence floor**: [high / medium / low]

### H3: [Name]
...

Phase 4: Decision (User Decides)

Present a comparison table and let the user choose.

Output format:

## Comparison

| | H1: [Name] | H3: [Name] |
|---|---|---|
| **Approach** | ... | ... |
| **Evidence** | ... | ... |
| **Weakest link** | ... | ... |
| **Confidence** | ... | ... |
| **Trade-offs** | ... | ... |
| **Reversibility** | ... | ... |

## Recommendation

[Your analysis of which is stronger and why — but the user decides]

## What would you like to go with?

After the user decides, document the rationale:

## Decision Record

**Problem**: [Original question]
**Chosen**: [H-name] — [one-line summary]
**Rationale**: [Why this won, citing evidence]
**Rejected**: [Other hypotheses and why they lost]
**Revisit when**: [Conditions that should trigger re-evaluation]

Persistence

Save reasoning artifacts to .agent-history/reasoning/<slug>/:

.agent-history/reasoning/<slug>/
  hypotheses.md    # Phase 1 output
  verification.md  # Phase 2 output
  evidence.md      # Phase 3 output
  decision.md      # Phase 4 output (if reached)

Create the directory at the start of Phase 1. Write each file as its phase completes.

Slug generation: Lowercase the problem statement, take first 4-5 words, join with hyphens. Example: "how should we handle caching" -> how-should-we-handle-caching

Execution

  1. Parse the problem — Read $ARGUMENTS. If empty, ask what decision needs reasoning.

  2. Gather context — Use Read, Grep, Glob to understand the relevant codebase before generating hypotheses. Don't hypothesize in a vacuum.

  3. Run Phase 1 — Generate hypotheses, present to user, wait for confirmation.

  4. Run Phase 2-4 on user request — Each phase is a separate turn. Don't auto-advance. The user says "verify" or "gather evidence" or "decide" to move forward.

  5. Early exit is fine — If the answer becomes obvious during Phase 1 or 2, say so. The framework serves the decision, not the other way around.

Shortcuts

  • /sc-hypothesize [problem] — Start from Phase 1
  • "verify" / "check logic" — Run Phase 2 on existing hypotheses
  • "evidence" / "test these" — Run Phase 3
  • "decide" / "compare" — Run Phase 4
  • "add hypothesis: [idea]" — Add a user-supplied hypothesis at any point
  • "kill H2" — Remove a hypothesis from consideration

Related Commands

SituationNext step
Open-ended uncertainty, no clear options/sc-socratic
Quick implementation after decidingImplement the chosen option directly
Challenge a conclusion adversarially/sc-review-and-refactor (refute-findings route)
Full feature workflow with architecturePlan the architecture in plan mode, then implement it

Socratic Thinking Partner

Think WITH the user, not FOR them. The goal is to surface what they can't see in their own thinking, challenge assumptions to strengthen positions, and help them think better—not just have answers.

The Toolkit

Apply these operations as the situation demands:

| Operation | Purpose | When to Use | |-----------|---------|-------------| | **Assumptions** | Surface hidden beliefs | Any proposal or plan | | **Evidence** | Probe the basis for claims | Confident assertions | | **Consequences** | Trace implications | Decisions with tradeoffs | | **Opposition** | Steelman the alternative | Strong positions | | **Meta-question** | Find what they should ask | Stuck or circular thinking | | **Exclusion** | Define by what's NOT | Scope creep or vague goals |

Core Questions

  • Assumptions: "What must be true for this to work?"
  • Evidence: "How do you know? What would change your mind?"
  • Consequences: "If you're wrong, what happens?"
  • Opposition: "What's the strongest argument against this?"
  • Meta-question: "What question should you actually be asking?"
  • Exclusion: "What should we explicitly NOT do?"

Situation Recognition

Classify the situation into one of these shapes. Do not pattern-match on user phrasing; read the semantic intent:

SituationApproach
Deciding — user comparing options or facing a choiceSurface tradeoffs, challenge both sides
Blocked — stalled progress, unclear obstacleFind the real obstacle, propose smallest next step
Evaluating — user wants a plan or proposal examinedSurface risks and hidden assumptions
Learning — user building understanding of how X worksDraw out existing knowledge first
Designing — user shaping a structure or systemDiverge exploration, then converge to MVP
Undifferentiated uncertaintyAsk what kind of thinking they need

Execution Pattern

  1. Gather context - Use Read, Grep, Glob to understand the actual situation. Don't question in a vacuum.

  2. Apply 2-3 operations - Pick what fits. Don't spray all techniques at every problem.

  3. Surface the question - End with what they should be asking next. Often more valuable than an answer.

  4. Propose action - Concrete next step. Avoid analysis paralysis.

Anti-Patterns

Check yourself for these failure modes:

Anti-PatternSymptomFix
TheaterGoing through motionsGenuine curiosity about their thinking
Infinite LoopQuestions without closureSet a decision point
Answer ExtractionGiving answers disguised as questionsActually wait for their response
Vacuum QuestioningAbstract questions without contextGround in actual code/files first

For detailed anti-pattern descriptions and recovery strategies, see references/anti-patterns.md.

Response Format

## Context
[What you understand about the situation - grounded in actual files/code/evidence]

## Inquiry
[2-3 targeted questions from the toolkit, chosen for this specific situation]

---
[Continue dialogue based on responses]

## The Question
[What they should be asking now - surface this explicitly]

## Next
[Concrete action to take]

When NOT to Use This

  • User wants a direct answer and knows what they're asking
  • Simple factual questions with clear answers
  • Implementation tasks where requirements are clear
  • User explicitly says "just do it" or "don't make me think"

This skill is for uncertainty, not efficiency. Don't apply Socratic dialogue to tasks that just need execution.

Advanced Techniques

For specific situations requiring deeper techniques:

  • Decision-making: See references/decisions.md for multi-path verification and tradeoff analysis
  • Debugging mental models: See references/debugging.md for systematic assumption excavation
  • Design thinking: See references/design.md for diverge-then-converge patterns
  • Teaching/learning: See references/learning.md for drawing out knowledge and building capability

Related Commands

When a specific technique warrants focused application, suggest these specialized commands:

SituationCommandWhen to Suggest
Challenge a conclusion/sc-review-and-refactor (refute-findings route)After reaching a decision, to have a fresh agent try to disprove it
Debug a problem/sc-review-and-refactor (hypothesis-rca route)When tracing root causes in code/systems
Verify factual claims/sc-review-and-refactor (verify-claims route)When accuracy of assertions matters
Specify work for agents/sc-context-wizardAfter clarity is reached, before implementation
Validate completed work/sc-review-and-refactor (requirements-trace route)After implementation, to verify against requirements

These commands provide structured protocols for specific situations. Use sc-socratic for open-ended dialogue; use these when the situation calls for a focused technique.

Examples

See examples/ for complete dialogue transcripts:

  • stuck-on-architecture.md - Helping someone unstick on a design decision
  • challenging-a-plan.md - Strengthening a proposal through opposition

Think Functional

FP discipline for agent-assisted development. Not about switching languages — about structuring code so agents write it well and humans review it fast.

Why FP Matters for Agents

Agents are pattern matchers. They compress training data into a world model, then map between representations: f(pattern_in, context, constraints) => pattern_out. FP makes the patterns explicit.

FP PropertyAgent BenefitHuman Benefit
Type signatures encode intentOne line = full context. Input, output, effects. No retrieval needed.Skim signatures, skip bodies
Pure functions are self-containedEntire function is contiguous text. No hidden state to chase.Trust pure code, scrutinize edges
Composition is the architectureAgents pattern-match the wiring, generate the partsReview wiring, ignore parts
Constraints prevent lazinessCan't introduce side effects where the type system forbids themStructural enforcement, not convention

The Reframe

When approaching any design decision:

Instead of: "What object/class should own this behavior?" Ask: "What's the pure transform, and where does the effect happen?"

Every function is one of three things:

TypeWhat It DoesWho ReviewsAgent Writes Well?
Pure transformData in, data out. No effects.Skim or skipYes — self-contained, testable
Effect at the edgeIO, network, DOM, persistenceRead every lineNeeds guidance — effects are contextual
CompositionWires pure + edge togetherThis IS the architectureNo — human decides the wiring

The Toolkit

Apply these operations to any code design problem:

Separate: Pure from Impure

Ask: "If I deleted every side effect from this function, what computation remains?"

That computation is your pure core. Extract it. The side effects become a thin shell that calls the pure function and does IO with the result.

BEFORE: fetchUser(id) { data = await fetch(url); return validate(data); }
AFTER:  validateUser(data) { ... }  // pure
        fetchUser(id) { data = await fetch(url); return validateUser(data); }  // edge

Push Effects Outward

Ask: "Can the caller handle this effect instead of the callee?"

Effects belong at the outermost layer possible. Pushing the read out of the callee turns the function pure and lets the caller — who already knows the context — supply the data.

// BEFORE: callee reads localStorage; can't be tested without a DOM mock
function renderTheme(): string {
  const prefs = JSON.parse(localStorage.getItem("prefs") ?? "{}");
  return prefs.dark ? "dark" : "light";
}

// AFTER: caller reads, callee computes; pure function, trivial test
function renderTheme(prefs: { dark?: boolean }): string {
  return prefs.dark ? "dark" : "light";
}
// at the edge:
const prefs = JSON.parse(localStorage.getItem("prefs") ?? "{}");
renderTheme(prefs);

Make Illegal States Unrepresentable

Ask: "Can the type system prevent this bug, or does it rely on runtime discipline?"

Three encodings cover most real bugs — branded types for confusable values, Result<T, E> for fallible computation, and exhaustive switch for finite sums.

// (a) Branded type + smart constructor — raw strings can't reach UserId-typed APIs
type UserId = string & { readonly __brand: "UserId" };
const UserId = (raw: string): UserId | null =>
  /^u_[a-z0-9]{8}$/.test(raw) ? (raw as UserId) : null;

// (b) Result<T, E> — failure is in the return type, not in exceptions
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
const parseAge = (s: string): Result<number, "NaN" | "Negative"> => {
  if (s.trim() === "") return { ok: false, error: "NaN" }; // Number("") === 0 — guard first
  const n = Number(s);
  if (Number.isNaN(n)) return { ok: false, error: "NaN" };
  if (n < 0) return { ok: false, error: "Negative" };
  return { ok: true, value: n };
};

// (c) Exhaustive switch — adding a new variant becomes a compile error
type Shape = { kind: "circle"; r: number } | { kind: "square"; side: number };
const area = (s: Shape): number => {
  switch (s.kind) {
    case "circle": return Math.PI * s.r ** 2;
    case "square": return s.side ** 2;
    default: { const _: never = s; throw new Error(`Unhandled: ${JSON.stringify(_)}`); }
  }
};

Enforce Through Structure, Not Convention

Ask: "If an agent ignores my instructions, does the code still work correctly?"

Agents are lazy. They'll take shortcuts if shortcuts compile. Convention says "don't put side effects here." Structure says "this module physically cannot import the side-effect library." Prefer structure. Stack two real mechanisms — editor-time lint plus a build/CI graph check — so a violation fails before review.

The two configs below sketch the shape of those checks: a per-file glob, a list of forbidden imports, a list of forbidden globals, and a from/to graph constraint. Tooling syntax shifts between releases (ESLint v9 moved to flat config; the depcruise CLI changed across major versions), so verify the exact form against your toolchain's current docs rather than copy-pasting.

// .eslintrc.json — inside any *.pure.ts file, block effectful imports
// (modules) AND effectful globals (browser APIs the import rule cannot see).
{
  "overrides": [
    {
      "files": ["**/*.pure.ts"],
      "rules": {
        "no-restricted-imports": ["error", {
          "patterns": ["zustand", "zustand/*", "react", "react-dom",
                       "**/persistence/*", "**/effects/*"]
        }],
        "no-restricted-globals": ["error",
          "localStorage", "sessionStorage", "fetch",
          "document", "window", "navigator"
        ]
      }
    }
  ]
}
// .dependency-cruiser.cjs — graph-level rule, run as part of CI. Fails the
// build when any *.pure.ts file pulls in an effectful package or a
// persistence/effect directory, even if lint was bypassed locally.
module.exports = {
  forbidden: [
    {
      name: "no-effects-in-pure",
      severity: "error",
      from: { path: "\\.pure\\.ts$" },
      to:   { path: "(node_modules/(zustand|react|react-dom)|/persistence/|/effects/)" }
    }
  ]
};

The naming convention (.pure.ts) and directory layout are organizational scaffolding — they give the lint and graph rules a stable target to match. Convention catches one agent on a good day; the lint rule catches every agent on every keystroke; the graph rule catches the violations that slip past lint and fails CI. Branded types do the same job at the value level — preventing pixel coords from reaching hex math without a runtime check.

Narrow the Interface

Ask: "What's the minimum this function needs to know?"

A function that takes the whole world hides its real input. Extract a pure core that names exactly what it consumes; let a thin shell handle the rest.

// BEFORE: 8 lines, mixes effect + computation, takes whole AgentState
function nextHexLabel(state: AgentState): string {
  if (!state.selected) return "";
  const hex = state.board.hexes[state.selected.hexId];
  if (!hex) return "";
  const n = hex.q + hex.r;                          // <-- the actual computation
  return `${hex.q},${hex.r} (#${n})`;
}

// AFTER: pure core takes only what it needs; edge shell does the lookup
const formatHexLabel = (hex: { q: number; r: number }): string =>
  `${hex.q},${hex.r} (#${hex.q + hex.r})`;          // pure, narrow input

function nextHexLabel(state: AgentState): string {  // 3-line edge shell
  const hex = state.selected && state.board.hexes[state.selected.hexId];
  return hex ? formatHexLabel(hex) : "";
}

Applied to Stores (Zustand, Redux, etc.)

State management is where FP discipline pays off most in frontend code:

RuleWhy
No side effects in actionsActions become pure state transitions. Testable without mocking.
No cross-store calls in actionsWire cross-cutting concerns at the composition root. Stores stay independent.
No persistence in store filesExtract to subscription files. Store logic is pure; persistence is an edge effect.
No logging in actionsEvent stores or subscriptions handle observability. Actions compute new state, period.

Store action template:

1. Read current state
2. Compute new state (call pure functions)
3. Single set() call
4. Return value for caller — no side effects

Applied to Handlers

Handlers dispatch on message type and perform effects. Use dependency injection to keep them testable:

interface HandlerDeps {
  getAgent: (id: string) => Agent | undefined;
  // inject only what's needed
}
function createHandler(deps: HandlerDeps): (msg: Message) => void

The handler factory is pure (given deps, returns a function). The deps are wired at the composition root. Testing injects mock deps without touching real stores.

File Organization

Make purity visible in the filesystem:

feature/
  types.ts          # Pure types, no runtime
  foo.pure.ts       # Pure transforms — agents write these freely
  fooStore.ts       # State transitions — review action shapes
  fooPersistence.ts # Edge effects — review carefully
  Foo.tsx           # UI — inherently impure, review interaction logic

The .pure.ts suffix signals to both agents and reviewers: this file has no side effects, is enforced by linting, and can be trusted if the types check.

Review Protocol

When reviewing agent-written code through an FP lens:

  1. Architecture (composition): Read this carefully. Does the wiring make sense? Are effects at the edges?
  2. Edge functions (IO, DOM, network): Read every line. These are where bugs live.
  3. Pure functions: Check types match. Skim body. If types are right and tests pass, the implementation is almost certainly correct.
  4. Test summaries: Are edge cases covered? Are pure functions tested with property-based or example-based tests?

Time allocation: 60% on composition + edges, 30% on tests, 10% on pure function bodies.

Anti-Patterns

Anti-PatternSymptomFix
Purity theater.pure.ts file that secretly mutates a closureEnforce with linting, not just naming
Effect sandwichPure-impure-pure in one function bodySplit into three functions, compose at call site
Overly narrow types15 tiny interfaces when 3 would doGroup by usage pattern, not by minimal surface
Redundant sum-type shapeNesting Option inside Either when one constructor of Either already encodes the missing case (e.g., Either<Error, T> — the Left already represents absence/failure; no Option needed)Pick the sum type whose constructors already encode the cases you need; don't compose them when one is sufficient.
Convention copWriting comments like "DO NOT add side effects here"Add a lint rule instead. Agents don't read comments.

When NOT to Use This

  • Performance-critical hot paths where mutation is measurably faster
  • Inherently effectful code (terminal emulation, canvas rendering, WebSocket lifecycle) — don't force purity where the entire purpose is effects. Wrap it cleanly instead.
  • Prototyping where you're still discovering the right abstraction — premature purity extraction slows exploration
  • One-off scripts that run once and get deleted

The Question

For your current design problem:

  1. What's the pure computation hiding inside the effectful function?
  2. Can the effect be pushed one layer outward?
  3. If an agent writes this, what context does it need? Can the type signature provide that context instead of retrieval?

The best code for agent-assisted development is code where the types tell the whole story.

Commands 2

/sc-install-rules

Install SimpleClaude's bundled rule files into Claude Code's rules system. Rules auto-load based on file context (via paths: frontmatter), bypassing the skill-trigger-phrase failure mode for file-type-bound guidance.

Available rules

Source: ${CLAUDE_PLUGIN_ROOT}/rules/*.md

Current bundle:

  • effective-go.md — Go idioms and conventions (paths: **/*.go)
  • effective-neovim.md — Neovim plugin style (paths: **/*.lua, **/lua/**/*)
  • frontend-design.md — Distinctive frontend aesthetics (paths: tsx/jsx/astro/vue/svelte/html/css/scss)
  • philosophy-of-software-design.md — Ousterhout's design principles (paths: common code files)
  • art-of-readable-code.md — Boswell/Foucher readability guidelines (paths: common code files)

Install flow

Execute the following steps:

  1. Enumerate bundle. List every .md in ${CLAUDE_PLUGIN_ROOT}/rules/ with its paths: frontmatter so the user sees what will install.

  2. Ask destination (default: user-level, since the bundled rules are language/framework-scoped and apply across projects):

    • User-level: ~/.claude/rules/ — applies to all projects
    • Project-level: .claude/rules/ — scoped to current project (check in git if appropriate)
  3. Ask selection. Offer all (default), none, or a space-separated list of rule names (e.g. effective-go frontend-design).

  4. For each selected rule:

    • Compute target path: <dest-dir>/<rule-name>.md
    • If target does NOT exist: copy source → target
    • If target EXISTS: show a diff summary, ask the user overwrite/skip
    • Never silently overwrite
  5. Report what was installed, skipped, or overwritten. Remind the user that rules auto-load — no restart needed.

Constraints

  • Use Bash only for mkdir -p of the destination directory and for simple file copy verification. Use Read + Write for the actual copy so frontmatter is preserved exactly.
  • Never write to system paths or outside the chosen destination.
  • If ${CLAUDE_PLUGIN_ROOT}/rules/ is empty, say so and exit.
  • If the user's Claude Code version doesn't support rules (unlikely but worth a sanity check), warn but proceed — installing unused markdown is harmless.

Updating later

Re-running /sc-install-rules after the plugin updates will detect existing installs and prompt overwrite per-file. No automatic merge — if the user has hand-edited a rule, they say "skip" to keep theirs.

Parallel Worktree Team

Analyze the requested work by entering Plan Mode, then decompose it into parallelizable streams, then execute them simultaneously using git worktrees for isolation and Agent Teams within Tmux for coordination.

Prerequisites

Agent Teams is an experimental feature. The user's session must have been started with CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 set in the environment, otherwise TeamCreate, SendMessage, and team-aware Agent spawning will be unavailable. If team tools fail with "tool not found", stop and tell the user to relaunch Claude Code with that env var.

Input

$ARGUMENTS

Phase 1: Analyze and Decompose

Produce a decomposition artifact that Phase 2 and Phase 5 consume mechanically. Do this work inside Plan Mode so the user approves the artifact before any worktree or team is created.

Step 1: Read project context

  1. Read the project's CLAUDE.md for conventions, the build/check/test/lint commands, and commit rules.
  2. Explore the codebase enough to know — for each candidate stream — the exact paths that will be created or modified.

Step 2: Classify every cross-stream dependency

For every pair of streams where one references the other, classify the dependency as exactly one of the following types. The type determines merge ordering in Phase 5 and the blocked_by wiring in Phase 2.

  • type/interface — Stream B imports types, interfaces, or generated bindings that Stream A defines (or vice versa). A must merge before B.
  • data/file-write — Stream B reads files that Stream A writes (fixtures, schemas, generated assets, migrations). A must merge before B.
  • build/compile — Stream B's build, bundler, or compiler resolves symbols exported by Stream A. A must merge before B.
  • test-only — Stream B's tests reference Stream A's public API but Stream B's production code does not. Either order is acceptable only if the test fixtures are isolated to B's stream; otherwise treat as type/interface and sequence A first.
  • none — Stream is foundational; no cross-stream dependency.

Step 3: Apply overlap-detection rules

Apply these rules literally. They are not heuristics.

  1. Two streams overlap if they modify the same file.
  2. Overlap is acceptable only when one stream is strictly additive — append-only changes such as adding new exports, new test cases, or new entries to a registry — and the other stream does not also rewrite the additive region.
  3. Otherwise, overlapping streams MUST take one of three remediations:
    • sequence them via blocked_by (one merges first),
    • merge them into a single stream, or
    • split the shared surface into a foundational stream that both depend on and that merges first.
  4. Streams that touch shared symbols (types, constants, interfaces, public exports) in non-additive ways MUST NOT run in parallel. Promote the shared surface into a foundational stream.

Step 4: Emit the decomposition artifact

For each stream (target 2-4 streams), emit one fenced yaml block with exactly these fields:

- name: <short-name>                      # used for branch and worktree naming; kebab-case
  files_modified: [<path>, <path>]        # files this stream edits in place
  files_created: [<path>]                 # files this stream creates from scratch
  blocked_by: [<stream-name>, ...]        # other stream names that must merge first; [] if foundational
  dependency_type: type/interface | data/file-write | build/compile | test-only | none
  deliverables: <one line describing what ships from this stream>
  verify_cmd: <the project's check/test/lint command scoped to this stream>

Rules for the artifact:

  • blocked_by entries reference other name values from this same artifact — never task IDs (those don't exist yet) and never file paths.
  • If blocked_by is non-empty, dependency_type MUST be one of the non-none types and MUST justify the ordering (e.g. type/interface is why A blocks B).
  • If blocked_by is [], dependency_type MUST be none.
  • Every file in files_modified and files_created is owned by exactly one stream unless overlap is justified per Step 3 rule #2.

Step 5: Present for approval

Present the full set of yaml blocks to the user inside the plan. Do not exit Plan Mode and do not proceed to Phase 2 until the user approves the decomposition.

Phase 2: Set Up Infrastructure

Create worktrees

One worktree per stream, branched from the current branch:

PARENT_BRANCH=$(git branch --show-current)
mkdir -p .worktrees
git worktree add .worktrees/<stream-name> $PARENT_BRANCH -b <stream-branch>

Symlink dependencies

Each worktree needs access to installed packages:

eg. for npm projects:

ln -sf "$(pwd)/node_modules" ".worktrees/<stream-name>/node_modules"

Other language ecosystems require appropriate and equivalent package symlinking.

Also symlink any other shared directories the project needs (check CLAUDE.md for patterns).

Create team

Call the TeamCreate tool with team_name: <descriptive-name> (required) and description: <what we're doing>. With teammateMode: "tmux" configured in the user's settings, each spawned agent gets its own tmux pane for live visibility.

Create tasks from the decomposition artifact

Walk the Phase 1 artifact in order. For each stream entry:

  1. Call TaskCreate with subject set to the stream name and description set to its deliverables (both required). Record the returned task ID against the stream name so you can resolve names to IDs in the next step.
  2. After every stream has a task ID, walk the artifact a second time. For each stream entry whose blocked_by list is non-empty, call TaskUpdate with taskId set to that stream's task ID and addBlockedBy set to the list of task IDs that its blocked_by stream names resolve to. (TaskCreate does not accept addBlockedBy — dependencies must be added after creation.)
  3. Create one consolidation task via TaskCreate, then call TaskUpdate on it with addBlockedBy set to every stream task ID.
  4. After spawning each teammate in Phase 3, assign its task by calling TaskUpdate with taskId set to the stream's task ID and owner set to the teammate's name so the task list reflects who is working on what.

Phase 3: Spawn Agents

For each stream, call the Agent tool with these parameters using their exact schema names:

  • description: a short label for the stream's work (required)
  • prompt: the detailed instructions string described below (required)
  • subagent_type: "general-purpose"
  • name: <stream-name>-agent
  • team_name: <team-name> (the team created in Phase 2)
  • mode: "bypassPermissions"
  • run_in_background: true

Do NOT pass isolation: "worktree". That parameter makes the Agent tool create its own temporary worktree on a separate branch — different from the named .worktrees/<stream-name>/ branches this command provisions and merges in Phase 5. The agent's commits would land on the Agent-tool-managed branch (returned in the tool result but not tracked here), silently breaking Phase 5's merge. The agent must cd into the named worktree via its prompt (see deliverable #1 below).

Spawn all stream agents in a single assistant message so the Agent tool calls execute in parallel.

Each agent's prompt MUST include:

  1. Worktree path — "All work happens in /absolute/path/.worktrees/<stream-name>/. cd into that directory first, then verify with git rev-parse --show-toplevel before starting."
  2. Specific deliverables — exactly what to create, modify, extract
  3. Verification command — the project's check/test/lint command to run in the worktree
  4. Commit rules:
    • Use conventional commits (feat:, refactor:, fix:, style:, test:)
    • Stage selectively: git add <file1> <file2> — never git add -A
    • Commit messages in present tense, imperative mood
  5. Completion protocol — mark task as completed, send summary to team-lead

Phase 4: Monitor and Wait

  • Agents notify the orchestrator on completion; consume those notification results directly. TaskOutput is deprecated — do NOT call it on agent tasks, and do NOT Read the agent's .output file (it is a symlink to the full sub-agent JSONL transcript and will overflow your context window).
  • Do NOT duplicate work agents are doing.
  • When an agent completes, shut it down. First, call TaskUpdate with taskId set to the agent's task ID and status set to "completed". Then call SendMessage with to set to the agent's teammate name (not recipient) and message set to the object {"type": "shutdown_request"}. Because message is an object, summary is not required.
  • On failure: Read the agent's output, assess whether the failure is isolated to that stream or affects others. Fix in the worktree or abort and replan — do not merge a broken stream.

Phase 5: Consolidate

Merge in topological order of the blocked_by graph — streams whose blocked_by is [] merge first:

git checkout <parent-branch>

# Merge each stream branch in order
git merge <stream-1-branch> --no-edit
git merge <stream-2-branch> --no-edit
git merge <stream-3-branch> --no-edit

If merge conflicts occur:

  1. Identify conflicting files
  2. Resolve conflicts (the orchestrator understands both sides)
  3. git add <resolved-files> && git commit --no-edit

After all merges, run the full verification suite.

Phase 6: Clean Up

# Remove worktrees (warn on failure — don't swallow errors)
git worktree remove .worktrees/<stream-1>
git worktree remove .worktrees/<stream-2>
git worktree remove .worktrees/<stream-3>

# Delete stream branches (merged, no longer needed)
git branch -d <stream-1-branch> <stream-2-branch> <stream-3-branch>

Clean up the team by calling the TeamDelete tool (no parameters — it auto-resolves the current session's team). TeamDelete fails if any teammates are still active, so confirm every agent was shut down in Phase 4 before this step.

Principles

  • Minimize file overlap between streams. If two streams must modify the same file, one should block the other or accept merge conflicts.
  • Agents own their commits. The orchestrator only makes merge commits.
  • Merge order matters. Foundational changes (types, interfaces, shared utilities) merge first. Dependent changes (consumers of those types) merge after.
  • Verify at every stage. Each agent verifies in its worktree. Orchestrator verifies after each merge and after full consolidation.
  • Fail fast. If an agent reports failures, investigate before merging anything.

Success Criteria

  • All stream branches pass verification independently
  • All branches merged without unresolved conflicts
  • Full verification passes on consolidated branch
  • Worktrees and stream branches cleaned up
  • Team deleted

Sponsors

Details

Marketplace
kylesnowschwartz/SimpleClaude
Source
plugins/sc-skills
Author
Kyle Snow Schwartz
Category
Development
License
MIT
Keywords
skills, thinking, hypothesis-testing, file-querying, image-generation, rules, claude-code

More from kylesnowschwartz/SimpleClaude

All 9