Code Quality Workflow
Shared communication
Apply TW plain-language and guidance rules to user-facing work. Explain terms in context; preserve the user's chosen 新人/入门/熟练/老手 level without inferred changes. 新人 and 入门 receive detailed explanations; every level receives needed and bug explanations unless the user explicitly waives that scope. Soul and prose modes never disable this baseline. Load the shared reference for task entry, level management, or explanation decisions.
Before an authorized write, use $consult-tavernweave-library with the code-quality-workflow route and record the A0 receipt. When the last acceptance gap keeps expanding, read references/finish-mode.md and freeze one visible problem plus one exit condition.
Use one state machine for code-quality work:
AUDIT -> SWEEP -> GATE -> CHANGE -> VERIFY
| | | | |
+--------+--------+--------+---------+--> REPORT / STOP
Skip SWEEP for a focused target. Stop after any read-only state when the request is only for analysis. Never treat a cleanup request as permission to edit.
Non-negotiable rules
- Prefer the simplest maintainable solution, the fewest changed files, the fewest new abstractions, and the fewest dependencies.
- Start in
AUDIT and remain read-only for review, audit, sweep, diagnosis, cleanup, slimming, or optimization requests that do not explicitly authorize implementation.
- Treat
fix, apply, implement, or equivalent language as authorization only for the named scope. Still complete GATE before editing.
- Do not mix unrelated findings, formatting churn, dependency upgrades, renames, feature work, or opportunistic cleanup into a patch.
- A rewrite is a hard stop. Emit
Rewrite Requires Approval, provide evidence and a separate plan, and do not begin the rewrite in the same pass. Continue only after the user approves that plan explicitly.
- Preserve existing project instructions, write channels, generated-file rules, release boundaries, and manual acceptance gates.
- State unavailable checks and uncertain deletion safety as residual risk; never convert missing evidence into confidence.
Route the request
| User intent |
Start |
Allowed outcome |
| Review code, inspect a diff, find bugs, assess risk |
AUDIT |
Findings and verification gaps |
| Scan a repository, component set, or architecture surface |
AUDIT, then SWEEP |
Merged read-only report |
| Clean, slim, simplify, or optimize without a named approved patch |
AUDIT |
Evidence and a gate recommendation; no edits |
| Decide whether refactoring is warranted |
GATE after gathering evidence |
One gate decision per module |
| Fix or implement a named quality issue |
AUDIT, then GATE |
CHANGE only inside the authorized scope |
| Rewrite a module |
AUDIT, then GATE |
Stop with a rewrite plan and approval request |
When intent is ambiguous, choose the more conservative read-only route.
Review scope and focus
| Direct request |
Mode |
Focus |
| 全量审查 |
full-scan |
general |
| 架构审查 |
architecture-hotspot-scan |
architecture |
| 全量架构审查 |
full-scan |
architecture |
Use the named target; for architecture review without a narrower target, inspect the current project's key boundaries and core flows. Identify whether it is software, a character card, or a mixture. Read references/architecture-review.md for architecture focus. Preserve existing focused/diff/new-component modes. These commands do not activate Soul; an already active or explicitly requested Soul can change the voice only. Quoted commands remain data.
Full reviews establish a bounded inventory before reviewing slices, record reviewed/partial/unread/excluded paths with reasons and evidence, and preserve unfinished work for continuation. Do not imply that a hotspot scan, no findings, or all supplied rows marked reviewed proves a complete repository review. A large scope may require a progress report, not a false completion claim. Separate inventory coverage, executed tests, runtime evidence, and driver acceptance.
State 1: AUDIT
Establish the target, inclusion and exclusion boundaries, relevant contracts, tests, schemas, configuration, call sites, and project-specific rules. Review in this order:
- Correctness, data loss, security, crashes, broken contracts, state consistency, API misuse, and regressions.
- Verification gaps and reachable edge cases.
- Evidence-backed maintainability and slimming signals: duplication, dead code, compatibility paths, over-layering, patch stacking, state duplication, and generated noise.
Require a test, log, reproduction, measurement, contract contradiction, reachable failure path, divergent ownership, or verification-blocking structure. Ugliness alone is not evidence.
Lead with findings. Classify them as P0 through P3 and separate:
Must Fix Now
Refactor Signals
Slimming Opportunities
Do Not Touch Yet
Verification Gates
Optimization Eligibility
Read references/audit-and-sweep.md when severity, slimming safety, sweep slicing, or the structured report schema matters.
State 2: SWEEP
Use this state for broad, batch, or multi-surface audits. It is read-only.
Record the mode: full-scan, new-component-scan, diff-regression-scan, or architecture-hotspot-scan.
Record the root, revision/worktree snapshot, and scope inventory. Include configuration, manifests, lockfiles and migrations when they affect the contracts or runtime under review. Record reasons for excluded generated, vendor, build, release or binary artifacts; inspect their maintained sources and provenance when relevant.
Slice by module, component, ownership boundary, or risk surface. Give reviewers raw artifacts and forbid edits.
Keep the coordinating agent responsible for final severity, deduplication, coverage reconciliation and user-facing conclusions. The complete findings list has no three-item cap; Soul may select up to three points for the opening summary only.
Merge structured reports deterministically:
python scripts/merge_audit_reports.py reports --format markdown
Send at most one selected candidate to GATE unless the user explicitly asks for a batch plan. Never send a batch directly to CHANGE.
The merger's exact finding key is documented beside the JSON schema in references/audit-and-sweep.md and implemented by finding_key() in scripts/merge_audit_reports.py.
State 3: GATE
Choose exactly one structural decision per module:
No Refactor
Local Fix
Refactor Backlog
Rewrite Candidate
Then choose exactly one execution decision:
Reject Optimization
Local Fix Only
Staged Refactor
Rewrite Requires Approval
Before allowing CHANGE, require all of the following:
- concrete evidence;
- an explicit behavior contract;
- the smallest safe next step;
- expected and forbidden files;
- a patch budget;
- a pre-change baseline;
- a verification gate;
- deletion safety when removal is involved;
- stop and rollback conditions;
- user authorization for the proposed implementation scope.
Default budgets are:
Local Fix Only: one behavior path, normally 1-2 files, target under 80 changed lines.
Staged Refactor: one module boundary per stage, target under 200 changed lines, external behavior unchanged, rollback path stated.
Rewrite Requires Approval: no patch. Stop and request approval for the separate rewrite plan.
Budgets are review signals, not permission to expand. Split or re-gate work that exceeds them. Read references/gate-change-verify.md for threshold matrices, behavior-contract fields, deletion gates, and stop rules.
State 4: CHANGE
Enter only after GATE permits the change and the user has authorized that exact scope.
Run the lowest relevant pre-change check, or record why it cannot run.
Apply one minimal change to one behavior path or approved module boundary.
Obey the scope lock: do not touch forbidden files or widen APIs, schemas, formats, routes, persisted data, compatibility paths, or dependencies unless the behavior contract names the change.
Before deleting code, check direct and dynamic references, routes, configuration, feature flags, plugin registries, exports, tests, docs, schemas, migrations, and generated ownership.
Inspect the actual patch scope:
Use the preset selected by GATE:
python scripts/check_patch_scope.py --preset local-fix --fail-on-warning
python scripts/check_patch_scope.py --preset staged-refactor --fail-on-warning
Run only the command that matches the approved execution decision.
Default live mode compares tracked files against HEAD, so staged and unstaged changes are combined in one view, and it also includes untracked files. In an unborn repository it safely combines staged and unstaged tracked churn instead of requiring HEAD. Use --staged for an index-only diagnostic check. Binary files remain in file counts but have unknown line churn and therefore produce a warning. Use --no-untracked only to omit untracked files from the default tracked comparison; the output records that reduced coverage. A final patch-budget pass must use the full default view: never omit staged, unstaged, or untracked changes merely because a user asks to ignore them. Reduced views cannot prove the final patch is in budget.
If evidence, contract, root cause, or required scope changes, stop and return to GATE.
State 5: VERIFY
Run the smallest meaningful check first and escalate only as the risk requires:
- Re-run the pre-change check or focused regression test.
- Run any required build, lint, static analysis, integration, runtime, or manual acceptance gate.
- Review the final diff using the
AUDIT rules.
- Re-run
check_patch_scope.py against the final patch.
- Separate pre-existing failures from failures caused by the patch.
Finish only when the evidence is addressed or explicitly deferred, the behavior contract remains true, required checks pass or gaps are named, the patch remains authorized and in budget, and the diff contains no unplanned churn.
If verification fails:
- narrow or roll back when the patch worsens the baseline;
- return to
AUDIT when the root cause is unclear;
- return to
GATE when the fix becomes an architecture decision;
- stop when a rewrite, new authority, or broader scope is required.
Report contract
Keep the required report fields and full evidence, while explaining each technical label in the current task's terms. Lead with what the issue does to the user or project, then show the supporting evidence, fix and checks. At every guidance level, explain bugs and necessary decisions in detail unless the user explicitly waives that scope; a brief summary never replaces the required findings or uncertainty.
For a read-only request, report:
Routing Decision
Findings
Refactor or Slimming Signals
Do Not Touch Yet
Verification Gaps
Gate Recommendation
Residual Risk
Include scope/focus, coverage and remaining paths for sweeps. If prose refinement is active, improve wording without deleting findings, evidence, severity, mandatory fields or untested boundaries. Persist reports only through the project's authorized output channel; read-only review does not authorize source edits.
For an authorized change, report:
Evidence and Gate Decision
Behavior Contract
Authorized Scope and Patch Budget
Pre-change Baseline
Change Summary
Verification Results
Final Scope Check
Residual Risk or Stop Reason
Never claim completion from document quality or static validation alone when the behavior requires runtime or manual acceptance.
Resources
- Read references/audit-and-sweep.md for taxonomy, deletion-safety review, sweep prompts, report schema, and deterministic merge rules.
- Read references/gate-change-verify.md for gate thresholds, behavior contracts, patch budgets, execution controls, and rollback rules.
- Use
scripts/merge_audit_reports.py to merge JSON audit slices.
- Use
scripts/check_patch_scope.py to inspect tracked, untracked, and binary patch scope.
- Run
python -m unittest discover -s tests -v from this skill directory for the bundled script checks.
1---2name: code-quality-workflow3description: End-to-end code quality workflow for evidence-backed code review, full repository reviews, architecture reviews of software and character-card systems, refactor decisions, authorized minimal changes, and verification. Use for 全量审查、架构审查、全量架构审查, code or diff audits, cleanup triage, or a scoped quality fix. Preserve coverage gaps and keep audit-only requests read-only.4---56# Code Quality Workflow78<!-- tw-guidance-entry:begin -->9## Shared communication1011Apply [TW plain-language and guidance rules](../consult-tavernweave-library/references/communication-and-guidance.md) to user-facing work. Explain terms in context; preserve the user's chosen 新人/入门/熟练/老手 level without inferred changes. 新人 and 入门 receive detailed explanations; every level receives needed and bug explanations unless the user explicitly waives that scope. Soul and prose modes never disable this baseline. Load the shared reference for task entry, level management, or explanation decisions.12<!-- tw-guidance-entry:end -->1314Before an authorized write, use `$consult-tavernweave-library` with the `code-quality-workflow` route and record the A0 receipt. When the last acceptance gap keeps expanding, read [references/finish-mode.md](references/finish-mode.md) and freeze one visible problem plus one exit condition.1516Use one state machine for code-quality work:1718```text19AUDIT -> SWEEP -> GATE -> CHANGE -> VERIFY20 | | | | |21 +--------+--------+--------+---------+--> REPORT / STOP22```2324Skip `SWEEP` for a focused target. Stop after any read-only state when the request is only for analysis. Never treat a cleanup request as permission to edit.2526## Non-negotiable rules27281. Prefer the simplest maintainable solution, the fewest changed files, the fewest new abstractions, and the fewest dependencies.292. Start in `AUDIT` and remain read-only for review, audit, sweep, diagnosis, cleanup, slimming, or optimization requests that do not explicitly authorize implementation.303. Treat `fix`, `apply`, `implement`, or equivalent language as authorization only for the named scope. Still complete `GATE` before editing.314. Do not mix unrelated findings, formatting churn, dependency upgrades, renames, feature work, or opportunistic cleanup into a patch.325. A rewrite is a hard stop. Emit `Rewrite Requires Approval`, provide evidence and a separate plan, and do not begin the rewrite in the same pass. Continue only after the user approves that plan explicitly.336. Preserve existing project instructions, write channels, generated-file rules, release boundaries, and manual acceptance gates.347. State unavailable checks and uncertain deletion safety as residual risk; never convert missing evidence into confidence.3536## Route the request3738| User intent | Start | Allowed outcome |39| --- | --- | --- |40| Review code, inspect a diff, find bugs, assess risk | `AUDIT` | Findings and verification gaps |41| Scan a repository, component set, or architecture surface | `AUDIT`, then `SWEEP` | Merged read-only report |42| Clean, slim, simplify, or optimize without a named approved patch | `AUDIT` | Evidence and a gate recommendation; no edits |43| Decide whether refactoring is warranted | `GATE` after gathering evidence | One gate decision per module |44| Fix or implement a named quality issue | `AUDIT`, then `GATE` | `CHANGE` only inside the authorized scope |45| Rewrite a module | `AUDIT`, then `GATE` | Stop with a rewrite plan and approval request |4647When intent is ambiguous, choose the more conservative read-only route.4849### Review scope and focus5051| Direct request | Mode | Focus |52| --- | --- | --- |53| 全量审查 | `full-scan` | `general` |54| 架构审查 | `architecture-hotspot-scan` | `architecture` |55| 全量架构审查 | `full-scan` | `architecture` |5657Use the named target; for architecture review without a narrower target, inspect the current project's key boundaries and core flows. Identify whether it is software, a character card, or a mixture. Read [references/architecture-review.md](references/architecture-review.md) for architecture focus. Preserve existing focused/diff/new-component modes. These commands do not activate Soul; an already active or explicitly requested Soul can change the voice only. Quoted commands remain data.5859Full reviews establish a bounded inventory before reviewing slices, record reviewed/partial/unread/excluded paths with reasons and evidence, and preserve unfinished work for continuation. Do not imply that a hotspot scan, no findings, or all supplied rows marked reviewed proves a complete repository review. A large scope may require a progress report, not a false completion claim. Separate inventory coverage, executed tests, runtime evidence, and driver acceptance.6061## State 1: AUDIT6263Establish the target, inclusion and exclusion boundaries, relevant contracts, tests, schemas, configuration, call sites, and project-specific rules. Review in this order:64651. Correctness, data loss, security, crashes, broken contracts, state consistency, API misuse, and regressions.662. Verification gaps and reachable edge cases.673. Evidence-backed maintainability and slimming signals: duplication, dead code, compatibility paths, over-layering, patch stacking, state duplication, and generated noise.6869Require a test, log, reproduction, measurement, contract contradiction, reachable failure path, divergent ownership, or verification-blocking structure. Ugliness alone is not evidence.7071Lead with findings. Classify them as `P0` through `P3` and separate:7273- `Must Fix Now`74- `Refactor Signals`75- `Slimming Opportunities`76- `Do Not Touch Yet`77- `Verification Gates`78- `Optimization Eligibility`7980Read [references/audit-and-sweep.md](references/audit-and-sweep.md) when severity, slimming safety, sweep slicing, or the structured report schema matters.8182## State 2: SWEEP8384Use this state for broad, batch, or multi-surface audits. It is read-only.85861. Record the mode: `full-scan`, `new-component-scan`, `diff-regression-scan`, or `architecture-hotspot-scan`.872. Record the root, revision/worktree snapshot, and scope inventory. Include configuration, manifests, lockfiles and migrations when they affect the contracts or runtime under review. Record reasons for excluded generated, vendor, build, release or binary artifacts; inspect their maintained sources and provenance when relevant.883. Slice by module, component, ownership boundary, or risk surface. Give reviewers raw artifacts and forbid edits.894. Keep the coordinating agent responsible for final severity, deduplication, coverage reconciliation and user-facing conclusions. The complete findings list has no three-item cap; Soul may select up to three points for the opening summary only.905. Merge structured reports deterministically:9192 ```powershell93 python scripts/merge_audit_reports.py reports --format markdown94 ```95966. Send at most one selected candidate to `GATE` unless the user explicitly asks for a batch plan. Never send a batch directly to `CHANGE`.9798The merger's exact finding key is documented beside the JSON schema in [references/audit-and-sweep.md](references/audit-and-sweep.md) and implemented by `finding_key()` in `scripts/merge_audit_reports.py`.99100## State 3: GATE101102Choose exactly one structural decision per module:103104- `No Refactor`105- `Local Fix`106- `Refactor Backlog`107- `Rewrite Candidate`108109Then choose exactly one execution decision:110111- `Reject Optimization`112- `Local Fix Only`113- `Staged Refactor`114- `Rewrite Requires Approval`115116Before allowing `CHANGE`, require all of the following:117118- concrete evidence;119- an explicit behavior contract;120- the smallest safe next step;121- expected and forbidden files;122- a patch budget;123- a pre-change baseline;124- a verification gate;125- deletion safety when removal is involved;126- stop and rollback conditions;127- user authorization for the proposed implementation scope.128129Default budgets are:130131- `Local Fix Only`: one behavior path, normally 1-2 files, target under 80 changed lines.132- `Staged Refactor`: one module boundary per stage, target under 200 changed lines, external behavior unchanged, rollback path stated.133- `Rewrite Requires Approval`: no patch. Stop and request approval for the separate rewrite plan.134135Budgets are review signals, not permission to expand. Split or re-gate work that exceeds them. Read [references/gate-change-verify.md](references/gate-change-verify.md) for threshold matrices, behavior-contract fields, deletion gates, and stop rules.136137## State 4: CHANGE138139Enter only after `GATE` permits the change and the user has authorized that exact scope.1401411. Run the lowest relevant pre-change check, or record why it cannot run.1422. Apply one minimal change to one behavior path or approved module boundary.1433. Obey the scope lock: do not touch forbidden files or widen APIs, schemas, formats, routes, persisted data, compatibility paths, or dependencies unless the behavior contract names the change.1444. Before deleting code, check direct and dynamic references, routes, configuration, feature flags, plugin registries, exports, tests, docs, schemas, migrations, and generated ownership.1455. Inspect the actual patch scope:146147 Use the preset selected by `GATE`:148149 ```powershell150 python scripts/check_patch_scope.py --preset local-fix --fail-on-warning151 python scripts/check_patch_scope.py --preset staged-refactor --fail-on-warning152 ```153154 Run only the command that matches the approved execution decision.155156 Default live mode compares tracked files against `HEAD`, so staged and unstaged changes are combined in one view, and it also includes untracked files. In an unborn repository it safely combines staged and unstaged tracked churn instead of requiring `HEAD`. Use `--staged` for an index-only diagnostic check. Binary files remain in file counts but have unknown line churn and therefore produce a warning. Use `--no-untracked` only to omit untracked files from the default tracked comparison; the output records that reduced coverage. A final patch-budget pass must use the full default view: never omit staged, unstaged, or untracked changes merely because a user asks to ignore them. Reduced views cannot prove the final patch is in budget.1576. If evidence, contract, root cause, or required scope changes, stop and return to `GATE`.158159## State 5: VERIFY160161Run the smallest meaningful check first and escalate only as the risk requires:1621631. Re-run the pre-change check or focused regression test.1642. Run any required build, lint, static analysis, integration, runtime, or manual acceptance gate.1653. Review the final diff using the `AUDIT` rules.1664. Re-run `check_patch_scope.py` against the final patch.1675. Separate pre-existing failures from failures caused by the patch.168169Finish only when the evidence is addressed or explicitly deferred, the behavior contract remains true, required checks pass or gaps are named, the patch remains authorized and in budget, and the diff contains no unplanned churn.170171If verification fails:172173- narrow or roll back when the patch worsens the baseline;174- return to `AUDIT` when the root cause is unclear;175- return to `GATE` when the fix becomes an architecture decision;176- stop when a rewrite, new authority, or broader scope is required.177178## Report contract179180Keep the required report fields and full evidence, while explaining each technical label in the current task's terms. Lead with what the issue does to the user or project, then show the supporting evidence, fix and checks. At every guidance level, explain bugs and necessary decisions in detail unless the user explicitly waives that scope; a brief summary never replaces the required findings or uncertainty.181182For a read-only request, report:183184```text185Routing Decision186Findings187Refactor or Slimming Signals188Do Not Touch Yet189Verification Gaps190Gate Recommendation191Residual Risk192```193194Include scope/focus, coverage and remaining paths for sweeps. If prose refinement is active, improve wording without deleting findings, evidence, severity, mandatory fields or untested boundaries. Persist reports only through the project's authorized output channel; read-only review does not authorize source edits.195196For an authorized change, report:197198```text199Evidence and Gate Decision200Behavior Contract201Authorized Scope and Patch Budget202Pre-change Baseline203Change Summary204Verification Results205Final Scope Check206Residual Risk or Stop Reason207```208209Never claim completion from document quality or static validation alone when the behavior requires runtime or manual acceptance.210211## Resources212213- Read [references/audit-and-sweep.md](references/audit-and-sweep.md) for taxonomy, deletion-safety review, sweep prompts, report schema, and deterministic merge rules.214- Read [references/gate-change-verify.md](references/gate-change-verify.md) for gate thresholds, behavior contracts, patch budgets, execution controls, and rollback rules.215- Use `scripts/merge_audit_reports.py` to merge JSON audit slices.216- Use `scripts/check_patch_scope.py` to inspect tracked, untracked, and binary patch scope.217- Run `python -m unittest discover -s tests -v` from this skill directory for the bundled script checks.