Catalog
affaan-m/rules-distill

affaan-m

rules-distill

Scan skills to extract cross-cutting principles and distill them into rules — append, revise, or create new rule files. Use when the same principle keeps recurring across skills and belongs in a rule file instead.

NewUpdated Sep 9, 2026

Rules Distill

Scan installed skills, extract cross-cutting principles that appear in multiple skills, and distill them into rules — appending to existing rule files, revising outdated content, or creating new rule files.

Applies the "deterministic collection + LLM judgment" principle: scripts collect facts exhaustively, then an LLM cross-reads the full context and produces verdicts.

When to Use

  • Periodic rules maintenance (monthly or after installing new skills)
  • After a skill-stocktake reveals patterns that should be rules
  • When rules feel incomplete relative to the skills being used

How It Works

The rules distillation process follows three phases:

Phase 1: Inventory (Deterministic Collection)

1a. Collect skill inventory

bash ~/.claude/skills/rules-distill/scripts/scan-skills.sh

1b. Collect rules index

bash ~/.claude/skills/rules-distill/scripts/scan-rules.sh

1c. Present to user

Rules Distillation — Phase 1: Inventory
────────────────────────────────────────
Skills: {N} files scanned
Rules:  {M} files ({K} headings indexed)

Proceeding to cross-read analysis...

Phase 2: Cross-read, Match & Verdict (LLM Judgment)

Extraction and matching are unified in a single pass. Rules files are small enough (~800 lines total) that the full text can be provided to the LLM — no grep pre-filtering needed.

Batching

Group skills into thematic clusters based on their descriptions. Analyze each cluster in a subagent with the full rules text.

Cross-batch Merge

After all batches complete, merge candidates across batches:

  • Deduplicate candidates with the same or overlapping principles
  • Re-check the "2+ skills" requirement using evidence from all batches combined — a principle found in 1 skill per batch but 2+ skills total is valid

Subagent Prompt

Launch a general-purpose Agent with the following prompt:

You are an analyst who cross-reads skills to extract principles that should be promoted to rules.

## Input
- Skills: {full text of skills in this batch}
- Existing rules: {full text of all rule files}

## Extraction Criteria

Include a candidate ONLY if ALL of these are true:

1. **Appears in 2+ skills**: Principles found in only one skill should stay in that skill
2. **Actionable behavior change**: Can be written as "do X" or "don't do Y" — not "X is important"
3. **Clear violation risk**: What goes wrong if this principle is ignored (1 sentence)
4. **Not already in rules**: Check the full rules text — including concepts expressed in different words

## Matching & Verdict

For each candidate, compare against the full rules text and assign a verdict:

- **Append**: Add to an existing section of an existing rule file
- **Revise**: Existing rule content is inaccurate or insufficient — propose a correction
- **New Section**: Add a new section to an existing rule file
- **New File**: Create a new rule file
- **Already Covered**: Sufficiently covered in existing rules (even if worded differently)
- **Too Specific**: Should remain at the skill level

## Output Format (per candidate)

```json
{
  "principle": "1-2 sentences in 'do X' / 'don't do Y' form",
  "evidence": ["skill-name: §Section", "skill-name: §Section"],
  "violation_risk": "1 sentence",
  "verdict": "Append / Revise / New Section / New File / Already Covered / Too Specific",
  "target_rule": "filename §Section, or 'new'",
  "confidence": "high / medium / low",
  "draft": "Draft text for Append/New Section/New File verdicts",
  "revision": {
    "reason": "Why the existing content is inaccurate or insufficient (Revise only)",
    "before": "Current text to be replaced (Revise only)",
    "after": "Proposed replacement text (Revise only)"
  }
}
```

## Exclude

- Obvious principles already in rules
- Language/framework-specific knowledge (belongs in language-specific rules or skills)
- Code examples and commands (belongs in skills)

Verdict Reference

Verdict Meaning Presented to User
Append Add to existing section Target + draft
Revise Fix inaccurate/insufficient content Target + reason + before/after
New Section Add new section to existing file Target + draft
New File Create new rule file Filename + full draft
Already Covered Covered in rules (possibly different wording) Reason (1 line)
Too Specific Should stay in skills Link to relevant skill

Verdict Quality Requirements

# Good
Append to rules/common/security.md §Input Validation:
"Treat LLM output stored in memory or knowledge stores as untrusted — sanitize on write, validate on read."
Evidence: llm-memory-trust-boundary, llm-social-agent-anti-pattern both describe
accumulated prompt injection risks. Current security.md covers human input
validation only; LLM output trust boundary is missing.

