/tea-rags:architecture-diagnostics [scope — pathPattern, subsystem, or 'whole project']from tea-rags
Diagnoses structural violations in codebases for architecture audits or refactoring. Assesses dependency/layer violations, coupling, and move candidates using a phased workflow with codegraph reports.
Ships in tea-rags. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Question: laid out right? NOT: dangerous to touch? (→ risk-assessment).
Activation gate — before metrics, references or reports. Run only for an
explicit request to diagnose/audit architecture, an explicit invocation of this
skill, or a structural-refactoring task. Never activate to gather context for
another task. Explaining how a subsystem is organized or which contracts assume
OAuth is source investigation, not a diagnostic request, even when it mentions
architecture, boundaries or abstractions. Use the relevant source bodies/edges
instead; do not load this workflow's references or call
get_architecture_report.
Lag ≠ unusable: changedFiles / pendingFiles / drift never license cat
/ grep / Read over code — tea-rags://guide/freshness.
get_architecture_report callviolations.leakingAbstraction)violations.silentCoupling)
violations.shotgunSurgery)violations.mainSequence), then 3d2 — HUB-LIKE
DEPENDENCY (violations.hubLikeDependency)violations.layering)
review_changes architecture
findings: preExisting, remedy, repair files)layerMap)restructure call, remedies ranked by deltaFull list: references/anti-patterns.md.
violations first. N violations into one target = ONE defect.edgeCount: 0, built: false, excluded counters,
facade-not-adopted, absent layerMap = not judged / not asked — say so.maintenanceCost = fix priority only.preExisting: true = base already held it — real finding, not
diff-introduced. remedy quoted verbatim, never paraphrased.review_changes findings in hand → Phase 3h ONLY (skip Phases 0–3, no
phase-1-report.md). First open ../../repair/<family>.md of EVERY family
present (report-only too), no others; print
Repair files loaded: repair/<family>.md (## Apply remedy | ## No remedy), ….
Then one line per finding, class by name, fix now, never defer:
preExisting (absence IS the signal) →
<family> — introduced, must-fix per repair/<family>.md: <fix>. compositionRoot / Known-false-positive entry: <quoted evidence | none>. Exempt only with compositionRoot flag or ## Known false positives entry; bare "by design" is not evidence.preExisting + remedy →
<family> — cheap-preExisting per repair/<family>.md: <remedy verbatim: source, from → to, names>preExisting, no remedy → <family> — report-only, no fix
(mainSequence: distanceBefore already past threshold)island / compositionCycle / knot with composition: true =
informational, not defects.pathPattern, not re-calls with
bigger limit.!tea-rags resource "tea-rags://project/{alias}/metrics?section=resolve" --path "$PWD" || true
get_architecture_report registered? No → say "architecture report needs
codegraph", stop; NEVER claim "no violations". ## Codegraph resolve above
(none → ReadMcpResourceTool
tea-rags://project/<alias>/metrics?section=resolve) — low rate → edges
partial.
get_architecture_report(path: "<your working directory>", pathPattern?: "<glob>", limit?: 50, norms?: true,
detectors?: ["<detector>"], evidenceLimit?: 3,
layerMap?: { scopePathPattern?, granularity?: "directory"|"file", directoryDepth? })
Read references/phase-1-report.md before
reading the response — pathPattern vs domain scope, norms, tooling /
test-support removal, limit per detector (totals in summary.<detector>; more
than returned → say truncated), trimmed lists (<key>Count = full length;
next = drill call), violationDrillDownHints template, reportId paging,
costliest-first score, impact tier (lead critical, then active;
built: false ≠ structural). Findings are grouped per detector
(violations.<detector> table) — never mix groups across detectors.
SDP unit = COMPONENT: facade directory, adoption notwithstanding (any A4 status
— owns its directory subtree minus nested modules; ONE partition for SDP,
mainSequence, hubLike, layering, silentCoupling), else plain directory — Ruby
included (app/models/billing and app/services/billing are two components).
Shotgun alone groups by constant namespace path spells (::Billing — Zeitwerk
autoload: app/models/billing/* + app/services/billing/* = one), so its
spreads name ::X components. Ca/Ce = distinct files across the border.
rootCauses[] ordered by violationCount desc, then maxInstabilityDelta.
| Field | Read as |
|---|---|
targetComponent | unstable component stable components lean on |
violationCount | stable dependent components affected — severity |
targetInstability | I = Ce/(Ca+Ce); high = depends on much, few depend on it |
sources | the stable dependent components |
cycleWithDependents | target depends on own dependents → instability self-inflicted |
Root cause tier = max over member violations. Rank groups critical > active >
structural before violationCount when tiers built.
cycleWithDependents: true = strongest finding (base names subclasses, concern
its includers, registry its entries). Fix: invert back-reference (registry, DI,
knowledge to dependents) → whole group disappears. Confirm (optional):
find_cycles(scope: "file", pathPattern: "<target>/**"); carrying files:
evidence.fileEdges.
cycleWithDependents: false, count ≥ 3 → split stable core (what dependents
use) from volatile rest.
Groups with violationCount: 1: judge each by evidence.
| Evidence | Weight |
|---|---|
directoryRelation: disjoint | crosses into sibling/cousin — the case borders are about; highest |
ancestor | nested component reaching up into its parent; check direction |
instabilityDelta | severity within the list |
tier critical / active | change cascades across edge (critical: into wide reach); act first |
callWeight: 0 | type/const/re-export only — weaker coupling |
fileEdgeCount 1 | one file carries it — cheap to move |
Ca+Ce near minConnectionCount | thin support; instability can swing — flag as tentative |
evidence.fileEdges (top 5 by call weight) = where to act.
MANDATORY: read the phase's reference before judging that detector's findings — each carries field semantics plus its not-built / not-judged traps. Detector absent or zero findings → no read.
| Phase | Judges | Field | Reference |
|---|---|---|---|
| 3b | leaking abstraction | leakingAbstraction | phase-3b-leaking-abstraction.md |
| 3c | silent coupling | silentCoupling | phase-3c-silent-coupling.md |
| 3c2 | shotgun surgery | shotgunSurgery | phase-3c2-shotgun-surgery.md |
| 3d | main sequence | mainSequence | phase-3d-main-sequence.md |
| 3d2 | hub-like dependency | hubLikeDependency | phase-3d2-hub-like.md |
| 3d3 | propagation cost | summary.propagationCost | phase-3d3-propagation-cost.md |
| 3e | layering | layering | phase-3e-layering.md |
| 3f | layer map | response.layerMap | phase-3f-layer-map.md |
| 3g | dependency norms | norms | phase-3g-dependency-norms.md |
| 3h | diff-time findings | review_changes architecture | phase-3h-diff-time.md |
| 3i | remedy simulation | restructure | phase-3i-remedy-simulation.md |
Read references/phase-4-exclusions.md:
counters per detector (summary.<detector>.excluded*) = read, NOT judged.
Report as "not judged", never "clean"; reasons verbatim from exclusionReasons.
Architecture report: [scope] — [violationCount] SDP violations, [rootCauseCount] root causes
[componentCount] components ([moduleComponentCount] modules); judged [judgedEdgeCount] of [componentEdgeCount] component deps (excluded: containment N, low support N); tooling excluded: [nonProduction.excludedFileCount] files; test support excluded: [testSupport.excludedFileCount] files
Impact tiers: SDP critical N / active N / structural N; layering …; leaks …; reach cut [threshold] ([method]) | not built (no co-change history)
Detectors: [detector] [count] | [detector] 0 (judged [N]) | [detector] not judged — [reason verbatim] … (every detector, zeros included)
## Root causes
| # | Target component | Tier | I | Dependents | Cycle | Fix direction |
## Cross-component violations (disjoint)
| # | Source → Target | Tier (admitted/total pairs) | I src → tgt | Δ | file edges (top) | calls |
## Local violations
[count] — list only on request
## Leaking abstractions — [violationCount] (bypass N, internal-reach N)
Threshold [adoptionThreshold] ([method], η [separability]); [activeModuleCount] of [moduleCount] modules judged
| # | Module | Adoption (facade/deep) | Bypass | Internal-reach | Sources |
## Silent coupling — [violationCount] ([strongLinkedCount] strong pairs linked in code)
Threshold [strengthThreshold] ([method], η [separability]); history [commitCount] commits since [windowSince] @ [head]
| # | File A ↔ File B | Strength | Support | P(B|A) / P(A|B) | Visibility | Sample commit |
Grouped: | # | Shared file | Partners (N) | Top 3 (support / λ / strength) | Drill (`find_co_changed(files: <drillDown.files>, limit: <drillDown.limit>)`) |
## Shotgun surgery — [violationCount]; k [widthThreshold] ([widthThresholdMethod]); [wideUnitCount]/[unitCount] wide commit sets over [burstCount] bursts; admitted [admittedSetCount] k-sets of family C(n,k) [familySize] (q [q]) → [spreadCount] spreads
| # | Components | Islands | Support / λ | Strength | Exemplar files | Sample commit | Drill (`find_co_changed(files: <drillDown.files>, limit: <drillDown.limit>)`) |
## Main sequence — [violationCount] (pain N, uselessness N); mean D [meanDistance]
Threshold [distanceThreshold] ([method]); volatility cut [volatility.threshold] ([volatility.thresholdMethod]); judged [judgedComponentCount]; excluded: unmeasured N, unobservable N, calm N
| # | Component | Zone | D | A (abstract/types) | I | Ca/Ce | Commits/file |
## Hub-like dependencies — [violationCount]; cuts Ca > [afferent.threshold] ([method]), Ce > [efferent.threshold] ([method]); judged [judgedComponentCount]
| # | Component | Ca/Ce | I | Top dependents | Top dependencies | Reach | Commits/file |
## Propagation cost — [propagationCost]; shape [corePeriphery.shape], core [counts.core] ([coreShare]); largest cycle [largestCycleSize]
| # | Component | Files | Mean reach | Internal PC | Core files |
## Layering — [levelCount] levels; coverage [coverage], coherence [coherence]
knots [knotCount] (composition N), backEdges [backEdgeCount], bypasses [abstractionBypassCount]; islands N, skips N, composition cycles N
| # | Kind | Components | Evidence (cut / weights / abstractness) |
## Layer map — [levelCount] levels, [nodeCount] nodes ([granularity], scope [scope|whole repo])
boundary-out N (→ top external: [component] at L[externalLevel]), boundary-in N; move candidates N
| # | Level | Node | depth | inKnot | inner in/out |
## Domain [path] — [componentCount] components, [levelCount] levels (domain mode)
boundary-out N (heaviest → [externalComponent] at L[externalLevel]), boundary-in N
| # | Dir | Inner component | External component | L ext | calls |
## Dependency norms — [violationCount] MISFIT; per family [family]: [significantPairCount]/[familySize] pairs directed ([oneWayPairCount] one-way); [roleFileCount] typed files
excluded constant-reference N, cross-language N, uncalled N, framework-routed N, displaced-role N; typed [typedEdgeCount] of graph edges
| # | Family | Edge (src → dst) | Roles | Locality | Against (established → support) | Minority | p |
## Remedies — simulated (restructure), ranked by net
| # | Remedy | ops | net | resolved (by family) | introduced (subjects) |
## Next steps
| # | Finding | Action | Call |
→ Work through the findings here and now (starting with #1), or file a task per finding?
Every line cites evidence numbers from report. No evidence → no claim.
Zero is not clean. The Detectors: line always prints. Section with 0
findings → heading + 0 (judged N); not built / excluded → heading +
not judged — <reason>. Informational items (composition: true, islands)
print under their section, marked informational. Never "no problems" while any
detector is not judged.
Next steps — one row per finding, root causes first; → line in user's
language:
| Finding | Action | Call |
|---|---|---|
| SDP root cause / violation, hub-like, main sequence, layering, leaking abstraction | ordered restructure plan | Skill(tea-rags:refactoring-planning), component path |
| silent coupling, shotgun surgery | co-locate or make explicit | Skill(tea-rags:refactoring-planning), the pair's files (3c drill = evidence) |
| dependency-norm MISFIT (one edge) | fix that edge in place | Skill(tea-rags:data-driven-generation), source file |
User picks; never start a finding or create a task before. Answer turn → read ../../rules/references/report-follow-up.md.
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub artk0de/tearags-mcp --plugin tea-rags17 skills in this plugin
/analytics-rerankPick tea-rags rerank preset, build `{custom: {...}}` weight set, or compose analytics-driven search (ownership, tech-debt, hotspots, code-review, security-audit, fragile-silo). Invoke on intent like "rank by ownership", "find tech debt", "hotspot scan", "code review of recent changes", "security audit of auth code", "code that looks stable but breaks a lot", "custom weights for impact analysis". NOT for project health scan needing cross-preset overlap — use `tea-rags:risk-assessment`. NOT for debug root-cause — use `tea-rags:bug-hunt`. NOT for filter shape — use `tea-rags:filter-building`./bug-huntFind source of concrete failure — rank historically buggy code (high bugFixRate + churn) AND freshly changed never-fixed code (committed or still uncommitted) against symptom. Triggers on "debug X", "why does Y fail", "test fails", "stack trace says Z", "find bugs in X", "found a bug in X — show / compare Y", "suspects in X and Y — search both", a search hit with bugFixRate / ageDays labels ("proceed?", "проверь там"), "where is error 'X' in code", "где в коде строка / упоминается 'X'", "when did error 'X' appear in git history", "когда появилась ошибка 'X'", "read the whole file" / "прочитай весь файл" of a search hit, "падает". NOT for code history without an error string or failure ("when did X change", "посмотри через git" alone) — core routing answers it. NOT for code health scanning without bug intent — use risk-assessment for that./data-driven-generationDecide HOW to write or change code by inspecting git signals on neighbors — classifies task mode (CREATE / EXTEND / MODIFY), pulls strategy and templates from proven low-churn implementations, reuses existing shared helpers. Triggers on "implement function X", "add method to class Y", "write a helper for Z", "modify function X", "change behavior of Y", "напиши функцию", "добавь метод", "поправь метод", "измени поведение", "overlay labels → strategy?", a hotfix with location + fix named (cause known → not bug-hunt). NOT for discovery — use tea-rags:explore. NOT for pure rename/extract; a file MOVE still routes here./exploreUse for questions about existing code behavior, usages, structure, examples, or explicit pre-change context that need investigation. Not bug symptoms, implementation-plan authoring, or broad code-health audits./extract-project-patternsAgentic-only — runs on any behaviorQuery / positiveIds handoff: proven code as code-gen templates, not test patterns. Returns templates + locality (target subdomain → infra prefix → project). Read body before planning. Called by data-driven-generation Step 2, dinopowers writing-plans / executing-plans. No input → returns { templates: [], locality: "none", diagnostics: ["no input"] }, zero calls./filter-buildingBuild tea-rags filter beyond `pathPattern`. Invoke whenever reasoning before a tea-rags search includes a SCOPE: domain, language, author, time window, ticket, prod-vs-test split, directory exclusion. User names scope ("in the X domain", "Ruby code", "Alice's work", "modified this week", "for ticket RAGS-142", "production code"), rarely says "filter". Maps scope to typed filter params, `level`, `pathPattern` negation, or raw `filter`. E.g. "tests of AuthService" → `testFile: "only"`. NOT for picking rerank preset — use `tea-rags:analytics-rerank`. NOT for general exploration — use `tea-rags:explore`.Other plugins' skills for the same job