contextplate 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- contextplate/__init__.py +7 -0
- contextplate/__main__.py +5 -0
- contextplate/adapters/__init__.py +50 -0
- contextplate/adapters/aider.py +28 -0
- contextplate/adapters/base.py +85 -0
- contextplate/adapters/claude.py +181 -0
- contextplate/adapters/codex.py +119 -0
- contextplate/adapters/copilot.py +57 -0
- contextplate/adapters/core.py +197 -0
- contextplate/adapters/cursor.py +55 -0
- contextplate/adapters/gemini.py +31 -0
- contextplate/adopt.py +596 -0
- contextplate/cli.py +308 -0
- contextplate/config.py +306 -0
- contextplate/doctor.py +147 -0
- contextplate/frontmatter.py +226 -0
- contextplate/globs.py +84 -0
- contextplate/model.py +185 -0
- contextplate/presets.py +165 -0
- contextplate/scaffold.py +162 -0
- contextplate/templates/check.sh +44 -0
- contextplate/templates/hooks/format.py +74 -0
- contextplate/templates/hooks/guard.py +121 -0
- contextplate/templates/hooks/session_context.py +79 -0
- contextplate/templates/scaffold/AGENTS.md +29 -0
- contextplate/templates/scaffold/agents/agents/researcher.md +16 -0
- contextplate/templates/scaffold/agents/agents/reviewer.md +20 -0
- contextplate/templates/scaffold/agents/agents/test-runner.md +17 -0
- contextplate/templates/scaffold/agents/rules/ai-assets.md +12 -0
- contextplate/templates/scaffold/agents/rules/docs.md +11 -0
- contextplate/templates/scaffold/agents/skills/adr/SKILL.md +12 -0
- contextplate/templates/scaffold/agents/skills/adr/template.md +21 -0
- contextplate/templates/scaffold/agents/skills/handoff/SKILL.md +17 -0
- contextplate/templates/scaffold/agents/skills/plan-task/SKILL.md +15 -0
- contextplate/templates/scaffold/agents/skills/plan-task/template.md +28 -0
- contextplate/templates/scaffold/ai_app/data/README.md +5 -0
- contextplate/templates/scaffold/ai_app/evals/README.md +7 -0
- contextplate/templates/scaffold/ai_app/prompts/README.md +17 -0
- contextplate/templates/scaffold/docs/agent-context.md +42 -0
- contextplate/templates/scaffold/docs/architecture.md +27 -0
- contextplate/templates/scaffold/docs/decisions/0001-record-architecture-decisions.md +22 -0
- contextplate/templates/scaffold/docs/glossary.md +7 -0
- contextplate/templates/scaffold/work/handoff.md +22 -0
- contextplate/writer.py +396 -0
- contextplate-0.1.0.dist-info/METADATA +201 -0
- contextplate-0.1.0.dist-info/RECORD +49 -0
- contextplate-0.1.0.dist-info/WHEEL +4 -0
- contextplate-0.1.0.dist-info/entry_points.txt +3 -0
- contextplate-0.1.0.dist-info/licenses/LICENSE +21 -0
contextplate/adopt.py
ADDED
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
"""`ctxplate adopt`: organize an existing repository.
|
|
2
|
+
|
|
3
|
+
Imports whatever agent configuration already exists (CLAUDE.md, .cursorrules,
|
|
4
|
+
.claude/rules, .cursor/rules, .github/instructions, skills, subagents, MCP
|
|
5
|
+
servers) into the neutral layout, backs up originals that would otherwise be
|
|
6
|
+
duplicated, and fills in only what is missing. Dry run by default.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
import shutil
|
|
14
|
+
import tomllib
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from . import CONFIG_PATH, frontmatter
|
|
19
|
+
from .config import DEFAULT_MODULES, Config
|
|
20
|
+
from .model import SKILL_NAME_RE
|
|
21
|
+
from .presets import commands_for, detect
|
|
22
|
+
from .scaffold import canonical_files
|
|
23
|
+
|
|
24
|
+
INSTRUCTION_SOURCES = [
|
|
25
|
+
("CLAUDE.md", "claude"),
|
|
26
|
+
(".claude/CLAUDE.md", "claude"),
|
|
27
|
+
(".github/copilot-instructions.md", "copilot"),
|
|
28
|
+
("GEMINI.md", "gemini"),
|
|
29
|
+
(".cursorrules", "cursor"),
|
|
30
|
+
(".windsurfrules", None),
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
HARNESS_SIGNALS = {
|
|
34
|
+
"claude": ["CLAUDE.md", ".claude"],
|
|
35
|
+
"codex": [".codex"],
|
|
36
|
+
"copilot": [
|
|
37
|
+
".github/copilot-instructions.md",
|
|
38
|
+
".github/instructions",
|
|
39
|
+
".github/agents",
|
|
40
|
+
".github/skills",
|
|
41
|
+
],
|
|
42
|
+
"cursor": [".cursor", ".cursorrules"],
|
|
43
|
+
"gemini": ["GEMINI.md", ".gemini"],
|
|
44
|
+
"aider": [".aider.conf.yml"],
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
CLAUDE_TOOLS = {
|
|
48
|
+
"Read": "read",
|
|
49
|
+
"NotebookRead": "read",
|
|
50
|
+
"Grep": "search",
|
|
51
|
+
"Glob": "search",
|
|
52
|
+
"LS": "search",
|
|
53
|
+
"WebSearch": "web",
|
|
54
|
+
"WebFetch": "web",
|
|
55
|
+
"Bash": "shell",
|
|
56
|
+
"PowerShell": "shell",
|
|
57
|
+
"Edit": "edit",
|
|
58
|
+
"Write": "edit",
|
|
59
|
+
"MultiEdit": "edit",
|
|
60
|
+
"NotebookEdit": "edit",
|
|
61
|
+
}
|
|
62
|
+
COPILOT_TOOLS = {
|
|
63
|
+
"read": "read",
|
|
64
|
+
"search": "search",
|
|
65
|
+
"web": "web",
|
|
66
|
+
"execute": "shell",
|
|
67
|
+
"shell": "shell",
|
|
68
|
+
"edit": "edit",
|
|
69
|
+
}
|
|
70
|
+
MODEL_TIERS = {"haiku": "fast", "opus": "strong", "fast": "fast", "inherit": "inherit"}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class Plan:
|
|
75
|
+
preset: str
|
|
76
|
+
harnesses: list[str]
|
|
77
|
+
commands: dict[str, str]
|
|
78
|
+
modules: dict[str, bool]
|
|
79
|
+
mcp: dict[str, dict] = field(default_factory=dict)
|
|
80
|
+
writes: dict[str, str] = field(default_factory=dict) # canonical files to create
|
|
81
|
+
moves: list[tuple[str, str]] = field(default_factory=list) # (original, backup)
|
|
82
|
+
notes: list[str] = field(default_factory=list)
|
|
83
|
+
keep_formatter: bool = True
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def backup_path(src: str) -> str:
|
|
87
|
+
flat = src.replace("\\", "/").lstrip("./").replace("/", "__")
|
|
88
|
+
return f".agents/imported/{flat}.bak"
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _read(p: Path) -> str:
|
|
92
|
+
return p.read_text(encoding="utf-8", errors="replace")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _split(text: str) -> tuple[dict, str]:
|
|
96
|
+
try:
|
|
97
|
+
meta, body = frontmatter.split(text)
|
|
98
|
+
except frontmatter.FrontmatterError:
|
|
99
|
+
return {}, text
|
|
100
|
+
return meta or {}, body
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _paths(value) -> list[str]:
|
|
104
|
+
if value is None:
|
|
105
|
+
return []
|
|
106
|
+
if isinstance(value, str):
|
|
107
|
+
return [p.strip() for p in value.split(",") if p.strip()]
|
|
108
|
+
return [str(p) for p in value]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _rule_text(description: str, paths: list[str], body: str) -> str:
|
|
112
|
+
meta = {"description": description}
|
|
113
|
+
if paths:
|
|
114
|
+
meta["paths"] = paths
|
|
115
|
+
return frontmatter.compose(meta, body)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _slug(name: str) -> str:
|
|
119
|
+
s = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
|
|
120
|
+
return s or "imported"
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def detect_harnesses(root: Path) -> list[str]:
|
|
124
|
+
return [
|
|
125
|
+
h for h, signals in HARNESS_SIGNALS.items() if any((root / s).exists() for s in signals)
|
|
126
|
+
]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def plan(
|
|
130
|
+
root: Path,
|
|
131
|
+
*,
|
|
132
|
+
harnesses: list[str] | None = None,
|
|
133
|
+
preset: str | None = None,
|
|
134
|
+
name: str | None = None,
|
|
135
|
+
minimal: bool = False,
|
|
136
|
+
) -> Plan:
|
|
137
|
+
if (root / CONFIG_PATH).exists():
|
|
138
|
+
raise ValueError(
|
|
139
|
+
f"{CONFIG_PATH} already exists. This repo is already adopted; run `ctxplate sync`."
|
|
140
|
+
)
|
|
141
|
+
preset = preset or detect(root)
|
|
142
|
+
detected = detect_harnesses(root)
|
|
143
|
+
chosen = (
|
|
144
|
+
harnesses
|
|
145
|
+
if harnesses is not None
|
|
146
|
+
else (detected or ["claude", "codex", "copilot", "cursor", "gemini"])
|
|
147
|
+
)
|
|
148
|
+
modules = dict(DEFAULT_MODULES)
|
|
149
|
+
commands = commands_for(preset, root)
|
|
150
|
+
commands["check"] = ""
|
|
151
|
+
if minimal:
|
|
152
|
+
modules.update({"docs": False, "work": False, "ai_app": False})
|
|
153
|
+
p = Plan(preset=preset, harnesses=chosen, commands=commands, modules=modules)
|
|
154
|
+
if not detected and harnesses is None:
|
|
155
|
+
p.notes.append(
|
|
156
|
+
"No agent tool config found; enabling claude, codex, copilot, cursor, gemini. Edit `harnesses` to trim."
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
if (root / "scripts" / "check.sh").exists():
|
|
160
|
+
modules["check_script"] = False
|
|
161
|
+
commands["check"] = "./scripts/check.sh"
|
|
162
|
+
p.notes.append("Kept your existing scripts/check.sh and set it as the check command.")
|
|
163
|
+
|
|
164
|
+
settings = root / ".claude" / "settings.json"
|
|
165
|
+
if settings.is_file():
|
|
166
|
+
try:
|
|
167
|
+
if json.loads(_read(settings)).get("hooks", {}).get("PostToolUse"):
|
|
168
|
+
p.keep_formatter = False
|
|
169
|
+
p.notes.append(
|
|
170
|
+
"Your Claude settings already run a PostToolUse hook, so ContextPlate's format hook is off ([format] is empty)."
|
|
171
|
+
)
|
|
172
|
+
except ValueError:
|
|
173
|
+
pass
|
|
174
|
+
|
|
175
|
+
_plan_instructions(root, p)
|
|
176
|
+
imported_rules = _plan_rules(root, p)
|
|
177
|
+
_plan_skills(root, p)
|
|
178
|
+
_plan_commands(root, p)
|
|
179
|
+
imported_agents = _plan_agents(root, p)
|
|
180
|
+
_plan_mcp(root, p)
|
|
181
|
+
if (root / ".claude" / "workflows").is_dir():
|
|
182
|
+
p.notes.append(".claude/workflows/ is Claude-only and was left as is.")
|
|
183
|
+
|
|
184
|
+
cfg = Config(
|
|
185
|
+
harnesses=chosen,
|
|
186
|
+
name=name or root.resolve().name,
|
|
187
|
+
description="",
|
|
188
|
+
preset=preset,
|
|
189
|
+
modules=modules,
|
|
190
|
+
commands=commands,
|
|
191
|
+
)
|
|
192
|
+
for path, content in canonical_files(cfg).items():
|
|
193
|
+
if (root / path).exists() or path in p.writes:
|
|
194
|
+
continue
|
|
195
|
+
if minimal and path != "AGENTS.md":
|
|
196
|
+
continue
|
|
197
|
+
if path.startswith(".agents/rules/") and imported_rules:
|
|
198
|
+
continue
|
|
199
|
+
if path.startswith(".agents/agents/") and Path(path).stem in imported_agents:
|
|
200
|
+
continue
|
|
201
|
+
p.writes[path] = content
|
|
202
|
+
dir_harness = {
|
|
203
|
+
".claude/": "claude",
|
|
204
|
+
".cursor/": "cursor",
|
|
205
|
+
".github/": "copilot",
|
|
206
|
+
".gemini/": "gemini",
|
|
207
|
+
".codex/": "codex",
|
|
208
|
+
}
|
|
209
|
+
for src, _ in p.moves:
|
|
210
|
+
for prefix, h in dir_harness.items():
|
|
211
|
+
if src.startswith(prefix) and h not in chosen:
|
|
212
|
+
p.notes.append(
|
|
213
|
+
f"{src} moves into .agents/ but `{h}` is not enabled, so it will not be regenerated."
|
|
214
|
+
)
|
|
215
|
+
break
|
|
216
|
+
return p
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _plan_instructions(root: Path, p: Plan) -> None:
|
|
220
|
+
if (root / "AGENTS.md").exists():
|
|
221
|
+
others = [src for src, _ in INSTRUCTION_SOURCES if (root / src).exists()]
|
|
222
|
+
if others:
|
|
223
|
+
p.notes.append(
|
|
224
|
+
"Kept AGENTS.md as the main instructions. Also found "
|
|
225
|
+
+ ", ".join(others)
|
|
226
|
+
+ "; merge anything still useful into AGENTS.md, then delete the duplicates."
|
|
227
|
+
)
|
|
228
|
+
return
|
|
229
|
+
primary = next((src for src, _ in INSTRUCTION_SOURCES if (root / src).is_file()), None)
|
|
230
|
+
if primary is None:
|
|
231
|
+
return # scaffold will create AGENTS.md
|
|
232
|
+
text = _read(root / primary)
|
|
233
|
+
p.writes["AGENTS.md"] = text if text.endswith("\n") else text + "\n"
|
|
234
|
+
p.moves.append((primary, backup_path(primary)))
|
|
235
|
+
p.notes.append(
|
|
236
|
+
f"AGENTS.md created from {primary} (original backed up to {backup_path(primary)})."
|
|
237
|
+
)
|
|
238
|
+
if re.search(r"(?m)^@\S+", text):
|
|
239
|
+
p.notes.append(
|
|
240
|
+
"The imported instructions use @imports; only Claude Code and Copilot expand them. Inline anything other tools need."
|
|
241
|
+
)
|
|
242
|
+
rest = [src for src, _ in INSTRUCTION_SOURCES if src != primary and (root / src).is_file()]
|
|
243
|
+
if rest:
|
|
244
|
+
p.notes.append(
|
|
245
|
+
"Also found "
|
|
246
|
+
+ ", ".join(rest)
|
|
247
|
+
+ "; merge anything still useful into AGENTS.md, then delete them."
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _add_rule(
|
|
252
|
+
p: Plan, root: Path, name: str, content: str, origin: str, seen: dict[str, str]
|
|
253
|
+
) -> None:
|
|
254
|
+
body = _split(content)[1].strip()
|
|
255
|
+
if name in seen:
|
|
256
|
+
if seen[name] == body:
|
|
257
|
+
return
|
|
258
|
+
name = f"{name}-{origin}"
|
|
259
|
+
seen[name] = body
|
|
260
|
+
target = f".agents/rules/{name}.md"
|
|
261
|
+
if (root / target).exists() or target in p.writes:
|
|
262
|
+
return
|
|
263
|
+
p.writes[target] = content
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _plan_rules(root: Path, p: Plan) -> bool:
|
|
267
|
+
seen: dict[str, str] = {}
|
|
268
|
+
found = False
|
|
269
|
+
base = root / ".claude" / "rules"
|
|
270
|
+
if base.is_dir():
|
|
271
|
+
for f in sorted(base.rglob("*.md")):
|
|
272
|
+
meta, body = _split(_read(f))
|
|
273
|
+
name = _slug(f.relative_to(base).with_suffix("").as_posix())
|
|
274
|
+
desc = str(meta.get("description") or name)
|
|
275
|
+
_add_rule(
|
|
276
|
+
p, root, name, _rule_text(desc, _paths(meta.get("paths")), body), "claude", seen
|
|
277
|
+
)
|
|
278
|
+
p.moves.append(
|
|
279
|
+
(f.relative_to(root).as_posix(), backup_path(f.relative_to(root).as_posix()))
|
|
280
|
+
)
|
|
281
|
+
found = True
|
|
282
|
+
base = root / ".cursor" / "rules"
|
|
283
|
+
if base.is_dir():
|
|
284
|
+
for f in sorted(list(base.rglob("*.mdc")) + list(base.rglob("*.md"))):
|
|
285
|
+
meta, body = _split(_read(f))
|
|
286
|
+
rel = f.relative_to(root).as_posix()
|
|
287
|
+
name = _slug(f.relative_to(base).with_suffix("").as_posix())
|
|
288
|
+
desc = str(meta.get("description") or name)
|
|
289
|
+
globs = _paths(meta.get("globs"))
|
|
290
|
+
always = meta.get("alwaysApply") is True or f.suffix == ".md" and not meta
|
|
291
|
+
if not always and not globs:
|
|
292
|
+
# "Apply intelligently" rules load by description: that is a skill.
|
|
293
|
+
skill = _slug(name)
|
|
294
|
+
if SKILL_NAME_RE.match(skill) and not (root / ".agents/skills" / skill).exists():
|
|
295
|
+
p.writes[f".agents/skills/{skill}/SKILL.md"] = frontmatter.compose(
|
|
296
|
+
{"name": skill, "description": desc}, body
|
|
297
|
+
)
|
|
298
|
+
p.notes.append(f"{rel} loads by description, so it became the skill `{skill}`.")
|
|
299
|
+
else:
|
|
300
|
+
_add_rule(
|
|
301
|
+
p, root, name, _rule_text(desc, [] if always else globs, body), "cursor", seen
|
|
302
|
+
)
|
|
303
|
+
p.moves.append((rel, backup_path(rel)))
|
|
304
|
+
found = True
|
|
305
|
+
base = root / ".github" / "instructions"
|
|
306
|
+
if base.is_dir():
|
|
307
|
+
for f in sorted(base.rglob("*.instructions.md")):
|
|
308
|
+
meta, body = _split(_read(f))
|
|
309
|
+
rel = f.relative_to(root).as_posix()
|
|
310
|
+
name = _slug(f.name[: -len(".instructions.md")])
|
|
311
|
+
apply_to = _paths(meta.get("applyTo"))
|
|
312
|
+
paths = [] if apply_to in (["**"], ["**/*"]) else apply_to
|
|
313
|
+
desc = str(meta.get("description") or name)
|
|
314
|
+
_add_rule(p, root, name, _rule_text(desc, paths, body), "copilot", seen)
|
|
315
|
+
p.moves.append((rel, backup_path(rel)))
|
|
316
|
+
found = True
|
|
317
|
+
return found
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _plan_commands(root: Path, p: Plan) -> None:
|
|
321
|
+
"""Claude custom commands (.claude/commands/*.md) become manual skills."""
|
|
322
|
+
base = root / ".claude" / "commands"
|
|
323
|
+
if not base.is_dir():
|
|
324
|
+
return
|
|
325
|
+
claude_syntax = False
|
|
326
|
+
for f in sorted(base.rglob("*.md")):
|
|
327
|
+
rel = f.relative_to(root).as_posix()
|
|
328
|
+
name = _slug(f.relative_to(base).with_suffix("").as_posix())
|
|
329
|
+
target = f".agents/skills/{name}/SKILL.md"
|
|
330
|
+
meta, body = _split(_read(f))
|
|
331
|
+
if not ((root / target).exists() or target in p.writes):
|
|
332
|
+
first = next((ln.strip("# ").strip() for ln in body.splitlines() if ln.strip()), name)
|
|
333
|
+
out: dict = {"name": name, "description": str(meta.get("description") or first)[:1024]}
|
|
334
|
+
if "allowed-tools" in meta:
|
|
335
|
+
out["allowed-tools"] = meta["allowed-tools"]
|
|
336
|
+
md: dict = {"invocation": "manual"}
|
|
337
|
+
if "argument-hint" in meta:
|
|
338
|
+
md["argument-hint"] = str(meta["argument-hint"])
|
|
339
|
+
for k, v in meta.items():
|
|
340
|
+
if k not in ("description", "allowed-tools", "argument-hint"):
|
|
341
|
+
md[f"claude-{k}"] = v if isinstance(v, str) else json.dumps(v)
|
|
342
|
+
out["metadata"] = md
|
|
343
|
+
p.writes[target] = frontmatter.compose(out, body)
|
|
344
|
+
claude_syntax = claude_syntax or bool(re.search(r"\$ARGUMENTS|\$\d|!`", body))
|
|
345
|
+
p.moves.append((rel, backup_path(rel)))
|
|
346
|
+
p.notes.append("Claude commands in .claude/commands/ became manual skills in .agents/skills/.")
|
|
347
|
+
if claude_syntax:
|
|
348
|
+
p.notes.append(
|
|
349
|
+
"Some imported commands use Claude-only syntax ($ARGUMENTS, !`cmd`); other tools will read it as plain text."
|
|
350
|
+
)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _plan_skills(root: Path, p: Plan) -> None:
|
|
354
|
+
for src in (".claude/skills", ".cursor/skills", ".github/skills"):
|
|
355
|
+
base = root / src
|
|
356
|
+
if not base.is_dir():
|
|
357
|
+
continue
|
|
358
|
+
for d in sorted(x for x in base.iterdir() if x.is_dir() and (x / "SKILL.md").exists()):
|
|
359
|
+
target = f".agents/skills/{d.name}"
|
|
360
|
+
exists = (root / target).exists() or any(k.startswith(target + "/") for k in p.writes)
|
|
361
|
+
for f in sorted(x for x in d.rglob("*") if x.is_file()):
|
|
362
|
+
rel = f.relative_to(root).as_posix()
|
|
363
|
+
if not exists:
|
|
364
|
+
try:
|
|
365
|
+
text = _read(f)
|
|
366
|
+
except OSError:
|
|
367
|
+
continue
|
|
368
|
+
if f.name == "SKILL.md":
|
|
369
|
+
text = _neutral_skill(text)
|
|
370
|
+
p.writes[f"{target}/{f.relative_to(d).as_posix()}"] = text
|
|
371
|
+
p.moves.append((rel, backup_path(rel)))
|
|
372
|
+
if exists:
|
|
373
|
+
p.notes.append(
|
|
374
|
+
f"Skill `{d.name}` already exists in .agents/skills; backed up the copy from {src}."
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _neutral_skill(text: str) -> str:
|
|
379
|
+
meta, body = _split(text)
|
|
380
|
+
if not meta:
|
|
381
|
+
return text
|
|
382
|
+
out = {
|
|
383
|
+
k: meta[k]
|
|
384
|
+
for k in ("name", "description", "license", "compatibility", "allowed-tools")
|
|
385
|
+
if k in meta
|
|
386
|
+
}
|
|
387
|
+
md = dict(meta.get("metadata") or {})
|
|
388
|
+
if meta.get("disable-model-invocation") is True:
|
|
389
|
+
md["invocation"] = "manual"
|
|
390
|
+
if "argument-hint" in meta:
|
|
391
|
+
md["argument-hint"] = str(meta["argument-hint"])
|
|
392
|
+
for k, v in meta.items():
|
|
393
|
+
if k not in out and k not in ("metadata", "disable-model-invocation", "argument-hint"):
|
|
394
|
+
md[f"claude-{k}"] = v if isinstance(v, str) else json.dumps(v)
|
|
395
|
+
if md:
|
|
396
|
+
out["metadata"] = md
|
|
397
|
+
return frontmatter.compose(out, body)
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _agent_doc(name: str, description: str, tools, model: str, overrides: dict, body: str) -> str:
|
|
401
|
+
meta: dict = {"name": name, "description": description}
|
|
402
|
+
if tools is not None:
|
|
403
|
+
meta["tools"] = tools
|
|
404
|
+
meta["model"] = model
|
|
405
|
+
meta.update(overrides)
|
|
406
|
+
return frontmatter.compose(meta, body)
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def _plan_agents(root: Path, p: Plan) -> set[str]:
|
|
410
|
+
names: set[str] = set()
|
|
411
|
+
|
|
412
|
+
def add(name: str, doc: str, rel: str) -> None:
|
|
413
|
+
p.moves.append((rel, backup_path(rel)))
|
|
414
|
+
if name in names or (root / ".agents/agents" / f"{name}.md").exists():
|
|
415
|
+
return
|
|
416
|
+
names.add(name)
|
|
417
|
+
p.writes[f".agents/agents/{name}.md"] = doc
|
|
418
|
+
|
|
419
|
+
for f in (
|
|
420
|
+
sorted((root / ".claude/agents").glob("*.md")) if (root / ".claude/agents").is_dir() else []
|
|
421
|
+
):
|
|
422
|
+
meta, body = _split(_read(f))
|
|
423
|
+
name = _slug(str(meta.get("name") or f.stem))
|
|
424
|
+
tools = None
|
|
425
|
+
claude_tools = _paths(meta.get("tools")) if meta.get("tools") else []
|
|
426
|
+
if claude_tools:
|
|
427
|
+
mapped = []
|
|
428
|
+
for t in claude_tools:
|
|
429
|
+
n = CLAUDE_TOOLS.get(t)
|
|
430
|
+
if n and n not in mapped:
|
|
431
|
+
mapped.append(n)
|
|
432
|
+
tools = mapped
|
|
433
|
+
overrides = {
|
|
434
|
+
f"claude.{k}": v
|
|
435
|
+
for k, v in meta.items()
|
|
436
|
+
if k not in ("name", "description", "tools", "model")
|
|
437
|
+
and isinstance(v, (str, bool, int))
|
|
438
|
+
}
|
|
439
|
+
if any(t not in CLAUDE_TOOLS for t in claude_tools):
|
|
440
|
+
# Keep Claude's exact list (e.g. TodoWrite, MCP tools); other tools get the neutral subset.
|
|
441
|
+
overrides["claude.tools"] = ", ".join(claude_tools)
|
|
442
|
+
model = str(meta.get("model") or "inherit")
|
|
443
|
+
tier = MODEL_TIERS.get(model)
|
|
444
|
+
if tier is None:
|
|
445
|
+
overrides["claude.model"] = model
|
|
446
|
+
tier = "inherit"
|
|
447
|
+
add(
|
|
448
|
+
name,
|
|
449
|
+
_agent_doc(name, str(meta.get("description", "")), tools, tier, overrides, body),
|
|
450
|
+
f.relative_to(root).as_posix(),
|
|
451
|
+
)
|
|
452
|
+
|
|
453
|
+
for src, ext in (
|
|
454
|
+
(".cursor/agents", "*.md"),
|
|
455
|
+
(".github/agents", "*.md"),
|
|
456
|
+
(".gemini/agents", "*.md"),
|
|
457
|
+
):
|
|
458
|
+
base = root / src
|
|
459
|
+
if not base.is_dir():
|
|
460
|
+
continue
|
|
461
|
+
harness = src.split("/")[1].lstrip(".")
|
|
462
|
+
harness = {"github": "copilot"}.get(harness, harness)
|
|
463
|
+
for f in sorted(base.glob(ext)):
|
|
464
|
+
meta, body = _split(_read(f))
|
|
465
|
+
stem = f.name.removesuffix(".agent.md").removesuffix(".md")
|
|
466
|
+
name = _slug(str(meta.get("name") or stem))
|
|
467
|
+
tools = None
|
|
468
|
+
if harness == "copilot" and meta.get("tools"):
|
|
469
|
+
tools = sorted(
|
|
470
|
+
{
|
|
471
|
+
COPILOT_TOOLS[t.lower()]
|
|
472
|
+
for t in _paths(meta["tools"])
|
|
473
|
+
if t.lower() in COPILOT_TOOLS
|
|
474
|
+
}
|
|
475
|
+
)
|
|
476
|
+
if harness == "cursor" and meta.get("readonly") is True:
|
|
477
|
+
tools = ["read", "search"]
|
|
478
|
+
overrides = {}
|
|
479
|
+
if meta.get("model") and str(meta["model"]) not in ("inherit",):
|
|
480
|
+
overrides[f"{harness}.model"] = str(meta["model"])
|
|
481
|
+
for k, v in meta.items():
|
|
482
|
+
if k not in ("name", "description", "tools", "model", "readonly") and isinstance(
|
|
483
|
+
v, (str, bool, int)
|
|
484
|
+
):
|
|
485
|
+
overrides[f"{harness}.{k}"] = v
|
|
486
|
+
add(
|
|
487
|
+
name,
|
|
488
|
+
_agent_doc(
|
|
489
|
+
name, str(meta.get("description", "")), tools, "inherit", overrides, body
|
|
490
|
+
),
|
|
491
|
+
f.relative_to(root).as_posix(),
|
|
492
|
+
)
|
|
493
|
+
|
|
494
|
+
base = root / ".codex/agents"
|
|
495
|
+
if base.is_dir():
|
|
496
|
+
for f in sorted(base.glob("*.toml")):
|
|
497
|
+
try:
|
|
498
|
+
data = tomllib.loads(_read(f))
|
|
499
|
+
except tomllib.TOMLDecodeError:
|
|
500
|
+
p.notes.append(
|
|
501
|
+
f"Could not parse {f.relative_to(root).as_posix()}; left it in place."
|
|
502
|
+
)
|
|
503
|
+
continue
|
|
504
|
+
name = _slug(str(data.get("name") or f.stem))
|
|
505
|
+
tools = ["read", "search"] if data.get("sandbox_mode") == "read-only" else None
|
|
506
|
+
overrides = {
|
|
507
|
+
f"codex.{k}": v
|
|
508
|
+
for k, v in data.items()
|
|
509
|
+
if k not in ("name", "description", "developer_instructions", "sandbox_mode")
|
|
510
|
+
and isinstance(v, (str, bool, int))
|
|
511
|
+
}
|
|
512
|
+
add(
|
|
513
|
+
name,
|
|
514
|
+
_agent_doc(
|
|
515
|
+
name,
|
|
516
|
+
str(data.get("description", "")),
|
|
517
|
+
tools,
|
|
518
|
+
"inherit",
|
|
519
|
+
overrides,
|
|
520
|
+
str(data.get("developer_instructions", "")),
|
|
521
|
+
),
|
|
522
|
+
f.relative_to(root).as_posix(),
|
|
523
|
+
)
|
|
524
|
+
return names
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def _neutral_server(s: dict) -> dict | None:
|
|
528
|
+
if "command" in s:
|
|
529
|
+
out = {"command": s["command"]}
|
|
530
|
+
if s.get("args"):
|
|
531
|
+
out["args"] = [re.sub(r"\$\{env:(\w+)\}", r"${\1}", str(a)) for a in s["args"]]
|
|
532
|
+
if s.get("env"):
|
|
533
|
+
out["env"] = {
|
|
534
|
+
k: re.sub(r"\$\{env:(\w+)\}", r"${\1}", str(v)) for k, v in s["env"].items()
|
|
535
|
+
}
|
|
536
|
+
return out
|
|
537
|
+
url = s.get("url") or s.get("httpUrl") or s.get("serverUrl")
|
|
538
|
+
if not url:
|
|
539
|
+
return None
|
|
540
|
+
out = {"url": re.sub(r"\$\{env:(\w+)\}", r"${\1}", str(url))}
|
|
541
|
+
if s.get("headers"):
|
|
542
|
+
out["headers"] = {
|
|
543
|
+
k: re.sub(r"\$\{env:(\w+)\}", r"${\1}", str(v)) for k, v in s["headers"].items()
|
|
544
|
+
}
|
|
545
|
+
return out
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def _plan_mcp(root: Path, p: Plan) -> None:
|
|
549
|
+
sources = []
|
|
550
|
+
for rel, key in (
|
|
551
|
+
(".mcp.json", "mcpServers"),
|
|
552
|
+
(".cursor/mcp.json", "mcpServers"),
|
|
553
|
+
(".gemini/settings.json", "mcpServers"),
|
|
554
|
+
(".vscode/mcp.json", "servers"),
|
|
555
|
+
):
|
|
556
|
+
f = root / rel
|
|
557
|
+
if f.is_file():
|
|
558
|
+
try:
|
|
559
|
+
sources.append((rel, json.loads(_read(f)).get(key, {})))
|
|
560
|
+
except ValueError:
|
|
561
|
+
p.notes.append(f"{rel} is not valid JSON; skipped its MCP servers.")
|
|
562
|
+
f = root / ".codex/config.toml"
|
|
563
|
+
if f.is_file():
|
|
564
|
+
try:
|
|
565
|
+
sources.append((".codex/config.toml", tomllib.loads(_read(f)).get("mcp_servers", {})))
|
|
566
|
+
except tomllib.TOMLDecodeError:
|
|
567
|
+
p.notes.append(".codex/config.toml is not valid TOML; skipped its MCP servers.")
|
|
568
|
+
for _rel, servers in sources:
|
|
569
|
+
for name, s in servers.items():
|
|
570
|
+
if name in p.mcp or not isinstance(s, dict):
|
|
571
|
+
continue
|
|
572
|
+
neutral = _neutral_server(s)
|
|
573
|
+
if neutral:
|
|
574
|
+
p.mcp[name] = neutral
|
|
575
|
+
if p.mcp:
|
|
576
|
+
p.notes.append(f"Imported MCP servers into the config: {', '.join(p.mcp)}.")
|
|
577
|
+
|
|
578
|
+
|
|
579
|
+
def apply(root: Path, p: Plan) -> None:
|
|
580
|
+
for src, dest in p.moves:
|
|
581
|
+
s, d = root / src, root / dest
|
|
582
|
+
if not s.exists():
|
|
583
|
+
continue
|
|
584
|
+
d.parent.mkdir(parents=True, exist_ok=True)
|
|
585
|
+
shutil.move(str(s), str(d))
|
|
586
|
+
parent = s.parent
|
|
587
|
+
while parent != root and parent.exists() and not any(parent.iterdir()):
|
|
588
|
+
parent.rmdir()
|
|
589
|
+
parent = parent.parent
|
|
590
|
+
for path, content in p.writes.items():
|
|
591
|
+
target = root / path
|
|
592
|
+
if target.exists():
|
|
593
|
+
continue
|
|
594
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
595
|
+
with open(target, "w", encoding="utf-8", newline="\n") as fh:
|
|
596
|
+
fh.write(content)
|