agentleFS
BordaBorda/AI-Rig/plugins/CLAUDE.md

AI-Rig / plugins

CLAUDE.md31 starsChanged 3 months agoApache-2.0View on GitHub

Any policy change in one listed instruction file must trigger a relevance review of every other listed file before completion. Synchronize applicable shared policy in either direction; preserve intentional agent-specific differences and record when no counterpart change is needed. Plugins under plugins/. See README.md for user-facing detail. Sections below with a "Full ... : AUTHORING.md §X" pointer have narrow-trigger detail (worked checklists, mechanism rationale, precedent, catalogues) in plugins/AUTHORING.md, same directory — load on demand, not needed for routine edits. In…

The file

Show its rules and text

We split this CLAUDE.md into the rules it gives an agent

27 rules. About 0 are common, 11 are distinctive, and 16 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈11

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 16

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Ask the user when evidence cannot establish whether a difference is intentional, the correct common behavior is ambiguous, or a counterpart …

    line 16
  2. Very specific:

    Before completion, repeat the scan for missed or stale uses, run affected contract/calibration/package checks, and summarize synchronized …

    line 17
  3. Very specific:

    Never underscores: CommonMark accepts only letters, digits and hyphens in a raw-HTML tag name, so <foo_bar> is not a tag — it is prose, and …

    line 30
  4. Very specific:

    Never use bare #N for local ordinals (list items, step indices, ranks, internal check IDs) or bare @word for non-GitHub tokens (decorators, …

    line 44
  5. Distinctive:

    Keep the measured fact, mechanism, and each deliberate exclusion with its reason.

    line 60
  6. Very specific:

    Prefer an early-exit guard ([ -n "$X" ] || exit 0) over wrapping the rest of the block in if.

    line 75
  7. Very specific:

    All size/length limits: tokens primary, lines secondary.

    line 82
  8. Very specific:

    Every file added to plugins/*/skills/*/modes/, plugins/*/skills/*/templates/, or plugins/*/skills/_shared/ must satisfy one condition:

    line 96
  9. Very specific:

    Check R2 (/foundry:audit plugins) detects violations.

    line 100
  10. Distinctive:

    Keep surrounding "follow/execute protocol" prose — only the load mechanism changes

    line 119
  11. Very specific:

    Every file installable via claude plugin install <name>@borda-ai-rig.

    line 152
  12. Distinctive:

    When local main is ahead of the remote — whenever work is committed but unpushed — every new worktree starts on a stale base.

    line 162
  13. Very specific:

    Root fix: keep origin/main current. A stale remote-tracking ref is the actual cause.

    line 169
  14. Very specific:

    Independent instances: never cross-ref via local/relative path (breaks after install) — reference only via installed plugin-prefixed name …

    line 180
  15. Very specific:

    Not manifested: an optional provider's contract that is worthless without the provider (codemap-py's claude-skills/_shared/*.md) — …

    line 191
  16. Very specific:

    No plugin dependency system in Claude Code — never propose "install foo as prerequisite" as a resilience fix.

    line 194
  17. Very specific:

    Never: use $HOME/.claude/skills/_shared/...

    line 201
  18. Very specific:

    Never: read another plugin's _shared or bin/ (resolve_shared_path.py foundry from a non-foundry plugin, --foundry, $_FOUNDRY_SHARED, …

    line 202
  19. Distinctive:

    Every diagram closes with a footer stating the non-normative status, the update obligation and its normative source, so the rule travels …

    line 236
  20. Very specific:

    Not covered by §Shared File Authoring Rule (that governs modes/, templates/, _shared/).

    line 243
  21. Distinctive:

    Do not grow a text guard by enumerating bypass strings: this guard grew from about 328 to about 2800 lines, then about 3400, through …

    line 302
  22. Distinctive:

    Add a quiet class only with a positive model: use a short explicit table of allowed programs and options, never a deny-list of known-bad …

    line 303
  23. Distinctive:

    Never put round, finding, probe or task numbers in test names, titles, labels, markers or comments.

    line 308
  24. Distinctive:

    Before any edit, delete, or addition to plugin files — self-challenge:

    line 312
  25. Distinctive:

    Complete and clean?: No gaps/TODOs, no dead instructions, no orphaned cross-refs, no leftover stubs

    line 316
  26. Distinctive:

    Verified?: Every claim backed by code/disk evidence — no hypothesis or assumption stated as fact

    line 317
  27. Very specific:

    Digest-pinned?: Before a mass edit of shipped files (comments, formatting, lint), search the repo for the sha256 of each target's HEAD …

    line 319

≈ “Common” is an estimate: at least 1 in 5 of the 28,633 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md
<!-- scope: project-local plugin authoring rules — not synced to ~/.claude/ -->

Plugin Authoring Rules

<!-- policy-sibling-sync: CLAUDE.md, AGENTS.md, plugins/AGENTS.md, plugins/CLAUDE.md -->

Any policy change in one listed instruction file must trigger a relevance review of every other listed file before completion. Synchronize applicable shared policy in either direction; preserve intentional agent-specific differences and record when no counterpart change is needed.

Plugins under plugins/. See README.md for user-facing detail. Sections below with a "Full ... : AUTHORING.md §X" pointer have narrow-trigger detail (worked checklists, mechanism rationale, precedent, catalogues) in plugins/AUTHORING.md, same directory — load on demand, not needed for routine edits.

Change Consistency

  • Before any plugin addition, edit, or deletion, ask which other uses share the same behavior or contract, then scan the owning plugin and other plugins for similar implementations, invocation patterns, consumers, documentation, tests, and calibration cases. Do not limit the scan to exact names or already-touched files.
  • Record relevant counterparts before implementation. Apply the change to every counterpart that shares the contract, including removal of obsolete references after deletions; extend file ownership and verification scope explicitly when needed.
  • Preserve intentional differences in behavior, permissions, platform support, and plugin independence. Similar wording alone does not justify identical changes, a shared abstraction, or a new cross-plugin dependency.
  • Ask the user when evidence cannot establish whether a difference is intentional, the correct common behavior is ambiguous, or a counterpart requires authority outside the requested scope. Present the concrete counterparts and recommended treatment; continue unaffected authorized work.
  • Before completion, repeat the scan for missed or stale uses, run affected contract/calibration/package checks, and summarize synchronized counterparts plus intentional exclusions with reasons. A confirmed applicable counterpart left inconsistent keeps the task incomplete unless the user explicitly defers it.

Markdown Annotation Convention

In .md plugin files, prose annotations, notes, and load directives use > blockquotes. Use # only for real Markdown headings and, inside fenced bash/python blocks, code comments — never as a fake prose comment or load directive, since that changes heading hierarchy.

> loads: modes/resume.md   ✓    # loads: modes/resume.md   ✗ (H1)

Structural Tag Names — Hyphens, Never Underscores

  • Structural block tags (<routing-boundaries>, <antipatterns-to-flag>, <core-principles>) use hyphens between words.
  • Never underscores: CommonMark accepts only letters, digits and hyphens in a raw-HTML tag name, so <foo_bar> is not a tag — it is prose, and every Markdown formatter escapes it to \<foo_bar>, breaking Claude's block navigation.
  • Enforced by check_tag_symmetry.py --check underscore-tag.

Markdown Code-Block Comments

  • Code block comments: procedural code (steps an agent/skill executes) — explain WHY only (non-obvious constraint, workaround, incident ref, safety rationale), never WHAT/HOW; remove self-documenting comments.
  • Example/pattern code (illustrates a pattern, not executed directly) — comments may also document expected output, motivation, or when to apply.
  • Self-documenting-comment examples: AUTHORING.md §Markdown No-Wrap.

GitHub Reference Scoping — #N and @name

<!-- policy-sibling: plugins/cc_foundry/rules/git-commit.md, plugins/cc_foundry/rules/_full/git-commit.md, plugins/cc_oss/skills/_shared/shepherd-voice.md, plugins/cc_oss/skills/release/guidelines/writing-rules.md — same GH #/@ scoping policy restated for each consumer's own context. Editing this section → grep repo for `policy-sibling` to find every copy, update in lockstep (rationale + precedent: §Policy Duplication Marker below). -->
  • #N bare in prose = GitHub issue/PR/discussion number only; @name bare in prose = a real GitHub username mention only. Both become live link/notify tokens in a GH comment, PR body, issue, or commit message.
  • Never use bare #N for local ordinals (list items, step indices, ranks, internal check IDs) or bare @word for non-GitHub tokens (decorators, role handles). Use plain numbers/words, or backticks for code-shaped tokens only; never backticks to defang a real person's handle.
  • #N is same-repo only; cross-repo references need the full URL, never #N or owner/repo#N.
  • @name needs certainty of ping intent. Drop @ if uncertain, except release-note/CHANGELOG contributor credit, which is deliberate ping intent and stays live.
  • Full forbidden/OK catalogue: AUTHORING.md §GitHub Reference Scoping.

Writing Style — Compression Tiers

  • Three compression tiers by reader:
    • User-facing docs = verbose (full sentences, rationale).
    • Reports/human-read output = normal caveman (drop filler, keep clarity).
    • Agent source/handover files/inter-agent prose = ultra caveman (max compression, fragments OK).
  • Code, commands, file:line refs, JSON keys/envelopes are always verbatim, never compressed.
  • Full tier table + unsure-rule: AUTHORING.md §Writing Style — Compression Tiers.
  • Comments inside .md code blocks are prose, not code — ultra caveman. The verbatim rule covers code; a # comment beside it is agent-source prose and compresses like any other.
  • Comments are re-sent into context on every invocation of that skill, so verbosity recurs. Keep to one or two lines, fragments, no articles or hedging.
  • Strip dates, audit/basket names and back-references ("2026-08 audit (…)", "already computed above") — git history holds provenance.
  • Keep the measured fact, mechanism, and each deliberate exclusion with its reason.
  • Never remove or reword # timeout: N — parsed by the harness to set the Bash tool timeout; it is functional, not documentation. Same for # tmpdir-exempt:, # noqa:, # shellcheck.
  • Compress wording, never content, for any comment encoding a constraint, a why-not, or a bug that was fixed — those comments are why the bug stays fixed. Losing one silently re-opens it.
  • Size follows importance. Spine text (workflow steps, gates, deliverable contracts, high-stakes rules) is complete first and short second; complement text (rationale, examples, measurement detail, flag-only steps) stays small and moves behind a load boundary (a flag-loaded mode file, _full/) rather than being squeezed in place. /foundry:audit --efficiency E11 (bin/size_importance.py) flags only text it can prove is complement; doubt means spine.
  • .py files are exempt: Python docstrings and comments stay plain and extensive. They serve maintainers, and cost nothing at skill-load time.

Worked before/after example, recurring casualties of a compression pass (modals, logic conjunctions, paragraph scope, actors/qualifiers, test-pinned sentences), and the pass-yield note: AUTHORING.md §Comment Compression.

Code Density — Bash/Code Blocks

  • Balance compression and readability in inline bash/code blocks; tune both.
  • Readability comes from variable names, not extra blank lines, comments, or nesting. MATCH_REPORT/GATE_LINE need no surrounding whitespace; cryptic names do.
  • Validate compression by tokens actually used ($(( $(wc -c < file) / 3 )), per §Length Unit Convention), not snippet appearance.
  • Cutting information-free lines (blank separators, nested empty blocks, or loops a single grep/pipeline replaces) lowers the real count.
  • Renaming a variable shorter but vaguer does not lower the real cost; it moves cost to the next reader.
  • Prefer an early-exit guard ([ -n "$X" ] || exit 0) over wrapping the rest of the block in if.
  • Collapse a loop-with-break searching for one match into a single grep/awk/pipeline when the semantics are identical (mind edge cases — e.g. a glob expanding to zero files feeding a filter with no explicit input turns into a stdin hang).
  • Drop blank lines between statements that read as one step; keep one where it marks a genuine phase change.
  • Terse code never overrides correctness — a safety check (fail-closed on an unverifiable value) stays even if it costs a line.

Length Unit Convention

  • All size/length limits: tokens primary, lines secondary. Format N tokens (~M lines) (e.g. 10K tokens (~500 lines)); never lines-only or chars-only as sole unit.
  • Token estimate: $(( $(wc -c < file) / 3 )). The /4 rule of thumb predates the tokenizer introduced with Claude Opus 4.7 and carried by every current model, which emits roughly 30% more tokens for the same text — /4 under-reports by about that margin, so a file measured under a cap can sit over it.
  • Applies to per-file limits, per-turn budgets, envelope caps, and consolidator thresholds.
  • Rationale + full apply-list: AUTHORING.md §Length Unit Convention.

File Layout

  • .claude-plugin/plugin.json — version + metadata; agents/, skills/, README.md, CLAUDE.md (optional); rules/, hooks/ — foundry only (exception: bridge_cc-codex/rules/ = packaged contract docs pinned by its tests, not Claude-loaded rules)
  • bin/ — standalone executables (.py, ≥3.10, see §Installability), auto-added to Bash PATH; each executable block first resolves and exports PLUGIN_ROOT through the shared resolver, then invokes python "$PLUGIN_ROOT/bin/<script>.py". Scope: deterministic transforms only — decision flow/branching/agent-dispatch stays in SKILL.md prose. Full language policy: AUTHORING.md §bin/ Language Policy. Narrow bootstrap exception: shared POSIX bin/python, native Windows bin/python.cmd, and Codemap runtime launchers select and validate Python before Python code can run; application logic stays in Python, with arguments, streams, and exit status preserved and no workload retries.
  • Inline SKILL.md blocks: bash default; Python only when bash needs JSON parsing, multi-line strings, or numeric computation (Bash(python:*) is allow-listed in every plugin, so a bare python … call never prompts; a capture form VAR=$(python …) still trips the "Contains expansion" gate).
  • references/<agent>/*.md — agent sidecar fragments, loaded via cat only when token-free; fragments with executable bootstrap tokens use a plugin loader or render_plugin_root.py. Never nest under agents/ (registers as an uncontrolled dispatchable agent) or bin/ (PATH-scanned); skills/<name>/ is safe. Mechanism: AUTHORING.md §references/<agent> Nesting Mechanism.

Shared File Authoring Rule (modes/, templates/, _shared/)

  • Every file added to plugins/*/skills/*/modes/, plugins/*/skills/*/templates/, or plugins/*/skills/_shared/ must satisfy one condition:
    1. Its basename appears as a literal string in ≥1 consumer .md file (e.g. # loads: upgrade.md).
    2. It contains <!-- file: <basename> — consumers: ... --> (cross-plugin consumers).
  • At authoring time, add the loads-comment or header to the consumer before creating the shared file. A grep-based orphan check deletes unmarked files with zero hits.
  • Check R2 (/foundry:audit plugins) detects violations.
  • Why + precedent: AUTHORING.md §Shared File Authoring Rule.

Policy Duplication Marker

  • Policies restated across multiple files (each consumer needs the rule inline in its own reading context) have no structural sibling link; plain grep for refined-rule violations will not surface stale copies.
  • Rule: Documents declaring a shared policy-sibling-sync set at the top use that document-level contract. A policy change in any listed document triggers relevance review of the others while preserving intentional differences.
  • For a policy duplicated outside that declared set, add <!-- policy-sibling: <path1>, <path2>, ... --> in every copy and inspect every listed copy before completion.
  • Precedent + worked example: AUTHORING.md §Policy Duplication Marker.

Loading Shared Docs — Bash cat or a plugin loader, never the Read tool

Load _shared/*.md (+ modes/, templates/) through Bash — never the Read tool. Read tool path-matches version-pinned cache paths (plugin update re-prompts permission); a Bash command command-matches its allow rule (Bash(cat:*), Bash(python:*)). Choose the form according to whether the document contains executable bootstrap tokens:

  • Resolve + cat: cat "$VAR/foo.md", with $VAR resolved in the same bash block — bash state doesn't persist cross-call. Use only for documents without executable bootstrap tokens; otherwise emit through render_plugin_root.py or a plugin-owned loader.
  • Plugin-owned loader: a script in the consuming plugin's own bin/ that resolves the doc and prints it in one Bash call, e.g. python "$PLUGIN_ROOT/bin/dev_load_shared.py" foo.md after that block's guarded resolver prologue (foundry: load_shared_doc.py, load_mode.py). It renders only the plain ${CLAUDE_PLUGIN_ROOT} bootstrap token to the validated absolute owning-plugin path, preserves all other bytes, fails visibly when the doc is missing (unless the call opts into warn-and-skip), and resolves only its own plugin's files (§Self-Contained _shared).

Both forms:

  • Keep surrounding "follow/execute protocol" prose — only the load mechanism changes
  • Either form is compliant within its token constraint; never revert one to the other, and never to Read `$VAR/foo.md`. Audit/curator: accept both within that constraint. Migrating a plugin's sites between forms is a deliberate, explicitly scoped change, never an opportunistic edit.

Sentinel Reads — read, not $(cat ...)

Single-line sentinel read-back: IFS= read -r VAR < "${TMPDIR:-/tmp}/<name>-${CSID}" 2>/dev/null || VAR=<default> — never VAR=$(cat ...). Command substitution $(...) triggers "Contains expansion" permission prompt in subagents regardless of allow list. Bare cat "$VAR/foo.md" (section above) unaffected — no substitution. Full rule + newline caveat: cc_foundry/rules/claude-config.md §TMPDIR Sentinel Scoping. Every plugin registers one Bash PreToolUse auto-allow hook, hooks/allow-dispatch.js, and ships two required decision modules behind it (canonical: cc_foundry; propagated via propagate_shared.py). Foundry adds a third, optional gh-read lane; siblings run two. hooks/sentinel-read-allow.js matches by shape: the legacy idiom, $(date -u +FMT) stamps, and the read-form itself (its first token IFS= matches no prefix allow-rule) in read-only compounds. For capture-substitutions no shape can cover ($(python …), $(git rev-parse …), $(jq …)), hooks/blueprint-allow.js matches by provenance: the normalized command must be an exact digest hit in the plugin's committed blueprint-manifest.json. Foundry alone ships hooks/github-read-allow.js, which allows a command made only of allowlisted gh reads; the shared dispatcher skips this lane where its module is absent. No module is registered itself; the dispatcher asks them in rank order — provenance, shape, gh read — emits the first allow, and appends one audit record describing what each said. Full detail in cc_foundry/permissions-guide.md §"Contains expansion" gate and §Audit records.

Blueprint Blocks — Keep the Text Invariant

  • blueprint-allow.js matches exact normalized text. Any rewrite before execution misses the manifest and prompts; authoring choices decide coverage:
  • Runtime values arrive through shell variables, never <placeholder> text. gh api "repos/$SLUG/commits/$TAG" is invariant; gh api repos/<org>/<repo>/commits/<tag> forces substitution and can never match.
  • A literal default beside a # substitute: comment is a placeholder in disguise. MODE=each # substitute: each | grouped matches the manifest unedited, so the default silently wins on every run (measured: a resolve run that selected grouped landed 12 per-item commits). A user-chosen value from a closed set → one fixed block per value (echo grouped > "$SENTINEL"), the orchestrator runs exactly the matching one. Free-text values keep a placeholder but the block aborts on it unsubstituted (case "$X" in *'<'*'>'*|"") echo "! BLOCKED …"; exit 1;; esac). Never cite an existing # substitute block as precedent. <!-- policy-sibling: plugins/CLAUDE.md §Blueprint Blocks (canonical), plugins/cc_foundry/agents/challenger.md, plugins/cc_oss/skills/resolve/modes/item-selection.md (Step 3d), plugins/cc_oss/skills/resolve/modes/push.md (Step 10), plugins/cc_oss/skills/review/modes/acceptance-gate.md (reject gate) -->
  • Isolate any command carrying a multi-line quote or heredoc into its own fenced block. The generator bails out of per-command extraction for such a block; every other command silently loses its entry and prompts individually. One GraphQL query cost 8 sibling commands theirs.
  • State files are data: read them, never source or run them. A sentinel holding KEY=value lines is read back with while IFS='=' read -r _SK _SV; do case "$_SK" in KEY) KEY=$_SV ;; esac; done < "$F", never . "$F": a value carrying outside text (a PR's CI check names, a path with a space) would run as a command inside an auto-allowed block. Likewise a value read from state is never a command word (bash -c "$CMD", $RUNNER pytest). The generator refuses all three, and a data heredoc (only python - <<'PY' code keeps its entry), and admits a mutating bin/ helper (commit_*, purge_*, revert_*, …) only when listed in _MUTATING_HELPERS with its guard.
  • Never ask prose for a derived value without shipping the producing command. "parse gh pr checks output → extract failing names", with no block, yields an improvised pipeline: text differs each run, always prompts, and remains unreviewed. The observed one used grep -P, absent on BSD/macOS.

Growing Ledgers — Append, Never Rewrite

A file that only grows — .jsonl record logs, .tsv rows, .log files, diaries, journals, results ledgers — is appended to, never re-written. A read-modify-Write round trip re-emits every earlier record through the model: one dropped or reworded line silently rewrites history, and the cost grows with the ledger.

  • Name the mechanism in every instruction that adds to a ledger. "Append", or "append with the Write/Edit tool", is not a mechanism.
  • Model-valued record (metric, verdict, prose the model decides): Write exactly one record to <ledger>.rec with the Write tool, then run the fixed-text block's guarded resolver prologue followed by python "$PLUGIN_ROOT/bin/append_ledger.py" "$LEDGER", with LEDGER resolved from a sentinel or state file via IFS= read -r (§Sentinel Reads). The script appends the staged file, supplies a trailing newline the Write tool may have omitted, and deletes the .rec so the next Write creates it fresh. Every cc_* plugin ships a byte-identical copy (propagate_shared.py MANIFEST).
  • Never the shell form cat "$L.rec" >> "$L" && rm -f "$L.rec". rm has no allow entry beyond .temp/state/*, and the blueprint manifest drops every block that runs it, so that form prompts on every append. A bare cat also glues the next record onto a record saved without a trailing newline.
  • Parallel writers each stage their own <ledger>.<writer>.rec; one append_ledger.py call after every writer has returned appends them all, sorted by name. Two writers never share one .rec.
  • Values already in the shell or on disk: printf '…\n' … >> "$LEDGER", jq -c … >> "$LEDGER", or append_ledger.py "$LEDGER" --from <files> (appends and keeps the sources).
  • Corrections are new records, not edits. A later verdict on an earlier entry is appended as an event line, and readers take the last record per key. Values derived after the fact go to a sidecar file (e.g. results-deltas.jsonl), never back into the ledger.
  • Exempt — editing or rewriting is correct here: single-value state (state.json, sentinels); mtime-clock agent-watch-*.tsv batch files; compaction contracts; digest- or validator-bound rendered artifacts; dedup and merge reconciliation; the artifact being refined (a report section, a release draft, a placeholder filled in place); frozen plans.
  • Guard: tests/instructions/test_append_only_ledgers.py fails on a skill, agent, or mode sentence that pairs "append" with the Write or Edit tool without naming the .rec staging.
  • Schema-owning helper exception: loop-rounds.jsonl and loop-metrics.jsonl are appended by adversarial_loop.py --append / --append-metrics, and a run's gaps.jsonl by gap_ledger.py append (byte-identical copy per emitting plugin; cc_oss stages gap-only records in gaps.jsonl.rec and calls gap_emit.py append, which fills the run identity and delegates to it). Each validates the staged .rec against the ledger and deletes it. Never append_ledger.py for these three.
  • Codex Rig counterpart: same .rec staging, no append_ledger.py — the helper owning each ledger's schema appends and validates the staged record (codex-rig/shared/native-skill-contract.md §Append-Only Ledgers). Intentional: Codex has no permission matcher or blueprint manifest, and per-schema validation refuses a bad record before it lands.

Installability

  • Every file installable via claude plugin install <name>@borda-ai-rig; no dependency on source tree — installed path only; no hardcoded paths to sibling plugins or plugins/<name>/ dirs
  • No hardcoded absolute user paths (/Users/<name>/, /home/<name>/, /tmp/) — critical, breaks on every other machine. Always ~/, $(git rev-parse --show-toplevel), or $CLAUDE_PLUGIN_ROOT. Check R3.
  • Validate: after claude plugin install, all agents/skills/rules/hooks resolve without a local plugins/ tree
  • Root selection belongs to the shared resolver: each executable block begins PLUGIN_ROOT=$(python "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name <plugin>) || exit $?; export PLUGIN_ROOT, then calls helpers as python "$PLUGIN_ROOT/bin/<name>.py". The host substitutes the plain token in skills and agents; loaders render it in emitted fragments. Never use the defaulted token or bootstrap from cwd-relative paths. The resolver selects the install record before validated cache versions; its final source fallback is restricted to its own AI-Rig checkout with cwd inside that checkout. Check C32.
  • Agent spawns require health monitoring: every Agent() spawn runs in the background — the skill spawns, ends the turn, and resumes on the completion notification. Any skill calling Agent() must implement CLAUDE.md §6 (per-agent deadline file checked by agent_watch.py on each wake-up, ⏱ at once for a missed deadline or a notification without output; never a waiting tool — ScheduleWakeup, ListAgents, Monitor — a fixed-interval poll, or a no-op call holding the turn open) — reference _FOUNDRY_SHARED/agent-spawn-protocol.md, don't reproduce inline. Check C35.
  • bin/ executables are Python (.py), never shell (.sh) — these plugins must run on Windows, where .sh does not execute. Call sites use python "$PLUGIN_ROOT/bin/<name>.py", never bash …/<name>.sh. Python must itself stay portable: temp dir via os.environ.get("TMPDIR") or (tempfile.gettempdir() if os.name == "nt" else "/tmp") (mirrors the shell's ${TMPDIR:-/tmp}: bare gettempdir() honours TEMP/TMP first on POSIX, and a bare /tmp is absent on native Windows Python), session token via os.environ.get("CSID") or os.environ.get("CLAUDE_CODE_SESSION_ID") or "shared" (never os.getppid()), pathlib over string path concatenation. (codemap-py/bin/setup_scan_env.sh is no longer logic: it is a deprecated exec shim delegating to setup_scan_env.py, kept only for pre-existing call sites.)

Worktree Base — verify before trusting agent output

  • Agent worktrees are created from origin/main, not local main (reflog: branch: Created from origin/main).
  • When local main is ahead of the remote — whenever work is committed but unpushed — every new worktree starts on a stale base.
  • A stale-base diff silently reverts everything committed since.
  • Measured 2026-08-07: 3 of 7 agent worktrees were cut from a commit predating that session entirely.
  • One would have reverted a 44-guard correctness fix and deleted 219 unrelated files.
  • Successful agents differed only in running a fast-forward first.
  • Spawned agent, step 0: git merge main --ff-only then assert git merge-base --is-ancestor main HEAD. Abort and report if it fails. Include this verbatim in any spawn prompt that may run in a worktree — an agent cannot opt out of worktree placement, so it must self-correct.
  • Orchestrator, before transplanting anything: git -C <worktree> log --oneline -1 must equal local main. Never git apply a worktree diff without this check. If the base is stale, salvage new files only and re-derive edits to existing files against current main.
  • Root fix: keep origin/main current. A stale remote-tracking ref is the actual cause; the guards above are mitigation.
  • Detection tell: a file the agent never touched differs from main — that is proof of a stale base, not of agent error.

Naming

Plugin-prefixed refs always (foundry:sw-engineer, oss:review — never bare names); agent subagent_type must match filename (sw-engineer.md → foundry:sw-engineer).

Cross-References

  • description field = routing signal; calibrated threshold routing accuracy ≥90%
  • NOT-for lines mandatory in every agent; /audit Check 16 flags ≥40% overlap
  • Independent instances: never cross-ref via local/relative path (breaks after install) — reference only via installed plugin-prefixed name (foundry:sw-engineer)
  • Opt-in gating required: any cross-plugin usage must check availability first and degrade gracefully if absent — unchecked call = broken UX for users without that plugin
  • Prose references too: any /plugin:skill mention in <notes>, follow-ups, or docs prose must include (requires `<plugin>` plugin) inline caveat. Check 28c.

Fallback / Resilience Infrastructure

  • Self-defeating plugin trap: a hook/skill handling absent plugin foo cannot live inside foo; if foo is absent, the hook never runs.
  • Rule: resilience code lives in the plugin whose users need protecting, not the plugin being protected against.
  • Correct placement: every plugin dispatching agents from others ships its own fallback hook.
  • Source of truth is one plugin; byte-identical copies propagate via plugins/cc_foundry/bin/propagate_shared.py (MANIFEST maps canonical → copies, e.g. agent-router.js: foundry → oss/develop/research).
  • For a manifested file, edit canonical then run propagate_shared.py --apply; check mode is the default and takes no flag (--check exits 2), enforced in pre-commit and audit Check 14e.
  • Not manifested: an optional provider's contract that is worthless without the provider (codemap-py's claude-skills/_shared/*.md) — consumers read the active install live; see §Self-Contained _shared optional-provider exception.
  • make sync-* installs plugins/Codex Rig from the public remote only; it does not propagate cross-plugin files.

No plugin dependency system in Claude Code — never propose "install foo as prerequisite" as a resilience fix; circular, requires the thing that might be absent. Examples + per-plugin-variance exceptions: AUTHORING.md §Fallback / Resilience Infrastructure.

Self-Contained _shared

  • Every plugin points at its own skills/_shared. No global path, no sibling reach-in. Enforced by audit Check 27.
  • Resolve via the plugin's own resolver: cc_foundry/cc_oss bin/resolve_shared_path.py <own-plugin> skills/_shared; cc_develop bin/dev_shared_resolve.py; cc_research bin/resolve_shared.py.
  • Bare plugins/<own-plugin>/skills/_shared is allowed only as the final fallback tier (§Installability).
  • Never use $HOME/.claude/skills/_shared/... or bare .claude/skills/_shared/...: that path does not exist (/foundry:setup symlinks only rules/*.md + TEAM_PROTOCOL.md), and a SKILL.md there silently shadows Claude Code's bundled skill of the same name. Incident + precedent: AUTHORING.md §Self-Contained _shared.
  • Never read another plugin's _shared or bin/ (resolve_shared_path.py foundry from a non-foundry plugin, --foundry, $_FOUNDRY_SHARED, $_FOUNDRY_BIN, literal plugins/cc_<other>/), except the optional-provider instances and the loop-checker resolver below.
  • Shared content needed by two plugins is duplicated, not borrowed: copy into each and add a MANIFEST entry in propagate_shared.py to stay byte-identical.
  • Optional-provider contract exception — sanctioned runtime reads or execution of another plugin's file. A consumer may read or execute a provider plugin's shipped file when all three hold: (a) the consumer's feature is a no-op without that provider (gated on the provider's CLI/presence), so the content has no value in the provider's absence; (b) resolution goes through the active install record — resolve_shared_path.py <provider> <subdir>, registry tier first; the resolver's newest-cache tier (which skips .orphaned_at dirs) is a degraded fallback reached only when no usable install record exists or the recorded install lacks the subdir, and a wrapper never globs the cache itself; (c) absence degrades to the consumer's own fallback line. Current instances: (1) resolve_shared_path.py codemap-py claude-skills/_shared reads the contract for codemap-gates.md / codemap-context.md; (2) resolve_shared_path.py foundry bin executes the provider's compact_gate.py rather than reading a file. Consumers call the propagated bin/compaction_boundary.py, which resolves through its sibling resolver, checks that compact_gate.py exists, and prints the consumer's own fallback line compact-gate: continue (foundry gate unavailable) when the provider is missing or the gate fails. The compaction-contract.md Boundary block keeps the inline form: [ -f "$_GD/compact_gate.py" ] on the resolver call's same line plus the same fallback echo. Add each new instance to this enumerated list and audit Check 27. Conditions (a)–(c) apply to both. A frozen manifested copy would drift silently against whatever provider version the user actually runs. Content needed to survive a plugin's absence (agent-resolution tables, degraded-mode instructions) never qualifies — the catch-22 rule below stands.
  • Loop-checker resolver exception — sanctioned execution of another plugin's bin/ copy, not an optional-provider instance. rules/_full/adversarial-loop.md ships byte-identical in every cc_* plugin (propagate_shared.py MANIFEST, canonical in Codex Rig), so it cannot name its own plugin, and a rule gets no plugin-root variable. Its Claude resolver therefore globs the cache for any plugin's bin/adversarial_loop.py, itself a byte-identical MANIFEST copy, and takes the newest by modification time whose version directory carries no .orphaned_at, with the source-tree path as fallback. Every copy of one release is the same file. Under mixed releases the pick may come from another release; newer checkers still read older ledger and actions schemas. Limited to this rule-helper pair: no other rule, skill or wrapper may glob the cache for a sibling's bin/.
  • Corollary: a standalone install of any single plugin must work with no other plugin present. Agent-dispatch fallback (hooks/agent-router.js + per-plugin _shared/agent-resolution.md) is unaffected and stays.

Plugin Tests

  • Ruff enforces test style through the pinned ruff-check pre-commit hook: docstrings on every test module, class, method and function (D100–D103, tests only), the 120-character docstring line (W505), the pytest.skip() ban (TID251). The other rules are checked by review: cc_foundry/rules/python-testing.md §Mechanical Enforcement (Codex: codex-rig/shared/global-baseline-details.md §"Testing details"). Fix the test; never add a custom checker script.
  • Classify a check before writing it — if the test did not exist, could anything actually break undetected? If not, it is linting and belongs in a pre-commit hook or Ruff rule, not pytest.
  • Helpers stay in the owning plugin's tests/ — conftest.py or an _-prefixed module. Never import across plugins: installed_plugin tests run from the installed plugin without the repository (§Installability).
  • Test-tree layout — past 15 test files, tests/ groups into topic subfolders of 4 or more files; helpers and the tree-wide conftest.py stay at the plugin's tests/ root. Full rule: python-testing.md §File Layout.
  • Shipped executables stay self-contained — bin/ and hooks never import a test helper; byte-identical propagated copies stay identical, never diverged for a test's convenience.
  • Real-tool tests stay real — integration, packaging, installed_plugin, live, end-to-end hook runs. Mock only boundaries the test does not cover, never for speed.
  • Markdown contract tests parse line by line (python-testing.md §Tests Reading Markdown or Prose). Never reflow or edit instruction Markdown to make a test pass.
  • Codex counterpart: same rules, plugins/AGENTS.md §Plugin Tests.

README Sync

Edit agents/skills/rules/hooks → update plugin README.md before done. Unsynced change = incomplete.

  • Added/removed → update README table; changed trigger/scope/NOT-for/hook behaviour → update README description
  • Changed user-facing API (flags, arg names, invocation syntax, skill modes) → revise affected README sections + all cross-plugin READMEs referencing that interface (search other plugin READMEs before declaring done)
  • Changed agent model tier → update README Model line + agent-relationships tiering paragraph + curator.md antipatterns table if agent appears there
  • Significant behaviour change (new phase, changed default, removed option) → note it in README; breaking → mark ! BREAKING in the change description

Skill Diagram Sync — animated SVG execution diagrams

<!-- policy-sibling: plugins/AGENTS.md §Diagram Sync -->

A multi-agent or multi-gate skill may ship one animated SVG diagram of its runs, blocking gates, agent fan-out and any work that overlaps, at <plugin>/assets/images/<skill>-arch.svg, embedded in that skill's README section. A plugin may also ship one plugin-level overview of how its parts connect (components, process boundaries, permissions, transport) at <plugin>/assets/images/<plugin-topic>-architecture.svg, embedded in the plugin README; a plugin without multi-agent skills ships that overview instead of per-skill diagrams. It is the only copy: there is no Markdown sidecar. It is documentation, never a contract — the skill never loads it, so it costs nothing at invocation and carries no authority.

  • SKILL.md and modes/*.md win on any disagreement (for a plugin-level overview: the plugin's shipped source and contract docs). A diagram that contradicts them is a defect in the diagram, never a licence to change behaviour to match the picture.
  • Update it in the same commit as any change to step order, gate placement, agent fan-out, spawn width, what runs beside what, or — for an overview — a component, process boundary, permission or transport it shows. Review every diagram that names the touched skill or component; record "no diagram change needed" when none applies. A stale diagram is worse than none — a reader trusts it precisely because it is short. Edit the SVG text directly; keep every fact in <text> so it stays greppable, and render it once to confirm nothing overlaps.
  • Every diagram closes with a footer stating the non-normative status, the update obligation and its normative source, so the rule travels with the file.
  • Each SKILL.md with a diagram carries one HTML comment before its first heading naming the SVG, so an editor meets the obligation at the point of edit.
  • Diagrams claim an overlap only where the skill genuinely dispatches work in one response turn. Never document aspirational parallelism.
  • Format is a block schema, not a step list. Named blocks flow top to bottom; FAN n marks where work splits into lanes dispatched together, JOIN where they are collected. A block names what it contains, never its step number — step numbering and per-step detail belong in SKILL.md and add nothing at this level. FAN means concurrent, never merely plural: a split into mutually exclusive paths, where exactly one ever runs, is a branch and is drawn as one, since labelling it FAN would sell exclusive dispatch as parallel work. ▣ marks an Agent() spawn only — a Skill() call is named inline, and batched tool calls such as parallel Reads are in-block detail; neither is a fan. Sections after the flow: fan/join table (lanes, what bounds width, where they join), gates table, mode branches where topology genuinely differs, degenerate cases. A short step-anchor table may close the diagram for navigation only.
  • An unlabeled arrow means only "block finished, next block starts". Every other transition carries a short pill naming its condition: a loop back to the same or an earlier block (with its bound, e.g. loop ≤3 · until truth check passes), a skip or bypass, a retry, a conditional branch, a stop or exit (with its reason). A bare arc on a card, or a dashed line with no explanation, is a defect. FAN and JOIN bars need no pill. Where several paths share stages, a compact stage × path matrix (own, reused from another path, absent) lets a reader see the reuse at a glance. Layout may snake left to right in rows to use the width; keep fonts at 10.5px or larger.
  • A stage drawn more than once must be visibly the same stage. Give it one solid home card; every repeat is a dashed reuse ghost with the same title, accent colour and shape (agent slab stays a slab, gate stays a hexagon), a ↺ marker and a tag naming the home (↺ same as GATHER (notes)), and no new detail. A stage that runs twice in one path carries a ×2 badge. The matrix uses the same ↺ marker and colour, and the legend explains it. Mark only reuse the source shows.
  • Cards stay short and structured. A card body is at most 4 fragment lines of about 45 characters (label: value, A · B · C), never sentences; longer detail goes into a compact table row or stays in SKILL.md, where it is normative. Mark the key noun, gate or artifact with a bold <tspan> (at most 2 per line) and qualifiers, conditions and bounds with an italic <tspan>; never bold a whole line. Emphasis stays inside the same <text>, so every fact remains greppable.
  • Not covered by §Shared File Authoring Rule (that governs modes/, templates/, _shared/); an SVG under assets/images/ needs no consumer reference beyond its README embed and the SKILL.md comment. No script, external font or link inside the SVG: it must render inside an <img> on GitHub.
  • Optional per skill. Add one where runs, gates and fan-out are hard to hold in the head; skip it for a linear single-agent skill, where it would only duplicate the step list.

Versioning

Apply the repository Version Continuity rule to serialized artifact schemas separately from this plugin SemVer gate; compare each schema family with its own committed HEAD baseline before handoff.

Commit gate: Any plugins/<name>/ non-test file in git diff HEAD requires the pre-bump checklist (AUTHORING.md §Versioning) before git add.

All changed files under tests/ → no bump, skip entirely. When a shipped test requires regenerated package-manifest hashes, that generated manifest is supporting test metadata: validate it but do not bump the version or update the changelog. Each touched plugin bumps independently.

Pure test, CI, and documentation changes need no changelog entry unless they change shipped product or plugin behavior.

Every changelog bullet states what changed and its user-visible impact (what now works, breaks less, or behaves differently). A bare file or mechanism name — "Sync report-header-table.js", "update helper", "refactor" — says nothing to the reader; name the behaviour, never only the propagation step. Each claim must trace to the diff.

A changelog entry claiming a cost, token or time saving cites (measured: <label>) for a complete foundry:profile before/after pair, or says (unmeasured). Run python plugins/cc_foundry/bin/profile_pair.py check-claims plugins/<plugin>/CHANGELOG.md --section Unreleased for a pending ## Unreleased section. When amending a commit that already renamed the pending section, use --section <version> with that commit's version heading. The command exits 1 when the named section matches no heading.

Changelog shape: a plain list. Every line of a section is a - entry or a sub-entry of one; no free paragraph before, between or after entries, and no blank lines between items. One entry per topic: a few related sentences saying what changed and its user-visible impact, compact but complete. Sub-bullets only enumerate parallel items. No rationale, implementation mechanics or long example lists; compress, never drop a change. Match the released sections below. mdformat (the save hook and pre-commit) turns the whole list loose when any item has a blank line and re-adds every blank you remove one edit at a time, so delete them all in one write and confirm the section has none.

Versions are decided at commit time. While editing, a plugin's manifests keep their HEAD version. The commit step runs the pre-bump checklist, writes the single bump to every shipped manifest and renames that plugin's ## Unreleased changelog heading to ## <version> in the same commit, so the heading equals every shipped manifest. An entry-exempt change has no ## Unreleased section: there is no heading to rename and the bump alone lands. When the version is determined, also consolidate that version's changelog entries in the same step: apply the grouping rule below (one entry per topic, same-topic entries adjacent and merged, reverted changes dropped, most user-visible first) before the heading is renamed.

Changelog: continuous refinement under ## Unreleased. Edit the changelog as you work, not at commit time. When a change is notable (user-visible behaviour, contract, permission, flag or default), add an entry for it or update the existing entry for that topic in the top ## Unreleased section, creating it above the newest released heading when missing. Refine an entry instead of appending a second one when the same topic changes again, and drop it when the change is reverted. A heading that exists in HEAD's changelog is released history: never add or reword a bullet there; a change that needs one is a new entry in ## Unreleased. When amending a commit that already flipped its heading, the baseline is that commit's parent and its own heading is the pending section.

Changelog grouping. Keep a section readable and consistent: one top-level entry per topic (a feature, workflow, guard, platform or fix family), entries of one topic adjacent, the most user-visible topics first, and topic wording reused from earlier sections of the same file. Sub-bullets enumerate parallel facets of that topic. Merge small related fixes into one entry instead of one entry per file or commit.

Baseline = HEAD every time: Re-read it fresh each session; never trust prior-session recall. Amending or rewriting a commit that already bumps: baseline = that commit's parent (root CLAUDE.md §Version Continuity).

Per-plugin version in .claude-plugin/plugin.json, space 0.X.Y:

Change typeBump
Fix, wording, refactor, cleanup, or restoring behaviour to original design intentY
New capability, new agent/skill, new designed behaviour (not intended before)X
Test-only changes (adding/editing tests/*.py or tests/*_sh.py, no source file changes)none — skip

npm plugin exception: OpenCode Rig ships no .claude-plugin or .codex-plugin manifest. Its version authority is plugins/opencode-rig/package.json, mirrored by rig.json, src/version.ts, and the README Current version: marker. Apply the same bump table to package.json from its own HEAD baseline, then run node plugins/opencode-rig/scripts/sync_version.mjs --write so all four sources move together; --check is the gate.

Rule: Ask "was this supposed to work this way?"

  • Yes + it didn't → Y (fix).
  • No, new intent → X (feature).
  • Internal restructuring always Y, regardless of size or visibility.
  • Classify from the plugin's ## Unreleased changelog section, the running record of its notable changes, not from a fresh diff read: an entry describing a new capability, agent, skill or designed behaviour → X; only fix, wording or refinement entries → Y; a non-test change with no ## Unreleased section → Y. Only entries for changes this commit lands count. A change that deserves an entry but has none is a changelog defect: add the entry, then classify. The commit step reads file names only (git diff HEAD --name-only), never the full diff.
  • Bump once per commit at the highest-magnitude entry: both Y- and X-class changes → bump X only, reset Y to 0.
  • Read baseline via git show HEAD:<plugin-path>/.claude-plugin/plugin.json | grep version, never from disk. If on-disk differs from HEAD, still calculate the bump from HEAD: an on-disk value equal to the result already landed for this pending commit (do not bump again), any other value is reset to the result.
  • Scope is the commit, never the session: splitting one session's work into N commits means N bumps for every plugin each commit touches, each derived from the preceding commit.

Full pre-bump checklist (test-only guard, on-disk-vs-HEAD double-check, calculation steps, worked example, multi-manifest note): AUTHORING.md §Versioning.

Permission Gates — Diff Against HEAD

  • A feature that adds a permission gate, approval question or stop first diffs its gate list against HEAD behaviour. An operation that ran without a stop at HEAD keeps running without one unless the user asked for the new stop.
  • Default to relaxed; tighten only with a concrete, user-accepted justification. Push stays user-approved (asked every time, or once at the start of an oss:resolve run with the git-push-run question covering that run's one push) and force push forbidden; no other git class gains an always-ask stop.
  • Codex Rig counterpart: same rule, plugins/AGENTS.md §Permission Gates.

Shell-Text Guards — What Not To Do

Repository-maintainer rules for the opencode-rig shell guard; these instructions do not apply to shipped user content.

  • Do not grow a text guard by enumerating bypass strings: this guard grew from about 328 to about 2800 lines, then about 3400, through repeated reviews that kept finding more because each new spelling is another hole.
  • Add a quiet class only with a positive model: use a short explicit table of allowed programs and options, never a deny-list of known-bad forms, so permission follows understood behaviour.
  • State in user docs that a text classifier is a speed bump, not a security boundary; further hardening requires a sandbox or isolation decision because string rules cannot enforce isolation.
  • Fix a review budget up front; when spent, document the residue as limits and open gaps instead of widening the guard, because spelling enumeration does not converge.
  • A read-only list entry never gains write options; a program that can write or run code leaves the list, because its name alone cannot establish safety.
  • Decide program identity in one function and use it for every lookup; never match raw spelling at another site, because divergent identity rules create bypasses.
  • Never put round, finding, probe or task numbers in test names, titles, labels, markers or comments; name by scope and behaviour and merge tests into scope-named files, so evidence remains understandable without review history.

Edit Quality Gate

Before any edit, delete, or addition to plugin files — self-challenge:

  • Best approach? Simpler path exists → take it; no unnecessary complexity or speculative abstractions
  • No side effects? Cross-refs still resolve, existing callers unaffected, no behavior regression
  • Complete and clean? No gaps/TODOs, no dead instructions, no orphaned cross-refs, no leftover stubs
  • Verified? Every claim backed by code/disk evidence — no hypothesis or assumption stated as fact
  • bin/ scripts wired? Created/edited bin/ script? Consumer .md references basename before commit (inline invocation or <!-- file: ... consumers: ... --> header in owning plugin). Run check_orphaned_bin.py — must exit 0.
  • Digest-pinned? Before a mass edit of shipped files (comments, formatting, lint), search the repo for the sha256 of each target's HEAD bytes (git show HEAD:<path> | shasum -a 256), not its git blob OID, excluding regenerated manifests; leave pinned files untouched. Example: plugins/codex-rig/skills/code-review/review_context.py, pinned by review_execution_validation.py for historical-run admission.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.