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.
Files changed (49) hide show
  1. contextplate/__init__.py +7 -0
  2. contextplate/__main__.py +5 -0
  3. contextplate/adapters/__init__.py +50 -0
  4. contextplate/adapters/aider.py +28 -0
  5. contextplate/adapters/base.py +85 -0
  6. contextplate/adapters/claude.py +181 -0
  7. contextplate/adapters/codex.py +119 -0
  8. contextplate/adapters/copilot.py +57 -0
  9. contextplate/adapters/core.py +197 -0
  10. contextplate/adapters/cursor.py +55 -0
  11. contextplate/adapters/gemini.py +31 -0
  12. contextplate/adopt.py +596 -0
  13. contextplate/cli.py +308 -0
  14. contextplate/config.py +306 -0
  15. contextplate/doctor.py +147 -0
  16. contextplate/frontmatter.py +226 -0
  17. contextplate/globs.py +84 -0
  18. contextplate/model.py +185 -0
  19. contextplate/presets.py +165 -0
  20. contextplate/scaffold.py +162 -0
  21. contextplate/templates/check.sh +44 -0
  22. contextplate/templates/hooks/format.py +74 -0
  23. contextplate/templates/hooks/guard.py +121 -0
  24. contextplate/templates/hooks/session_context.py +79 -0
  25. contextplate/templates/scaffold/AGENTS.md +29 -0
  26. contextplate/templates/scaffold/agents/agents/researcher.md +16 -0
  27. contextplate/templates/scaffold/agents/agents/reviewer.md +20 -0
  28. contextplate/templates/scaffold/agents/agents/test-runner.md +17 -0
  29. contextplate/templates/scaffold/agents/rules/ai-assets.md +12 -0
  30. contextplate/templates/scaffold/agents/rules/docs.md +11 -0
  31. contextplate/templates/scaffold/agents/skills/adr/SKILL.md +12 -0
  32. contextplate/templates/scaffold/agents/skills/adr/template.md +21 -0
  33. contextplate/templates/scaffold/agents/skills/handoff/SKILL.md +17 -0
  34. contextplate/templates/scaffold/agents/skills/plan-task/SKILL.md +15 -0
  35. contextplate/templates/scaffold/agents/skills/plan-task/template.md +28 -0
  36. contextplate/templates/scaffold/ai_app/data/README.md +5 -0
  37. contextplate/templates/scaffold/ai_app/evals/README.md +7 -0
  38. contextplate/templates/scaffold/ai_app/prompts/README.md +17 -0
  39. contextplate/templates/scaffold/docs/agent-context.md +42 -0
  40. contextplate/templates/scaffold/docs/architecture.md +27 -0
  41. contextplate/templates/scaffold/docs/decisions/0001-record-architecture-decisions.md +22 -0
  42. contextplate/templates/scaffold/docs/glossary.md +7 -0
  43. contextplate/templates/scaffold/work/handoff.md +22 -0
  44. contextplate/writer.py +396 -0
  45. contextplate-0.1.0.dist-info/METADATA +201 -0
  46. contextplate-0.1.0.dist-info/RECORD +49 -0
  47. contextplate-0.1.0.dist-info/WHEEL +4 -0
  48. contextplate-0.1.0.dist-info/entry_points.txt +3 -0
  49. contextplate-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,7 @@