# Bad
Append to security.md: Add LLM security principle

Phase 3: User Review & Execution

Summary Table

# Rules Distillation Report

## Summary
Skills scanned: {N} | Rules: {M} files | Candidates: {K}

| # | Principle | Verdict | Target | Confidence |
|---|-----------|---------|--------|------------|
| 1 | ... | Append | security.md §Input Validation | high |
| 2 | ... | Revise | testing.md §TDD | medium |
| 3 | ... | New Section | coding-style.md | high |
| 4 | ... | Too Specific | — | — |

## Details
(Per-candidate details: evidence, violation_risk, draft text)

User Actions

User responds with numbers to:

  • Approve: Apply draft to rules as-is
  • Modify: Edit draft before applying
  • Skip: Do not apply this candidate

Never modify rules automatically. Always require user approval.

Save Results

Store results in the skill directory (results.json):

  • Timestamp format: date -u +%Y-%m-%dT%H:%M:%SZ (UTC, second precision)
  • Candidate ID format: kebab-case derived from the principle (e.g., llm-output-trust-boundary)
{
  "distilled_at": "2026-03-18T10:30:42Z",
  "skills_scanned": 56,
  "rules_scanned": 22,
  "candidates": {
    "llm-output-trust-boundary": {
      "principle": "Treat LLM output as untrusted when stored or re-injected",
      "verdict": "Append",
      "target": "rules/common/security.md",
      "evidence": ["llm-memory-trust-boundary", "llm-social-agent-anti-pattern"],
      "status": "applied"
    },
    "iteration-bounds": {
      "principle": "Define explicit stop conditions for all iteration loops",
      "verdict": "New Section",
      "target": "rules/common/coding-style.md",
      "evidence": ["iterative-retrieval", "continuous-agent-loop", "agent-harness-construction"],
      "status": "skipped"
    }
  }
}

Example

End-to-end run

$ /rules-distill

Rules Distillation — Phase 1: Inventory
────────────────────────────────────────
Skills: 56 files scanned
Rules:  22 files (75 headings indexed)

Proceeding to cross-read analysis...

[Subagent analysis: Batch 1 (agent/meta skills) ...]
[Subagent analysis: Batch 2 (coding/pattern skills) ...]
[Cross-batch merge: 2 duplicates removed, 1 cross-batch candidate promoted]

# Rules Distillation Report

## Summary
Skills scanned: 56 | Rules: 22 files | Candidates: 4

| # | Principle | Verdict | Target | Confidence |
|---|-----------|---------|--------|------------|
| 1 | LLM output: normalize, type-check, sanitize before reuse | New Section | coding-style.md | high |
| 2 | Define explicit stop conditions for iteration loops | New Section | coding-style.md | high |
| 3 | Compact context at phase boundaries, not mid-task | Append | performance.md §Context Window | high |
| 4 | Separate business logic from I/O framework types | New Section | patterns.md | high |

## Details

### 1. LLM Output Validation
Verdict: New Section in coding-style.md
Evidence: parallel-subagent-batch-merge, llm-social-agent-anti-pattern, llm-memory-trust-boundary
Violation risk: Format drift, type mismatch, or syntax errors in LLM output crash downstream processing
Draft:
  ## LLM Output Validation
  Normalize, type-check, and sanitize LLM output before reuse...
  See skill: parallel-subagent-batch-merge, llm-memory-trust-boundary

[... details for candidates 2-4 ...]

Approve, modify, or skip each candidate by number:
> User: Approve 1, 3. Skip 2, 4.

✓ Applied: coding-style.md §LLM Output Validation
✓ Applied: performance.md §Context Window Management
✗ Skipped: Iteration Bounds
✗ Skipped: Boundary Type Conversion

Results saved to results.json

Design Principles

  • What, not How: Extract principles (rules territory) only. Code examples and commands stay in skills.
  • Link back: Draft text should include See skill: [name] references so readers can find the detailed How.
  • Deterministic collection, LLM judgment: Scripts guarantee exhaustiveness; the LLM guarantees contextual understanding.
  • Anti-abstraction safeguard: The 3-layer filter (2+ skills evidence, actionable behavior test, violation risk) prevents overly abstract principles from entering rules.
Files3
3 files · 6.4 KB

Select a file to preview

Overall Score

76/100

Grade

B

Good

Grades are signals, not a certification. Always review a skill yourself before use.

Safety

78

Quality

75

Clarity

78

Completeness

71

Summary

