agentleFS
TalonT-OrgTalonT-Org/AutoSkillit/.claude/skills/audit-cohesion/SKILL.md

audit-cohesion

Skill5 starsChanged 6 months agoMITView on GitHub

Audit codebase for internal cohesion - how well components fit together and maintain consistent patterns. Distinct from audit-arch (which checks rule violations); this checks integration fitness and convergence. Use when user says "audit cohesion", "check cohesion", "cohesion audit", or "alignment check".

1 other project uses a version of this, 1 of them edited.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

12 rules. About 0 are common, 8 are distinctive, and 4 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈8

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    After major refactors to verify integration fitness

    line 23
  2. Distinctive:

    Before planning new features to understand current alignment state

    line 24
  3. Distinctive:

    Update an existing report — always generate new

    line 30
  4. Distinctive:

    Use subagents for parallel exploration (one per cohesion dimension)

    line 34
  5. Very specific:

    All output goes under {{AUTOSKILLIT_TEMP}}/audit-cohesion/ (create if needed)

    line 35
  6. Very specific:

    The report must be plan-ready: Every finding must contain enough detail that a /make-plan invocation can act on it without re-investigating …

    line 44
  7. Distinctive:

    Question: Do parallel structures maintain consistent patterns, or have they diverged?

    line 95
  8. Distinctive:

    After all subagents return:

    line 443
  9. Very specific:

    Ensure {{AUTOSKILLIT_TEMP}}/audit-cohesion/ exists (mkdir -p).

    line 455
  10. Very specific:

    Write to {{AUTOSKILLIT_TEMP}}/audit-cohesion/cohesion_audit_{YYYY-MM-DD_HHMMSS}.md — always one file, never split.

    line 457
  11. Distinctive:

    Test fixtures and cached LLM responses

    line 511
  12. Distinctive:

    Before claiming a documentation error, read the actual file at the cited path — don't rely on the CLAUDE.md ASCII tree representation.

    line 540

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Cohesion Audit Skill

Audit the codebase for internal cohesion: how well components integrate and maintain consistent patterns across boundaries.

Key Distinction: audit-arch checks whether architectural rules are followed (violations). audit-cohesion checks whether components fit together (alignment, consistency, completeness). A codebase can pass all architectural rules yet still have poor cohesion — parallel structures that diverge, registries with missing entries, or scattered features.

When to Use

  • User says "audit cohesion", "check cohesion", "cohesion audit", "alignment check"
  • After major refactors to verify integration fitness
  • Before planning new features to understand current alignment state

Critical Constraints

NEVER:

  • Modify any source code files
  • Update an existing report — always generate new
  • Duplicate findings that belong in audit-arch (rule violations)

ALWAYS:

  • Use subagents for parallel exploration (one per cohesion dimension)
  • All output goes under {{AUTOSKILLIT_TEMP}}/audit-cohesion/ (create if needed)
  • Final report: {{AUTOSKILLIT_TEMP}}/audit-cohesion/cohesion_audit_{YYYY-MM-DD_HHMMSS}.md — always one file, never split
  • Subagents must NOT create their own files — they return findings in their response text only
  • Score each dimension (STRONG, ADEQUATE, WEAK, FRACTURED)

Output Quality Standard

The report must be plan-ready. Every finding must contain enough detail that a /make-plan invocation can act on it without re-investigating the codebase.

ENUMERATE, do not summarize. The following are NOT acceptable findings:

Bad (anemic)Good (actionable)
"16 fields missing from registry"Table listing each missing field name, its source file:line, and suggested lifecycle category
"Several source modules without tests"Table listing each untested module path and what it does
"Export depth inconsistent"Table listing each symbol that requires deep imports, its deep path, and where consumers import it from
"48 files use broad exception handlers"Table listing each file:line, the exception type caught, and what it catches

Minimum per dimension: Each dimension section MUST contain:

  1. A findings table (markdown table with columns appropriate to the dimension)
  2. Specific file:line references for every gap, violation, or inconsistency
  3. Enough context that someone unfamiliar could locate and fix each issue

