/docs-hygiene:audit-encapsulation [detect|sweep|fix <file>:<line>|file-issues] [--repo <repo> ...]from docs-hygiene
Detects external citations reaching into a skill's private internals beyond its public API surface. Use before publishing plugins or refactoring skills.
Ships in docs-hygiene. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Skills have a public API and a private body; the contract is context/public-surface-contract.md (bundled with this skill). External consumers (rules, agents, other skills, prose docs) must cite the public surface only, so editing the private body never breaks them.
Distinct from /docs-hygiene:extract-ssot (content duplication via Rule of Three). Encapsulation violations are single-violation matters. Rule of Three does not gate them.
The Skill surface is defined by context/public-surface-contract.md: public = frontmatter + documented actions + args/flags + /skill-name slash invocation + the scripts/ entry surface; private = everything else inside .claude/skills/<X>/ or plugins/<plugin>/skills/<X>/ (any other subdirectory, all *.schema.json at any depth, all heading anchors). That file holds the data-file and scripts/ entry-surface carve-outs and the rip-and-paste-portability rationale. This skill also audits cites against two authoring surfaces the contract file does not enumerate:
| Surface | Public (cite externally) | Private |
|---|---|---|
Rule file (.claude/rules/*.md) | All H2/H3 headings (entire file is shared vocabulary) | n/a |
Scheduled-automation prompt (e.g. .claude/routines/*.md, if the consumer repo keeps them) | Top-of-file orchestration prompt | Internal exclusion lists, escape conditions |
Workflows and git hooks needing logic that also lives in a skill must not reach into skill internals. Pick a sharing technique by logic size: scripts/ facade (a public scripts/<name>.sh entry delegating to a private backend; hooks/CI invoke it), intentional duplication, plugin packaging, or headless claude -p '/skill <action>' invocation, per context/public-surface-contract.md "CI / git-hook consumption. Entry surface, not internals".
The choice is per-cite. The bundled detect.sh is a candidate enumerator: exit 1 means candidates remain after mechanical filters, not adjudicated violations. Classify (filter taxonomy below) before treating a hit as illegal. Do not hard-gate CI or pre-commit on detect.sh's exit code alone.
| Argument | Action | Purpose |
|---|---|---|
(empty) / detect | Default | Run detection grep, classify legal vs illegal, output violation table. Behind the no-scope confirmation below when nothing narrows the scope |
sweep | Explicit repo-wide detect | Default detect minus the no-scope confirmation, for when the user already said "whole repo" |
fix <file>:<line> | Targeted remediation | Interactive Path A (promote-out) vs Path B (route-via-/<skill>) for one hit |
file-issues | Batch | File one tracking work item per illegal hit in the consumer's tracker (e.g. gh issue create), after reading the house style (${CLAUDE_PLUGIN_ROOT}/reference/issue-house-style.md) and applying it; emit a checklist if no tracker is available |
--repo <repo> (and the other target forms) | Several repositories | detect/sweep once per repository, per ${CLAUDE_PLUGIN_ROOT}/reference/target-scope.md and ../../context/clean-tree-fallback.md "Several repositories"; detect.sh runs from inside each root and scans only that repository. The per-repository subagents run in waves of 2–3, the pacing cap below. fix <file>:<line> with --repo <repo> beside it edits that repository's hit in its own worktree and pull request ("Writes stay per repository" there); file-issues files each hit in its own repository's tracker |
One action per response.
Shared clean-tree / no-scope shape: ../../context/clean-tree-fallback.md.
Read it when the bare invocation is unattended or non-interactive (the case the rules below leave
unstated), or when editing those rules.
This skill's trigger is "no inherited scope", not only "clean tree": a dirty tree with unrelated
edits still needs the confirm when nothing names the detect surface.
The default action's domain is the whole repo, but a bare invocation does not prove the user meant that. With no inherited working set (no diff in flight, no prior audit notes, nothing in the conversation narrowing the scope), ask one confirmation before running detection, presenting these prescribed defaults for adjustment:
| Default | Value |
|---|---|
| Scope | entire tracked repo (the detect script's scan domain) |
| Mode | detect + classify only; remediation stays a separate, user-approved step |
| Worker fan-out | off. Classify in-session. When the user opts into subagent classification or remediation, run 2–3 concurrent workers, no more (our pacing cap, independent of the harness's own concurrent-subagent limit: pointer), and check each worker's cited evidence before accepting its classification, while rate-limit telemetry is absent; when the rate-limits plugin's snapshot is readable, resolve pacing from its reader contract instead (that contract owns the snapshot path, staleness rule, and thresholds. Read them there) |
An inherited scope, or a scope the user stated in the invocation ("across the repo",
"audit this directory"), suppresses the question; audit that surface directly. sweep is the
explicit opt-in that skips the confirmation and runs the repo-wide detect immediately.
bash "${CLAUDE_SKILL_DIR}/scripts/detect.sh" (--apply-filters optional)
With --apply-filters, stderr summary keys are raw / mech-filtered / candidates. Exit 1 = candidates remain; exit 0 = no candidates (not a clean bill of health. See limitations below).
Matched shapes:
<X>/<any-subdir>/..., regardless of subdir name, including uppercase / single-char / digit-leading / underscore-leading segments) except scripts/ (entry-surface carve-out, see below)<X>/SKILL.md#<anchor>, <X>/<subdir>/<file>.md#<anchor>)*.schema.json file at any depth (<X>/<file>.schema.json)Matched path prefixes: .claude/skills/<X>/..., plugins/<plugin>/skills/<X>/..., and relative forms (skills/<X>/... plugin-README short cites, plus ../-prefixed cites whose lexical resolution lands on a private skill surface, including sibling-skill links that never spell skills/ in the cite text).
Cross-plugin shapes, in a marketplace monorepo (a plugins/ directory), flagged when the citing file sits under plugins/<q>/ and the cite names another plugin <p> (p≠q):
plugins/<p>/skills/<X>plugins/<p>/skills/<X>/SKILL.mdplugins/<p>/skills/<X>/scripts/...../-prefixed path, or as a github.com/<owner>/<repo>/tree|blob/<ref>/... or raw.githubusercontent.com/<owner>/<repo>/<ref>/... URLA cite inside the same plugin stays legal. Subdirectory, anchor and schema cites keep their existing rows.
Own marketplace id: when .claude-plugin/marketplace.json names the marketplace, <plugin>@<id> for that id is flagged on any line that is not an install recipe (plugin install|uninstall|update|enable|disable). Third-party ids never match.
Every text file type under the scanned surfaces is read (binary files and node_modules/ are skipped), not only md/sh/json/yml/yaml.
Allowlist: docs/conventions/audit-encapsulation-allowlist.tsv (or --allowlist <file>), one path<TAB>reason row per exempt file or dir/ prefix; # lines and blank lines are skipped, a row with no reason is an error (exit 2). Use it only for fixtures, evals and tests that exist to exercise a detector; a real cite is fixed, not listed.
Legal external cites: bare <X>/SKILL.md path in a consumer repo, from outside plugins/, or inside the same plugin (discouraged but legal; natural-language + slash invocation is canonical), <X>/<file>.json data files at skill root (data-file carve-out), and <X>/scripts/<entry> entry scripts from callers outside plugins/ or inside the same plugin (entry-surface carve-out below).
scripts/ entry-surface carve-out: a skill's scripts/ is its declared entry surface per context/public-surface-contract.md. Harness / CI / hooks / workflow registries outside plugins/ may path-cite a skill's entry scripts directly, so this inbound audit treats their <X>/scripts/... cites as legal (like data files). A file under plugins/<q>/ citing another plugin's scripts/ is flagged: plugin-to-plugin goes by /plugin:skill. The skill-to-skill half (a sibling SKILL.md citing another skill's scripts/ stays slash-only) is out of this inbound audit's scope; a consuming repo that wants it enforced wires its own outbound gate.
The script scans the consumer repo it runs in: every .claude/ child directory except skills/ (self-citation domain; opt in via --include-skills for skill-maintenance review) and worktrees/, plus .github/, docs/, .lefthook/, plugins/, root instruction/config files (AGENTS.md, CLAUDE.md, README.md, CONTRIBUTING.md, lefthook.yml), and .claude/ top-level files, each filtered to what exists. .claude/skills/ is scanned only with --include-skills.
Or invoke the skill (the agent applies the filter taxonomy below):
/docs-hygiene:audit-encapsulation detect
--apply-filters drops only the mechanically-decidable subset (self-citation and worktree paths). Remaining rows are candidates: apply KIND-1/2/3, mirror-automation, glob-config, and plugin-cache judgment in-session before calling anything a violation.
| Filter | Hit shape | Why legal |
|---|---|---|
| Self-citation | A skill cites its own internals. Absolute (.claude/skills/<X>/... / plugins/<plugin>/skills/<X>/...), bare skills/<X>/..., or a ../ cite that resolves into the same skill | Intra-skill progressive disclosure (per context/public-surface-contract.md) |
| KIND-1 meta-prose | A rule or doc describing the encapsulation contract itself, or documenting skill internals as a worked example / historical narrative / empirically-verified quirk; a file:line cited as evidence in a decision record (an ADR, a docs/upstream/ record) of what the decision read (a markdown link the record uses as a live pointer is still a violation) | Self-referential explanatory prose, not citation |
| KIND-2 forced-cite | Another tool's semantics structurally require a verbatim path (a path-scoped rule trigger, a watch-glob, a drift-gate comparing against a vendored copy) | Citation is the structural contract |
| KIND-3 self-test | This skill's / a hook's own regression fixtures embed literal violation strings | Exercise the filter; not real citations |
| Mirror-automation | A scheduled-automation prompt (e.g. .claude/routines/<name>.md) cites .claude/skills/<name>/<private-path> when its basename matches the skill name | Such prompts are cron arms of slash skills; mirror cites are part of the skill contract per the Public surface matrix |
| Glob-config | Skill-internal path used as a glob/filter in an exclusion list, hooks allowlist, or .gitignore, not a content Read cite | Structural filter syntax, not progressive-disclosure content (overlaps KIND-2; named separately for grading) |
| Plugin cache | ~/.claude/plugins/cache/<plugin>/... | Upstream territory; foreign contract. Never matches the detector PATTERN (not under a skill root), so --apply-filters has no cache branch. Classify as legal if it appears in a manual/agent sweep |
| Worktree path | <worktree-root>/<n>/.claude/skills/<X>/... (per the repo's worktree convention, e.g. .worktrees/, .claude/worktrees/, .git/worktrees/) | Worktrees share the tracked tree; same rules apply at the root path |
| Intra-plugin cite (only where the consuming repo has declared the plugin-monorepo convention) | A file under plugins/<p>/ cites plugins/<p>/skills/<s>/<private-path>, same <p>. Covers a sibling skill body, a plugin-level context/, reference/ or agents/ doc, and the plugin README.md | The plugin, not the skill, is the shipping unit there: one manifest, one version, skills that never travel apart, so the absent-path breakage this contract prevents cannot occur. See context/public-surface-contract.md, "Layered convention". Cross-plugin cites stay illegal, and heading anchors stay illegal either way |
Hits that survive all filters = illegal. Report.
The intra-plugin filter is off unless the consuming repo has declared that convention and is built that way: one manifest and one version per plugin, no per-skill manifest, and no install path that separates two skills in one plugin. Check before applying it; the unrelaxed taxonomy is the default. A path that does not resolve as written is still a defect even when this filter would otherwise make it legal.
Use when the caller needs data the private file contains, and the data is genuinely shared vocabulary or constraint.
/docs-hygiene:extract-ssot verify via the Skill tool (the 6-gate refuse-fast check) against the private file's content.claude/rules/<topic>.md, or extend an existing one)/docs-hygiene:rename-references via the Skill tool to sweep all syntactic forms/skill-name invocation (caller wants the behavior)Use when the caller wants the skill's behavior, not the data: the reference into the private body is a workaround for a missing public action.
/<skill-name> <action> <args># TODO(audit-encapsulation): missing /<skill> <action> markerWhen invoked from another skill's execute pass (e.g. /docs-hygiene:extract-ssot execute):
| Step | Action |
|---|---|
| 1 | Run the detection grep against the caller list (or repo-wide) |
| 2 | Classify each match via the filter taxonomy: legal hit vs violation |
| 3 | For each violation, choose Path A (promote) or Path B (route via /name) |
| 4 | Do not preserve a violation because "it works today". Broken-window pattern |
| 5 | If Path B is needed but the action is missing, file a tracking work item and stop. Don't ship a partial fix |
| 6 | Invoke /docs-hygiene:rename-references via the Skill tool to sweep after edits |
A surfaced violation is never silently ignored: fix it, capture it as a side note to the user, or file a tracking work item.
# Encapsulation audit — N violations
## Violations
| File | Line | Cite | Suggested path |
|------|------|------|----------------|
| ... | ... | `<skill>/<dir>/<file>` | A or B |
## Filtered (legal — sample for verification)
| File | Line | Filter applied |
|------|------|----------------|
## Summary
- Total raw hits: M
- Mechanically filtered: M-C
- Candidates (need taxonomy classification): C
- Adjudicated illegal after filters: N
- Path A candidates: a
- Path B candidates: b
- Missing public action (Path B blocked): c
## Recommended next step
`/docs-hygiene:audit-encapsulation fix <file>:<line>` for one-by-one or `/docs-hygiene:audit-encapsulation file-issues` for batch work-item filing
# TODO(audit-encapsulation) marker requirement.| When | Check | Evidence |
|---|---|---|
| Pre-detection | git ls-files enumerable in scope | Bash output |
| Post-detection | Each raw hit classified per filter taxonomy or illegal | Diff against filter table |
| Pre-fix | Path A vs Path B chosen with explicit data-vs-behavior reasoning | Session notes or plan artifact |
| Post-fix | Detection grep re-run; violation count decreased | Bash output |
| Post-fix | /docs-hygiene:rename-references sweep ran | Tool output |
/docs-hygiene:extract-ssot| Reference | Load when |
|---|---|
context/public-surface-contract.md | Classifying a detect hit as legal or illegal, or wiring the detector into CI or a git hook. |
/docs-hygiene:extract-ssot verify | Before committing to a Path A promote-out, to refuse a bad extraction cheaply. |
/docs-hygiene:extract-ssot execute | Carrying out an approved Path A migration: writes the SSOT, sweeps the citations. |
/docs-hygiene:extract-ssot | The hit is really duplication rather than a boundary breach. |
/docs-hygiene:rename-references | A remediation renamed a heading, and every citing form still needs sweeping. |
| Condition | Action |
|---|---|
context/public-surface-contract.md changes | Re-sync the Public surface matrix here and the pattern comments in scripts/detect.sh |
Scan scope changes in scripts/detect.sh (dirs, file globs, include flags) | Update the Detection scan-scope sentence here so docs and script cannot drift |
| A new CI workflow or git hook needs skill logic | Pick a technique from context/public-surface-contract.md "CI / git-hook consumption. Entry surface, not internals"; prefer a skill scripts/ facade the hook invokes. No vendored copy |
| Violations recur across audits | Promote the detect action to a scheduled cadence in the consumer repo (e.g. /loop or /schedule) |
| Anthropic ships a native skill-boundary linter | Demote this skill to advisory or sunset it |
What SKILL.md sets; muted values are Claude Code's defaults
10 skills in this plugin
/audit-derivabilityAudit derivabilityRead-only audit of whether a doc earns its existence or an agent can re-derive it from code, config, and structure: verdict per file (delete, convert-to-pointer, keep-as-derivation-cache, keep-owns-facts). Use when: 'is this doc worth keeping', 'audit doc value', 'prune redundant docs', or derivability. Not for noise: /docs-hygiene:audit-noise. Load it before judging whether a doc should stay or go./audit-noiseAudit noiseRead-only audit of tracked markdown (rule/skill/convention doc) for nine noise shapes: stale historical citation, ghost ref, preamble, tracker back-ref, negation without positive, conversational residue. Use when 'audit markdown noise', 'find ghost refs', 'declutter', sweep for noise. Not for code comments: /code-tidying:remove-comments. Load it before listing a doc's leftover lines to cut before sharing it./audit-progressive-disclosureAudit progressive disclosureRead-only progressive-disclosure audit of agent instruction markdown: grades file and context loading across always-loaded, invocation-loaded, on-demand tiers; flags split, hub-and-spoke, disclosure defect. Use when 'progressive disclosure', 'split this file', 'too much context'. Not for noise: /docs-hygiene:audit-noise; QA: /skill-quality:check. Load it before advising what in a CLAUDE.md or rule stays loaded./compressCompress markdown (drop filler/hedging; keep directives, thresholds, examples; articles per compress_articles) with semantic-diff revert guard; default, audit/compare (read-only). Use when 'compress this doc', 'tighten markdown', 'cut prose'. Not for compaction: /compact, noise: /docs-hygiene:audit-noise, or SSOT: /docs-hygiene:extract-ssot./extract-ssotExtract SSOTDeduplicate repeated markdown (rule files, skill bodies, ADRs, docs) into one source of truth, migrating call sites to cite it by exact heading; below Rule of Three, offers non-abstracting remedies and refuses a new SSOT artifact. Use when prose, literals, or concepts recur: 'DRY this prose', 'extract a shared rule', 'single source of truth for X'. Load it before planning one place for text copied into files. Load it too when a rule pasted into several files should change in one place, or a user proposes a new shared file for it./rename-referencesRename referencesSweep stale references after rename (slash-token, path, chain prose, table row, frontmatter glob grep misses); audit rename, preview, blocklist. Use when 'rename X to Y', 'find stale refs', 'after git mv', I renamed skill/X, sweep references, broken refs, pre-PR rename check. Not for casing rules: /docs-naming:audit-file-names (if enabled).npx claudepluginhub melodic-software/claude-code-plugins --plugin docs-hygieneOther plugins' skills for the same job