research

IndyDevDan / disler — Transferable Code Patterns

Jul 14, 2026

Mined from the actual code (not the videos) in disler's Claude Code repos. Every pattern below is cited to a real file path in a cloned repo, with the load-bearing snippet quoted. Clone locations:

  • ~/Developer/reference-repos/claude-code-hooks-mastery/ (3.8k★ — the hooks bible)
  • ~/Developer/reference-repos/single-file-agents/ (433★ — one-file agents)
  • disler/infinite-agentic-loop (600★) — read via gh api (not cloned)

Focus, per the user's enforcement-hook + model-routing + unattended-loop doctrine: the hook scripts, their settings.json wiring, the exit-code/JSON block channels, the parallel-subagent concurrency primitives, and the model-tiered agent conventions.


0. Repo landscape (what's worth mining)

gh api users/disler/repos top signal for CC-agent work:

repo why it matters
3817 claude-code-hooks-mastery Every hook event wired + guardrails + TTS + validators. Primary.
1480 claude-code-hooks-multi-agent-observability Hooks stream events to a live dashboard (not mined here; same hook shapes)
600 infinite-agentic-loop Two-prompt wave-based parallel fan-out with fresh-context-per-wave
433 single-file-agents Whole agent (deps+prompt+tools+loop) in one uv run file
157 fork-repository-skill Fork the running terminal agent N ways

1. HOOKS SUBSYSTEM (the main event)

1.1 Every hook event is wired, and it's declarative + portable

claude-code-hooks-mastery/.claude/settings.json wires 13 hook events — including newer ones most setups don't touch (PermissionRequest, PostToolUseFailure, SubagentStart, Setup):

"PreToolUse":  [{ "matcher": "", "hooks": [{ "type": "command",
   "command": "uv run $CLAUDE_PROJECT_DIR/.claude/hooks/pre_tool_use.py" }] }],
"Stop":        [{ "matcher": "", "hooks": [{ "type": "command",
   "command": "uv run $CLAUDE_PROJECT_DIR/.claude/hooks/stop.py --chat" }] }],
"SubagentStop":[{ "matcher": "", "hooks": [{ "type": "command",
   "command": "uv run $CLAUDE_PROJECT_DIR/.claude/hooks/subagent_stop.py --notify" }] }],
"UserPromptSubmit":[{ "hooks": [{ "type": "command",
   "command": "uv run .../user_prompt_submit.py --log-only --store-last-prompt --name-agent" }] }]

Two transferable moves:

  • $CLAUDE_PROJECT_DIR anchors every command to the project root — the whole .claude/ tree is copy-pasteable between projects with no path edits.
  • Flags select behavior (--chat, --notify, --name-agent, --log-only). One script, multiple wirings. You dial the same hook up/down per project by editing the command string, not the code.

1.2 UV single-file hooks: zero-install, self-contained (PEP 723)

Every hook is a standalone uv run script with inline deps. From .claude/hooks/subagent_stop.py:

#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "python-dotenv",
#     "anthropic",
# ]
# ///

Why it matters: no venv, no pip install, no requirements.txt drift. uv resolves and caches deps on first run. A hook can pull anthropic for an LLM call without polluting the project env. How to apply: this is the packaging format to standardize your own ~/.claude/hooks/*.py on — it survives being dropped into any repo. (Your model-pin-guard.py could carry its own deps this way.)

1.3 The enforcement primitive: exit code 2 + stderr → goes to Claude

.claude/hooks/pre_tool_use.py is the canonical BLOCK-mode guardrail. Two real rules:

# .env protection — blocks Read/Edit/Write/Bash touching .env (but allows .env.sample)
if is_env_file_access(tool_name, tool_input):
    print("BLOCKED: Access to .env files containing sensitive data is prohibited", file=sys.stderr)
    print("Use .env.sample for template files instead", file=sys.stderr)
    sys.exit(2)  # Exit code 2 blocks tool call AND shows stderr to Claude

# Dangerous rm -rf detection
if tool_name == 'Bash' and is_dangerous_rm_command(command):
    print("BLOCKED: Dangerous rm command detected and prevented", file=sys.stderr)
    sys.exit(2)

The rm -rf detector is worth stealing wholesale — it normalizes whitespace/case, then runs layered regex for flag permutations AND dangerous path targets:

normalized = ' '.join(command.lower().split())
patterns = [
    r'\brm\s+.*-[a-z]*r[a-z]*f',   # rm -rf, rm -fr, rm -Rf
    r'\brm\s+--recursive\s+--force',
    r'\brm\s+-r\s+.*-f',
]
# then: if rm is recursive, also block dangerous targets: /  ~  $HOME  ..  *  .

The .env guard uses a negative-lookahead so templates survive: r'\b\.env\b(?!\.sample)'.

The load-bearing contract: exit(2) + write to stderr = the block reason is fed back to the model, so it self-corrects. exit(0) = allow. Any other non-zero = non-blocking error. This is exactly the user's "hook enforcement, not prompt prose" doctrine, and it's the shape model-pin-guard.py already follows. Steal: the regex library + the dual-message stderr (what's blocked + what to do instead).

1.4 The OTHER channel: structured JSON output (advise vs block vs inject context)

Exit-code-2 is the blunt block. The richer channel is stdout JSON. Two distinct uses:

(a) Inject context at session start.claude/hooks/session_start.py:

output = {
    "hookSpecificOutput": {
        "hookEventName": "SessionStart",
        "additionalContext": context   # git branch, uncommitted count, gh issues, TODO.md
    }
}
print(json.dumps(output)); sys.exit(0)

The context is assembled from live state — git branch + uncommitted file count, gh issue list --limit 5, and the contents (first 1000 chars) of .claude/CONTEXT.md, TODO.md, .github/ISSUE_TEMPLATE.md:

context_files = [".claude/CONTEXT.md", ".claude/TODO.md", "TODO.md", ".github/ISSUE_TEMPLATE.md"]
for file_path in context_files:
    if Path(file_path).exists():
        context_parts.append(f"\n--- Content from {file_path} ---")
        context_parts.append(content[:1000])

Why it matters for THIS user: you noted CLAUDE.md prose silently drops on compaction and isn't inherited by subagents. A SessionStart hook that re-injects the load-bearing context as additionalContext is the durable path — it fires on startup, resume, AND clear (the source field), so it re-primes after every compaction/clear. This is the reliable way to make "standing behavior" actually stand.

(b) Block with a reason via JSON.claude/hooks/validators/validate_file_contains.py:

if success:
    print(json.dumps({"result": "continue", "message": message})); sys.exit(0)
else:
    print(json.dumps({"result": "block", "reason": message})); sys.exit(1)

1.5 ⭐ Validator-as-Stop-hook: closed-loop "keep working until the deliverable meets spec"

This is the single highest-value pattern for the user's finish-condition doctrine. validate_file_contains.py is designed to run as a Stop hook. It finds the newest file in a target dir (via git status --porcelain for untracked + mtime within N minutes), then checks it contains required literal strings. If not, it blocks the Stop and returns an imperative correction message:

MISSING_CONTENT_ERROR = (
    "VALIDATION FAILED: File '{file}' is missing {count} required section(s).\n\n"
    "MISSING SECTIONS:\n{missing_list}\n\n"
    "ACTION REQUIRED: Use the Edit tool to add the missing sections to '{file}'. "
    "Each section must appear exactly as shown above (case-sensitive). "
    "Do not stop until all required sections are present in the file."
)

Wired (from the script's own docstring) as:

Stop:
  - hooks:
      - type: command
        command: "uv run .../validate_file_contains.py -d specs -e .md
                  --contains '## Task Description' --contains '## Objective'"

Why it matters: the agent physically cannot end the turn until the artifact satisfies a machine-checkable contract, and the block message tells it exactly what to fix. This is your "finish conditions demand pasted proof / closed-loop per-phase checklist (PLANF3)" doctrine as an enforceable hook instead of prose. Generalize --contains into: "tests green string present", "## Deviations section exists", "no TODO left", etc. The dead-man's-switch detail: the script catches all exceptions and allows through on internal error (result: continue, exit 0) so a bug in the validator never bricks the session — fail-open on infra error, fail- closed on contract violation.

1.6 PreCompact transcript backup — guard against compaction loss

.claude/hooks/pre_compact.py backs up the full transcript before Claude compacts:

def backup_transcript(transcript_path, trigger):
    backup_dir = Path("logs") / "transcript_backups"
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    # copies transcript_path -> logs/transcript_backups/<session>_<trigger>_<ts>.jsonl

The hook input carries trigger (manual vs auto). Apply: pairs with 1.4(a) — one hook saves the pre-compaction state, the SessionStart hook re-injects the essentials after. Directly addresses the "context drops on compaction" problem in your memory.

1.7 Every hook is also a structured logger (free observability)

Uniform pattern across all hooks: append the raw stdin JSON to logs/<event>.json.

log_path = os.path.join(os.getcwd(), "logs", "stop.json")
# read-or-init list, append input_data, write back indented

stop.py --chat additionally converts the .jsonl transcript into a readable logs/chat.json array. This is the substrate the sibling repo claude-code-hooks-multi-agent-observability streams to a live dashboard. Apply: cheap, uniform event capture — every hook logs its own event type; you get a full audit trail for free, and a Stop hook can post-process the whole transcript.


2. PARALLEL-SUBAGENT CONCURRENCY PRIMITIVES

2.1 ⭐ fcntl.flock TTS mutex — serialize a shared resource across parallel subagents

When many subagents finish at once, their SubagentStop hooks all try to speak → overlapping audio garbage. .claude/hooks/utils/tts/tts_queue.py solves it with a real cross-process file lock:

fd = os.open(str(_LOCK_FILE), os.O_RDWR | os.O_CREAT, 0o644)
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)   # non-blocking exclusive lock
# ... on failure: os.close(fd), sleep with exponential backoff (0.1s -> cap 1.0s), retry until timeout

The lock file stores {agent_id, timestamp, pid}. Stale-lock recovery checks whether the holder is still alive before stealing the lock:

if age > max_age_seconds and lock_info.get("pid"):
    try:
        os.kill(pid, 0)      # signal 0 = "does this pid exist?" (doesn't kill)
        return               # still running, leave it
    except (OSError, ProcessLookupError):
        _LOCK_FILE.unlink()  # holder is dead, safe to clear

Usage in subagent_stop.py:

cleanup_stale_locks(max_age_seconds=60)
if acquire_tts_lock(agent_id, timeout=30):
    try: announce_subagent_completion(summary_message)
    finally: release_tts_lock(agent_id)

Why it matters for THIS user: your fan-out doctrine (OpenClaw maxConcurrent: 8, per-subagent budget caps) means multiple agents hit shared resources concurrently. This is a copy-pasteable, dependency-free (fcntl is stdlib) mutex + PID-liveness stale-lock reaper for any shared resource a hook touches under fan-out — a run-log file, a rate-limited API, a single terminal bell. The os.kill(pid, 0) liveness check is the non-obvious part most naive lock implementations get wrong.

2.2 Provider fallback ladders (fail-silent, never block the agent)

Two ladders, both selected purely by which API keys are present:

  • TTS (get_tts_script_path, repeated in stop/notification/subagent_start): ElevenLabs → OpenAI → pyttsx3 (offline, always works).
  • LLM (stop.py:get_llm_completion_message): OpenAI → Anthropic → Ollama (local) → random canned message.

Every call is wrapped capture_output=True, timeout=10 and every failure path is a silent pass. Principle: a cosmetic/telemetry hook must NEVER block or slow the agent — degrade to a cheaper provider, then to a canned string, then to nothing. Note the inversion vs the naming hook (2.3): completion messages prefer cloud-first (quality), naming prefers local-first (cost/latency). Choose the ladder direction by what the call is for.

2.3 Local-first cheap labeling: the agent-naming loop

user_prompt_submit.py --name-agent generates a one-word session name, Ollama first (5s local), Anthropic fallback (10s), cached so it only runs once per session:

if name_agent and "agent_name" not in session_data:
    result = subprocess.run(["uv","run",".../ollama.py","--agent-name"], timeout=5)
    if result.returncode == 0 and (name:=result.stdout.strip()) and len(name.split())==1 and name.isalnum():
        session_data["agent_name"] = name
    else:  # fall back to Anthropic Haiku
        ...

Cached to .claude/data/sessions/<session_id>.json; the status line then reads it back. Apply: for high-frequency, low-stakes labeling (naming, tagging, routing hints), run a local model first and only escalate to a paid API on failure/invalid output — the validation gate (len==1 and isalnum()) is what makes the cheap model safe to trust.

2.4 Cheap-model summarization off the transcript (Haiku 4.5)

.claude/hooks/utils/llm/task_summarizer.py — on SubagentStop, extract the subagent's original task from its transcript and have Haiku turn it into a spoken <20-word summary:

message = client.messages.create(
    model="claude-haiku-4-5-20251001",  # fast + cheap
    max_tokens=100, temperature=0.7,
    messages=[{"role": "user", "content": prompt}],
)

The task text comes from extract_task_context() reading the hook's agent_transcript_path JSONL and pulling the first user-type message. Apply: hooks have access to transcript_path / agent_transcript_path — you can post-process an entire subagent run with a cheap model at Stop time (summarize, extract deviations, grade against acceptance criteria) without touching the main loop. This is the mechanism to auto-append to your handoffs/RUN-STATE.md on every SubagentStop.


3. AGENT / SUBAGENT CONVENTIONS

3.1 ⭐ Model-tiered agent triplets — routing doctrine as a filesystem convention

.claude/agents/crypto/ ships the same capability three times, differing only in the model: line and color:. The body is a one-line pointer to a shared prompt:

crypto-coin-analyzer-haiku.md   → model: haiku   color: green
crypto-coin-analyzer-sonnet.md  → model: sonnet  color: yellow
crypto-coin-analyzer-opus.md    → model: opus    color: red

Each file's entire body:

---
name: crypto-coin-analyzer-opus
description: Cryptocurrency analysis specialist... Use proactively when given one ticker...
tools: WebSearch, Bash, Write
model: opus
color: red
---
Read and Execute: .claude/commands/agent_prompts/crypto_coin_analyzer_agent_prompt.md

Why it matters for THIS user: this is your scored routing matrix encoded as files. One shared prompt (single source of truth), three thin wrappers = three named dispatch targets at haiku/sonnet/opus cost tiers. color gives instant visual tier ID in the UI (green=cheap, red=expensive). You can @crypto-coin-analyzer-haiku for a throwaway pass and @...-opus when it must land — no prompt duplication, no silent model inheritance. The "body = Read and Execute: <shared file>" indirection is the trick that keeps the three in sync.

3.2 meta-agent: an agent whose only job is to write new agents

.claude/agents/meta-agent.md (model: opus, tools Write, WebFetch, firecrawl, MultiEdit). Its discipline is transferable to any generator agent:

  • Step 0 = fetch live docs first: scrapes docs.anthropic.com/.../sub-agents and .../settings#tools-available before generating, so it never emits against a stale schema.
  • Infer the minimal tool set: "a code reviewer needs Read, Grep, Glob; a debugger needs Read, Edit, Bash." Least-privilege by construction.
  • Description is written FOR auto-delegation: "Craft a clear, action-oriented description ... This is critical for Claude's automatic delegation ... Use 'Use proactively for...'."
  • Output is a strict frontmatter+body template; model defaults to sonnet unless specified.

Apply: when you build generators (spec-writers, agent-writers, hook-writers), bake in "scrape current docs → infer minimal capabilities → write delegation-optimized description → emit to fixed path." The proactive-description advice is the lever that makes subagents actually get auto-selected.

3.3 Natural-language fan-out via a command

.claude/commands/cook.md is the whole fan-out spec — no orchestration code:

Run these 7 sub agent tasks simultaneously in parallel:
1. crypto-coin-analyzer: Analyze DOGE...
4. meta-agent: Create a 'security-vulnerability-scanner' agent...

Apply: a slash command that just enumerates N named-subagent tasks is enough to trigger parallel fan-out. Mixing worker agents (analyzers) with generator agents (meta-agent) in one wave is a legitimate pattern — build capability and use capability in the same run.


4. THE INFINITE AGENTIC LOOP (fan-out under a context budget)

disler/infinite-agentic-loop/.claude/commands/infinite.md is a two-prompt system: a spec file + this orchestrator command. Phases: (1) read spec → (2) reconnaissance of output_dir (find highest existing iteration number) → (3) plan → (4) parallel sub-agent wave → (5) infinite orchestration. The transferable mechanics:

Wave sizing by count:

count 1-5:  launch all agents simultaneously
count 6-20: batches of 5
"infinite":  waves of 3-5, monitoring context, spawning new waves

Fresh context per wave (the key scaling trick):

"Each wave uses fresh agent instances to avoid context accumulation. Main orchestrator maintains lightweight state tracking. Progressive summarization of completed iterations."

Each agent gets a distinct "innovation dimension" so parallel outputs don't collide, plus a directory snapshot taken at launch time and an explicit uniqueness directive.

Graceful conclusion at the budget edge:

WHILE context_capacity > threshold:
    plan next wave (size from remaining context) → launch → monitor → update snapshot
    if approaching limits: complete final wave and summarize

Why it matters for THIS user: this is the reference design for your unattended-loop + per-subagent-budget doctrine. The load-bearing ideas: (a) reconnaissance-before-generation (agents read existing state and continue from max+1, making the loop resumable/idempotent); (b) fresh subagents per wave keep the orchestrator's context flat while output grows — the orchestrator holds only a lightweight snapshot, not the accumulated work; (c) explicit per-agent differentiation prevents the classic fan-out failure of N agents producing the same thing. Bound waves to your budgetMaxCostUsd and you have a safe walk-away generator.


5. SINGLE-FILE AGENTS (the loop, distilled)

single-file-agents/ packs deps + prompt + tools + agentic loop into ONE uv run file. Naming: sfa_<capability>_<provider>_v<version>.py. Anatomy from sfa_duckdb_anthropic_v2.py:

Bounded compute loop with a hard cap (raises on exhaustion):

parser.add_argument("-c", "--compute", type=int, default=10, help="Maximum number of agent loops")
...
while True:
    compute_iterations += 1
    if compute_iterations >= args.compute:
        raise Exception(f"Maximum compute loops reached: {compute_iterations}/{args.compute}")

This is the SFA equivalent of your "every unattended run carries a hard cap." The loop raises rather than silently returning partial work.

Force a tool call every turn:

response = client.messages.create(..., tools=[...], tool_choice={"type": "any"})

tool_choice={"type":"any"} means the model must act, never just chatter — keeps the loop progressing.

Reasoning baked into every tool schema (CoT as a required param):

<parameter><name>reasoning</name><type>string</type>
  <description>Why we need to list tables relative to user request</description>
  <required>true</required></parameter>

Every tool requires a reasoning field. The model must justify each call — visible chain-of- thought that also aids debugging. Steal this for your own tool definitions.

Exploration vs commit separation:

run_test_sql_query(...)   # results visible to AGENT ONLY — for iterating
run_final_sql_query(...)  # results shown to USER — the commit; loop returns after this

A "draft" tool and a "commit" tool. The agent iterates privately on test, and only the explicit final call surfaces to the user and ends the run. Apply: give agents a safe sandbox tool to iterate + a distinct irreversible commit tool — separates trial from action.

XML-structured prompt (<purpose>/<instructions>/<tools>/<user-request>) with {{user_request}} templating — disler's house style across every SFA and command.


6. TOP STEALS (ranked for THIS user's doctrine)

  1. ⭐ Validator-as-Stop-hook closed-loop enforcementhooks-mastery/.claude/hooks/validators/validate_file_contains.py. A Stop hook that blocks the turn until the deliverable contains machine-checkable proof strings, returning an imperative "ACTION REQUIRED... Do not stop until..." message. This is your "finish conditions demand pasted proof / per-phase checklist" doctrine as a real hook, not prose. Fail-open on validator error, fail-closed on contract violation. Generalize --contains into your per-phase gates.

  2. ⭐ fcntl.flock mutex + PID-liveness stale-lock reaperhooks-mastery/.claude/hooks/utils/tts/tts_queue.py. Dependency-free cross-process lock for any shared resource under fan-out; os.kill(pid, 0) liveness check before stealing a stale lock. Directly serves your OpenClaw maxConcurrent / per-subagent-budget fan-out — use it to serialize writes to handoffs/RUN-STATE.md or any rate-limited resource.

  3. ⭐ Model-tiered agent tripletshooks-mastery/.claude/agents/crypto/*-{haiku,sonnet,opus}.md. Your scored routing matrix as files: one shared prompt, three thin wrappers differing only in model:+color:. Named dispatch at three cost tiers with zero prompt duplication and no silent model inheritance.

  4. ⭐ SessionStart additionalContext injection + PreCompact backupsession_start.py (git status + gh issue list + TODO.md → hookSpecificOutput.additional Context) and pre_compact.py (transcript backup). The durable fix for "CLAUDE.md prose drops on compaction": one hook backs up pre-compaction state, the other re-injects essentials on every startup/resume/clear.

  5. ⭐ pre_tool_use.py exit-2 guardrail libraryhooks-mastery/.claude/hooks/pre_tool_use.py. The canonical enforcement shape you already run (exit 2 + stderr → Claude self-corrects). Steal the rm -rf permutation regex and the .env negative-lookahead block (\b\.env\b(?!\.sample)) straight into your deny/hook layer.

  6. Bounded agentic loop mechanicssingle-file-agents/sfa_duckdb_anthropic_v2.py + infinite-agentic-loop/.../infinite.md. Hard --compute cap that raises on exhaustion; tool_choice={"type":"any"} to force progress; a required reasoning param on every tool (CoT-as-schema); test-vs-final tool separation; and the wave-based fan-out with fresh-context-per-wave + reconnaissance-before- generation for resumable, context-flat, walk-away loops.

Runner-up steals: UV/PEP-723 single-file hook packaging (§1.2, make ~/.claude/hooks/* self-contained); local-first-then-cloud cheap labeling with a validation gate (§2.3); cheap-Haiku post-processing of a subagent transcript at Stop time to auto-write your run log (§2.4); uniform per-event JSON logging for free observability (§1.7).


Appendix — file-path index (all real, verified)

Hooks (~/Developer/reference-repos/claude-code-hooks-mastery/.claude/):

  • settings.json — 13-event wiring, $CLAUDE_PROJECT_DIR, flag-driven behavior
  • hooks/pre_tool_use.py — rm-rf + .env exit-2 guardrail
  • hooks/session_start.py — additionalContext injection (git/issues/TODO)
  • hooks/pre_compact.py — transcript backup before compaction
  • hooks/user_prompt_submit.py — agent-naming loop (ollama→anthropic), session data
  • hooks/stop.py / hooks/subagent_stop.py — TTS notify + transcript→chat.json
  • hooks/subagent_start.py / hooks/notification.py — spawn/notify TTS
  • hooks/utils/tts/tts_queue.py — fcntl.flock mutex + PID stale-lock reaper
  • hooks/utils/llm/task_summarizer.py — Haiku 4.5 transcript summarizer
  • hooks/validators/validate_file_contains.py — Stop-hook deliverable enforcement
  • status_lines/status_line_v6.py — context-window % progress bar status line
  • agents/meta-agent.md — agent-that-writes-agents (opus)
  • agents/crypto/*-{haiku,sonnet,opus}.md — model-tiered triplets
  • commands/cook.md — 7-way natural-language fan-out

Single-file agents (~/Developer/reference-repos/single-file-agents/):

  • sfa_duckdb_anthropic_v2.py — bounded loop, tool_choice=any, reasoning-param, test/final split
  • CLAUDE.md — the SFA philosophy (uv + embedded deps + one capability per file)

Infinite loop (disler/infinite-agentic-loop, via gh api):

  • .claude/commands/infinite.md — wave-based parallel fan-out orchestrator prompt

Inferences are marked [UNVERIFIED] inline where present; none load-bearing were needed — every pattern above is quoted from a file actually read.