If a dimension has no findings (scores STRONG), still provide the evidence: what was checked, how many items passed, and key file paths examined.


Subagent Output Requirements

Each subagent MUST structure its response as:

## Dimension: C{N} — {Name}
### Score: {STRONG|ADEQUATE|WEAK|FRACTURED}

### Methodology
{What was searched, how many items checked, key directories examined}

### Findings Table
| {columns appropriate to dimension} |
|---|
| {row per finding} |

### Evidence
{For each finding, the specific file:line, what was expected, what was found}

### Compliant Patterns
{Specific examples of things that ARE working well, with file:line}

Subagents must NOT return prose summaries. They must return structured data (tables, lists with file:line). If a subagent returns "X items are inconsistent" without listing each item, the finding is incomplete and must be expanded before inclusion in the report.


Cohesion Dimensions

C1: Structural Symmetry

Question: Do parallel structures maintain consistent patterns, or have they diverged?

Audit Strategy:

  1. Directory-level comparison — produce a side-by-side table:
Directory/FileModule A Has?Module B Has?Symmetric?Notes
handlers/YesYesYes—
config.pyYes (single file)Yes (directory/)NONaming: BaseConfig vs ConfigManager

List ALL directories and key files, not just divergent ones.

  1. Repository pattern comparison — for each repository, verify:
RepositoryExtends Base?Has Interface?Has Factory Method?Method Pattern
  1. Node implementation comparison — for each node pattern:
PatternModule A ImplementationModule B ImplementationConsistent?
Request dispatchSend via handler chainSend via handler chainYes
State wrapperStateManager......
  1. Prompt template comparison:
Template TypeModule A PathModule B PathShared PartialsDivergence

C2: Interface Completeness

Question: Are Protocol/ABC contracts complete — every interface fully implemented, every DI slot wired?

Audit Strategy:

  1. Protocol → concrete implementation mapping — find every Protocol and ABC class, then find its concrete implementation(s):
Protocol/ABCFile:LineMethods DefinedConcrete ImplementationImpl File:LineAll Methods Implemented?

Flag any protocol with zero implementations, or any concrete class missing an abstract method.

  1. DI container field population — for the main dependency injection container(s), compare declared fields vs factory wiring:
FieldTypeOptional?Wired in Factory?Factory ValueNotes

Flag any field that is declared but not populated in the composition root factory.

  1. Abstract method coverage — for ABC hierarchies with multiple levels (base → sub-ABC → concrete), verify each concrete class implements all inherited abstract methods:
Concrete ClassInherits FromAbstract Methods RequiredMethods ImplementedComplete?
  1. Factory function completeness — for each factory/builder pattern:
Factory FunctionFile:LineReturnsAll Fields Populated?Stale Comments?

Flag any factory whose docstring or inline comments claim a different field count than the actual implementation.


C3: Feature Locality

Question: Is related functionality co-located, or scattered across unrelated packages?

Audit Strategy:

  1. Feature file map — for each major feature, enumerate ALL participating files:
FeatureFile PathRole in FeaturePackage
Cachingsrc/module_a/cache.pyModule A cachingcore
Cachingsrc/module_b/cache/manager.pyModule B cachingcore
Cachinglib/shared/cache_base.pyBase abstractionshared

Audit the major cross-cutting features in the project.

  1. SDK utility audit — for each SDK module, count its importers by package:
Shared ModuleTotal ImportersModule A OnlyModule B OnlySharedVerdict
lib/shared/scope.py8080Misplaced — module B only
  1. Import fan-in — list every module with 10+ importers:
ModuleImporter CountIs Shared Infrastructure?

C4: Naming Convention Consistency

Question: Are naming patterns consistent across the codebase?

Audit Strategy:

  1. Class suffix inventory — group all classes by their suffix pattern:
SuffixCountExamplesExceptions
*Repository27PlanRepository, PhaseRepository—
*Manager2CacheManager, StateManagerMixed naming strategy
  1. Method verb audit — for each verb used in repository/node methods:
