From foundry
Create, update, or delete agents, skills, rules, and hooks with full cross-reference propagation. Non-trivial writes (agent/skill content-edits and creates) are delegated to foundry:self-mentor subagents; hook content-edits are delegated to sw-engineer; large cross-ref fan-outs (> 3 files) also delegate. The parent orchestrates and handles MEMORY.md, README, audit, and the final report. Also manages settings.json permissions atomically with permissions-guide.md.
npx claudepluginhub borda/ai-rig --plugin foundryThis skill is limited to using the following tools:
<objective>
Searches, retrieves, and installs Agent Skills from prompts.chat registry using MCP tools like search_skills and get_skill. Activates for finding skills, browsing catalogs, or extending Claude.
Searches prompts.chat for AI prompt templates by keyword or category, retrieves by ID with variable handling, and improves prompts via AI. Use for discovering or enhancing prompts.
Creates isolated Git worktrees for feature branches with prioritized directory selection, gitignore safety checks, auto project setup for Node/Python/Rust/Go, and baseline verification.
Manage the lifecycle of agents, skills, rules, and hooks in the .claude/ directory. Handles creation with rich domain content, atomic renames with cross-reference propagation, content editing (agent/skill edits delegated to foundry:self-mentor subagent; hook edits delegated to sw-engineer; rule edits inline), and clean deletion with broken-reference cleanup. Keeps the MEMORY.md inventory in sync with what actually exists on disk.
create agent <name> "description" — create a new agent with generated domain contentcreate skill <name> "description" — create a new skill with workflow scaffoldcreate rule <name> "description" — create a new rule file with frontmatter and sectionsupdate <name> <new-name> — rename; type auto-detected from diskupdate <name> "change description" — content-edit; agent/skill edits delegated to foundry:self-mentor, hook edits delegated to sw-engineer, rule edits inlineupdate <name> <spec-file.md> — content-edit from spec file; agent/skill edits delegated to foundry:self-mentor, hook edits delegated to sw-engineer, rule edits inlinedelete <name> — delete; type auto-detected from disk (agents, skills, rules, hooks); asks user if ambiguousadd perm <rule> "description" "use case" — add a permission to settings.json allow list and permissions-guide.mdremove perm <rule> — remove a permission from settings.json allow list and permissions-guide.mdWebSearch, Bash(cmd:*), WebFetch(domain:example.com)--skip-audit — optional flag: skip the Step 9 /audit validation (use when running inside an audit fix loop to avoid recursion)Update/delete mode — the name is looked up across agents, skills, and rules automatically:
AskUserQuestion to ask: (a) agent, (b) skill, (c) ruleUpdate second-argument discrimination:
.md extension) → rename mode.md → content-edit mode (agent/skill: foundry:self-mentor subagent; hook: sw-engineer subagent; rule: inline)Examples:
/manage create agent task-planner "Planning specialist for decomposing epics into actionable tasks"/manage create skill benchmark "Benchmark orchestrator for measuring and comparing performance across commits"/manage create rule torch-patterns "PyTorch coding patterns — compile, AMP, distributed"/manage update example-agent example-agent-v2/manage update my-agent "add a section on error handling patterns"/manage update optimize docs/specs/YYYY-MM-DD-<spec-name>.md/manage update testing "add a section on snapshot testing with syrupy"/manage delete old-agent-name/manage add perm "Bash(jq:*)" "Parse and filter JSON" "Extract fields from REST API responses"/manage remove perm "Bash(jq:*)".claude/agents.claude/skills.claude/rules.claude/hooksmaintain colors manually — add new agent colors here when creating agents; this static list is advisory only — the live Grep in Step 3 is the authoritative check for colors in use
Task hygiene: Before creating tasks, call TaskList. For each found task:
completed if the work is clearly donedeleted if orphaned / no longer relevantin_progress only if genuinely continuingTask tracking: per CLAUDE.md, create tasks (TaskCreate) for each major phase. Mark in_progress/completed throughout. On loop retry or scope change, create a new task.
Extract operation, type, name, and optional arguments from $ARGUMENTS.
Validation rules:
^[a-z][a-z0-9-]*$ (kebab-case)create: name must NOT already exist on disk; description is requiredupdate/delete: name MUST already exist on diskupdate rename: new-name must NOT already exist on diskadd perm: rule must NOT already exist in settings.json allow list; description and use case are requiredremove perm: rule MUST already exist in settings.json allow listType auto-detection (for update and delete): run all four Glob checks in parallel:
agents/<name>.md, path .claude/skills/<name>/SKILL.md, path .claude/rules/<name>.md, path .claude/hooks/<name>.js, path .claude/Results:
AskUserQuestion: "Multiple entities named <name> found. Which one? (a) agent (b) skill (c) rule (d) hook"<name> found" and stopFor create, check only the relevant type's path.
# Check permission existence (for add perm / remove perm)
python3 -c "import json,sys; d=json.load(open('.claude/settings.json')); sys.exit(0 if '<rule>' in d['permissions']['allow'] else 1)" 2>/dev/null
Update second-argument discrimination — apply after type is resolved:
.md extension) → rename mode: validate new-name does NOT already exist.md → content-edit mode: validate the spec file exists on disk; no new-name uniqueness checkIf validation fails, report the error and stop.
Step skip rules:
Before creating anything, check if existing agents/skills already cover the requested functionality:
Read(file_path=..., limit=3) on each .md in agents/) and skills (use Read(file_path=..., limit=3) on each SKILL.md)AskUserQuestion to ask whether to proceed, extend, or abort, with options: "Extend existing (Recommended)" (add to the overlapping one instead), "Proceed" (create new agent/skill as planned), "Abort" (stop here)Skip this step for update, delete, and perm operations.
Snapshot the current roster for later comparison. Steps 2 and 3 are independent reads — issue Glob calls for both in the same response.
Use Glob (pattern agents/*.md, path .claude/) for agents and Glob (pattern skills/*/, path .claude/) for skills to build the name lists. Use Grep (pattern ^color:, glob agents/*.md, path .claude/, output mode content) to collect colors currently in use.
Extract names inline from the Glob results — strip the .claude/agents/ prefix and .md suffix for agent names; strip the .claude/skills/ prefix and trailing / for skill names; strip the .claude/rules/ prefix and .md suffix for rule names. Sort alphabetically when building the roster string.
Branch into one of these modes:
Fetch the latest Claude Code agent frontmatter schema to ensure the template is current:
https://code.claude.com/docs/en/sub-agents with instruction: "Write your full findings (schema fields, new fields, deprecated fields) to /tmp/manage-schema-$(date +%s).md using the Write tool. Return ONLY a compact JSON envelope on your final line — nothing else after it: {\"status\":\"done\",\"file\":\"/tmp/manage-schema-<ts>.md\",\"fields\":N,\"new\":N,\"deprecated\":N,\"confidence\":0.N,\"summary\":\"N fields, N new, N deprecated\"}"
name, description, tools, disallowedTools, model, permissionMode, maxTurns, effort, initialPrompt, skills, mcpServers, hooks, memory, background, isolation), current model shorthands, and any new fieldsmaxTurns for long-running agents), include it with a sensible default and inline comment.Pick the first unused color from the AVAILABLE_COLORS pool (compare against colors found in Step 3)
Choose model based on role complexity:
opusplan — plan-gated roles (solution-architect, oss:shepherd, foundry:self-mentor): long-horizon reasoning + plan modeopus — complex implementation roles (sw-engineer, qa-specialist, research:scientist, perf-optimizer): deep reasoning without plan modesonnet — focused execution roles (data-steward, web-explorer, doc-scribe): pattern-matching, structured outputhaiku — high-frequency diagnostics roles (linting-expert, oss:ci-guardian): rule-application, structured lint outputSpawn foundry:self-mentor subagent to generate and write the agent file — generating 200–400 lines of domain content inline inflates the main context:
Read the agent scaffold template at `.claude/skills/manage/templates/agent-scaffold.md`.
Also read the schema file at the path returned in the step 1 JSON to incorporate any new frontmatter fields.
Create `.claude/agents/<name>.md` with:
- Frontmatter: name=<name>, description=<description>, model=<model>, color=<color>; add any broadly-useful new fields from the schema
- Body: rich domain-specific content for the role described by the description, following all content rules and tool selection guidelines in the scaffold template
Write the file using the Write tool.
Return ONLY: {"status":"done","file":".claude/agents/<name>.md","lines":N,"confidence":0.N}
Fetch the latest Claude Code skill frontmatter schema to ensure the template is current:
https://code.claude.com/docs/en/skills with instruction: "Write your full findings (schema fields, new fields, deprecated fields) to /tmp/manage-skill-schema-$(date +%s).md using the Write tool. Return ONLY a compact JSON envelope on your final line — nothing else after it: {\"status\":\"done\",\"file\":\"/tmp/manage-skill-schema-<ts>.md\",\"fields\":N,\"new\":N,\"deprecated\":N,\"confidence\":0.N,\"summary\":\"N fields, N new, N deprecated\"}"
name, description, argument-hint, disable-model-invocation, user-invocable, allowed-tools, model, effort, shell, paths, context, agent, hooks), and any new fieldsmodel or context: fork only when the skill's described purpose clearly benefits from them.Spawn foundry:self-mentor subagent to create the directory and generate the skill file — content generation is non-trivial and should not inflate the main context:
Run: `mkdir -p .claude/skills/<name>` using the Bash tool.
Read the skill scaffold template at `.claude/skills/manage/templates/skill-scaffold.md`.
Also read the schema file at the path returned in the step 1 JSON to incorporate any new frontmatter fields.
Create `.claude/skills/<name>/SKILL.md` with:
- Frontmatter: name=<name>, description=<description>; add other fields per schema and scaffold guidance
- Body: rich workflow scaffold derived from the description, following all content rules in the scaffold template
Write using the Write tool.
Return ONLY: {"status":"done","file":".claude/skills/<name>/SKILL.md","lines":N,"confidence":0.N}
Atomic update — write new file before deleting old:
Read .claude/agents/<old-name>.md using the Read tool.
Write new file to .claude/agents/<new-name>.md using the Write tool (copy content of old file with name: line updated to <new-name>).
Verify the new file exists and is valid: Read(file_path=".claude/agents/<new-name>.md", limit=5)
# 4. Delete old file only after new file is confirmed
rm .claude/agents/<old-name>.md # timeout: 5000
Atomic update — create new directory before removing old:
mkdir -p .claude/skills/<new-name> # timeout: 5000
name: line in frontmatter, Write to new location.Read(file_path=".claude/skills/<new-name>/SKILL.md", limit=5)# 4. Remove old directory only after new is confirmed
rm -r .claude/skills/<old-name> # timeout: 5000
rm .claude/agents/<name>.md # timeout: 5000
rm -r .claude/skills/<name> # timeout: 5000
.claude/ file conventions:Read `.claude/agents/<name>.md`.
Apply this change: <directive>
Rules:
- Preserve frontmatter fields (name, description, tools, model, color) unless the change explicitly targets them
- Preserve XML tags (<role>, <core_knowledge>, <workflow>, <notes>) — targeted edits only; do not rewrite unchanged sections
- If the change modifies the agent's purpose: update the description: frontmatter field
- After editing: verify XML tag balance, step numbering, cross-ref validity
Write all changes using the Edit tool.
Return ONLY: {"status":"done","file":".claude/agents/<name>.md","edits":N,"description_changed":true|false,"confidence":0.N}
Use description_changed from the returned JSON to decide whether Steps 5–7 need cross-ref propagation.
.claude/ file conventions:Read `.claude/skills/<name>/SKILL.md`.
Apply this change: <directive>
Rules:
- Preserve frontmatter fields (name, description, argument-hint, disable-model-invocation, allowed-tools)
- Preserve XML tags (<objective>, <inputs>, <workflow>, <notes>) — targeted edits only; do not rewrite unchanged sections
- If the change modifies the skill's purpose: update the description: frontmatter field
- After editing: verify XML tag balance, step numbering, workflow gate completeness
Write all changes using the Edit tool.
Return ONLY: {"status":"done","file":".claude/skills/<name>/SKILL.md","edits":N,"description_changed":true|false,"confidence":0.N}
Use description_changed from the returned JSON to decide whether Steps 5–7 need cross-ref propagation.
.claude/rules/<name>.md using the Read tool.## sections — no XML tagsdescription: and paths: frontmatter fieldsNo schema fetch needed — rule files are simpler than agents/skills (only frontmatter + free-form markdown sections).
Write .claude/rules/<name>.md with this structure:
---
description: <one-line description from user>
paths:
- '<glob pattern matching the rule's scope>'
---
## <First Section Title>
[Real domain-specific rules derived from the description — not generic boilerplate. 20-60 lines total.]
Content rules:
## sections for major topics, bullets for individual rulesAtomic update — write new file before deleting old:
.claude/rules/<old-name>.md using the Read tool.name: frontmatter field — the filename IS the identifier. Write a new file at .claude/rules/<new-name>.md with identical content.rm .claude/rules/<old-name>.md rm .claude/rules/<name>.md # timeout: 5000
Hook files are JavaScript — delegate to sw-engineer (not foundry:self-mentor) for implementation-quality edits:
Read `.claude/hooks/<name>.js`.
Apply the hook authoring standards from the `\<hook_authoring>` section in your agent definition — file-header structure, exit code semantics, stdin pattern, and anti-patterns.
Apply this change: <directive>
Rules:
- Preserve the file header block (PURPOSE, HOW IT WORKS, EXIT CODES) unless the change explicitly modifies that logic
- Preserve CommonJS require() style; do not convert to ESM
- stdin must use event-based accumulation (process.stdin.on("data"/"end")); never readFileSync("/dev/stdin")
- All subprocess calls must use execFileSync or spawnSync (args array — no execSync with shell strings)
- All logic must be wrapped in try/catch; catch always exits 0
- After editing: verify exit codes match documented cases, no shell injection surface added
Write all changes using the Edit tool.
Return ONLY: {"status":"done","file":".claude/hooks/<name>.js","edits":N,"confidence":0.N}
rm .claude/hooks/<name>.js # timeout: 5000
After deleting a hook, also remove its entry from
.claude/settings.jsonhooks configuration so Claude Code does not try to invoke a missing file.
Adds a rule to both settings.json and permissions-guide.md atomically.
Determine the guide category from the rule prefix:
WebSearch → ## WebWebFetch(domain:...) → ## WebFetch — allowed domainsBash(gh ...) → ## GitHub CLI — read-onlyBash(git log:*), Bash(git show:*), Bash(git diff:*), Bash(git rev-*:*), Bash(git ls-*:*), Bash(git -C:*), Bash(git branch:*), Bash(git tag:*), Bash(git status:*), Bash(git describe:*), Bash(git shortlog:*) → ## Git — read-onlyBash(git add:*), Bash(git checkout:*), Bash(git stash:*), Bash(git restore:*), Bash(git clean:*), Bash(git apply:*) → ## Git — local writeBash(pytest:*), Bash(python ...), Bash(ruff:*), Bash(mypy:*), Bash(pip ...) → ## Python toolchainBash(brew ...), Bash(codex:*) → ## macOS / ecosystemBash(...) → ## Shell utilitiesUpdate settings.json — parse, append, write back:
python3 -c " # timeout: 5000
import json
with open('.claude/settings.json') as f:
d = json.load(f)
d['permissions']['allow'].append('<rule>')
with open('.claude/settings.json', 'w') as f:
json.dump(d, f, indent=2)
f.write('\n')
"
permissions-guide.md — append a new row to the end of the correct section (before its trailing --- separator). New row format:| `<rule>` | <description> | <use case> |
Use the Edit tool to insert the row: find the last table row in the target section and insert after it.
python3 -c "import json; d=json.load(open('.claude/settings.json')); print('OK' if '<rule>' in d['permissions']['allow'] else 'MISSING')" # timeout: 5000
grep -F '`<rule>`' .claude/permissions-guide.md
Removes a rule from both settings.json and permissions-guide.md atomically.
settings.json — parse, filter, write back:python3 -c " # timeout: 5000
import json
with open('.claude/settings.json') as f:
d = json.load(f)
d['permissions']['allow'] = [p for p in d['permissions']['allow'] if p != '<rule>']
with open('.claude/settings.json', 'w') as f:
json.dump(d, f, indent=2)
f.write('\n')
"
Update permissions-guide.md — use the Edit tool to remove the table row containing `<rule>`.
Verify both files are clean:
python3 -c "import json; d=json.load(open('.claude/settings.json')); print('OK' if '<rule>' not in d['permissions']['allow'] else 'STILL PRESENT')" # timeout: 5000
grep -cF '`<rule>`' .claude/permissions-guide.md && echo "STILL IN GUIDE" || echo "OK"
Search all .claude/ markdown files for the changed name and update references:
Use the Grep tool to find all references to the name across the config:
<name>, glob agents/*.md, path .claude/, output mode content<name>, glob skills/*/SKILL.md, path .claude/, output mode content<name>, glob rules/*.md, path .claude/, output mode content<name>, file .claude/CLAUDE.md, output mode content<name>, file README.md, output mode contentFor update (rename): Count the files grep returns. For ≤ 3 files: apply inline with the Edit tool. For > 3 files: spawn foundry:self-mentor subagent — inline edits across many files inflate the main context:
Apply these cross-reference updates (<old-name> → <new-name>):
<list each file path with the required substitution>
Use the Edit tool for each file (replace_all: true where appropriate).
Return ONLY: {"status":"done","files_updated":N}
For delete: Review each reference. If the deleted name appears in:
For create: No cross-ref propagation needed (new names have no existing references).
For content-edit: Run cross-ref propagation only if the entity's description: frontmatter changed — propagate the new description text to any MEMORY.md or README summary lines that quote it. Skip entirely if only internal content (workflow steps, rules) changed.
MEMORY.md is Claude Code's auto-memory file — it is not stored under .claude/. It is injected into the conversation context at session start. The absolute path appears near the top of the system prompt (e.g. ~/.claude/projects/.../memory/MEMORY.md). Use that absolute path with the Edit tool.
Regenerate the inventory lines from what actually exists on disk:
Use Glob (agents/*.md, path .claude/) for agents, Glob (skills/*/, path .claude/) for skills, and Glob (rules/*.md, path .claude/) for rules to get file paths. Extract names inline from the returned paths (strip path prefix and .md/trailing-/ suffix) and join them as a comma-separated string directly in the response.
Use the Edit tool with the absolute auto-memory path from the conversation context to update these roster lines in MEMORY.md — they must stay in sync with disk state:
- Agents: doc-scribe, sw-engineer, ... (the roster line, not the path line)- Skills: review, research, ...- Rules (N): artifact-lifecycle, ... (update count N when rules are created or deleted)For content-edit operations: MEMORY.md roster update is only needed if the entity's description changed (it may appear in a MEMORY.md summary). If only internal content changed, skip this step.
Update the agent, skill, or rule tables as needed:
README.md (project root):
### Agents table — columns: | **name** | Short tagline | Key capabilities |### Skills table — columns: | **name** | \/name` | Description |`.claude/README.md (config README) — Rules table only:
| rule-file | Applies to | What it governs |All README tables are self-documenting — keep descriptions concise (one line), consistent in tone with surrounding rows. Do not add/remove table columns.
For content-edit (agent/skill): Update README only if the entity's description changed. Skip if only internal workflow/content changed.
Confirm no broken references remain:
Use the Grep tool to extract all backtick-quoted agent/skill name references (pattern `[a-z]+(-[a-z]+)+`, glob {agents/*.md,skills/*/SKILL.md}, path .claude/, output mode content).
Use Glob (agents/*.md, path .claude/) and Glob (skills/*/, path .claude/) for the on-disk inventory; extract names inline from the returned paths (strip path prefix and .md/trailing-/ suffix) for comparison.
Use Grep to search for the specific changed name and confirm:
Add rules to the on-disk inventory check: use Glob (rules/*.md, path .claude/) and extract names inline from the returned paths (strip prefix and .md suffix).
For create and update (rename) operations, also verify tool efficiency: cross-check the agent/skill's declared tools (tools: or allowed-tools:) against the tool names that actually appear in the workflow body. Any declared tool not referenced anywhere in the content should be flagged as a cleanup candidate in the Step 10 final report (report only — do not block the operation).
Run /audit to validate the created/modified file(s) and catch any issues introduced by this operation. Skip this step if invoked with --skip-audit or if the current manage operation is itself being executed as part of an audit fix run — the outer audit will cover it.
/audit
For a targeted check of only the affected file, spawn foundry:self-mentor directly:
create: audit the new file for structural completeness, cross-ref validity, and content qualityupdate: audit the renamed file and verify no stale references remaindelete: audit remaining files for broken references to the deleted nameInclude the audit findings in the final report. Do not proceed to sync if any critical findings remain.
Output a structured report containing:
create or update of an agent/skill run /calibrate <name> to baseline or verify the entity's recall and calibration after changes; for agent or skill create/update/delete also run /calibrate routing fast — any roster or description change affects routing; for perm operations confirm both settings.json and permissions-guide.md are updatedEnd your response with a ## Confidence block per CLAUDE.md output standards.
add perm and remove perm MUST update both settings.json and permissions-guide.md — they must stay in sync. Never update one without the other.README.md and rules table in .claude/README.md — keep row format consistent with existing rowsls), never manually calculated — this prevents driftname: frontmatter — the filename IS the identifier. Renames only change the file on disk and update cross-references; there is no frontmatter name: field to update.foundry:self-mentor subagents to prevent main-context inflation from large file reads and generations (200–600 line files). Rule content-edits stay inline (rule files are ≤ 80 lines). Cross-ref propagation (Step 5) delegates to foundry:self-mentor when > 3 files need updating. The subagent always returns a compact JSON envelope; the parent handles MEMORY.md (Step 6), README (Step 7), audit (Step 9), and the final report.update and delete search all four dirs in parallel (agents, skills, rules, hooks); the name is the unique identifier. If two entities share a name (rare), AskUserQuestion resolves the ambiguity..md path = content-edit. Unambiguous because names never contain spaces or end in .md./audit to verify config integrity/oss:review to validate generated content quality; for testing whether skill trigger descriptions fire correctly (trigger accuracy, A/B description testing), run /calibrate routing fast\<antipatterns_to_flag>) → /calibrate <agent> to measure whether recall and confidence calibration improved/calibrate routing fast to confirm routing accuracy is unaffectedadd perm/remove perm → confirm both settings.json and permissions-guide.md are updated; run /foundry:init to refresh ~/.claude/ settings/manage <op> → /audit → /calibrate <name> (quality) → /calibrate routing fast (routing)/manage <op> → /audit → /calibrate <name> (quality) → /calibrate routing fast (if roster changed)