"""claudemd-optimizer — CLAUDE.md dedupe, dead-rule-reference, and length/
structure analysis, ported from PinkyAI's `claudemd_optimizer` engine
module (see README.md "Provenance").
Never writes to disk. `analyze()` is a pure function returning a proposed
cleaned-up version of the content plus exactly what would change — a
human decides whether to apply it.
Honest scope: dedupe catches exact-repeated non-blank lines only (no
semantic/fuzzy similarity — that needs an embedding model, a dependency
this tool doesn't carry). Dead-rule detection only ever flags a token
matching a configured dotted `prefix.name` shape that isn't in the
known-ids set you supply — it never makes a generic "this looks unused"
guess over arbitrary prose.
Pure stdlib, no network call.
"""
from __future__ import annotations
import argparse
import sys
from dataclasses import dataclass, field
from pathlib import Path
HEADING_PREFIX = "#"
DEFAULT_KNOWN_RULE_PREFIXES = (
"secret.", "pii.", "dangerous_command.", "package_check.", "package_verify.",
"injection.", "entropy.", "path.", "git.", "cache.",
)
def estimate_tokens(text: str) -> int:
"""Rough token estimate for prose: ~4 characters per token, the
published chars-per-token rule of thumb for English text. Not a real
tokenizer -- an estimate with a commonly cited, not independently
re-verified here, ~15% accuracy bound. Returns 0 for empty text.
"""
chars = len(text)
if chars == 0:
return 0
return max(1, round(chars / 4.0))
def strip_trailing_punctuation(token: str) -> str:
return token.rstrip(".,:;)\"'")
def looks_like_a_rule_id(token: str, known_prefixes: tuple[str, ...]) -> bool:
return any(token.startswith(prefix) and len(token) > len(prefix) for prefix in known_prefixes)
@dataclass(frozen=True)
class DuplicateLine:
text: str
first_line: int
repeat_lines: tuple[int, ...]
@dataclass(frozen=True)
class DeadRuleReference:
rule_id: str
line: int
@dataclass(frozen=True)
class SkillMigrationCandidate:
heading: str
line: int
@dataclass(frozen=True)
class LengthStructureFinding:
line_count: int
threshold: int
exceeds_threshold: bool
skill_migration_candidates: tuple[SkillMigrationCandidate, ...] = field(default_factory=tuple)
@dataclass(frozen=True)
class OptimizeReport:
duplicates: tuple[DuplicateLine, ...]
dead_rules: tuple[DeadRuleReference, ...]
original_tokens: int
cleaned_tokens: int
cleaned_content: str
length_structure: LengthStructureFinding
@property
def tokens_saved(self) -> int:
return max(0, self.original_tokens - self.cleaned_tokens)
def analyze_length_structure(content: str, threshold: int) -> LengthStructureFinding:
"""Counts `content`'s lines against `threshold` and flags any heading
that starts with "When " (case-insensitive) as a skill-migration
candidate -- a deliberately narrow heuristic, not a general "this
reads like a workflow" guesser.
"""
candidates: list[SkillMigrationCandidate] = []
line_count = 0
for index, line in enumerate(content.splitlines()):
line_count = index + 1
trimmed = line.lstrip()
if not trimmed.startswith(HEADING_PREFIX):
continue
heading = trimmed.lstrip("#").strip()
if heading[:5].lower() == "when ":
candidates.append(SkillMigrationCandidate(heading=heading, line=line_count))
return LengthStructureFinding(
line_count=line_count,
threshold=threshold,
exceeds_threshold=line_count > threshold,
skill_migration_candidates=tuple(candidates),
)
def analyze(
content: str,
known_rule_ids: set[str],
length_threshold_lines: int = 300,
known_prefixes: tuple[str, ...] = DEFAULT_KNOWN_RULE_PREFIXES,
) -> OptimizeReport:
"""Analyzes `content` for exact-duplicate lines and stale rule-id
references against `known_rule_ids` -- see the module doc for what
each check does and doesn't catch.
"""
duplicates_by_text: dict[str, DuplicateLine] = {}
duplicate_order: list[str] = []
first_seen_at: dict[str, int] = {}
dead_rules: list[DeadRuleReference] = []
cleaned_lines: list[str] = []
for index, line in enumerate(content.splitlines()):
line_number = index + 1
trimmed = line.strip()
for raw_token in line.split():
token = strip_trailing_punctuation(raw_token)
if looks_like_a_rule_id(token, known_prefixes) and token not in known_rule_ids:
dead_rules.append(DeadRuleReference(rule_id=token, line=line_number))
if trimmed == "":
cleaned_lines.append(line)
continue
if trimmed in first_seen_at:
existing = duplicates_by_text.get(trimmed)
if existing is None:
duplicate_order.append(trimmed)
existing = DuplicateLine(text=trimmed, first_line=first_seen_at[trimmed], repeat_lines=())
duplicates_by_text[trimmed] = DuplicateLine(
text=existing.text, first_line=existing.first_line, repeat_lines=(*existing.repeat_lines, line_number)
)
else:
first_seen_at[trimmed] = line_number
cleaned_lines.append(line)
duplicates = tuple(duplicates_by_text[text] for text in duplicate_order)
cleaned_content = "\n".join(cleaned_lines)
original_tokens = estimate_tokens(content)
cleaned_tokens = estimate_tokens(cleaned_content)
length_structure = analyze_length_structure(content, length_threshold_lines)
return OptimizeReport(
duplicates=duplicates,
dead_rules=tuple(dead_rules),
original_tokens=original_tokens,
cleaned_tokens=cleaned_tokens,
cleaned_content=cleaned_content,
length_structure=length_structure,
)
def _print_report(report: OptimizeReport, *, show_diff: bool) -> None:
if not report.duplicates and not report.dead_rules and not report.length_structure.exceeds_threshold:
print("claudemd-optimizer: no duplicate lines, no stale rule references, length within threshold.")
for dup in report.duplicates:
repeats = ", ".join(str(n) for n in dup.repeat_lines)
print(f"[duplicate] first seen line {dup.first_line}, repeated at line(s) {repeats}: {dup.text!r}")
for dead in report.dead_rules:
print(f"[dead-rule] line {dead.line}: {dead.rule_id!r} not in --known-ids")
ls = report.length_structure
if ls.exceeds_threshold:
print(f"[length] {ls.line_count} lines exceeds the configured threshold of {ls.threshold}")
for cand in ls.skill_migration_candidates:
print(f"[skill-migration-candidate] line {cand.line}: {cand.heading!r} reads as workflow-specific")
if report.tokens_saved > 0:
print(f"\nApplying the proposed dedupe: ~{report.original_tokens} -> ~{report.cleaned_tokens} tokens "
f"(~{report.tokens_saved} saved). Estimate only, not a real tokenizer.")
if show_diff:
print("\n--- proposed cleaned content (not written to disk) ---")
print(report.cleaned_content)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Analyze a CLAUDE.md for duplicate lines, stale rule refs, and length.")
parser.add_argument("path", help="Path to the CLAUDE.md (or similar) file to analyze")
parser.add_argument("--known-ids", default="", help="Comma-separated list of currently-valid rule ids")
parser.add_argument(
"--known-prefixes",
default=",".join(DEFAULT_KNOWN_RULE_PREFIXES),
help="Comma-separated dotted-id prefixes worth checking for staleness",
)
parser.add_argument(
"--threshold",
type=int,
default=300,
help="Line-count guideline for the length/structure check (default 300 -- pick what fits your own project's context budget; not a claimed official figure)",
)
parser.add_argument("--diff", action="store_true", help="Also print the proposed cleaned content")
args = parser.parse_args(argv)
content = Path(args.path).read_text(encoding="utf-8")
known_ids = {i.strip() for i in args.known_ids.split(",") if i.strip()}
known_prefixes = tuple(p for p in args.known_prefixes.split(",") if p)
report = analyze(content, known_ids, args.threshold, known_prefixes)
_print_report(report, show_diff=args.diff)
return 1 if (report.duplicates or report.dead_rules or report.length_structure.exceeds_threshold) else 0
if __name__ == "__main__":
sys.exit(main())