VerbCountFilesSynonym Conflicts
get_21832 filesNone
fetch_??Conflicts with get_?
  1. File naming audit — find files that break the dominant pattern:
FilePattern ExpectedPattern FoundLocation
  1. Enum audit:
Enum ClassValue StyleLocationConsistent?

C5: Test-Source Alignment

Question: Does the test structure mirror the source structure, with no orphans or gaps?

Audit Strategy:

  1. Source-to-test mapping — for EVERY source module, find its test:
Source ModuleTest FileExists?Test Count
src/module_a/handler.pytests/module_a/test_handler.pyYes12
lib/shared/utils.py—NO0

List ALL gaps — every source file without a corresponding test file.

  1. Orphan detection — test files whose source no longer exists:
Test FileExpected SourceSource Exists?
  1. Classification audit — tests in wrong directories:
Test FileCurrent DirExpected DirReason
  1. Stale fixture detection:
Fixture FileReferenced ByStill Valid?

C6: Registration Completeness

Question: Are all registries internally consistent and complete — every registered entry has an implementation, every implementation is registered?

Audit Strategy:

  1. MCP tool registry completeness — find the gate frozensets (GATED_TOOLS, UNGATED_TOOLS) and cross-reference every tool name against handler functions and documentation:
Tool NameIn Gate Frozenset (which)Handler FunctionHandler File:Line@app.tool() registered?In CLAUDE.md?Notes

Flag any tool in the frozenset without a handler, any handler not in the frozenset, and any CLAUDE.md attribution to the wrong file.

  1. Decorator-based rule registry — for @semantic_rule (or equivalent auto-registration decorator) find all decorated functions vs all emitted finding IDs:
Decorator name=Registered UnderEmitted Finding IDsMismatch?

Flag cases where one decorated function emits findings under different IDs than the one it is registered under.

  1. CLI command registration — enumerate all @app.command() (or equivalent) decorators and cross-reference against documentation:
CommandRegistered at File:LineDocumented?Notes

Flag commands registered in code but absent from CLAUDE.md.

  1. Skill/plugin registry completeness — count skill directories (those with SKILL.md) and verify count matches documented claim:
Skill DirectoryHas SKILL.md?Listed in CLAUDE.md?Name Match?

C7: Recipe-to-Skill Coherence

Question: Are pipeline recipe YAML definitions internally consistent — do all external references (skills, tools, Python callables, capture keys) resolve?

Audit Strategy:

  1. Skill reference resolution — for every run_skill step in every recipe, verify the skill_command resolves to an existing skill:
RecipeStep NameSkill CommandIs Dynamic (${{...}})?Skill Directory Exists?Has SKILL.md?

Flag any static reference that does not resolve. Flag dynamic references as unverifiable and note the input variable that controls them.

  1. Tool name validity — for every step that specifies a tool type (run_cmd, run_skill, run_python, etc.), verify the tool name appears in the registry (GATED_TOOLS or UNGATED_TOOLS):
RecipeStep NameTool NameIn Registry?
  1. Python callable resolution — for every run_python step, verify the dotted module path and function name resolve to an importable callable:
RecipeStep NameModule PathFunction NameModule Importable?Function Exists?
  1. Capture key coherence — for every ${{ captures.X }} reference in a recipe step (in skill_command, cwd, python_args, etc.), verify that key X was declared as a capture_key in an upstream step:
RecipeStep NameReferences captures.XX Defined Upstream?Defining Step

Flag forward references (using a key before the step that defines it) and phantom references (key never defined).


C8: Export Surface Coherence

Question: Are __init__.py exports consistent, complete, and intentional?

Audit Strategy:

  1. Symbol accessibility audit — for key public symbols, check import depth:
SymbolShallow Import (from lib.X import Y)Deep Import Required?Consumer Count
ConfigYesNo45
AppStateNofrom lib.schema.state.app_state import ...23

List EVERY symbol that requires deep imports but has 5+ consumers.

  1. __all__ consistency:
