explain
Explain WHY a piece of code is structured the way it is. Synthesises architectural-memory similar-symbols, git history (blame + commits + PR context), AGENTS.md/CLAUDE.md principles, and any plan documents that mention the target. Useful for onboarding ("why is this here?"), debugging ("why is X structured this way and not Y?"), and refactoring ("can I change this safely or is there hidden context?"). Pick by INPUT: a TOPIC to survey comes here ("have we touched rate limiting?"); a CLAIM to test goes to /investigate ("that landed in July" — it uses --history as one of its instruments). Invoke on the question's shape, don't pre-check the target exists first — Step 0 validates it and reports cleanly if missing; don't Grep/Glob and answer directly instead. Triggers on: "why is this", "explain this code", "why does this exist", "what is this for", "/explain", "give me context on". Full command syntax: see the Usage section in this skill.
- License 许可
- MIT
- 最近更新
- 2026-11-10
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- explain
- description
- Explain WHY a piece of code is structured the way it is. Synthesises architectural-memory similar-symbols, git history (blame + commits + PR context), AGENTS.md/CLAUDE.md principles, and any plan documents that mention the target. Useful for onboarding ("why is this here?"), debugging ("why is X structured this way and not Y?"), and refactoring ("can I change this safely or is there hidden context?"). Pick by INPUT: a TOPIC to survey comes here ("have we touched rate limiting?"); a CLAIM to test goes to /investigate ("that landed in July" — it uses --history as one of its instruments). Invoke on the question's shape, don't pre-check the target exists first — Step 0 validates it and reports cleanly if missing; don't Grep/Glob and answer directly instead. Triggers on: "why is this", "explain this code", "why does this exist", "what is this for", "/explain", "give me context on". Full command syntax: see the Usage section in this skill.
02 资源文件 3
- 参考文档references/history-mode.md3.3 KB
- 参考文档references/verification-discipline.md27.7 KB
- 参考文档references/worktree-preflight.md3.3 KB
03 SKILL.md 正文
Code Explainer
This skill's last line is an end marker naming the skill between em-dashes, after the Reference files table. If that last line is not in your context (context compaction keeps only the start of a skill), re-read
.claude/skills/explain/SKILL.mdin full before continuing — the later steps still apply.
Worktree preflight — in a linked git worktree the synced tooling tree
scripts/.claude-skills/is absent — it is gitignored, sogit worktree adddoes not populate it, and every command below that uses it dies on a bareMODULE_NOT_FOUND. Runnpm run skills:hydratefirst. If this repo defines no such script,references/worktree-preflight.mdholds the entry to add — ask the user first, since it edits theirpackage.json.
Usage
Usage:
/explain <file> — Explain the file's purpose + history
/explain <file>:<line> — Explain a specific line/section
/explain <symbol-name> — Find + explain a function/class by name
/explain <file>:<line> --depth=full — Include full neighbourhood + all blame
/explain --history "<topic>" — "Did we already solve this?" — cross-source search
Multi-source synthesiser for "why is this here?" questions. Given a target (file, file:line, or symbol name), gathers context from four sources and produces one coherent explanation.
This skill does NOT modify code. Read-only — gathers + synthesises.
Step 0 — Parse Target
Input shapes:
| Input | Action |
|---|---|
<file> (e.g., scripts/openai-audit.mjs) |
Whole-file mode — explain purpose + history |
<file>:<line> (e.g., scripts/openai-audit.mjs:412) |
Section mode — explain the symbol containing that line |
<symbol-name> (e.g., runMultiPassCodeAudit) |
Symbol mode — find the file:line via architectural-memory + Grep, then explain |
--history "<topic>" |
History mode — "did we already solve this?" — jump to §History Mode below; skip Steps 1–5 |
Validate the file exists (file/section/symbol modes only). If symbol mode
- symbol not found, exit with "Symbol '<name>' not found in repo via
architectural-memory or grep — narrow the query (try
<file>:<line>)."
History Mode — --history "<topic>"
When the input is --history "<topic>" (e.g. /explain --history "rate limiting"),
the question is "have we touched this before?" rather than "why is this here?"
Skip the file-shaped Steps 1–5 and run the cross-source aggregator instead.
Invocation
node scripts/explain-history.mjs --topic "rate limiting"
Optional flags: --since "GIT-SINCE-DATE", --paths "CSV-OF-PATHS", --limit N.
Add --skip-arch when the cloud is offline or when the user wants
faster local-only search.
The aggregator searches git log (three passes, incl. -G so moves are not
missed), architectural memory, plan documents and the brainstorm session ledger,
and returns one JSON document with per-source results plus a chronological
timeline. Render it as a Markdown digest: the helper's summary verbatim, a
most-recent-first timeline, then per-source tables — omit empty source-sections;
an empty timeline reads "No prior touches found — this appears to be new ground."
→ references/history-mode.md — read when running --history, for the source
detail, the exact digest template and how to read the result.
Output rules — same as §Output rules below: read-only, and every claim in the
digest maps to one of the four source sections. Cost: ~$0.0003 for the
arch-memory embedding (skipped when --skip-arch or cloud is offline); the other
three sources are local-only.
Step 1 — Gather Architectural-Memory Context
If cross-skill.mjs exists in the repo and Supabase is configured:
# 1. Near-duplicates and similar symbols
node scripts/cross-skill.mjs get-neighbourhood --json '{
"targetPaths": ["<file>"],
"intentDescription": "Understand the purpose and shape of <symbol-or-file>",
"k": 6
}'
# 2. Domain assignment (Plan v6 §2.4 — anchors the explanation in
# the architecture map's domain structure)
node scripts/cross-skill.mjs compute-target-domains --json '{
"targetPaths": ["<file>"]
}'
# 3. Caller domains (cross-domain reach detection — Plan v6 §2.4)
node scripts/cross-skill.mjs get-callers-for-file --json '{
"path": "<file>"
}'
Use the result to:
- Identify what this symbol does (the
purposeSummaryof the matching record) - Identify near-duplicates — sibling symbols solving similar problems
- Identify recommended uses — if the matched record's recommendation is
reuse, that's a signal this is the canonical version of a pattern - Identify the file's home domain (from
compute-target-domains.domains[0]) — emit as**Domain**: \<X>`` in the output - Identify cross-domain reach (from
get-callers-for-file) — see deterministic spec below
Cross-domain reach detection (deterministic — Gemini-R2-G3)
Let homeDomain = compute-target-domains.domains[0] and callerDomains = get-callers-for-file.callerDomains. Trigger the "Cross-domain reach
detected" finding if and only if all of:
callerDomains.length > 0(importers exist)nonSelfCallerDomains = callerDomains.filter(d => d !== homeDomain)has length > 0 (any external-domain caller is the leak)homeDomainis NOTnull/"unknown"AND is NOT in the cross-cutting allowlist:["shared-lib", "shared-frontend", "core", "utils", "scripts"](Audit-Gemini-G4: untagged files would otherwise spam false-positive cross-domain warnings on every importer — skip the check entirely when the file's home domain is unknown)get-callers-for-file.snapshotProvenance === "import-graph-populated"(skip silently if "pre-feature-snapshot" / "no-active-snapshot" / "cloud-disabled" — false signal otherwise)
When triggered, render exactly:
**Cross-domain reach detected**: `<homeDomain>` file called from
`<nonSelfCallerDomains[0]>`, `<nonSelfCallerDomains[1]>` (etc) — explain whether this is intentional shared API vs leaked internal.
Omit the section entirely when not triggered.
If Supabase is offline → skip all three subcommands and note
[arch-memory: unavailable] in the output.
Step 2 — Gather Git History
FILE=scripts/lib/*.mjs # the file you're explaining
LINE=42 # the line, if one was specified — omit -L flags otherwise
# Who wrote it + when (last 5 lines of context if line is specified)
git blame -L $LINE,+5 "$FILE"
# When the file was created + changed (last 10 commits)
git log --oneline -10 -- "$FILE"
# Recent commits that touched the symbol (if line known)
# NOTE: use git's native +offset syntax — git does NOT evaluate "LINE+10"
# arithmetic in -L. Pass +10 directly so git computes line + 10 internally
# (Gemini-R1-G4 fix).
git log -L $LINE,+10:"$FILE" --oneline | head -10
# PR context (if gh CLI available)
LAST_COMMIT=$(git log -1 --format=%H -- "$FILE")
gh api "repos/{owner}/{repo}/commits/$LAST_COMMIT/pulls" --jq '.[].title' 2>/dev/null
Extract:
- Author + date of the most recent change to this section
- Commit message that introduced the section (often has the WHY)
- PR title if available (often has the requirement / bug context)
- Co-evolution — files frequently changed together (signals coupling)
Step 3 — Find Principle Citations
Search AGENTS.md, CLAUDE.md, and any docs/plans/*.md for mentions of:
- The file path
- The symbol name
- Patterns this code uses (e.g., "single source of truth", "graceful degradation" — these often have explicit citations near the relevant code)
grep -rn "<symbol-name>\|<file>" AGENTS.md CLAUDE.md docs/plans/ 2>/dev/null | head -20
Look specifically for:
- Plans that planned this code (often explain WHY a particular design)
- "Accepted Technical Debt" entries (explain what compromises were made)
- "Do NOT" rules (explain the discipline being enforced)
Step 4 — Read the Code Itself
Read the target file (or the symbol's enclosing function/class). Look for:
- Doc comments — explicit author intent
- Type signatures — what contract is being enforced
- Imports — what this depends on
- Surrounding code — how it's called
For section mode (file:line): read 30 lines of context around the target line.
Step 5 — Synthesise
Produce a single Markdown response with these sections (omit any that have no data):
## What it is
One sentence describing the symbol/file purpose.
## Why it exists (history)
- Created **YYYY-MM-DD** by **<author>** in commit `abc1234` ("commit message")
- Most recent substantive change: **YYYY-MM-DD** by **<author>** ("commit message")
- Originating PR: #N "<title>" (if known)
- Co-evolved with: <files frequently changed together>
## Why this shape (architectural context)
- Plan: `docs/plans/<plan-file>.md` motivated this design (cite the relevant section)
- Principle citations from AGENTS.md / CLAUDE.md: <list>
- Architectural-memory ranking: this is the **canonical** version of <pattern> / OR a **sibling** to <other symbols>
- Accepted technical debt: <relevant entries from AGENTS.md "Accepted Technical Debt">
## Near-duplicates / related code
If architectural-memory found similar symbols, list them with similarity scores:
| Sim | Symbol | Path | Purpose |
|---|---|---|---|
| 0.85 | `<other>` | `path:line` | <purpose> |
Note explicitly whether this is the canonical version or an alternate.
## Safe-change advice
Based on coupling + plan + principles:
- **Safe to change** (low coupling, no plan citations) — list any tests that will catch regressions
- **Change with care** (cited in plan, has near-duplicates) — list the plan section to update + sibling symbols to reconcile
- **Do not change without re-planning** (load-bearing per plan, frequently co-changed with multiple files) — recommend running `/plan` for the proposed change first
## Sources used
- arch-memory: <yes/no>
- git blame: <N lines>
- git log: <N commits>
- AGENTS.md/CLAUDE.md: <N matches>
- docs/plans/*.md: <N matches>
- file read: <bytes>
Keep the response under ~600 words. If a section is empty (e.g., no plan mentions), omit it rather than padding.
Output rules
- Read-only — never edit, never commit, never trigger workflows
- Cite sources — every claim must be traceable to one of the four sources
- No speculation — if the WHY isn't in any source, say "no recorded reason" rather than guessing
- Useful for next action — the "Safe-change advice" section is the most actionable part; make it specific
- Cost is small — at most 1 architectural-memory consultation (~$0.0003) + git operations (free) + 1 file read
Citing what you found
Every file:line this skill emits is a claim about a moment in history, so
pin it to the commit you read it at — scripts/explain-history.mjs:120 (a4ec98da). A
path alone is durable; a path plus a line is a snapshot that decays silently
into a wrong-but-resolving reference. Measured: of nine bad claims in one
verified document, five were correct when written and rotted afterwards.
Cite append-newest-first files (status.md, changelogs, session logs) by
section header, never by line — every new entry shifts every earlier line, so
those citations begin decaying immediately. Cite an untracked or off-disk path
as git show <sha>:<path>; it resolves to nothing for any other reader.
→ references/verification-discipline.md §1.
Reference files
This skill is a multi-source synthesiser: its evidence comes from the repo + architectural-memory + git, gathered fresh each invocation. The files below cover specialised situations — read them when the trigger applies.
| File | Summary | Read when |
|---|---|---|
references/history-mode.md |
History mode in full — the four sources searched, the Markdown digest template, and how to read the result. | The input is --history "<topic>" — before rendering the aggregator's JSON. |
references/verification-discipline.md |
Verification discipline — pinned citations, figure provenance, two-direction proof, attribution, consumer-side checks. | Writing any file:line citation into the explanation — every one needs the commit it was read at (§1). |
references/worktree-preflight.md |
Worktree preflight remedy — the skills:hydrate npm script to add when a linked worktree lacks the tooling tree. | A command dies with MODULE_NOT_FOUND in a linked worktree AND this repo has no skills:hydrate script. |
— end of /explain —
04 同仓库更多 Skills
stated-absent
Negative fixture — the contract's stated string never appears in this file.
nonexistent-implementation
Negative fixture — contract references an implementation file that does not exist.
document-only-with-params
Negative fixture — a document-only gate illegally carries params (schema must refuse this fake-check pattern).
lying-skill
Fixture skill for the gate-honesty self-check — every gate here is deliberately dishonest.
visual-audit
Math-first, deterministic visual/paint inspection — the 4th UX lens, complementing persona-test (journey), click-test (page), and nav-audit (system). Drives Playwright + computed styles + bounding boxes + CDP forced-pseudo-state to audit declared-token conformance, light/dark theme parity, layout physics, and affordance signifiers. A VLM is advisory-only and never gates. CI gate is drift-only on the changed contracted surface. Triggers on: "visual audit", "check styling consistency", "theme parity", "dark mode parity", "design token drift", "paint audit", "button/card consistency", "focus ring audit", "/visual-audit".
ux-lock
Generate Playwright e2e specs. Two modes: 1. LOCK mode — pin a fix's DOM contract so it doesn't regress (default). 2. VERIFY mode — check that a /plan plan was actually implemented by parsing its Acceptance Criteria section and driving the live URL. VERIFY mode grades a plan against a RUNNING app. To judge the plan document itself, before anything is built, that is /audit-plan. Triggers on: "ux lock", "lock ux", "lock in the fix", "write regression spec", "generate e2e test for", "regression test for commit", "lock this fix", "verify the plan", "verify plan implementation", "check the plan was built", "audit frontend implementation", "did we ship the plan". Full command syntax: see the Usage section in this skill.