-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompile_rules.py
More file actions
196 lines (153 loc) · 6.34 KB
/
compile_rules.py
File metadata and controls
196 lines (153 loc) · 6.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
"""
compile_rules.py
Compiles skill-rules.json into CLAUDE.md routing instructions.
Run after setup_target_project.py to activate intent-based skill routing.
Usage:
python compile_rules.py --target /path/to/project
python compile_rules.py --target /path/to/project --dry-run
"""
import json
import argparse
from pathlib import Path
from datetime import datetime
CLAUDE_MD_HEADER = """
## Skill Routing Rules (Auto-Generated — do not edit manually)
<!-- Generated by compile_rules.py on {timestamp} -->
When working on tasks, Claude MUST follow this routing table.
Match the user's intent against the patterns below and load the corresponding
skill BEFORE writing any code. Loading a skill means reading its SKILL.md and
applying its patterns, checklists, and code templates.
"""
CLAUDE_MD_FOOTER = """
## Orchestrator Protocol
For any non-trivial task, use the `/orchestrate` command or:
1. Read `dev/active/CONTEXT.md` to understand project state
2. Read `dev/active/TASK.md` for current task definition
3. Match intent to routing table above
4. Load matched skill(s) first
5. Invoke specialist agent if available
6. Update `dev/active/PLAN.md` before writing code
## Available Agents
| Agent | Purpose |
|-------|---------|
| planner | Implementation planning for complex features |
| architect | System design + API design decisions |
| tdd-guide | Test-driven development workflow |
| code-reviewer | Python code quality review |
| security-reviewer | Security analysis and audit |
| fastapi-specialist | FastAPI framework patterns |
| aws-specialist | AWS services integration |
| k8s-specialist | Kubernetes + container infrastructure |
| python-database-expert | PostgreSQL + SQLAlchemy + Alembic |
| python-debugger | Root cause analysis and debugging |
| pipecat-expert | Real-time voice/multimodal AI pipelines |
| twilio-expert | Twilio Programmable Voice + Media Streams |
| vapi-expert | Vapi webhook integration + call data |
## Skill Loading Instructions
To load a skill, read `.claude/skills/<skill-name>/SKILL.md` and apply all
patterns, checklists, and templates found there to the current task.
If a `resources/` directory exists, load referenced files on demand.
"""
# Skill → Agent mapping for the routing table
SKILL_AGENT_MAP: dict[str, str | None] = {
"python-patterns": "architect",
"async-python-patterns": "fastapi-specialist",
"python-testing": "tdd-guide",
"tdd-workflow": "tdd-guide",
"postgres-patterns": "python-database-expert",
"docker-patterns": "k8s-specialist",
"deployment-patterns": "k8s-specialist",
"security-review": "security-reviewer",
"design-doc-mermaid": "architect",
"perplexity-deep-search": "planner",
"verification-loop": "code-reviewer",
"strategic-compact": None,
"skill-creator": "architect",
}
def load_rules(rules_file: Path) -> dict:
if not rules_file.exists():
raise FileNotFoundError(f"skill-rules.json not found at: {rules_file}")
with open(rules_file) as f:
data = json.load(f)
if "skills" not in data:
raise ValueError(
f"Invalid skill-rules.json: missing 'skills' key in {rules_file}"
)
return data
def compile_to_claude_md(
rules: dict, claude_md_file: Path, dry_run: bool = False
) -> str:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")
lines = [CLAUDE_MD_HEADER.format(timestamp=timestamp)]
lines.append("| Intent | Skill to Load | Specialist Agent |\n")
lines.append("|--------|--------------|------------------|\n")
for skill in rules.get("skills", []):
name = skill["name"]
keywords = ", ".join(f"`{k}`" for k in skill.get("keywords", [])[:4])
agent = SKILL_AGENT_MAP.get(name)
agent_str = f"`{agent}`" if agent else "—"
lines.append(f"| {keywords} | `{name}` | {agent_str} |\n")
lines.append("\n### Detailed Pattern Matching\n\n")
for skill in rules.get("skills", []):
name = skill["name"]
description = skill.get("description", "")
patterns = skill.get("intentPatterns", [])
file_paths = skill.get("filePaths", [])
agent = SKILL_AGENT_MAP.get(name)
lines.append(f"#### `{name}`\n")
lines.append(f"{description}\n\n")
if patterns:
lines.append("**Trigger patterns** (regex on user message):\n")
for p in patterns:
lines.append(f"- `{p}`\n")
lines.append("\n")
if file_paths:
lines.append("**Active when editing**:\n")
for fp in file_paths:
lines.append(f"- `{fp}`\n")
lines.append("\n")
lines.append(f"**Action**: Load `.claude/skills/{name}/SKILL.md`")
if agent:
lines.append(f", then invoke `{agent}` agent")
lines.append("\n\n")
lines.append(CLAUDE_MD_FOOTER)
content = "".join(lines)
if dry_run:
print("=== DRY RUN: CLAUDE.md additions ===\n")
print(content)
return content
# Read existing CLAUDE.md
existing = ""
if claude_md_file.exists():
existing = claude_md_file.read_text()
# Remove previous generated block if it exists
start_marker = "## Skill Routing Rules (Auto-Generated"
idx = existing.find(start_marker)
if idx != -1:
existing = existing[:idx].rstrip()
updated = existing + "\n\n" + content if existing else content
claude_md_file.write_text(updated)
print(f"CLAUDE.md updated at: {claude_md_file}")
return content
def main():
parser = argparse.ArgumentParser(
description="Compile skill-rules.json into CLAUDE.md"
)
parser.add_argument("--target", required=True, help="Target project path")
parser.add_argument(
"--dry-run", action="store_true", help="Print output without writing"
)
args = parser.parse_args()
target = Path(args.target).resolve()
rules_file = target / ".claude" / "skills" / "skill-rules.json"
claude_md_file = target / "CLAUDE.md"
print(f"Reading rules from: {rules_file}")
rules = load_rules(rules_file)
skill_count = len(rules.get("skills", []))
print(f"Found {skill_count} skill(s) to compile")
compile_to_claude_md(rules, claude_md_file, dry_run=args.dry_run)
if not args.dry_run:
print("\nDone. Claude will now auto-route based on intent patterns.")
print(f" CLAUDE.md: {claude_md_file}")
if __name__ == "__main__":
main()