PackageHas __all__?__all__ CountActual Public SymbolsDelta
  1. Import pattern census — how do consumers actually import:
SymbolImport Variants FoundCount EachDominant Pattern
  1. Stale re-export detection:
Re-exportSource LocationTarget LocationTarget Exists?

C9: Error Handling Uniformity

Question: Are error patterns (exceptions, logging, error states) consistent across the codebase?

Audit Strategy:

  1. Exception class inventory:
Exception ClassBase ClassDefined InUsed In (files)Agent-Specific?

Flag duplicates (same name in different agents).

  1. Error state field comparison:
Error FieldIn Module A State?In Module B State?Same Semantics?
  1. Broad exception handler census — list EVERY except Exception or except BaseException:
File:LineException CaughtHandler ActionJustified?
  1. Logger initialization audit:
FileLogger PatternConsistent?

C10: Documentation-Code Alignment

Question: Does the project's primary architectural documentation (CLAUDE.md) accurately describe the actual code — no stale attributions, wrong names, or missing entries?

This dimension is distinct from audit-arch (which checks rule violations) and from C6 (which checks registry completeness). C10 checks whether PROSE DOCUMENTATION matches CODE REALITY. In this repo, CLAUDE.md is loaded as context in every Claude Code session, so inaccuracies there are directly load-bearing: a wrong file attribution misleads every investigation that uses CLAUDE.md as a starting point.

Audit Strategy:

  1. Tool-to-file attribution — for every tool listed in the CLAUDE.md MCP tools table or server module descriptions, verify the documented handler file matches the actual location:
Tool NameCLAUDE.md Claims FileActual Handler File:LineMatch?
  1. __init__.py re-export descriptions — for every sub-package whose CLAUDE.md description mentions re-exported symbols, verify the named symbols actually appear in that package's __all__:
Sub-packageCLAUDE.md States ExportsActual __all__Missing from DocsWrong Names
  1. Test file listing accuracy — compare the tests/ section of CLAUDE.md against actual test files on disk:
Test File (CLAUDE.md)Exists on Disk?Test File (on disk)In CLAUDE.md?

Flag files listed in CLAUDE.md that do not exist, and files on disk not listed in CLAUDE.md.

  1. Key Components description accuracy — for each module entry in CLAUDE.md's Key Components section, verify:
    • The described functions/classes actually exist at the stated location
    • The described public API matches the actual function signatures (param names, return types)
    • Any numeric claims (e.g., "7 checks", "15 gated tools") match the actual count in code
CLAUDE.md ClaimFile:LineVerified?Actual

Audit Workflow

Step 0: Initialize Code Index

mcp__code-index__set_project_path(path="{PROJECT_ROOT}")

Step 1: Launch Parallel Subagents

Spawn subagents for each cohesion dimension. Each subagent MUST be instructed:

"You are conducting a thorough cohesion audit. Your output must be EXHAUSTIVE — enumerate every item, do not summarize. Return structured tables, not prose. Every finding needs a file:line reference. If you find 16 missing fields, list all 16 with their source locations. If you find 48 files with broad exception handlers, list all 48. Completeness is more important than brevity. This is a research task — DO NOT modify any code."

Grouping (spawn 6 subagents, one dimension each or grouped by relatedness):

SubagentDimensionsFocus
1C1, C4Structural symmetry + naming consistency (side-by-side comparison tables)
2C2, C8Interface completeness + export surface (Protocol/DI audit + init gaps)
3C3, C9Feature locality + error handling (file mapping + exception census)
4C5, C10Test-source alignment + documentation-code alignment (enumerate EVERY source module, cross-reference CLAUDE.md)
5C6, C7Registration completeness + recipe-to-skill coherence (registry gap tables + YAML reference resolution)

Step 2: Consolidate Findings

