/foundry:distill [prune | memory | executables [<run-dir-or-report-path>] | "external <url-or-path>" | "<recurring task description>"] [--project] [--eager] [--keep "<items>"]from foundry
Analyzes Claude Code usage patterns and work history to surface concrete improvements: new agents/skills, memory pruning, consolidating lessons into rules/agent updates, or extracting executables from efficiency audit candidates. Supports modes for pruning memory, processing lessons, analyzing external resources, and extracting scripts.
Ships in foundry. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description, though model invocation is off: only you can start it.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Analyze how Claude Code is used, surface concrete improvements — new agents/skills to reduce repetition, or consolidate lessons into governance files (rules, agent instructions, skill updates) — without duplicating what exists.
NOT for single-file edits or quality checks — use /foundry:audit for config quality checks. NOT for audit-only scan for extraction candidates (use /foundry:audit --efficiency instead of distill executables for detection-only).
prune [--eager] — evaluate project memory file for stale, redundant, or verbose entries. Default: advisory diff + apply prompt. --eager: score every entry (Usage likelihood × Impact → Tier P0/P1/P2), print full scored table with # column, let user select by tier or item numbers, delegate edits to foundry:curator.memory [--eager] — read .notes/lessons.md, memory feedback files and recurring transcript tool failures (bin/mine_transcript_failures.py), distill recurring patterns into proposed rule files, agent instruction updates, skill workflow changes. --eager: include Pattern count, Strength, Tier columns in proposal table; let user select clusters to promote by tier or item numbers; delegate writes to foundry:curator.external <source> [--eager] — analyse external plugin, skill, or agentic resource, produce structured adoption proposal. <source> is URL, file path, or local directory. --eager: lower adoption bar — recommend partial adoption even for single useful components.executables [--eager] [<run-dir-or-report-path>] — perform bin/ extraction from /foundry:audit --efficiency Check 33 candidates. Auto-detects latest run dir under .reports/audit/; pass optional path to target specific run dir or report file. Runs inline Check 33 scan when no report exists. Default gates on HIGH/MEDIUM verdict. --eager: also surface LOW verdict clusters as extraction candidates. Spawns foundry:sw-engineer per cluster. Skip to Mode: Executables Extraction below.[--eager] <recurring task description> — use description as context when generating suggestions. --eager: lower frequency threshold from 3+ to 2+ occurrences; single high-effort occurrence also qualifies.--project — in prune and memory modes, show interactive project picker: enumerate all slugs under ~/.claude/projects/*/memory/ with MEMORY.md size in tokens, let user select which project(s) to operate on. Omit to operate on the current project's memory only (the working directory's memory dir, resolved by resolve_memory_dir.py) — other projects are never touched without the picker. No effect on other modes.Task hygiene — task tools may be deferred; load before first use: ToolSearch(query="select:TaskList,TaskCreate,TaskUpdate,TaskGet", max_results=4). Call TaskList first and triage each task it returns: completed if work clearly done, deleted if orphaned, keep in_progress only if genuinely continuing. Never spend a turn on bookkeeping alone — every TaskCreate/TaskUpdate ships in the same response as the next substantive tool call; one exception, TaskUpdate(completed) immediately before a long output block (rules/task-lifecycle.md).
PLUGIN_ROOT=$(python "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name foundry) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
python "$PLUGIN_ROOT/bin/parse-skill-flags.py" --flags eager,project --keep-state distill-state --out-file "${TMPDIR:-/tmp}/distill-state-${CSID}/keep-items" -- "$ARGUMENTS" >/dev/null # timeout: 5000 — no eval; distill-state-<flag>-${CSID} sentinels, keep-items into the state dir it makes, clears stale contract
IFS= read -r EAGER < "${TMPDIR:-/tmp}/distill-state-eager-${CSID}" 2>/dev/null || EAGER=false
IFS= read -r PROJECT_FLAG < "${TMPDIR:-/tmp}/distill-state-project-${CSID}" 2>/dev/null || PROJECT_FLAG=false
IFS= read -r CLEAN_ARGS < "${TMPDIR:-/tmp}/distill-state-clean-args-${CSID}" 2>/dev/null || CLEAN_ARGS=""
echo "EAGER=$EAGER" # shell vars don't persist across Bash calls — read from stdout
echo "PROJECT_FLAG=$PROJECT_FLAG"
echo "ARGUMENTS_FINAL=$CLEAN_ARGS"
Note:
EAGER,PROJECT_FLAGand strippedCLEAN_ARGSare set by this Bash block, but shell variable state does not persist across separate Bash() tool calls. After this block runs, read its stdout (EAGER=true/false,PROJECT_FLAG=true/false,ARGUMENTS_FINAL=...), carry those values as model-context references for all subsequent mode dispatch and threshold decisions. Do not rely on$EAGER/$PROJECT_FLAGas live shell variables in later steps — substitute the literal value read from stdout.PROJECT_FLAG=true: mode must run interactive picker before operating.
Report-first gate — every mode (default Step 5, prune, memory, external, executables, no exception). Invariant: user decides from a complete report, and the decision survives a host blanking pre-call text:
AskUserQuestion on what to apply, port, extract, prune or do next: print gate report in reply, rendered normal Markdown. Order: Write report file first → then, in the response that calls AskUserQuestion, print full report as reply text right before the call. No tool call between print and call. Question text still carries its plain summary (below).prune, memory, external, executables) and default Step 5 — carries all five; empty part stated none — <reason>, never left out:
⚠ unavailable / ⏱ timed_out, or none before gate — <reviewer> runs after apply.temp//.reports/ file = addition, never substitute. Write content, Bash stdout, question text, bare → <file> path ≠ printed report. Gate reached without printed report = violation: print it, then ask, question text keeping its plain summary._full/communication.md §Interactive Questions: named file first, printed once before the call) → full print, not Output Routing header/path/summary form. distill is no report-header follow-up (_shared/terminal-summaries.md final-reply-after-answer rule does not apply); saved file gets no --- YAML header.**Review verdict**: none — default mode runs no reviewer). Next steps (/foundry:manage create — user-invoked only — or edit existing) print as plain-text user-run commands. This line is the authoritative default-mode policy; _full/quality-gates.md §Output Routing defers here.→ <file> (communication.md §Interactive Questions) — carries the decision when a host blanks pre-call text.§Report-first gate) or one named exclusion (§Report-first gate exclusion: <name>). Exclusions: --project picker (scope choice, no report built yet); per-item approval after printed diff (Review first, Show diff first, draft approvals, deletion confirms — diff/draft printed first); follow-up within printed gate (asked only after the gate's first answer needs it; report already printed; its question text repeats counts, top recommendation, path).AskUserQuestion sentence, a - question: block with its - (x) label: options, or a sentence carrying an exclusion tag. Plain-text question or wait-for-reply = violation (communication.md §Interactive Questions); free text arrives via the tool's auto-added Other answer.<mode> open items); its gate and zero-result Open decisions both name it, never a hand-picked subset.Skip always offered.Mode-token normalization — all mode dispatches below compare against the first whitespace-delimited token of stripped
ARGUMENTS_FINALfrom stdout (after flag removal). Use this single rule consistently; don't rely on exact equality of the full$ARGUMENTSstring — trailing flags/spaces from prior parsing may differ.
--project scope check (run before the mode checks below): if PROJECT_FLAG (read from stdout above) is true and the first token is not prune or memory, print ⚠ `--project` ignored — it applies only to `prune` and `memory` modes. once and repeat it in the final reply (a mid-run print can arrive as an empty progress update), then continue with normal dispatch below.
If first token equals executables (i.e. executables alone or executables <path>, NOT a path or word that merely starts with the string executables): skip Steps 1–5 entirely and go to "Mode: Executables Extraction" below.
If first token equals prune: skip Steps 1–5 entirely and go to "Mode: Memory Pruning" below.
If first token equals memory: skip Steps 1–5 entirely and go to "Mode: Memory Distillation" below.
If first token equals external (i.e. external <source>, NOT a word that merely starts with the string external): a second token is required — it is the source to analyse. No second token: print ! MISSING — `external` needs a source: `/foundry:distill external <url-or-path>`. and stop; do not enter the mode, do not guess a source, do not fall back to default-mode analysis. Second token present: skip Steps 1–5 entirely and go to "Mode: External Distillation" below; that mode collects the live inventory at E7.
Use Glob tool to enumerate agents and skills across all sources — project-local AND plugin-namespaced — avoids false-gap findings when candidate already exists in plugin:
agents/*.md, path .claude/; pattern skills/*/SKILL.md, path .claude/*/agents/*.md, path plugins/; pattern */skills/*/SKILL.md, path plugins/${CLAUDE_PLUGIN_ROOT} is foundry's own version dir, so globbing */agents/*.md under it matches nothing, and globbing the whole cache double-counts orphaned versions# timeout: 30000
PLUGIN_ROOT=$(python "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name foundry) || exit $?; export PLUGIN_ROOT
find "$HOME/.claude/plugins/cache" -mindepth 2 -maxdepth 2 -type d 2>/dev/null | while IFS= read -r p; do
m="${p%/*}"; m="${m##*/}"
python "$PLUGIN_ROOT/bin/resolve_plugin_root.py" --plugin-name "${p##*/}" --marketplace "$m" 2>/dev/null | sed "s|^|PLUGIN_ROOT: ${p##*/} |"
done
Then use Glob tool on each printed root for pattern agents/*.md and skills/*/SKILL.md, tagging entries with that plugin name. No PLUGIN_ROOT: line printed → installed inventory unavailable: state it in the report and never read an empty inventory as "no such agent/skill exists".
For each agent/skill found, extract: name, description, tools, purpose. Tag each entry with plugin namespace (e.g. foundry:sw-engineer, oss:resolve) — used in Step 3 gap analysis to prevent recommending duplicates of plugin-namespaced agents/skills.
Look for signals of repetitive or specialist work. Guard each independent git command with git rev-parse --is-inside-work-tree >/dev/null 2>&1 before running it; outside a repository, report git history unavailable and continue with task and lesson evidence. First three git commands independent — run in parallel:
# timeout: 3000
# --- run these three in parallel ---
if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then git log --oneline -50; else echo "git history unavailable"; fi
if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then git log --name-only --pretty="" -30 | sort | uniq -c | sort -rn | head -20; else echo "git history unavailable"; fi
if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then git log --oneline -100 | cut -d' ' -f2 | sort | uniq -c | sort -rn | head -15; else echo "git history unavailable"; fi
Then use Glob tool (pattern todo_*.md, path .plans/active/) to list active task files; read each with Read tool. Also read .notes/lessons.md (if exists) for task history and conversation hints.
If ARGUMENTS_FINAL from the parse stdout is non-empty, use it as additional context for pattern analysis.
With --eager (lower thresholds):
PLUGIN_ROOT=$(python "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name foundry) || exit $?; export PLUGIN_ROOT
export CSID="${CLAUDE_CODE_SESSION_ID:-$PPID}"
_PRESERVE="run-dir=n/a"
python "$PLUGIN_ROOT/bin/write_skill_contract.py" --keep-file "${TMPDIR:-/tmp}/distill-state-${CSID}/keep-items" "foundry:distill" "gap-analysis (after work-pattern scan)" "n/a" "$_PRESERVE" "gap analysis (Step 3) → duplication check (Step 4) → report (Step 5)" # timeout: 5000
For each identified pattern, check:
Thresholds for recommendation:
Before recommending anything, run overlap check and anti-pattern checklist:
For each candidate agent/skill:
- Does any existing agent cover >50% of its scope? → enhance existing instead
(with --eager: lower to >30%; any shared single named capability → flag as boundary issue)
- Is the name/description confusingly similar to an existing one? → rename existing
Anti-pattern checklist — reject candidate if any apply:
Print report below in reply, rendered normal Markdown (§Report-first gate: all five parts, empty ones stated). Default mode has no gate: after the report, print next steps as plain-text user-run commands, never as a question (§Report-first gate, default-mode line).
## Agent/Skill Suggestions
**Summary**: [N patterns scanned · N gaps · N recommendations]
**Recommendations** (`none — <reason>` when empty):
### Existing Coverage (no gaps found)
- [agent/skill]: covers [pattern] well — no new file needed
### Recommend: New Agent — [name]
**Trigger**: [what recurring pattern or gap justifies this]
**Gap**: [what existing agents don't cover]
**Scope**: [what it would do — 3-5 bullet points]
**Suggested tools**: [Read, Write, Edit, Bash, etc.]
**Draft description**: "[one-line description for frontmatter]"
### Recommend: New Skill — [name]
**Trigger**: [what repetitive workflow justifies this]
**Gap**: [why existing skills don't cover it]
**Scope**: [what workflow steps it would orchestrate]
**Draft description**: "[one-line description for frontmatter]"
### Recommend: Enhance Existing — [agent/skill name]
**Add**: [specific capability missing from current version]
**Why**: [what recurring task would benefit]
### No Action Needed
[pattern]: already handled by [existing agent/skill]
**Findings table** (`none — <reason>` when no pattern found):
| Pattern | Occurrences | Covered by | Gap |
|---------|-------------|------------|-----|
| [pattern] | [N] | [agent/skill or —] | [yes/no] |
**Review verdict**: none — default mode runs no reviewer
**Open decisions**:
- [choice needing user input, e.g. which recommendation to scaffold — or `none — <reason>`]
## Confidence
**Score**: [0.NN]
**Gaps**:
- (-0.NN) [e.g., git history too shallow, task files not present, descriptions too generic to compare]
**Refinements**: N passes. [Pass 1: <what improved>. Pass 2: <what improved>.] — omit if 0 passes
rm -f .temp/state/skill-contract.md # clear contract — skill complete (compaction-contract.md §Lifecycle) # timeout: 5000
prunePLUGIN_ROOT=$(python "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name foundry) || exit $?; export PLUGIN_ROOT
python "$PLUGIN_ROOT/bin/load_mode.py" distill modes prune.md --fallback-source # timeout: 5000
Execute the mode loaded above.
memoryPLUGIN_ROOT=$(python "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name foundry) || exit $?; export PLUGIN_ROOT
python "$PLUGIN_ROOT/bin/load_mode.py" distill modes memory.md --fallback-source # timeout: 5000
Execute the mode loaded above.
externalPLUGIN_ROOT=$(python "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name foundry) || exit $?; export PLUGIN_ROOT
python "$PLUGIN_ROOT/bin/load_mode.py" distill modes external.md --fallback-source # timeout: 5000
Execute the mode loaded above.
executablesPLUGIN_ROOT=$(python "${CLAUDE_PLUGIN_ROOT}/bin/resolve_plugin_root.py" --plugin-name foundry) || exit $?; export PLUGIN_ROOT
python "$PLUGIN_ROOT/bin/load_mode.py" distill modes executables.md --fallback-source # timeout: 5000
Execute the mode loaded above.
Skill is introspective: looks at tooling itself, not just code
Invoke periodically (e.g. monthly) or after burst of correction/feedback; one-time snapshot, not continuous monitor
Suggestions are proposals — review before creating new files
After creating new agent/skill from suggestion, re-run skill once to confirm gap resolved, then stop
memory mode is primary consolidation path — run after any session with significant corrections, prevents lesson drift into MEMORY.md noise
Agent Teams signal tracking: when reviewing patterns, also look for:
--team or team-mode heuristics more/less than expected: flag over/under-use relative to CLAUDE.md §Agent Teams (teams are user-invoked only) and the per-tier ceilings in rules/agent-spawn.md §Parallel Spawn Ceilingssonnet teammates): flag for tier adjustmentexternal mode calibration: two concrete GT fixture cases defined in calibrate skills mode file — find via find "${CLAUDE_PLUGIN_ROOT}" -maxdepth 5 -path "*/calibrate/modes/skills.md" 2>/dev/null | head -1 with fallback to plugins/cc_foundry/skills/calibrate/modes/skills.md:
research: plugin structure: GT Group A candidates map to research plugin, digest recommended, install-as-is not triggeredFollow-up chains:
/foundry:manage create to scaffold and register it.claude/ edits apply at once; plugin-source edits reach ~/.claude/ only via plugin update/reinstall, after which /foundry:setup re-merges plugin settings/rules)memory proposals applied: /foundry:audit rules to verify new rule files structurally soundexecutables extraction complete: plugin bin/ scripts reach ~/.claude/ via plugin update/reinstall; run /foundry:audit --efficiency to confirm extract_count == 0What SKILL.md sets; muted values are Claude Code's defaults
lownpx claudepluginhub borda/ai-rig --plugin foundry11 skills in this plugin
/auditFull-sweep quality audit of .claude/ config — cross-references, permissions, model tiers, docs freshness. Scope tokens select what to audit; --upgrade applies docs-sourced improvements; --adversarial runs foundry:challenger + Codex adversarial review; --efficiency sweeps model tiers, token bloat, spawn patterns, boilerplate duplication, and bin/ extraction candidates (extraction performed separately via /foundry:distill executables); --consolidate proposes merging overlapping narrow rules into fewer broader ones and sharpening overlapping skill notes and agent clauses (advisory, edits nothing). Fix level chosen via conditional follow-up gate after report./brainstormIterative brainstorming skill for turning fuzzy ideas into approved tree documents. Diverges into branches, deepens and prunes them over many rounds, saves a tree doc. Run breakdown on the tree to distill it into a spec via guided questions. SKIP: a content outline to co-create, or one already approved and awaiting finished content (use foundry:create — create co-creates the outline, foundry:creator writes the finished artifact; brainstorm is for idea generation before an outline exists); a code-level implementation plan derived from an existing spec (use develop:plan (requires `develop` plugin)).Other plugins' skills for the same job