一键导入
improve-crate
Safe code improvement workflow for a single crate. Creates an integration branch, analyzes code quality, and applies fixes in parallel worktrees.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Safe code improvement workflow for a single crate. Creates an integration branch, analyzes code quality, and applies fixes in parallel worktrees.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
End-to-end workflow for adding a new tree-sitter language to big-code-analysis. Wires up the grammar crate, regenerates the language enum, implements Checker/Getter/Alterator/metrics, adds per-metric tests, updates docs, then runs simplify-rust, rust-optimize, and audit-tests. Does NOT commit — leaves the working tree dirty for final user review.
Audit a Rust crate in the big-code-analysis workspace for logic errors, complexity, bugs, security issues, and code smells. Operates at the crate level via `cargo -p`. Use when asked to audit or review a crate.
Audit a single Rust source file in the big-code-analysis workspace for logic errors, complexity, bugs, security issues, and code smells. Use when asked to audit or review a specific file.
Audit naming quality in a crate or directory for misleading, inconsistent, or unclear names. Use when asked to audit or review naming.
Audit test suites for tests that pass trivially, mask bugs, or assert the wrong thing. Finds tests designed to pass rather than designed to catch regressions.
Fix multiple GitHub issues on an integration branch. Issues touching different crates run in parallel worktrees; issues sharing a crate or affecting cross-language code run sequentially. Each goes through fix, simplify, review, and remediation before merging. Use when asked to fix several issues at once.
| name | improve-crate |
| description | Safe code improvement workflow for a single crate. Creates an integration branch, analyzes code quality, and applies fixes in parallel worktrees. |
Run a safe code improvement workflow on the Rust crate $ARGUMENTS. Creates
an integration branch, analyzes the crate for improvement opportunities,
applies fixes in parallel worktrees, and integrates successful changes.
Parse $ARGUMENTS as: <crate-name> [--dry-run]
<crate-name> (required): one of big-code-analysis,
big-code-analysis-cli, big-code-analysis-web--dry-run (optional): stop after Step 2 (analysis) and print the change
areas without spawning worktree agents.rs files in the crate's directorybig-code-analysis crate, scope is src/ and tests/big-code-analysis-cli / big-code-analysis-web, scope is the
matching subdirectory's src/ and tests/lib.rs
re-exports, public traits (ParserTrait, LanguageInfo, etc.), and
public types (Metrics, FuncSpace, language enums) are off-limits
unless the user explicitly authorizes a version bumpsrc/languages/
deliberately mirror each other; any change to one usually requires the
same change to all sibling language modulesWORKSPACE_CRATES=$(cargo metadata --format-version 1 --no-deps \
| jq -r '.packages[].name' | sort | paste -sd, -)
CRATE_DIR=$(cargo metadata --format-version 1 --no-deps \
| jq -r --arg name "$CRATE_NAME" \
'.packages[] | select(.name == $name) | .manifest_path' \
| xargs dirname 2>/dev/null)
if [[ -z "$CRATE_DIR" || ! -d "$CRATE_DIR/src" ]]; then
echo "Error: crate '$CRATE_NAME' not found." >&2
echo "Valid crates: $WORKSPACE_CRATES" >&2
exit 1
fi
git status --porcelain
If dirty, abort.
git checkout -b improve/<crate-name> main
If the branch already exists from a prior partial run, check it out and continue.
PROJECT_ROOT="$(git rev-parse --show-toplevel)"
if [[ "$PROJECT_ROOT" == *".claude/worktrees/"* ]]; then
ISOLATION_MODE="worktree"
else
ISOLATION_MODE="branch"
fi
Read Serena memories via serena:read_memory:
audit-state-<crate-name> — prior audit findingscode-improvement/<crate-name> — prior improvement runsIf code-improvement/<crate-name> exists, identify reviewed-clean,
changed, and skipped symbols.
This project is itself a code-metrics tool. Use its CLI to measure the crate under improvement:
cargo build -p big-code-analysis-cli >/dev/null 2>&1
./target/debug/bca metrics -O json "$CRATE_DIR" \
> /tmp/improve-metrics.json || true
Parse the metrics output (see src/output/dump_metrics.rs and the
serializers under src/output/ for the JSON schema). Extract
improvement targets:
| Metric threshold | Improvement dimension | What to look for |
|---|---|---|
| Cyclomatic complexity > 10 | Clarity | Decompose into smaller functions |
| Cognitive complexity > 15 | Clarity | Flatten nesting, extract helpers |
| SLOC > 100 | Clarity | Split along logical seams |
| Parameters > 3 | Clarity | Consolidate into option/config structs |
| Halstead estimated bugs > 0.5 | Correctness risk | Prioritize for review |
| Maintainability Index < 10 | All dimensions | Most work needed here |
If the CLI build fails, skip this substep and proceed without metrics —
the Explore agent in 2b can still discover targets by reading files,
just less efficiently. Do NOT substitute clippy::pedantic: its style
warnings are not a substitute for cyclomatic / cognitive / Halstead
ranking and would steer the agent toward noise.
Launch a single Explore agent (subagent_type: "Explore") with the prior
state from Step 1 and the metrics target list from Step 2a.
The agent must:
get_symbols_overview on each .rs source file (fall back
to Read if unavailable).find_symbol with include_body=true (or Read with line ranges) to
read the full body. Then scan remaining symbols that look complex.From/TryFrom impls,
copy-paste patterns, helpers that should be promoted from
per-language modules to a shared locationunwrap() /
expect() / panic!() in non-test code (forbidden by project
conventions), overly long functions, pub that should be
pub(crate) (but check lib.rs re-exports first), to_string_lossy()
on identifier pathsString where &str works,
missing with_capacitysrc/languages/, ALL affected sibling language
modules are included in the same area (you cannot improve one
language module without bringing the rest along)## Change Area 1: <conventional commit message>
- file.rs: symbol_a -- <what to improve>
- file.rs: symbol_b -- <what to improve>
If --dry-run, print the change areas and stop:
"Dry run complete. N change areas identified. Re-run without --dry-run
to apply."
CRITICAL: every agent MUST be launched with isolation: "worktree".
Launch all change area agents in parallel.
All agents MUST be processed sequentially. For each change area:
BRANCH="improve/${CRATE_NAME}-area-${AREA_NUMBER}"
if git rev-parse --verify "$BRANCH" >/dev/null 2>&1; then
git branch -D "$BRANCH"
fi
git checkout -b "$BRANCH" "improve/${CRATE_NAME}"
Launch ONE Agent (NO isolation: "worktree").
On SUCCESS:
git checkout "improve/${CRATE_NAME}"
git merge "$BRANCH" --no-edit
git branch -d "$BRANCH"
git checkout -- .
git reset HEAD
git checkout "improve/${CRATE_NAME}"
git branch -D "$BRANCH"
BEGIN AGENT PROMPT
You are improving code in crate <CRATE>. Your change area:
<CHANGE_AREA>
PROJECT_ROOT="$(git rev-parse --show-toplevel)"
if [[ "$PROJECT_ROOT" == *".claude/worktrees/"* ]]; then
ISOLATION_MODE="worktree"
else
ISOLATION_MODE="branch"
fi
echo "ISOLATION_MODE=$ISOLATION_MODE PROJECT_ROOT=$PROJECT_ROOT"
AGENT_BRANCH="$(git rev-parse --abbrev-ref HEAD)"
echo "AGENT_BRANCH=$AGENT_BRANCH"
HARD GATE: If AGENT_BRANCH is master, main, or HEAD (detached),
abort:
SKIPPED: Agent is on disallowed branch. AGENT_BRANCH=<branch>
BRANCH SAFETY: Do NOT switch branches.
In worktree mode: ALL file operations within PROJECT_ROOT.
If Serena MCP available, call serena:activate_project. Otherwise use
Read, Edit, Grep, Glob.
get_symbols_overview, find_symbol with
include_body=true, find_referencing_symbols before changing
anything callable externally.src/lib.rs, it is part of the published API surface. Do NOT change
its signature or behavior. Limit changes to internal implementation.src/languages/language_<X>.rs, apply the equivalent change in
every sibling language_*.rs that defines the same symbol.replace_symbol_body, insert_before_symbol,
insert_after_symbol.After your changes, run git diff HEAD and review each changed file in
full. Apply fixes directly:
Reuse:
From/TryFrom implFrom impllanguage_*.rs that could move to
src/macros/ / src/c_langs_macros/ / a shared module (follow
.claude/rules/macro-comments.md when consolidating into macros)Clarity:
unwrap(), expect(), panic!(), assert!() in non-test code →
must use ? or Result/Option (project convention forbids these
outside tests; documented invariants in expect("reason") are the
only exception)if/match → flatten with early returns or ?
(let-else and let-chains are available — edition 2024)pub items not used outside the crate → pub(crate) (but check
lib.rs re-exports first)to_string_lossy() on paths used as identifiers (use to_str()
with explicit error handling)Efficiency:
.clone() where a borrow sufficesString parameters where &str worksVec allocations where a slice or iterator would do.collect() into intermediate Vecwith_capacity() for collections built in loopsDo NOT: extract tiny helpers that obscure flow, simplify clear for
loops into unreadable iterator chains, or add lifetime annotations the
compiler infers.
cargo check -p <CRATE>
Review git diff HEAD against this checklist:
For each issue, classify:
Correctness:
None, non-UTF-8 paths,
deeply nested ASTs, pathological tree-sitter inputcargo insta test --review rather than blindly
acceptingPerformance:
Security:
to_string_lossy() on identifier pathsIf any finding requires an unsafe change (API change, data model change, public-trait change), STOP and report SKIPPED.
Run the fast per-agent gate (the canonical make pre-commit gate runs
once on the integration branch in Step 4 — do not pay its full cost per
change area):
cargo fmt --all -- --check
cargo clippy --workspace --all-targets -- -D warnings
cargo test --workspace --all-features
If validation fails:
For snapshot test changes: run cargo insta test --review and accept or
reject each snapshot deliberately. Do NOT blindly accept. If a change
shifts snapshots under tests/repositories/big-code-analysis-output/
(the integration-snapshot submodule), it is behaviour-changing: follow
the submodule discipline in AGENTS.md (accepted snapshots pushed to
the submodule remote, new submodule SHA recorded in the same commit) —
or treat the change as out of scope for this skill and SKIP, since
improvements here must stay behavior-neutral.
CURRENT_BRANCH="$(git rev-parse --abbrev-ref HEAD)"
if [ "$CURRENT_BRANCH" != "$AGENT_BRANCH" ]; then
echo "ERROR: Branch drift. Expected $AGENT_BRANCH, on $CURRENT_BRANCH"
git checkout -- .
git reset HEAD
# Report SKIPPED
fi
git status
git add <file1> <file2> ...
git commit -m "<conventional commit message>"
Commit format: <type>(<scope>): <subject>, e.g.
refactor(big-code-analysis): deduplicate operand-span helpers. (Keep
examples behavior-neutral — a change that reclassifies operators would
shift metric values and trigger the submodule discipline in 3e.)
SUCCESS (branch, commit, files, summary) or SKIPPED (reason).
END AGENT PROMPT
Branch mode: Skip the merges — integration happened inline in Step 3 — but still run the validation gate below.
git checkout improve/<crate-name>
git merge <worktree-branch-name> --no-edit
If conflict: git merge --abort and log.
After all merges (or directly, in branch mode), run make pre-commit on
the integration branch — the canonical validation gate (see "Validation
gates" in AGENTS.md; it adds udeps, doc warnings, the lint families,
the self-scan threshold gates, and make snapshot-anchors on top of the
cargo trio run in 3e). If make is unavailable, fall back to the raw
cargo gates from 3e. If it fails, bisect:
git revert -m 1 <merge-commit>
Write code-improvement/<crate-name>:
# Code Improvement: <crate-name>
last_run: YYYY-MM-DD
integration_branch: improve/<crate-name>
## Reviewed (clean)
- file.rs: symbols X, Y, Z -- no issues found (YYYY-MM-DD)
## Changed
- file.rs: symbols A, B -- commit <hash> (YYYY-MM-DD)
- <one-line summary>
## Skipped
- file.rs: symbol C -- reason: <why> (YYYY-MM-DD)
Update audit-state-<crate-name> so improved files are marked re-audited
at depth full.
## Crate Improvement: <crate-name>
Branch: improve/<crate-name>
### Applied
| # | Commit | Change | Files |
### Skipped
| # | Change Area | Reason |
### Statistics
- Change areas: N
- Applied: N
- Skipped: N
Remind the user: "Integration branch improve/<crate-name> is ready for
review. Merge to main when satisfied."
improve/<crate-name> into mainsrc/lib.rs without authorizationsrc/languages/Cargo.tomlgit push --force or destructive git operationsinsta snapshot updates — review each one