After all subagents return:

  1. Verify completeness — if a subagent returned summaries instead of enumerations, note it as an audit gap
  2. Collect findings per dimension into structured tables
  3. Assign dimension scores based on the enumerated data
  4. Compute overall cohesion score:
    • STRONG = 4, ADEQUATE = 3, WEAK = 2, FRACTURED = 1
    • Average across dimensions, weighted: C2 gets 2x weight (interface completeness is foundational), C10 gets 2x weight (documentation drift is load-bearing in a Claude Code context repo)
  5. Identify cross-dimension patterns — same subsystem appearing as a gap in multiple dimensions

Step 3: Write Report

Ensure {{AUTOSKILLIT_TEMP}}/audit-cohesion/ exists (mkdir -p).

Write to {{AUTOSKILLIT_TEMP}}/audit-cohesion/cohesion_audit_{YYYY-MM-DD_HHMMSS}.md — always one file, never split.

The report WILL be long. This is expected and correct — thoroughness over brevity. Do not reduce content to stay under any line count.

Step 4: Output Summary to Terminal

Display:

  • Overall cohesion score (numeric + label)
  • Per-dimension score table
  • Top 5 most impactful findings (with file:line)
  • Report file path(s)

Report Structure

Each dimension section in the report MUST follow this structure:

## C{N}: {Dimension Name}

### Score: {STRONG|ADEQUATE|WEAK|FRACTURED}

### Methodology
- Directories examined: {list}
- Items checked: {count}
- Tools used: {grep patterns, glob patterns}

### Findings

#### {Finding Category 1}

| {Column Headers Appropriate to Finding} |
|---|
| {One row per item — EVERY item, not a sample} |

#### {Finding Category 2}
{... same pattern ...}

### Compliant Patterns
- {file:line} — {what's working well and why}

### Remediation Checklist
- [ ] {Specific action item with file path}
- [ ] {Next action item}

Exclusions

Do NOT flag:

  • Generated files (migrations, schema DDL)
  • Third-party vendored code
  • Test fixtures and cached LLM responses
  • Temporary/debug files in temp/
  • Configuration template files in config/

Exception Whitelist

General Exceptions (GE)

These exceptions apply to cohesion audit findings. Before reporting, verify the finding does not match any entry below.

GE-10 — Naming convention enforcement applies to exported/public symbols only. Module-private classes not in __all__ are not naming violations. Source: [C4-C-1], [C4-C-2] April cohesion round.

GE-11 — public_name = _private_name in __init__.py is a standard re-export idiom — not "logic in __init__." Source: [C1-E] April cohesion round.

GE-12 — Modules with documented stdlib-only or early-boot constraints using bare logging are exempt from structured-logging conventions. Source: April cohesion round.

GE-13 — Grep tests/ for imports before claiming no test coverage. Absence of test_<module>.py is not evidence of missing coverage. Source: cohesion round 1 contest batches.

GE-15 — Documented optional/empty-when-skipped recipe context variables are not phantom. Source: [C7-3] April cohesion round.

C10 File-Verification Rule

Before claiming a documentation error, read the actual file at the cited path — don't rely on the CLAUDE.md ASCII tree representation. Source: [C10-D] April cohesion round.

Project-Specific Exceptions (PS)

PS-3 — test_check in server/tools_workspace.py omits the _require_enabled() guard by design: it uses the dual-tag headless detection path and must be callable from both interactive and headless sessions.

PS-5 — CLAUDE.md findings tracked in #713. Suppress cohesion findings related to CLAUDE.md accuracy until #713 closes.

PS-6 — remove_clone string booleans ("true"/"false") are a domain contract baked into recipe YAMLs; converting to Python bool would break recipe compatibility.


Score Guidelines

STRONG: Components fit together cleanly. Patterns are consistent, interfaces are complete. No action needed.

ADEQUATE: Minor gaps or inconsistencies that don't impede development. Low-priority cleanup opportunities.

WEAK: Noticeable friction when working across components. Developers need tribal knowledge to navigate inconsistencies. Should be addressed in next refactor cycle.

FRACTURED: Components don't fit together. Patterns are inconsistent, interfaces have gaps. Active impediment to development. Requires dedicated remediation effort.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.