name: quality-loop description: "Use when asked to review, audit, inspect quality, clean, fix, refactor, de-risk, or improve code in either scope: diff | entire codebase. Audits correctness/security/tests/DRY/simplicity/refactor/dead-code/perf/docs/frontend/deps quality and optionally fixes/refactors safely when fix_mode permits."
quality-loop — audit, triage, and gated fix/refactor pipeline
One Workflow-backed entry point for code-quality loops. It can review a diff or an entire codebase, normalize findings across specialist lanes, verify them adversarially, then either report, plan, or apply only safe/approved fixes.
When NOT to use
- You only need a commit, push, PR, or release operation. Human/operator owns commit and push.
- You need to delete old skills or wire OPS routing. This skill may recommend that later; it does not do it.
- You need product execution unrelated to quality findings. Use the normal implementation workflow first, then run this.
Parameters
Pass JSON via args:
| param | required | values |
|---|---|---|
scope |
yes | diff or codebase |
target |
no | repo/subdir; default . |
base |
no | diff base/ref; default HEAD |
depth |
no | quick, standard, deep; caps units, never quality classes |
classes |
no | subset of classes; default all |
fix_mode |
no | report default, plan, apply-safe, apply-approved |
fix_budget |
no | max fix waves/items |
include / exclude |
no | globs |
uiTarget / routes |
no | enables frontend_runtime |
out |
no | report path |
Quality classes: correctness, security, test_integrity, duplication_dry, simplicity, refactor_opportunity, architecture_fit, dead_code, performance, deps_secrets, docs_contracts, frontend_runtime, and code-review-and-quality calibrator.
Progressive references
Load these only when needed:
references/lane-prompts.md— per-class prompt templates.references/scope-and-anchors.md— complete diff capture, anchor types, codebase unit mapping.references/fix-safety.md— auto-safe vs human-gated fixes, over-fix guard, revert-on-red, OPS composability.references/consolidation-map.md— how this consolidates the seven older skills; do not remove them here.
Non-negotiables
scope=diffcaptures staged, unstaged, and untracked new source/test/config/doc additions; plaingit diffis insufficient.- Diff findings use anchor types:
diff_introduced,diff_modified,diff_amplified_existing_in_touched_file,diff_orphaned,diff_context_advisory. depthonly limits units/waves; it never silently drops quality classes.- Maintainability/DRY/refactor findings are peer classes; never auto-demote them to low severity.
- Mutations happen only when
fix_modeisapply-safeorapply-approved; otherwise report/plan only. - Each fix wave has a preservation contract, verification, lane re-audit, and revert-on-red.
- Exit when every verified finding is fixed+verified, refuted, deferred/wont-fix with reason, or blocked awaiting human input — not when a numeric warning target is hit.
Run it as a Workflow
export const meta = {
name: 'quality-loop',
description: 'Unified quality loop for scope=diff or scope=codebase: intake/snapshot -> resolve work-set -> prioritize without dropping classes -> parallel quality lanes -> normalize/dedupe -> tiered adversarial verify -> triage -> fix-plan -> gated apply -> reverify/re-audit/revert-on-red -> convergence report.',
phases: [
{ title: '0 Intake' },
{ title: '1 Work-set' },
{ title: '2 Prioritize' },
{ title: '3 Audit lanes' },
{ title: '4 Normalize' },
{ title: '5 Verify' },
{ title: '6 Triage' },
{ title: '7 Fix plan' },
{ title: '8 Apply' },
{ title: '9 Reverify' },
{ title: '10 Converge' },
],
}
const A = (typeof args === 'string') ? (() => { try { return JSON.parse(args) } catch (_) { return {} } })() : (args || {})
const scope = A.scope
if (!['diff', 'codebase'].includes(scope)) throw new Error('quality-loop requires args.scope = "diff" or "codebase"')
const target = (typeof A.target === 'string' && A.target) || '.'
const base = (typeof A.base === 'string' && A.base) || 'HEAD'
const depth = ['quick', 'standard', 'deep'].includes(A.depth) ? A.depth : 'standard'
const fixMode = ['report', 'plan', 'apply-safe', 'apply-approved'].includes(A.fix_mode) ? A.fix_mode : 'report'
const fixBudget = Number.isFinite(A.fix_budget) ? A.fix_budget : (depth === 'quick' ? 1 : depth === 'deep' ? 8 : 3)
const include = Array.isArray(A.include) ? A.include : []
const exclude = Array.isArray(A.exclude) ? A.exclude : []
const uiTarget = (typeof A.uiTarget === 'string' && A.uiTarget) || (typeof A.appUrl === 'string' && A.appUrl) || ''
const routes = Array.isArray(A.routes) ? A.routes : []
const out = (typeof A.out === 'string' && A.out) || null
const UNIT_CAP = depth === 'quick' ? 8 : depth === 'deep' ? 40 : 18
const APPLYING = fixMode === 'apply-safe' || fixMode === 'apply-approved'
const ANCHOR_TYPES = ['diff_introduced', 'diff_modified', 'diff_amplified_existing_in_touched_file', 'diff_orphaned', 'diff_context_advisory', 'codebase_unit']
const ALL_LANES = [
{ key: 'correctness', agentType: 'code-reviewer', focus: 'logic errors, broken invariants, boundary cases, data-flow regressions, concurrency/state mistakes' },
{ key: 'security', agentType: 'security-reviewer', focus: 'auth/authz gaps, injection, XSS/CSRF, secrets/PII exposure, unsafe file/network/database flows' },
{ key: 'test_integrity', agentType: 'quinn', focus: 'missing or weakened tests, superficial assertions, mocked-away behavior, flaky or non-deterministic verification' },
{ key: 'duplication_dry', agentType: 'architect', focus: 'costly duplication and structural sync risks; DRY is peer severity, not a nit bucket' },
{ key: 'simplicity', agentType: 'architect', focus: 'cleverness, unnecessary abstractions, excessive indirection, bloated control flow, poor naming/locality' },
{ key: 'refactor_opportunity', agentType: 'refactor-cleaner', focus: 'safe refactor opportunities, extraction/consolidation candidates, shallow modules, adapter/seam cleanup' },
{ key: 'architecture_fit', agentType: 'architect', focus: 'module boundaries, layering, project conventions, ADR/CONTEXT/CLAUDE.md fit, dependency direction' },
{ key: 'dead_code', agentType: 'refactor-cleaner', focus: 'introduced unused code, orphaned code, stale imports/exports/deps, dead branches; prove attribution and safety' },
{ key: 'performance', agentType: 'code-reviewer', focus: 'unbounded work, N+1, expensive hot paths, avoidable renders, sync I/O, memory/cache risks' },
{ key: 'deps_secrets', agentType: 'security-reviewer', focus: 'dependency posture, risky manifests/config, lockfile/dependency drift, hardcoded credentials or secret handling' },
{ key: 'docs_contracts', agentType: 'code-reviewer', focus: 'API/schema/CLI/config/docs/test-fixture contract drift, stale README/SOP expectations, migration or route contract mismatch' },
{ key: 'react_best_practices', agentType: 'code-reviewer', focus: 'FRONT-END ONLY — first classify whether this unit is React/front-end; if not, return findings=[] with note "react_best_practices skipped: non-frontend". If it is, use the installed vercel-react-best-practices skill as a read-only checklist for React-IDIOMATIC issues — especially STATE: derived/computed values wrongly stored in state, effects used to derive state, and complex stateful logic that should be extracted into a custom hook; plus effect-dependency correctness, hooks-rules violations, list/key usage, and avoidable re-renders. Framework-aware: skip Next.js / React Server Components / server-only rules for a Vite/SPA. This lane does NOT handle generic duplication (that is duplication_dry).' },
{ key: 'frontend_runtime', agentType: 'ui-reviewer', focus: 'runtime UI route checks: console/network errors, accessibility, CLS/perf, screenshots; conditional on uiTarget/routes' },
{ key: 'code-review-and-quality', agentType: 'code-reviewer', focus: 'independent calibrator using five axes: correctness, readability/simplicity, architecture, security, performance, plus verify-the-verification' },
]
const requestedClasses = Array.isArray(A.classes) && A.classes.length ? A.classes : ALL_LANES.map((l) => l.key)
const lanes = ALL_LANES.filter((l) => requestedClasses.includes(l.key))
const staticLanes = lanes.filter((l) => l.key !== 'frontend_runtime')
const runtimeLane = lanes.find((l) => l.key === 'frontend_runtime')
const FINDINGS_SCHEMA = {
type: 'object', additionalProperties: false,
properties: {
findings: { type: 'array', items: { type: 'object', additionalProperties: false,
properties: {
id: { type: 'string' }, class: { type: 'string' }, lane: { type: 'string' },
anchorType: { type: 'string', enum: ANCHOR_TYPES }, file: { type: 'string' }, line: { type: 'string' },
severity: { type: 'string', enum: ['critical', 'high', 'medium', 'low'] },
confidence: { type: 'string', enum: ['high', 'medium', 'low'] },
title: { type: 'string' }, evidence: { type: 'string' }, detail: { type: 'string' },
suggestedFix: { type: 'string' }, verificationNeeded: { type: 'string' }, auditUnit: { type: 'string' },
laneProvenance: { type: 'array', items: { type: 'string' } }, falsePositiveRisks: { type: 'array', items: { type: 'string' } },
fixability: { type: 'string', enum: ['auto-safe', 'human-gated', 'report-only', 'unknown'] },
}, required: ['id', 'class', 'lane', 'anchorType', 'file', 'line', 'severity', 'confidence', 'title', 'evidence', 'detail', 'suggestedFix', 'verificationNeeded', 'auditUnit', 'laneProvenance', 'falsePositiveRisks', 'fixability'] } },
note: { type: 'string' },
}, required: ['findings', 'note'],
}
const WORKSET_SCHEMA = {
type: 'object', additionalProperties: false,
properties: {
units: { type: 'array', items: { type: 'object', additionalProperties: false,
properties: {
id: { type: 'string' }, title: { type: 'string' }, kind: { type: 'string' },
paths: { type: 'array', items: { type: 'string' } }, changedPaths: { type: 'array', items: { type: 'string' } },
contextPaths: { type: 'array', items: { type: 'string' } }, risk: { type: 'string', enum: ['critical', 'high', 'medium', 'low'] },
riskReasons: { type: 'array', items: { type: 'string' } }, frontend: { type: 'boolean' },
}, required: ['id', 'title', 'kind', 'paths', 'changedPaths', 'contextPaths', 'risk', 'riskReasons', 'frontend'] } },
completeDiffPath: { type: 'string' }, completeDiffSummary: { type: 'string' }, note: { type: 'string' },
}, required: ['units', 'completeDiffPath', 'completeDiffSummary', 'note'],
}
const VERIFY_SCHEMA = { type: 'object', additionalProperties: false, properties: { refuted: { type: 'boolean' }, reason: { type: 'string' } }, required: ['refuted', 'reason'] }
const TRIAGE_SCHEMA = { type: 'object', additionalProperties: false, properties: { disposition: { type: 'string', enum: ['auto-safe', 'human-gated', 'report-only', 'wont-fix-with-reason', 'blocked'] }, reason: { type: 'string' }, approvalNeeded: { type: 'string' } }, required: ['disposition', 'reason', 'approvalNeeded'] }
const PLAN_SCHEMA = { type: 'object', additionalProperties: false, properties: { plan: { type: 'string' }, preservationContract: { type: 'string' }, verification: { type: 'array', items: { type: 'string' } }, wave: { type: 'integer' } }, required: ['plan', 'preservationContract', 'verification', 'wave'] }
const APPLY_SCHEMA = { type: 'object', additionalProperties: false, properties: { applied: { type: 'boolean' }, changedFiles: { type: 'array', items: { type: 'string' } }, reason: { type: 'string' } }, required: ['applied', 'changedFiles', 'reason'] }
phase('0 Intake')
const snapshot = await agent(
`Snapshot ${target} for quality-loop. Read-only. Capture cwd, git root if any, branch/status, scope=${scope}, base=${base}, depth=${depth}, fix_mode=${fixMode}, include=${JSON.stringify(include)}, exclude=${JSON.stringify(exclude)}. Do not edit.`,
{ label: 'snapshot', phase: '0 Intake' }
)
phase('1 Work-set')
const workset = scope === 'diff'
? await agent(
`Resolve the COMPLETE DIFF work-set for ${target} vs base ${base}. Capture staged diff, unstaged diff, and untracked new source/test/config/doc additions using git ls-files --others --exclude-standard and git diff --no-index /dev/null <file>. Exclude noise dirs (.git, node_modules, dist, build, coverage, .next, out, caches). Build bounded change units with changedPaths/contextPaths. Use diff anchors: diff_introduced, diff_modified, diff_amplified_existing_in_touched_file, diff_orphaned, diff_context_advisory. Pre-existing debt in a touched file may surface only as diff_amplified_existing_in_touched_file; unrelated whole-repo debt is advisory only.`,
{ label: 'workset:diff', phase: '1 Work-set', schema: WORKSET_SCHEMA }
)
: await agent(
`Map ${target} into bounded audit units for a whole-codebase quality loop. Include route+service+model+tests, frontend route+components+hooks+tests, auth seams, db/migration clusters, jobs/workers, config/security sets, and docs/contracts seams. Be complete but shallow; exclude noise dirs. Findings will use anchorType=codebase_unit.`,
{ label: 'workset:codebase', phase: '1 Work-set', schema: WORKSET_SCHEMA }
)
const allUnits = (workset && workset.units) || []
log(`Resolved ${allUnits.length} work unit(s); active classes: ${lanes.map((l) => l.key).join(', ')}`)
phase('2 Prioritize')
const ranked = await agent(
`Risk-rank these ${scope} units WITHOUT dropping any requested quality class. Depth may cap unit count only. Signals: user-facing/auth/PII, network/db/filesystem side effects, changed size/churn, sparse tests, dependency/config sensitivity, frontend/runtime surface, docs/API contract sensitivity, and project-critical paths. Return same units ordered with risk reasons.\n\nUNITS:\n${JSON.stringify(allUnits)}`,
{ label: 'prioritize', phase: '2 Prioritize', schema: WORKSET_SCHEMA }
)
const ordered = (ranked && ranked.units && ranked.units.length) ? ranked.units : allUnits
const selected = ordered.slice(0, UNIT_CAP)
const deferred = ordered.slice(UNIT_CAP)
const ledger = { scope, depth, unitCap: UNIT_CAP, discovered: ordered.length, reviewed: selected.length, deferred: deferred.length, classes: lanes.map((l) => l.key), fixMode, fixBudget }
log(`Selected ${selected.length}/${ordered.length} unit(s); ${deferred.length} deferred by depth cap only.`)
phase('3 Audit lanes')
const staticFindings = (await parallel(selected.map((u) => () =>
parallel(staticLanes.map((lane) => () =>
agent(
`Quality-loop lane=${lane.key} class=${lane.key} over unit "${u.title}" (${scope}). Focus: ${lane.focus}. Read relevant files only. Evidence-first: cite file:line/hunk/runtime observation. For diff scope, every graded finding must use one of the five diff anchor types and explain attribution; use diff_context_advisory for nearby/out-of-scope context only. For codebase scope, use anchorType=codebase_unit. DRY/simplicity/refactor are peer classes and may be high severity when they create real maintenance or sync risk. Return findings=[] if unsupported.`,
{ agentType: lane.agentType, label: `${lane.key}:${u.id || u.title}`, phase: '3 Audit lanes', schema: FINDINGS_SCHEMA }
)
)).then((rs) => rs.filter(Boolean).flatMap((r) => r.findings || []))
))).flat()
let runtimeFindings = []
if (runtimeLane && uiTarget) {
const rt = await agent(
`frontend_runtime lane for ${uiTarget}; routes=${routes.length ? routes.join(', ') : 'infer affected key routes'}. Use browser/devtools diagnostics only on dev/fixture data: console, network, a11y, CLS/perf, screenshots. Fail-soft if target/tooling unavailable. Return same finding schema with class=frontend_runtime and concrete runtime evidence.`,
{ agentType: 'ui-reviewer', label: 'frontend_runtime', phase: '3 Audit lanes', schema: FINDINGS_SCHEMA }
)
runtimeFindings = (rt && rt.findings) || []
}
const candidates = [...staticFindings, ...runtimeFindings]
phase('4 Normalize')
const normalized = candidates.length > 1 ? await agent(
`Normalize and dedupe quality-loop findings. Merge duplicates by same defect/root cause, keep highest severity, preserve all lane provenance, and set corroboration=confidence: 2+ distinct lanes => confidence high and detail mentions corroborated lanes. Do not drop distinct quality classes, especially DRY/simplicity/refactor. Keep advisory diff_context_advisory separate from graded findings.\n\nFINDINGS:\n${JSON.stringify(candidates, null, 2)}`,
{ label: 'normalize', phase: '4 Normalize', schema: FINDINGS_SCHEMA }
) : { findings: candidates, note: 'zero-or-one candidate' }
const findings = (normalized && normalized.findings) || []
phase('5 Verify')
const highCritical = findings.filter((f) => f.severity === 'critical' || f.severity === 'high')
const medium = findings.filter((f) => f.severity === 'medium')
const low = findings.filter((f) => f.severity === 'low')
const highVotes = await parallel(highCritical.map((f) => () =>
parallel([0, 1, 2].map((i) => () => agent(
`Adversarially REFUTE this critical/high finding. Default refuted=true if evidence is weak, not scope-anchored, not reproducible, already pre-existing outside scope, or unsafe to fix as proposed. For diff scope, challenge the anchor type and attribution.\n\nFINDING:\n${JSON.stringify(f)}`,
{ label: `skeptic:${f.id || f.file}:${i + 1}`, phase: '5 Verify', schema: VERIFY_SCHEMA }
))).then((votes) => ({ finding: f, votes, survives: votes.filter((v) => v && !v.refuted).length >= 2 }))
))
const medVotes = await parallel(medium.map((f) => () =>
agent(`Adversarially REFUTE this medium finding once; default refuted=true if unsupported or not scope-anchored.\n\nFINDING:\n${JSON.stringify(f)}`, { label: `skeptic-med:${f.id || f.file}`, phase: '5 Verify', schema: VERIFY_SCHEMA }).then((v) => ({ finding: f, survives: v && !v.refuted }))
))
const verified = [...highVotes.filter((v) => v && v.survives).map((v) => v.finding), ...medVotes.filter((v) => v && v.survives).map((v) => v.finding)]
const advisory = [...low, ...highVotes.filter((v) => v && !v.survives).map((v) => ({ ...v.finding, verificationStatus: 'refuted' })), ...medVotes.filter((v) => v && !v.survives).map((v) => ({ ...v.finding, verificationStatus: 'refuted' }))]
const fixerAgent = (klass) => klass === 'security' || klass === 'deps_secrets' ? 'security-reviewer' : klass === 'dead_code' || klass === 'refactor_opportunity' ? 'refactor-cleaner' : klass === 'duplication_dry' || klass === 'simplicity' || klass === 'architecture_fit' ? 'architect' : 'code-reviewer'
phase('6 Triage')
phase('7 Fix plan')
phase('8 Apply')
phase('9 Reverify')
const limited = verified.slice(0, fixBudget)
const outcomes = await parallel(limited.map((finding) => () => pipeline([finding],
() => agent(
`Triage this verified finding into exactly one disposition: auto-safe, human-gated, report-only, wont-fix-with-reason, blocked. Auto-safe is deterministic low-risk only. Human-gate security/auth/deps/schema/API/CLI/routes/cross-module DRY/architecture/test rewrites/risky dead-code.\n\nFINDING:\n${JSON.stringify(finding)}`,
{ label: `triage:${finding.id || finding.file}`, phase: '6 Triage', schema: TRIAGE_SCHEMA }
),
(triage) => agent(
`Create a fix plan for this finding and triage. Include preservation contract, expected verification, and smallest scope-bound wave. Apply over-fix guard: rule-of-three default, but allow 2-copy consolidation when structural sync risk exists (e.g. skeleton/data metadata drift). Prefer local metadata before generic helpers.\n\nFINDING:${JSON.stringify(finding)}\nTRIAGE:${JSON.stringify(triage)}`,
{ label: `fix-plan:${finding.id || finding.file}`, phase: '7 Fix plan', schema: PLAN_SCHEMA }
),
(plan) => APPLYING ? agent(
`Apply stage for fix_mode=${fixMode}. Mutate ONLY if allowed: apply-safe requires the finding triage to be auto-safe; apply-approved requires explicit approval evidence in args. Keep scope-bound, no dependency changes unless explicitly approved, no staging/commit/push. If not allowed, return applied=false.\n\nFINDING:${JSON.stringify(finding)}\nPLAN:${JSON.stringify(plan)}`,
{ agentType: fixerAgent(finding.class), label: `apply:${finding.id || finding.file}`, phase: '8 Apply', schema: APPLY_SCHEMA }
) : ({ applied: false, changedFiles: [], reason: `fix_mode=${fixMode}; report/plan only` }),
(applied) => agent(
`Reverify this finding after the apply stage. If applied=true, run the plan's verification, re-audit the changed unit with the relevant lane(s), and revert this wave on red if a safe immediate fix is not available. If applied=false, mark as dispositioned but unfixed with reason.\n\nFINDING:${JSON.stringify(finding)}\nAPPLY:${JSON.stringify(applied)}`,
{ label: `reverify:${finding.id || finding.file}`, phase: '9 Reverify' }
),
)))
phase('10 Converge')
const convergence = await agent(
`Synthesize the quality-loop result to ${out ? out : 'a fresh temp report path'}. Exit condition: no verified finding is undispositioned. Every verified finding must be fixed+verified, refuted, deferred/wont-fix with reason, report-only with reason, or blocked awaiting human input. Do NOT use a numeric zero-warning target. Include coverage ledger, class coverage, scope anchors, verified findings, advisory/refuted items, fix outcomes, changed files, verification run, deferred units, and close-gate verdict. Commit/push remain human-owned.\n\nSNAPSHOT:${JSON.stringify(snapshot)}\nLEDGER:${JSON.stringify(ledger)}\nVERIFIED:${JSON.stringify(verified)}\nADVISORY:${JSON.stringify(advisory)}\nOUTCOMES:${JSON.stringify(outcomes)}`,
{ label: 'converge', phase: '10 Converge' }
)
return {
scope, depth, fixMode, coverage: ledger,
candidateFindings: candidates.length,
normalizedFindings: findings.length,
verifiedFindings: verified.length,
advisoryOrRefuted: advisory.length,
fixOutcomes: outcomes,
deferredUnits: deferred.map((u) => u.title || u.id),
convergence,
}
If Workflow is unavailable, run the same stages sequentially, keep the same schemas/anchor rules, and state that parallel fan-out was unavailable.