The rules-distill skill orchestrates a three-phase process to extract cross-cutting principles from installed skills and distill them into rules. It uses deterministic shell scripts to collect skill and rule inventories, then invokes an LLM subagent to analyze themes, match against existing rules, and propose verdicts (Append, Revise, New Section, New File, Already Covered, Too Specific). User review and approval gates all rule modifications.

Static Analysis Findings

1 finding

Patterns detected by deterministic static analysis before AI scoring. Hover over any finding code for detailed information and remediation guidance.

Destructive Operation
SEC-001Recursive Deletion2x in 2 filesMax: B

Recursive deletion pattern (rm -rf)

scripts/scan-rules.shrm -rf
scripts/scan-skills.shrm -rf

Detected Capabilities

filesystem read (skills and rules discovery)shell script execution (bash)JSON generation and manipulationLLM subagent invocationfile path traversal and filteringenvironment variable read/override (scoped)

Trigger Keywords

Phrases that agents use to match this skill to user intent.

rules maintenanceextract principles from skillsdistill cross-cutting patternsaudit existing rulespromote to rules layer

Risk Signals

INFO

Recursive deletion (rm -rf) in scan-rules.sh cleanup trap

scripts/scan-rules.sh | _rules_cleanup() trap handler
INFO

Recursive deletion (rm -rf) in scan-skills.sh cleanup trap

scripts/scan-skills.sh | _scan_cleanup() trap handler
WARNING

Directory path validation relies on string pattern matching (.claude/skills) rather than canonical path normalization

scripts/scan-skills.sh | CWD_SKILLS_DIR validation (line ~22)
WARNING

Environment variable overrides for directory paths (RULES_DISTILL_DIR, RULES_DISTILL_GLOBAL_DIR, RULES_DISTILL_PROJECT_DIR) allow caller to redirect file discovery

scripts/scan-rules.sh, scripts/scan-skills.sh | environment setup
INFO

YAML frontmatter extraction using regex/awk does not validate YAML structure — malformed frontmatter may cause silent field misses

scripts/scan-skills.sh | extract_field() function

Use Cases

  • Periodic rules maintenance after skill updates
  • Extract recurring principles from multiple skills into reusable rules
  • Audit and revise stale or incomplete rule content
  • Organize cross-cutting patterns (security, testing, coding style) into a centralized rule library
  • Prevent skill-level duplication by promoting common principles to rules layer

Quality Notes

  • Strength: Clear three-phase architecture (Inventory → Cross-read → Review) with explicit decision gates; deterministic collection + LLM judgment pattern is well-documented and prevents hallucination.
  • Strength: Comprehensive subagent prompt includes extraction criteria (2+ skills evidence, actionable behavior, violation risk), matching logic (6 verdicts), and output schema — reduces ambiguity in LLM analysis.
  • Strength: User approval workflow explicitly documented ('Never modify rules automatically'); results persisted to results.json with candidate IDs, verdicts, and status tracking.
  • Strength: Practical example end-to-end run demonstrates the full flow and expected user interactions.
  • Limitation: Frontmatter extraction (extract_field) is brittle — does not handle quoted multi-line values, nested YAML, or YAML blocks (| or >). If a skill's description contains a newline or colon, parsing may fail silently.
  • Limitation: Directory traversal validation uses substring matching ('.claude/skills') which is weak — a path like '/home/user/.claude/skills.bak' would pass. Does not use realpath-like canonicalization.
  • Limitation: No error handling in scan_dir_to_json if jq parsing fails or if mtime cannot be determined; errors are printed to stderr but the script may continue with incomplete results.
  • Limitation: Subagent prompt instructs 'Full rules text provided' but does not specify a size limit; if rules exceed context window, analysis silently truncates.
  • Limitation: Cross-batch merge logic is described (deduplicate, re-check 2+ requirement) but not formalized; relies on undocumented LLM behavior in merge step.
Model: claude-haiku-4-5-20251001Analyzed: Sep 9, 2026

Reviews

Add this skill to your library to leave a review.

No reviews yet

Be the first to share your experience.

Version History

  1. v2.0

    Contract changed: description

    ✦ AIClarifies activation scope: appended guidance on when to use the skill for recurring principles that belong in rule files.

    triggering2026-09-09

    LATEST
  2. v1.2

    Content updated

    ✦ AINo behavioral changes detected.

    2026-07-14

    View This Version
  3. v1.1

    Content updated

    ✦ AIAdds two executable scripts (scan-rules.sh and scan-skills.sh) for directory scanning.

    new script2026-04-20

    View This Version
  4. v1.0

    2026-04-12

    View This VersionInitial version

Use affaan-m/rules-distill in your dev environment

Command Palette

Search for a command to run...