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/cli.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"""Command-line interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from . import CONFIG_PATH, __version__, adopt, doctor, writer
|
|
12
|
+
from .adapters import build_context, build_outputs
|
|
13
|
+
from .config import (
|
|
14
|
+
DEFAULT_MODULES,
|
|
15
|
+
HARNESSES,
|
|
16
|
+
MODULES,
|
|
17
|
+
Config,
|
|
18
|
+
ConfigError,
|
|
19
|
+
load,
|
|
20
|
+
render,
|
|
21
|
+
set_harnesses,
|
|
22
|
+
)
|
|
23
|
+
from .model import ContentError
|
|
24
|
+
from .presets import PRESETS, commands_for, detect
|
|
25
|
+
from .scaffold import canonical_files
|
|
26
|
+
|
|
27
|
+
CLI_NAMES = {
|
|
28
|
+
"claude": ["claude"],
|
|
29
|
+
"codex": ["codex"],
|
|
30
|
+
"gemini": ["gemini"],
|
|
31
|
+
"cursor": ["cursor-agent", "cursor"],
|
|
32
|
+
"copilot": ["copilot"],
|
|
33
|
+
"aider": ["aider"],
|
|
34
|
+
}
|
|
35
|
+
DEFAULT_HARNESSES = ["claude", "codex", "copilot", "cursor", "gemini"]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _parse_list(value: str | None, valid: dict, what: str) -> list[str] | None:
|
|
39
|
+
if value is None:
|
|
40
|
+
return None
|
|
41
|
+
if value == "all":
|
|
42
|
+
return list(valid)
|
|
43
|
+
if value == "none":
|
|
44
|
+
return []
|
|
45
|
+
items = [v.strip() for v in value.split(",") if v.strip()]
|
|
46
|
+
bad = [v for v in items if v not in valid]
|
|
47
|
+
if bad:
|
|
48
|
+
raise SystemExit(f"error: unknown {what} {bad}. Valid: {', '.join(valid)}")
|
|
49
|
+
return items
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def detect_installed() -> list[str]:
|
|
53
|
+
return [h for h, names in CLI_NAMES.items() if any(shutil.which(n) for n in names)]
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _print_result(result: writer.Result, verbose: bool) -> None:
|
|
57
|
+
for a in result.actions:
|
|
58
|
+
if a.kind == "unchanged" and not verbose:
|
|
59
|
+
continue
|
|
60
|
+
detail = f" ({a.detail})" if a.detail else ""
|
|
61
|
+
print(f" {a.kind:<9} {a.path}{detail}")
|
|
62
|
+
counts = {
|
|
63
|
+
k: result.count(k) for k in ("create", "update", "delete", "conflict", "keep", "unchanged")
|
|
64
|
+
}
|
|
65
|
+
summary = ", ".join(f"{v} {k}" for k, v in counts.items() if v)
|
|
66
|
+
print(f" {summary or 'nothing to do'}")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def do_sync(root: Path, *, dry_run=False, force=False, verbose=False, quiet=False) -> int:
|
|
70
|
+
cfg = load(root)
|
|
71
|
+
ctx = build_context(root, cfg)
|
|
72
|
+
result = writer.sync(root, build_outputs(ctx), dry_run=dry_run, force=force)
|
|
73
|
+
if not quiet:
|
|
74
|
+
_print_result(result, verbose)
|
|
75
|
+
for w in cfg.warnings + ctx.warnings:
|
|
76
|
+
print(f" warning: {w}")
|
|
77
|
+
if result.count("conflict"):
|
|
78
|
+
print(
|
|
79
|
+
" Conflicts were left untouched. Move your change into .agents/ (the source), then run `ctxplate sync --force`."
|
|
80
|
+
)
|
|
81
|
+
return 1 if (dry_run and result.changed) else 0
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def cmd_init(args) -> int:
|
|
85
|
+
root = Path(args.dir).resolve()
|
|
86
|
+
if root.exists() and any(p.name != ".git" for p in root.iterdir()) and not args.force:
|
|
87
|
+
print(
|
|
88
|
+
f"error: {root} is not empty. Use `ctxplate adopt` for existing projects, or --force.",
|
|
89
|
+
file=sys.stderr,
|
|
90
|
+
)
|
|
91
|
+
return 1
|
|
92
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
93
|
+
harnesses = _parse_list(args.harness, HARNESSES, "harness")
|
|
94
|
+
detected_note = ""
|
|
95
|
+
if harnesses is None:
|
|
96
|
+
harnesses = detect_installed() or DEFAULT_HARNESSES
|
|
97
|
+
detected_note = (
|
|
98
|
+
" (detected on PATH)" if detect_installed() else " (default; none detected on PATH)"
|
|
99
|
+
)
|
|
100
|
+
preset = args.preset or detect(root)
|
|
101
|
+
modules = dict(DEFAULT_MODULES)
|
|
102
|
+
for m in _parse_list(args.with_modules, MODULES, "module") or []:
|
|
103
|
+
modules[m] = True
|
|
104
|
+
for m in _parse_list(args.without_modules, MODULES, "module") or []:
|
|
105
|
+
modules[m] = False
|
|
106
|
+
cfg = Config(
|
|
107
|
+
harnesses=harnesses,
|
|
108
|
+
name=args.name or root.name,
|
|
109
|
+
description=args.description or "",
|
|
110
|
+
preset=preset,
|
|
111
|
+
modules=modules,
|
|
112
|
+
commands={**commands_for(preset), "check": ""},
|
|
113
|
+
format=dict(PRESETS[preset]["format"]),
|
|
114
|
+
)
|
|
115
|
+
if modules["ai_app"]:
|
|
116
|
+
from .config import AI_APP_NO_EDIT, AI_APP_NO_READ
|
|
117
|
+
|
|
118
|
+
cfg.no_read += AI_APP_NO_READ
|
|
119
|
+
cfg.no_edit += AI_APP_NO_EDIT
|
|
120
|
+
(root / ".agents").mkdir(exist_ok=True)
|
|
121
|
+
writer.write_text(root / CONFIG_PATH, render(cfg))
|
|
122
|
+
created = 0
|
|
123
|
+
for path, content in canonical_files(cfg).items():
|
|
124
|
+
target = root / path
|
|
125
|
+
if not target.exists():
|
|
126
|
+
writer.write_text(target, content)
|
|
127
|
+
created += 1
|
|
128
|
+
print(f"ctxplate init: {root}")
|
|
129
|
+
print(f" preset {preset}, harnesses {', '.join(harnesses) or 'none'}{detected_note}")
|
|
130
|
+
print(f" wrote {CONFIG_PATH} and {created} starter files")
|
|
131
|
+
do_sync(root)
|
|
132
|
+
if not args.no_git and not (root / ".git").exists() and shutil.which("git"):
|
|
133
|
+
subprocess.run(["git", "init", "-q"], cwd=root, check=False)
|
|
134
|
+
print(" initialized git repository")
|
|
135
|
+
print("\nNext:")
|
|
136
|
+
print(" 1. Fill in the <placeholders> in AGENTS.md (or ask your agent to, from the code).")
|
|
137
|
+
print(f" 2. Check [commands] in {CONFIG_PATH}, then `ctxplate sync`.")
|
|
138
|
+
print(" 3. `ctxplate doctor` any time to check budget and drift.")
|
|
139
|
+
return 0
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def cmd_adopt(args) -> int:
|
|
143
|
+
root = Path(args.dir).resolve()
|
|
144
|
+
try:
|
|
145
|
+
p = adopt.plan(
|
|
146
|
+
root,
|
|
147
|
+
harnesses=_parse_list(args.harness, HARNESSES, "harness"),
|
|
148
|
+
preset=args.preset,
|
|
149
|
+
minimal=args.minimal,
|
|
150
|
+
)
|
|
151
|
+
except ValueError as e:
|
|
152
|
+
print(f"error: {e}", file=sys.stderr)
|
|
153
|
+
return 1
|
|
154
|
+
print(f"ctxplate adopt: {root}{'' if args.apply else ' (dry run; nothing written)'}")
|
|
155
|
+
print(f" preset {p.preset}, harnesses {', '.join(p.harnesses)}")
|
|
156
|
+
if p.moves:
|
|
157
|
+
print(" back up (originals are re-generated from .agents/):")
|
|
158
|
+
for src, dest in p.moves:
|
|
159
|
+
print(f" move {src} -> {dest}")
|
|
160
|
+
if p.writes:
|
|
161
|
+
print(" create:")
|
|
162
|
+
for path in sorted(p.writes):
|
|
163
|
+
print(f" create {path}")
|
|
164
|
+
for n in p.notes:
|
|
165
|
+
print(f" note: {n}")
|
|
166
|
+
if not args.apply:
|
|
167
|
+
print("\nRe-run with --apply to make these changes, then review `git diff`.")
|
|
168
|
+
return 0
|
|
169
|
+
adopt.apply(root, p)
|
|
170
|
+
cfg = Config(
|
|
171
|
+
harnesses=p.harnesses,
|
|
172
|
+
name=root.name,
|
|
173
|
+
description="",
|
|
174
|
+
preset=p.preset,
|
|
175
|
+
modules=p.modules,
|
|
176
|
+
commands=p.commands,
|
|
177
|
+
format=dict(PRESETS[p.preset]["format"]) if p.keep_formatter else {},
|
|
178
|
+
mcp=p.mcp,
|
|
179
|
+
)
|
|
180
|
+
writer.write_text(root / CONFIG_PATH, render(cfg))
|
|
181
|
+
print(f" wrote {CONFIG_PATH}")
|
|
182
|
+
do_sync(root)
|
|
183
|
+
print(
|
|
184
|
+
"\nNext: review `git diff`, merge anything in .agents/imported/ that still matters into AGENTS.md or .agents/, then delete .agents/imported/."
|
|
185
|
+
)
|
|
186
|
+
return 0
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def cmd_sync(args) -> int:
|
|
190
|
+
root = Path(args.dir).resolve()
|
|
191
|
+
if args.check:
|
|
192
|
+
rc = do_sync(root, dry_run=True, verbose=args.verbose)
|
|
193
|
+
print(" in sync" if rc == 0 else " out of sync: run `ctxplate sync`")
|
|
194
|
+
return rc
|
|
195
|
+
print(f"ctxplate sync{' (dry run)' if args.dry_run else ''}: {root}")
|
|
196
|
+
rc = do_sync(root, dry_run=args.dry_run, force=args.force, verbose=args.verbose)
|
|
197
|
+
return 0 if args.dry_run else rc
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def cmd_doctor(args) -> int:
|
|
201
|
+
root = Path(args.dir).resolve()
|
|
202
|
+
rep = doctor.run(root, load(root))
|
|
203
|
+
for level, msg in rep.items:
|
|
204
|
+
print(f" {level:<4} {msg}")
|
|
205
|
+
if rep.has("fail") or (args.strict and rep.has("warn")):
|
|
206
|
+
return 1
|
|
207
|
+
return 0
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _toggle(args, enable: bool) -> int:
|
|
211
|
+
root = Path(args.dir).resolve()
|
|
212
|
+
cfg = load(root)
|
|
213
|
+
names = _parse_list(",".join(args.harnesses), HARNESSES, "harness") or []
|
|
214
|
+
current = list(cfg.harnesses)
|
|
215
|
+
for n in names:
|
|
216
|
+
if enable and n not in current:
|
|
217
|
+
current.append(n)
|
|
218
|
+
if not enable and n in current:
|
|
219
|
+
current.remove(n)
|
|
220
|
+
path = root / CONFIG_PATH
|
|
221
|
+
writer.write_text(path, set_harnesses(path.read_text(encoding="utf-8"), current))
|
|
222
|
+
print(f"harnesses: {', '.join(current) or 'none'}")
|
|
223
|
+
return do_sync(root)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def cmd_list(_args) -> int:
|
|
227
|
+
print("Harnesses (enable with `ctxplate enable <name>`):")
|
|
228
|
+
for k, v in HARNESSES.items():
|
|
229
|
+
print(f" {k:<9} {v}")
|
|
230
|
+
print(" (any other AGENTS.md-aware tool works without an entry)")
|
|
231
|
+
print("\nPresets (`--preset`):")
|
|
232
|
+
for k, v in PRESETS.items():
|
|
233
|
+
print(f" {k:<9} {v['title']}")
|
|
234
|
+
print("\nModules (`--with` / `--without`):")
|
|
235
|
+
for k, v in MODULES.items():
|
|
236
|
+
print(f" {k:<13} {v}")
|
|
237
|
+
return 0
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
241
|
+
ap = argparse.ArgumentParser(
|
|
242
|
+
prog="ctxplate",
|
|
243
|
+
description="ContextPlate: boilerplate for agent context. Declare it once; render it for every harness.",
|
|
244
|
+
)
|
|
245
|
+
ap.add_argument("--version", action="version", version=f"ctxplate (ContextPlate) {__version__}")
|
|
246
|
+
sub = ap.add_subparsers(dest="command", required=True)
|
|
247
|
+
|
|
248
|
+
p = sub.add_parser("init", help="create a new project")
|
|
249
|
+
p.add_argument("dir", nargs="?", default=".")
|
|
250
|
+
p.add_argument("--name")
|
|
251
|
+
p.add_argument("--description")
|
|
252
|
+
p.add_argument("--preset", choices=list(PRESETS))
|
|
253
|
+
p.add_argument("--harness", help="comma list, 'all', or 'none' (default: tools found on PATH)")
|
|
254
|
+
p.add_argument("--with", dest="with_modules", help=f"enable modules: {', '.join(MODULES)}")
|
|
255
|
+
p.add_argument("--without", dest="without_modules", help="disable modules")
|
|
256
|
+
p.add_argument("--no-git", action="store_true")
|
|
257
|
+
p.add_argument("--force", action="store_true", help="allow a non-empty directory")
|
|
258
|
+
p.set_defaults(func=cmd_init)
|
|
259
|
+
|
|
260
|
+
p = sub.add_parser("adopt", help="organize an existing repository (dry run unless --apply)")
|
|
261
|
+
p.add_argument("dir", nargs="?", default=".")
|
|
262
|
+
p.add_argument("--harness", help="comma list or 'all' (default: detected from existing files)")
|
|
263
|
+
p.add_argument("--preset", choices=list(PRESETS))
|
|
264
|
+
p.add_argument(
|
|
265
|
+
"--minimal",
|
|
266
|
+
action="store_true",
|
|
267
|
+
help="only import what exists; add no starter docs, roles, or skills",
|
|
268
|
+
)
|
|
269
|
+
p.add_argument("--apply", action="store_true")
|
|
270
|
+
p.set_defaults(func=cmd_adopt)
|
|
271
|
+
|
|
272
|
+
p = sub.add_parser("sync", help="regenerate harness files from .agents/")
|
|
273
|
+
p.add_argument("-C", dest="dir", default=".")
|
|
274
|
+
p.add_argument(
|
|
275
|
+
"--check", action="store_true", help="exit 1 if anything is out of date (for CI)"
|
|
276
|
+
)
|
|
277
|
+
p.add_argument("--dry-run", action="store_true")
|
|
278
|
+
p.add_argument("--force", action="store_true", help="overwrite generated files you edited")
|
|
279
|
+
p.add_argument("-v", "--verbose", action="store_true")
|
|
280
|
+
p.set_defaults(func=cmd_sync)
|
|
281
|
+
|
|
282
|
+
p = sub.add_parser("doctor", help="check context budget, placeholders, portability, drift")
|
|
283
|
+
p.add_argument("-C", dest="dir", default=".")
|
|
284
|
+
p.add_argument("--strict", action="store_true", help="treat warnings as failures")
|
|
285
|
+
p.set_defaults(func=cmd_doctor)
|
|
286
|
+
|
|
287
|
+
for name, enable in (("enable", True), ("disable", False)):
|
|
288
|
+
p = sub.add_parser(name, help=f"{name} harnesses and sync")
|
|
289
|
+
p.add_argument("harnesses", nargs="+")
|
|
290
|
+
p.add_argument("-C", dest="dir", default=".")
|
|
291
|
+
p.set_defaults(func=lambda a, e=enable: _toggle(a, e))
|
|
292
|
+
|
|
293
|
+
p = sub.add_parser("list", help="show harnesses, presets, and modules")
|
|
294
|
+
p.set_defaults(func=cmd_list)
|
|
295
|
+
return ap
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def main(argv: list[str] | None = None) -> int:
|
|
299
|
+
args = build_parser().parse_args(argv)
|
|
300
|
+
try:
|
|
301
|
+
return args.func(args)
|
|
302
|
+
except (ConfigError, ContentError, ValueError) as e:
|
|
303
|
+
print(f"error: {e}", file=sys.stderr)
|
|
304
|
+
return 1
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
if __name__ == "__main__":
|
|
308
|
+
sys.exit(main())
|
contextplate/config.py
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
"""Load, validate, and render .agents/contextplate.toml."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import tomllib
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from . import CONFIG_PATH
|
|
12
|
+
from .presets import PRESETS
|
|
13
|
+
|
|
14
|
+
HARNESSES: dict[str, str] = {
|
|
15
|
+
"claude": "Claude Code",
|
|
16
|
+
"codex": "OpenAI Codex",
|
|
17
|
+
"copilot": "GitHub Copilot (VS Code, CLI, cloud agent)",
|
|
18
|
+
"cursor": "Cursor",
|
|
19
|
+
"gemini": "Gemini CLI",
|
|
20
|
+
"aider": "Aider",
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
MODULES: dict[str, str] = {
|
|
24
|
+
"docs": "docs/ (architecture, glossary, decisions) plus the adr skill",
|
|
25
|
+
"work": "work/ (handoff, plans, scratch) plus plan-task and handoff skills",
|
|
26
|
+
"ai_app": "prompts/, evals/, data/ for projects that ship LLM features",
|
|
27
|
+
"hooks": "Claude Code hooks: protect files, session snapshot, auto-format",
|
|
28
|
+
"check_script": "scripts/check.sh: one command for lint + types + tests",
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
DEFAULT_MODULES = {"docs": True, "work": True, "ai_app": False, "hooks": True, "check_script": True}
|
|
32
|
+
|
|
33
|
+
DEFAULT_NO_READ = [".env", ".env.*", "!.env.example"]
|
|
34
|
+
DEFAULT_NO_EDIT = [
|
|
35
|
+
".env",
|
|
36
|
+
".env.*",
|
|
37
|
+
"!.env.example",
|
|
38
|
+
".git/**",
|
|
39
|
+
"package-lock.json",
|
|
40
|
+
"pnpm-lock.yaml",
|
|
41
|
+
"yarn.lock",
|
|
42
|
+
"bun.lock",
|
|
43
|
+
"bun.lockb",
|
|
44
|
+
"poetry.lock",
|
|
45
|
+
"uv.lock",
|
|
46
|
+
"Cargo.lock",
|
|
47
|
+
"go.sum",
|
|
48
|
+
"Gemfile.lock",
|
|
49
|
+
"composer.lock",
|
|
50
|
+
]
|
|
51
|
+
AI_APP_NO_READ = ["data/raw/**", "evals/results/**"]
|
|
52
|
+
AI_APP_NO_EDIT = ["data/raw/**"]
|
|
53
|
+
|
|
54
|
+
# Neutral model tiers -> harness model ids. Unmapped tiers inherit the session model.
|
|
55
|
+
DEFAULT_MODELS = {"claude": {"fast": "haiku", "strong": "opus"}, "cursor": {"fast": "fast"}}
|
|
56
|
+
|
|
57
|
+
COMMAND_KEYS = ["install", "dev", "lint", "typecheck", "test", "format", "check"]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class ConfigError(ValueError):
|
|
61
|
+
pass
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass
|
|
65
|
+
class Config:
|
|
66
|
+
harnesses: list[str]
|
|
67
|
+
name: str
|
|
68
|
+
description: str
|
|
69
|
+
preset: str = "generic"
|
|
70
|
+
modules: dict[str, bool] = field(default_factory=lambda: dict(DEFAULT_MODULES))
|
|
71
|
+
commands: dict[str, str] = field(default_factory=dict)
|
|
72
|
+
no_read: list[str] = field(default_factory=lambda: list(DEFAULT_NO_READ))
|
|
73
|
+
no_edit: list[str] = field(default_factory=lambda: list(DEFAULT_NO_EDIT))
|
|
74
|
+
format: dict[str, str] = field(default_factory=dict)
|
|
75
|
+
budget_tokens: int = 1200
|
|
76
|
+
index: str = "compact"
|
|
77
|
+
python: str = "python3"
|
|
78
|
+
models: dict[str, dict[str, str]] = field(
|
|
79
|
+
default_factory=lambda: json.loads(json.dumps(DEFAULT_MODELS))
|
|
80
|
+
)
|
|
81
|
+
mcp: dict[str, dict] = field(default_factory=dict)
|
|
82
|
+
warnings: list[str] = field(default_factory=list)
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def check_command(self) -> str:
|
|
86
|
+
if self.commands.get("check"):
|
|
87
|
+
return self.commands["check"]
|
|
88
|
+
if self.modules.get("check_script"):
|
|
89
|
+
return "./scripts/check.sh"
|
|
90
|
+
return self.commands.get("test", "")
|
|
91
|
+
|
|
92
|
+
def module(self, name: str) -> bool:
|
|
93
|
+
return bool(self.modules.get(name, False))
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def load(root: Path) -> Config:
|
|
97
|
+
path = root / CONFIG_PATH
|
|
98
|
+
if not path.exists():
|
|
99
|
+
raise ConfigError(f"No {CONFIG_PATH} here. Run `ctxplate init` or `ctxplate adopt` first.")
|
|
100
|
+
try:
|
|
101
|
+
raw = tomllib.loads(path.read_text(encoding="utf-8"))
|
|
102
|
+
except tomllib.TOMLDecodeError as e:
|
|
103
|
+
raise ConfigError(f"{CONFIG_PATH}: {e}") from e
|
|
104
|
+
return from_dict(raw)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _index(v) -> str:
|
|
108
|
+
v = str(v)
|
|
109
|
+
if v not in ("compact", "full", "off"):
|
|
110
|
+
raise ConfigError("[context].index must be compact, full, or off")
|
|
111
|
+
return v
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def from_dict(raw: dict) -> Config:
|
|
115
|
+
warnings: list[str] = []
|
|
116
|
+
known_top = {
|
|
117
|
+
"version",
|
|
118
|
+
"harnesses",
|
|
119
|
+
"project",
|
|
120
|
+
"modules",
|
|
121
|
+
"commands",
|
|
122
|
+
"protect",
|
|
123
|
+
"format",
|
|
124
|
+
"context",
|
|
125
|
+
"hooks",
|
|
126
|
+
"models",
|
|
127
|
+
"mcp",
|
|
128
|
+
}
|
|
129
|
+
for k in raw:
|
|
130
|
+
if k not in known_top:
|
|
131
|
+
warnings.append(f"unknown key `{k}` ignored")
|
|
132
|
+
|
|
133
|
+
harnesses = raw.get("harnesses", [])
|
|
134
|
+
if not isinstance(harnesses, list):
|
|
135
|
+
raise ConfigError('`harnesses` must be a list, e.g. ["claude", "codex"]')
|
|
136
|
+
bad = [h for h in harnesses if h not in HARNESSES]
|
|
137
|
+
if bad:
|
|
138
|
+
raise ConfigError(f"unknown harness {bad}. Valid: {', '.join(HARNESSES)}")
|
|
139
|
+
|
|
140
|
+
project = raw.get("project", {})
|
|
141
|
+
preset = project.get("preset", "generic")
|
|
142
|
+
if preset not in PRESETS:
|
|
143
|
+
raise ConfigError(f"unknown preset `{preset}`. Valid: {', '.join(PRESETS)}")
|
|
144
|
+
|
|
145
|
+
modules = dict(DEFAULT_MODULES)
|
|
146
|
+
for k, v in raw.get("modules", {}).items():
|
|
147
|
+
if k not in MODULES:
|
|
148
|
+
warnings.append(f"unknown module `{k}` ignored")
|
|
149
|
+
continue
|
|
150
|
+
modules[k] = bool(v)
|
|
151
|
+
|
|
152
|
+
commands = {k: "" for k in COMMAND_KEYS}
|
|
153
|
+
for k, v in raw.get("commands", {}).items():
|
|
154
|
+
commands[k] = str(v)
|
|
155
|
+
|
|
156
|
+
protect = raw.get("protect", {})
|
|
157
|
+
models = json.loads(json.dumps(DEFAULT_MODELS))
|
|
158
|
+
for h, mapping in raw.get("models", {}).items():
|
|
159
|
+
models.setdefault(h, {}).update({k: str(v) for k, v in mapping.items()})
|
|
160
|
+
|
|
161
|
+
mcp = raw.get("mcp", {}).get("servers", {})
|
|
162
|
+
for name, server in mcp.items():
|
|
163
|
+
if "command" not in server and "url" not in server:
|
|
164
|
+
raise ConfigError(f"mcp server `{name}` needs `command` (stdio) or `url` (http)")
|
|
165
|
+
|
|
166
|
+
return Config(
|
|
167
|
+
harnesses=harnesses,
|
|
168
|
+
name=project.get("name", "my-project"),
|
|
169
|
+
description=project.get("description", ""),
|
|
170
|
+
preset=preset,
|
|
171
|
+
modules=modules,
|
|
172
|
+
commands=commands,
|
|
173
|
+
no_read=list(protect.get("no_read", DEFAULT_NO_READ)),
|
|
174
|
+
no_edit=list(protect.get("no_edit", DEFAULT_NO_EDIT)),
|
|
175
|
+
format=dict(raw.get("format", {})),
|
|
176
|
+
budget_tokens=int(raw.get("context", {}).get("budget_tokens", 1200)),
|
|
177
|
+
index=_index(raw.get("context", {}).get("index", "compact")),
|
|
178
|
+
python=str(raw.get("hooks", {}).get("python", "python3")),
|
|
179
|
+
models=models,
|
|
180
|
+
mcp=mcp,
|
|
181
|
+
warnings=warnings,
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
# ---------------------------------------------------------------- rendering
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _s(v: str) -> str:
|
|
189
|
+
return json.dumps(v, ensure_ascii=False)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _list(items: list[str]) -> str:
|
|
193
|
+
if not items:
|
|
194
|
+
return "[]"
|
|
195
|
+
inner = ",\n".join(f" {_s(x)}" for x in items)
|
|
196
|
+
return "[\n" + inner + ",\n]"
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def render(cfg: Config) -> str:
|
|
200
|
+
"""Render a commented config file. Used by init and adopt."""
|
|
201
|
+
cmd_lines = []
|
|
202
|
+
comments = {
|
|
203
|
+
"install": "install dependencies",
|
|
204
|
+
"dev": "run locally",
|
|
205
|
+
"lint": "lint (part of check)",
|
|
206
|
+
"typecheck": "type check (part of check)",
|
|
207
|
+
"test": "run tests (part of check)",
|
|
208
|
+
"format": "format the whole repo",
|
|
209
|
+
"check": "leave empty to use scripts/check.sh",
|
|
210
|
+
}
|
|
211
|
+
for k in COMMAND_KEYS:
|
|
212
|
+
cmd_lines.append(f"{k} = {_s(cfg.commands.get(k, ''))} # {comments[k]}")
|
|
213
|
+
fmt_lines = [f"{_s(k)} = {_s(v)}" for k, v in cfg.format.items()] or [
|
|
214
|
+
'# "*.py" = "ruff format -q {file}"'
|
|
215
|
+
]
|
|
216
|
+
model_lines = []
|
|
217
|
+
for h, mapping in cfg.models.items():
|
|
218
|
+
model_lines.append(f"[models.{h}]")
|
|
219
|
+
model_lines.extend(f"{k} = {_s(v)}" for k, v in mapping.items())
|
|
220
|
+
model_lines.append("")
|
|
221
|
+
mcp_lines = []
|
|
222
|
+
for name, server in cfg.mcp.items():
|
|
223
|
+
mcp_lines.append(f"[mcp.servers.{_toml_key(name)}]")
|
|
224
|
+
for k, v in server.items():
|
|
225
|
+
mcp_lines.append(f"{k} = {_toml_value(v)}")
|
|
226
|
+
mcp_lines.append("")
|
|
227
|
+
if not mcp_lines:
|
|
228
|
+
mcp_lines = [
|
|
229
|
+
"# [mcp.servers.docs]",
|
|
230
|
+
'# url = "https://mcp.context7.com/mcp"',
|
|
231
|
+
'# headers = { CONTEXT7_API_KEY = "${CONTEXT7_API_KEY}" }',
|
|
232
|
+
"# [mcp.servers.local-tool]",
|
|
233
|
+
'# command = "npx"',
|
|
234
|
+
'# args = ["-y", "some-mcp-server"]',
|
|
235
|
+
"",
|
|
236
|
+
]
|
|
237
|
+
harness_list = ", ".join(_s(h) for h in cfg.harnesses)
|
|
238
|
+
modules = "\n".join(
|
|
239
|
+
f"{k} = {str(cfg.modules.get(k, False)).lower()} # {MODULES[k]}" for k in MODULES
|
|
240
|
+
)
|
|
241
|
+
return f"""# ContextPlate configuration. Edit this file, then run `ctxplate sync`.
|
|
242
|
+
# Canonical content lives in AGENTS.md and .agents/ (rules, skills, agents).
|
|
243
|
+
# Everything harness-specific (.claude/, .cursor/, .github/..., .codex/, .gemini/) is generated.
|
|
244
|
+
version = 1
|
|
245
|
+
|
|
246
|
+
# Which tools to generate files for: {", ".join(HARNESSES)}
|
|
247
|
+
# Any other AGENTS.md-aware tool works with no entry here.
|
|
248
|
+
harnesses = [{harness_list}]
|
|
249
|
+
|
|
250
|
+
[project]
|
|
251
|
+
name = {_s(cfg.name)}
|
|
252
|
+
description = {_s(cfg.description)}
|
|
253
|
+
preset = {_s(cfg.preset)} # {", ".join(PRESETS)}
|
|
254
|
+
|
|
255
|
+
[modules]
|
|
256
|
+
{modules}
|
|
257
|
+
|
|
258
|
+
[commands]
|
|
259
|
+
# Rendered into AGENTS.md and scripts/check.sh. Empty values are omitted.
|
|
260
|
+
{chr(10).join(cmd_lines)}
|
|
261
|
+
|
|
262
|
+
[protect]
|
|
263
|
+
# Gitignore-style patterns. Last match wins; "!" re-includes.
|
|
264
|
+
no_read = {_list(cfg.no_read)} # agents may not read (Claude permissions)
|
|
265
|
+
no_edit = {_list(cfg.no_edit)} # agents may not edit (Claude permissions + guard hook)
|
|
266
|
+
|
|
267
|
+
[format]
|
|
268
|
+
# Auto-format after each agent edit (Claude hook). First matching glob wins. {{file}} = edited file.
|
|
269
|
+
{chr(10).join(fmt_lines)}
|
|
270
|
+
|
|
271
|
+
[context]
|
|
272
|
+
budget_tokens = {cfg.budget_tokens} # `ctxplate doctor` warns when always-loaded context exceeds this
|
|
273
|
+
index = {_s(cfg.index)} # AGENTS.md pointer list: compact (names), full (with descriptions), off
|
|
274
|
+
|
|
275
|
+
[hooks]
|
|
276
|
+
python = {_s(cfg.python)} # interpreter for hook scripts; use "python" or "py" on Windows
|
|
277
|
+
|
|
278
|
+
# Neutral model tiers used in .agents/agents/*.md (model: fast | strong | inherit).
|
|
279
|
+
# Map a tier to a harness model id; unmapped tiers inherit the session model.
|
|
280
|
+
{chr(10).join(model_lines)}
|
|
281
|
+
# MCP servers, rendered into each harness's MCP config.
|
|
282
|
+
{chr(10).join(mcp_lines)}"""
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _toml_key(k: str) -> str:
|
|
286
|
+
return k if re.fullmatch(r"[A-Za-z0-9_-]+", k) else _s(k)
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _toml_value(v) -> str:
|
|
290
|
+
if isinstance(v, bool):
|
|
291
|
+
return str(v).lower()
|
|
292
|
+
if isinstance(v, (int, float)):
|
|
293
|
+
return str(v)
|
|
294
|
+
if isinstance(v, list):
|
|
295
|
+
return "[" + ", ".join(_toml_value(x) for x in v) + "]"
|
|
296
|
+
if isinstance(v, dict):
|
|
297
|
+
return "{ " + ", ".join(f"{_toml_key(k)} = {_toml_value(x)}" for k, x in v.items()) + " }"
|
|
298
|
+
return _s(str(v))
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def set_harnesses(text: str, harnesses: list[str]) -> str:
|
|
302
|
+
line = "harnesses = [" + ", ".join(_s(h) for h in harnesses) + "]"
|
|
303
|
+
new, n = re.subn(r"(?m)^harnesses\s*=\s*\[[^\]]*\]", line, text, count=1)
|
|
304
|
+
if n == 0:
|
|
305
|
+
new = re.sub(r"(?m)^(version\s*=.*)$", r"\1\n" + line.replace("\\", "\\\\"), text, count=1)
|
|
306
|
+
return new
|