1
+ """ContextPlate: declare coding-agent context once, render it for every harness."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ TOOL = "ctxplate"
6
+ CONFIG_PATH = ".agents/contextplate.toml"
7
+ LOCK_PATH = ".agents/contextplate.lock.json"
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,50 @@
1
+ """Harness adapters. Each turns canonical content into one tool's native files.
2
+
3
+ To add a harness: create a module with `outputs(ctx) -> list[Output]`, register
4
+ it in ADAPTERS, add it to config.HARNESSES, and document it in docs/harnesses.md.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+
11
+ from ..config import Config
12
+ from ..model import load_agents, load_rules, load_skills
13
+ from ..writer import Output
14
+ from . import aider, claude, codex, copilot, core, cursor, gemini
15
+ from .base import Context
16
+
17
+ ADAPTERS = {
18
+ "claude": claude.outputs,
19
+ "codex": codex.outputs,
20
+ "copilot": copilot.outputs,
21
+ "cursor": cursor.outputs,
22
+ "gemini": gemini.outputs,
23
+ "aider": aider.outputs,
24
+ }
25
+
26
+
27
+ def build_context(root: Path, cfg: Config) -> Context:
28
+ return Context(
29
+ root=root,
30
+ config=cfg,
31
+ rules=load_rules(root),
32
+ skills=load_skills(root),
33
+ agents=load_agents(root),
34
+ )
35
+
36
+
37
+ def build_outputs(ctx: Context) -> list[Output]:
38
+ outs = core.outputs(ctx)
39
+ for h in ctx.config.harnesses:
40
+ outs.extend(ADAPTERS[h](ctx))
41
+ if ctx.config.module("hooks"):
42
+ owned = [o.path for o in outs if o.strategy == "owned"]
43
+ outs.extend(core.hooks_runtime(ctx, owned))
44
+ if ctx.config.preset == "node" or (ctx.root / ".prettierignore").exists():
45
+ outs.append(
46
+ core.formatter_ignore(
47
+ ".prettierignore", [o.path for o in outs if o.strategy == "owned"]
48
+ )
49
+ )
50
+ return outs
@@ -0,0 +1,28 @@
1
+ """Aider: load AGENTS.md as read-only context via .aider.conf.yml."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ from ..writer import Output, read_text, strip_blocks
8
+ from .base import Context
9
+
10
+
11
+ def outputs(ctx: Context) -> list[Output]:
12
+ path = ctx.root / ".aider.conf.yml"
13
+ if path.exists() and re.search(
14
+ r"(?m)^read\s*:", strip_blocks(read_text(path), ".aider.conf.yml")
15
+ ):
16
+ ctx.warnings.append(
17
+ ".aider.conf.yml already has a `read:` key; add AGENTS.md to it yourself"
18
+ )
19
+ return []
20
+ return [
21
+ Output(
22
+ ".aider.conf.yml",
23
+ strategy="block",
24
+ block_id="aider",
25
+ content="read:\n - AGENTS.md",
26
+ owner="aider",
27
+ )
28
+ ]
@@ -0,0 +1,85 @@
1
+ """Shared adapter context and helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+
9
+ from ..config import Config
10
+ from ..model import Agent, Rule, Skill
11
+
12
+
13
+ @dataclass
14
+ class Context:
15
+ root: Path
16
+ config: Config
17
+ rules: list[Rule]
18
+ skills: list[Skill]
19
+ agents: list[Agent]
20
+ warnings: list[str] = field(default_factory=list)
21
+
22
+ def model_for(self, harness: str, tier: str) -> str | None:
23
+ if tier in ("", "inherit"):
24
+ return "inherit" if harness in ("claude", "cursor") else None
25
+ # Only neutral tiers are translated. Harness-specific model ids belong in
26
+ # per-harness overrides such as `claude.model: sonnet` so they never leak
27
+ # into another tool's config.
28
+ return self.config.models.get(harness, {}).get(tier)
29
+
30
+
31
+ def one_line(s: str) -> str:
32
+ return re.sub(r"\s+", " ", s or "").strip()
33
+
34
+
35
+ # ---------------------------------------------------------------- MCP translation
36
+
37
+
38
+ def mcp_claude(server: dict) -> dict:
39
+ if "command" in server:
40
+ out = {"type": "stdio", "command": server["command"]}
41
+ if server.get("args"):
42
+ out["args"] = list(server["args"])
43
+ if server.get("env"):
44
+ out["env"] = dict(server["env"])
45
+ return out
46
+ out = {"type": "http", "url": server["url"]}
47
+ if server.get("headers"):
48
+ out["headers"] = dict(server["headers"])
49
+ return out
50
+
51
+
52
+ def _cursor_env(v: str) -> str:
53
+ return re.sub(r"\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-[^}]*)?\}", r"${env:\1}", v)
54
+
55
+
56
+ def mcp_cursor(server: dict) -> dict:
57
+ if "command" in server:
58
+ out = {"command": server["command"]}
59
+ if server.get("args"):
60
+ out["args"] = [_cursor_env(str(a)) for a in server["args"]]
61
+ if server.get("env"):
62
+ out["env"] = {k: _cursor_env(str(v)) for k, v in server["env"].items()}
63
+ return out
64
+ out = {"url": _cursor_env(server["url"])}
65
+ if server.get("headers"):
66
+ out["headers"] = {k: _cursor_env(str(v)) for k, v in server["headers"].items()}
67
+ return out
68
+
69
+
70
+ def _strip_default(v: str) -> str:
71
+ return re.sub(r"\$\{([A-Za-z_][A-Za-z0-9_]*):-[^}]*\}", r"${\1}", v)
72
+
73
+
74
+ def mcp_gemini(server: dict) -> dict:
75
+ if "command" in server:
76
+ out = {"command": server["command"]}
77
+ if server.get("args"):
78
+ out["args"] = list(server["args"])
79
+ if server.get("env"):
80
+ out["env"] = {k: _strip_default(str(v)) for k, v in server["env"].items()}
81
+ return out
82
+ out = {"httpUrl": _strip_default(server["url"])}
83
+ if server.get("headers"):
84
+ out["headers"] = {k: _strip_default(str(v)) for k, v in server["headers"].items()}
85
+ return out
@@ -0,0 +1,181 @@
1
+ """Claude Code: CLAUDE.md, .claude/{rules,skills,agents,settings.json}, .mcp.json."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ from .. import frontmatter
8
+ from ..writer import Output
9
+ from .base import Context, mcp_claude
10
+
11
+ TOOLS = {
12
+ "read": ["Read"],
13
+ "search": ["Grep", "Glob"],
14
+ "web": ["WebSearch", "WebFetch"],
15
+ "shell": ["Bash"],
16
+ "edit": ["Edit", "Write"],
17
+ }
18
+ SETTINGS_SCHEMA = "https://json.schemastore.org/claude-code-settings.json"
19
+
20
+
21
+ def _perm_path(p: str) -> str:
22
+ neg = p.startswith("!")
23
+ core = p[1:] if neg else p
24
+ if "/" in core.rstrip("/"):
25
+ if core.startswith("./"):
26
+ core = core[2:]
27
+ core = "./" + core.lstrip("/")
28
+ return ("!" if neg else "") + core
29
+
30
+
31
+ def claude_md_block(ctx: Context) -> str:
32
+ cfg = ctx.config
33
+ lines = ["@AGENTS.md", "", "## Claude Code notes", ""]
34
+ if cfg.module("hooks"):
35
+ snap = "git state" + (", `work/handoff.md`, and active plans" if cfg.module("work") else "")
36
+ lines.append(
37
+ f"- A session snapshot ({snap}) is injected at start, after `/clear`, and after compaction."
38
+ )
39
+ lines.append(
40
+ "- Edits to protected and generated files are blocked by a hook; edit the source in `.agents/` instead."
41
+ )
42
+ if ctx.skills:
43
+ lines.append("- Skills: " + ", ".join(f"`/{s.name}`" for s in ctx.skills) + ".")
44
+ if ctx.agents:
45
+ lines.append(
46
+ "- Subagents: "
47
+ + ", ".join(f"`{a.name}`" for a in ctx.agents)
48
+ + ". Delegate noisy work (test runs, broad searches, reviews) so only summaries return."
49
+ )
50
+ return "\n".join(lines)
51
+
52
+
53
+ def skill_meta(skill) -> dict:
54
+ meta: dict = {"name": skill.name, "description": skill.description}
55
+ md = dict(skill.meta.get("metadata") or {})
56
+ if str(md.pop("invocation", "")).lower() == "manual":
57
+ meta["disable-model-invocation"] = True
58
+ if "argument-hint" in md:
59
+ meta["argument-hint"] = md.pop("argument-hint")
60
+ for k in list(md):
61
+ if k.startswith("claude-"):
62
+ v = md.pop(k)
63
+ if isinstance(v, str) and v.lower() in ("true", "false"):
64
+ v = (
65
+ v.lower() == "true"
66
+ ) # metadata values are strings by spec; Claude wants booleans
67
+ meta[k[len("claude-") :]] = v
68
+ for k in ("allowed-tools", "license", "compatibility"):
69
+ if k in skill.meta:
70
+ meta[k] = skill.meta[k]
71
+ if md:
72
+ meta["metadata"] = md
73
+ return meta
74
+
75
+
76
+ def settings(ctx: Context) -> dict:
77
+ cfg = ctx.config
78
+ deny = [f"Read({_perm_path(p)})" for p in cfg.no_read] + [
79
+ f"Edit({_perm_path(p)})" for p in cfg.no_edit
80
+ ]
81
+ data: dict = {"$schema": SETTINGS_SCHEMA, "permissions": {"deny": deny}}
82
+ check = cfg.check_command
83
+ if check and re.fullmatch(r"[\w./-]+(?: [\w./=-]+)*", check):
84
+ data["permissions"]["allow"] = [f"Bash({check})", f"Bash({check} *)"]
85
+ if cfg.module("hooks"):
86
+ py = cfg.python
87
+
88
+ def cmd(script: str) -> dict:
89
+ return {
90
+ "type": "command",
91
+ "command": f'{py} "$CLAUDE_PROJECT_DIR/.agents/hooks/{script}"',
92
+ }
93
+
94
+ hooks = {
95
+ "SessionStart": [
96
+ {"matcher": "startup|clear|compact", "hooks": [cmd("session_context.py")]}
97
+ ],
98
+ "PreToolUse": [
99
+ {"matcher": "Edit|Write|MultiEdit|NotebookEdit", "hooks": [cmd("guard.py")]}
100
+ ],
101
+ }
102
+ if cfg.format:
103
+ hooks["PostToolUse"] = [
104
+ {"matcher": "Edit|Write|MultiEdit", "hooks": [cmd("format.py")]}
105
+ ]
106
+ data["hooks"] = hooks
107
+ return data
108
+
109
+
110
+ def outputs(ctx: Context) -> list[Output]:
111
+ cfg = ctx.config
112
+ outs = [
113
+ Output(
114
+ "CLAUDE.md",
115
+ strategy="block",
116
+ block_id="claude",
117
+ content=claude_md_block(ctx),
118
+ position="top",
119
+ owner="claude",
120
+ )
121
+ ]
122
+
123
+ for r in ctx.rules:
124
+ body = r.body.lstrip("\n")
125
+ content = frontmatter.compose({"paths": r.expanded_paths}, body) if not r.always else body
126
+ outs.append(Output(f".claude/rules/{r.name}.md", content=content, owner="claude"))
127
+
128
+ for s in ctx.skills:
129
+ outs.append(
130
+ Output(
131
+ f".claude/skills/{s.name}/SKILL.md",
132
+ content=frontmatter.compose(skill_meta(s), s.body),
133
+ owner="claude",
134
+ )
135
+ )
136
+ for rel in s.files:
137
+ try:
138
+ text = (s.dir / rel).read_text(encoding="utf-8")
139
+ except UnicodeDecodeError:
140
+ ctx.warnings.append(
141
+ f"skipped binary file {s.dir.name}/{rel.as_posix()} for Claude skills"
142
+ )
143
+ continue
144
+ outs.append(
145
+ Output(
146
+ f".claude/skills/{s.name}/{rel.as_posix()}",
147
+ content=text,
148
+ executable=rel.suffix in (".sh", ".py"),
149
+ owner="claude",
150
+ )
151
+ )
152
+
153
+ for a in ctx.agents:
154
+ meta: dict = {"name": a.name, "description": a.description}
155
+ if a.tools is not None:
156
+ meta["tools"] = ", ".join(t for tool in a.tools for t in TOOLS[tool])
157
+ model = ctx.model_for("claude", a.model)
158
+ if model:
159
+ meta["model"] = model
160
+ meta.update(a.overrides.get("claude", {}))
161
+ outs.append(
162
+ Output(
163
+ f".claude/agents/{a.name}.md",
164
+ content=frontmatter.compose(meta, a.body),
165
+ owner="claude",
166
+ )
167
+ )
168
+
169
+ outs.append(
170
+ Output(".claude/settings.json", strategy="json", data=settings(ctx), owner="claude")
171
+ )
172
+ if cfg.mcp:
173
+ outs.append(
174
+ Output(
175
+ ".mcp.json",
176
+ strategy="json",
177
+ data={"mcpServers": {n: mcp_claude(s) for n, s in cfg.mcp.items()}},
178
+ owner="claude",
179
+ )
180
+ )
181
+ return outs
@@ -0,0 +1,119 @@
1
+ """OpenAI Codex: reads AGENTS.md and .agents/skills natively.
2
+
3
+ Generates .codex/agents/*.toml (custom subagents) and an MCP block in
4
+ .codex/config.toml (project config; Codex loads it for trusted projects).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ import tomllib
12
+
13
+ from ..writer import Output, read_text, strip_blocks
14
+ from .base import Context
15
+
16
+
17
+ def _str(s: str) -> str:
18
+ return json.dumps(s, ensure_ascii=False)
19
+
20
+
21
+ def _multiline(s: str) -> str:
22
+ s = s.strip("\n") + "\n"
23
+ if "'''" not in s:
24
+ return "'''\n" + s + "'''"
25
+ return _str(s)
26
+
27
+
28
+ def _value(v) -> str:
29
+ if isinstance(v, bool):
30
+ return str(v).lower()
31
+ if isinstance(v, int):
32
+ return str(v)
33
+ if isinstance(v, list):
34
+ return "[" + ", ".join(_value(x) for x in v) + "]"
35
+ if isinstance(v, dict):
36
+ return "{ " + ", ".join(f"{_key(k)} = {_value(x)}" for k, x in v.items()) + " }"
37
+ return _str(str(v))
38
+
39
+
40
+ def _key(k: str) -> str:
41
+ return k if re.fullmatch(r"[A-Za-z0-9_-]+", k) else _str(k)
42
+
43
+
44
+ def agent_toml(ctx: Context, a) -> str:
45
+ lines = [
46
+ f"# Generated by ctxplate from {a.source}. Edit the source, then run `ctxplate sync`.",
47
+ f"name = {_str(a.name)}",
48
+ f"description = {_str(a.description)}",
49
+ ]
50
+ if a.read_only:
51
+ lines.append('sandbox_mode = "read-only"')
52
+ model = ctx.model_for("codex", a.model)
53
+ if model:
54
+ lines.append(f"model = {_str(model)}")
55
+ for k, v in a.overrides.get("codex", {}).items():
56
+ lines.append(f"{_key(k)} = {_value(v)}")
57
+ lines.append(f"developer_instructions = {_multiline(a.body)}")
58
+ return "\n".join(lines) + "\n"
59
+
60
+
61
+ def mcp_block(ctx: Context) -> str | None:
62
+ servers = ctx.config.mcp
63
+ path = ctx.root / ".codex" / "config.toml"
64
+ taken: set[str] = set()
65
+ if path.exists():
66
+ try:
67
+ user_part = tomllib.loads(strip_blocks(read_text(path), ".codex/config.toml"))
68
+ taken = set(user_part.get("mcp_servers", {}))
69
+ except tomllib.TOMLDecodeError:
70
+ ctx.warnings.append(
71
+ ".codex/config.toml is not valid TOML; skipped MCP servers for Codex"
72
+ )
73
+ return None
74
+ lines = []
75
+ for name, s in servers.items():
76
+ if name in taken:
77
+ ctx.warnings.append(
78
+ f"Codex MCP server `{name}` is already defined in .codex/config.toml; left as is"
79
+ )
80
+ continue
81
+ lines.append(f"[mcp_servers.{_key(name)}]")
82
+ if "command" in s:
83
+ lines.append(f"command = {_str(s['command'])}")
84
+ if s.get("args"):
85
+ lines.append(f"args = {_value(list(s['args']))}")
86
+ if s.get("env"):
87
+ lines.append(f"env = {_value(dict(s['env']))}")
88
+ else:
89
+ lines.append(f"url = {_str(s['url'])}")
90
+ for hk, hv in (s.get("headers") or {}).items():
91
+ m = re.fullmatch(r"Bearer \$\{([A-Za-z_][A-Za-z0-9_]*)\}", str(hv))
92
+ if hk.lower() == "authorization" and m:
93
+ lines.append(f"bearer_token_env_var = {_str(m.group(1))}")
94
+ else:
95
+ lines.append(
96
+ f"# header `{hk}` not translated; configure it per the Codex MCP docs"
97
+ )
98
+ lines.append("")
99
+ return "\n".join(lines).rstrip() if lines else None
100
+
101
+
102
+ def outputs(ctx: Context) -> list[Output]:
103
+ outs = [
104
+ Output(f".codex/agents/{a.name}.toml", content=agent_toml(ctx, a), owner="codex")
105
+ for a in ctx.agents
106
+ ]
107
+ if ctx.config.mcp:
108
+ block = mcp_block(ctx)
109
+ if block:
110
+ outs.append(
111
+ Output(
112
+ ".codex/config.toml",
113
+ strategy="block",
114
+ block_id="mcp",
115
+ content=block,
116
+ owner="codex",
117
+ )
118
+ )
119
+ return outs
@@ -0,0 +1,57 @@
1
+ """GitHub Copilot: reads AGENTS.md and .agents/skills natively.
2
+
3
+ Generates path-scoped .github/instructions/*.instructions.md (applyTo),
4
+ custom agents in .github/agents/*.agent.md, and shares .mcp.json.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+
11
+ from .. import frontmatter
12
+ from ..writer import Output
13
+ from .base import Context, mcp_claude, one_line
14
+
15
+ TOOLS = {"read": "read", "search": "search", "web": "web", "shell": "execute", "edit": "edit"}
16
+
17
+
18
+ def instructions(r) -> str:
19
+ apply_to = ",".join(r.expanded_paths) if r.paths else "**"
20
+ head = f"---\napplyTo: {json.dumps(apply_to)}\ndescription: {json.dumps(one_line(r.description))}\n---\n"
21
+ return head + "\n" + r.body.lstrip("\n")
22
+
23
+
24
+ def outputs(ctx: Context) -> list[Output]:
25
+ outs = [
26
+ Output(
27
+ f".github/instructions/{r.name}.instructions.md",
28
+ content=instructions(r),
29
+ owner="copilot",
30
+ )
31
+ for r in ctx.rules
32
+ ]
33
+ for a in ctx.agents:
34
+ meta: dict = {"name": a.name, "description": a.description}
35
+ if a.tools is not None:
36
+ meta["tools"] = [TOOLS[t] for t in a.tools]
37
+ model = ctx.model_for("copilot", a.model)
38
+ if model:
39
+ meta["model"] = model
40
+ meta.update(a.overrides.get("copilot", {}))
41
+ outs.append(
42
+ Output(
43
+ f".github/agents/{a.name}.agent.md",
44
+ content=frontmatter.compose(meta, a.body),
45
+ owner="copilot",
46
+ )
47
+ )
48
+ if ctx.config.mcp:
49
+ outs.append(
50
+ Output(
51
+ ".mcp.json",
52
+ strategy="json",
53
+ data={"mcpServers": {n: mcp_claude(s) for n, s in ctx.config.mcp.items()}},
54
+ owner="copilot",
55
+ )
56
+ )
57
+ return outs