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/presets.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Stack presets: starting commands, rule scopes, and formatters.
|
|
2
|
+
|
|
3
|
+
Presets only seed .agents/contextplate.toml and the starter rules at init/adopt
|
|
4
|
+
time. After that the config file is the source of truth.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
PRESETS: dict[str, dict] = {
|
|
12
|
+
"generic": {
|
|
13
|
+
"title": "Any stack (fill in commands yourself)",
|
|
14
|
+
"detect": [],
|
|
15
|
+
"commands": {
|
|
16
|
+
"install": "",
|
|
17
|
+
"dev": "",
|
|
18
|
+
"lint": "",
|
|
19
|
+
"typecheck": "",
|
|
20
|
+
"test": "",
|
|
21
|
+
"format": "",
|
|
22
|
+
},
|
|
23
|
+
"format": {},
|
|
24
|
+
"source_paths": ["src/**", "lib/**", "app/**"],
|
|
25
|
+
"test_paths": ["tests/**", "test/**", "**/*.test.*", "**/*.spec.*"],
|
|
26
|
+
"source_rules": [],
|
|
27
|
+
"test_rules": [],
|
|
28
|
+
},
|
|
29
|
+
"python": {
|
|
30
|
+
"title": "Python (uv, ruff, pytest)",
|
|
31
|
+
"detect": ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt"],
|
|
32
|
+
"commands": {
|
|
33
|
+
"install": "uv sync",
|
|
34
|
+
"dev": "",
|
|
35
|
+
"lint": "ruff check .",
|
|
36
|
+
"typecheck": "",
|
|
37
|
+
"test": "pytest -q",
|
|
38
|
+
"format": "ruff format .",
|
|
39
|
+
},
|
|
40
|
+
"format": {"*.py": "ruff format -q {file}"},
|
|
41
|
+
"source_paths": ["**/*.py"],
|
|
42
|
+
"test_paths": ["tests/**/*.py", "**/test_*.py", "**/*_test.py"],
|
|
43
|
+
"source_rules": [
|
|
44
|
+
"Type hints on public functions. Prefer `pathlib` over `os.path`.",
|
|
45
|
+
],
|
|
46
|
+
"test_rules": ["Use pytest fixtures and `tmp_path`; no `unittest.TestCase` in new tests."],
|
|
47
|
+
},
|
|
48
|
+
"node": {
|
|
49
|
+
"title": "Node / TypeScript (npm scripts, prettier)",
|
|
50
|
+
"detect": ["package.json"],
|
|
51
|
+
"commands": {
|
|
52
|
+
"install": "npm ci",
|
|
53
|
+
"dev": "npm run dev",
|
|
54
|
+
"lint": "npm run lint",
|
|
55
|
+
"typecheck": "npm run typecheck",
|
|
56
|
+
"test": "npm test",
|
|
57
|
+
"format": "npx --no-install prettier --write .",
|
|
58
|
+
},
|
|
59
|
+
"format": {
|
|
60
|
+
"*.{ts,tsx,js,jsx,mjs,cjs,json,css,scss,html,yaml,yml}": "npx --no-install prettier --write --log-level silent {file}"
|
|
61
|
+
},
|
|
62
|
+
"source_paths": [
|
|
63
|
+
"src/**/*.{ts,tsx,js,jsx}",
|
|
64
|
+
"app/**/*.{ts,tsx,js,jsx}",
|
|
65
|
+
"lib/**/*.{ts,tsx,js,jsx}",
|
|
66
|
+
],
|
|
67
|
+
"test_paths": ["**/*.test.*", "**/*.spec.*", "tests/**", "__tests__/**"],
|
|
68
|
+
"source_rules": ["TypeScript strict mode. Avoid `any`; prefer `unknown` plus narrowing."],
|
|
69
|
+
"test_rules": [],
|
|
70
|
+
},
|
|
71
|
+
"go": {
|
|
72
|
+
"title": "Go (go vet, go test, gofmt)",
|
|
73
|
+
"detect": ["go.mod"],
|
|
74
|
+
"commands": {
|
|
75
|
+
"install": "go mod download",
|
|
76
|
+
"dev": "",
|
|
77
|
+
"lint": "go vet ./...",
|
|
78
|
+
"typecheck": "",
|
|
79
|
+
"test": "go test ./...",
|
|
80
|
+
"format": "gofmt -w .",
|
|
81
|
+
},
|
|
82
|
+
"format": {"*.go": "gofmt -w {file}"},
|
|
83
|
+
"source_paths": ["**/*.go"],
|
|
84
|
+
"test_paths": ["**/*_test.go"],
|
|
85
|
+
"source_rules": ['Return errors, do not panic. Wrap with `fmt.Errorf("...: %w", err)`.'],
|
|
86
|
+
"test_rules": ["Table-driven tests with `t.Run` subtests."],
|
|
87
|
+
},
|
|
88
|
+
"rust": {
|
|
89
|
+
"title": "Rust (cargo clippy, cargo test, rustfmt)",
|
|
90
|
+
"detect": ["Cargo.toml"],
|
|
91
|
+
"commands": {
|
|
92
|
+
"install": "cargo fetch",
|
|
93
|
+
"dev": "",
|
|
94
|
+
"lint": "cargo clippy --all-targets -- -D warnings",
|
|
95
|
+
"typecheck": "",
|
|
96
|
+
"test": "cargo test",
|
|
97
|
+
"format": "cargo fmt",
|
|
98
|
+
},
|
|
99
|
+
"format": {"*.rs": "rustfmt {file}"},
|
|
100
|
+
"source_paths": ["src/**/*.rs"],
|
|
101
|
+
"test_paths": ["tests/**/*.rs"],
|
|
102
|
+
"source_rules": ["No `unwrap()` outside tests. Propagate errors with `?`."],
|
|
103
|
+
"test_rules": [],
|
|
104
|
+
},
|
|
105
|
+
"jvm": {
|
|
106
|
+
"title": "Java / Kotlin (Gradle; Maven detected on adopt)",
|
|
107
|
+
"detect": ["build.gradle", "build.gradle.kts", "pom.xml", "settings.gradle.kts"],
|
|
108
|
+
"commands": {
|
|
109
|
+
"install": "",
|
|
110
|
+
"dev": "",
|
|
111
|
+
"lint": "",
|
|
112
|
+
"typecheck": "",
|
|
113
|
+
"test": "./gradlew test",
|
|
114
|
+
"format": "",
|
|
115
|
+
},
|
|
116
|
+
"format": {},
|
|
117
|
+
"source_paths": ["src/main/**"],
|
|
118
|
+
"test_paths": ["src/test/**"],
|
|
119
|
+
"source_rules": [],
|
|
120
|
+
"test_rules": [],
|
|
121
|
+
},
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def detect(root: Path) -> str:
|
|
126
|
+
for name, preset in PRESETS.items():
|
|
127
|
+
if any((root / f).exists() for f in preset["detect"]):
|
|
128
|
+
return name
|
|
129
|
+
return "generic"
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def commands_for(name: str, root: Path | None = None) -> dict[str, str]:
|
|
133
|
+
cmds = dict(PRESETS[name]["commands"])
|
|
134
|
+
if root is None:
|
|
135
|
+
return cmds
|
|
136
|
+
if name == "jvm" and (root / "pom.xml").exists() and not (root / "gradlew").exists():
|
|
137
|
+
cmds["test"] = "mvn -q test"
|
|
138
|
+
if (
|
|
139
|
+
name == "python"
|
|
140
|
+
and not (root / "uv.lock").exists()
|
|
141
|
+
and (root / "requirements.txt").exists()
|
|
142
|
+
):
|
|
143
|
+
cmds["install"] = "pip install -r requirements.txt"
|
|
144
|
+
if name == "node":
|
|
145
|
+
if (root / "pnpm-lock.yaml").exists():
|
|
146
|
+
cmds = {
|
|
147
|
+
k: v.replace("npm run", "pnpm")
|
|
148
|
+
.replace("npm ci", "pnpm install --frozen-lockfile")
|
|
149
|
+
.replace("npm test", "pnpm test")
|
|
150
|
+
for k, v in cmds.items()
|
|
151
|
+
}
|
|
152
|
+
pkg = root / "package.json"
|
|
153
|
+
if pkg.exists():
|
|
154
|
+
import json
|
|
155
|
+
|
|
156
|
+
try:
|
|
157
|
+
scripts = json.loads(pkg.read_text(encoding="utf-8")).get("scripts", {})
|
|
158
|
+
except (ValueError, OSError):
|
|
159
|
+
scripts = {}
|
|
160
|
+
for key in ("lint", "typecheck", "dev"):
|
|
161
|
+
if key not in scripts:
|
|
162
|
+
cmds[key] = ""
|
|
163
|
+
if "test" not in scripts:
|
|
164
|
+
cmds["test"] = ""
|
|
165
|
+
return cmds
|
contextplate/scaffold.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Canonical starter content written by `init` (and by `adopt` for missing pieces).
|
|
2
|
+
|
|
3
|
+
These files belong to the user after creation. contextplate never overwrites them.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import datetime as _dt
|
|
9
|
+
from importlib import resources
|
|
10
|
+
|
|
11
|
+
from . import frontmatter
|
|
12
|
+
from .config import Config
|
|
13
|
+
from .presets import PRESETS
|
|
14
|
+
|
|
15
|
+
GITKEEP = ""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _tmpl_root():
|
|
19
|
+
return resources.files("contextplate").joinpath("templates", "scaffold")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _walk(trav, prefix=""):
|
|
23
|
+
for entry in sorted(trav.iterdir(), key=lambda e: e.name):
|
|
24
|
+
rel = f"{prefix}{entry.name}"
|
|
25
|
+
if entry.is_dir():
|
|
26
|
+
yield from _walk(entry, rel + "/")
|
|
27
|
+
else:
|
|
28
|
+
yield rel, entry.read_text(encoding="utf-8")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _templates() -> dict[str, str]:
|
|
32
|
+
return dict(_walk(_tmpl_root()))
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def layout_lines(cfg: Config) -> str:
|
|
36
|
+
lines = [
|
|
37
|
+
"- `.agents/`: agent sources (rules, skills, roles, hooks) and `contextplate.toml`. Per-tool files are generated from here."
|
|
38
|
+
]
|
|
39
|
+
if cfg.module("docs"):
|
|
40
|
+
lines.append("- `docs/`: reference (`architecture.md`, `glossary.md`, `decisions/`).")
|
|
41
|
+
if cfg.module("work"):
|
|
42
|
+
lines.append(
|
|
43
|
+
"- `work/`: session state (`handoff.md`, `plans/`; `scratch/` is throwaway and gitignored)."
|
|
44
|
+
)
|
|
45
|
+
if cfg.module("check_script"):
|
|
46
|
+
lines.append(
|
|
47
|
+
"- `scripts/`: deterministic tooling. Prefer running a script over improvising commands."
|
|
48
|
+
)
|
|
49
|
+
if cfg.module("ai_app"):
|
|
50
|
+
lines.append(
|
|
51
|
+
"- `prompts/`, `evals/`, `data/`: assets for LLM features (see each folder's README)."
|
|
52
|
+
)
|
|
53
|
+
lines.append("- <Add your source and test folders, one line each.>")
|
|
54
|
+
return "\n".join(lines)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def workflow_lines(cfg: Config) -> str:
|
|
58
|
+
steps = []
|
|
59
|
+
if cfg.module("work"):
|
|
60
|
+
steps.append("Read `work/handoff.md` for current state.")
|
|
61
|
+
steps.append(
|
|
62
|
+
"For multi-step work, write a plan in `work/plans/` first (`plan-task` skill)."
|
|
63
|
+
)
|
|
64
|
+
steps.append(
|
|
65
|
+
'Work in small steps. Run the "Check everything" command before calling a task done.'
|
|
66
|
+
)
|
|
67
|
+
if cfg.module("docs"):
|
|
68
|
+
steps.append("Record non-obvious decisions in `docs/decisions/` (`adr` skill).")
|
|
69
|
+
if cfg.module("work"):
|
|
70
|
+
steps.append("Before ending a session, update `work/handoff.md` (`handoff` skill).")
|
|
71
|
+
return "\n".join(f"{i}. {s}" for i, s in enumerate(steps, 1))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _rule(description: str, paths: list[str], title: str, bullets: list[str]) -> str:
|
|
75
|
+
body = f"# {title}\n\n" + "\n".join(f"- {b}" for b in bullets) + "\n"
|
|
76
|
+
return frontmatter.compose({"description": description, "paths": paths}, body)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def starter_rules(cfg: Config) -> dict[str, str]:
|
|
80
|
+
p = PRESETS[cfg.preset]
|
|
81
|
+
source = _rule(
|
|
82
|
+
"Source code conventions",
|
|
83
|
+
p["source_paths"],
|
|
84
|
+
"Source code rules",
|
|
85
|
+
[
|
|
86
|
+
"Follow the existing pattern in the nearest sibling file before inventing a new one.",
|
|
87
|
+
"Public functions get a one-line docstring that states intent, not mechanics.",
|
|
88
|
+
"Fail loudly at boundaries. Never swallow errors silently.",
|
|
89
|
+
"No new dependency without asking. Prefer the standard library.",
|
|
90
|
+
*p["source_rules"],
|
|
91
|
+
"<Add stack-specific rules here. Delete this line when done.>",
|
|
92
|
+
],
|
|
93
|
+
)
|
|
94
|
+
tests = _rule(
|
|
95
|
+
"Test conventions",
|
|
96
|
+
p["test_paths"],
|
|
97
|
+
"Test rules",
|
|
98
|
+
[
|
|
99
|
+
"One behavior per test. Name tests after the behavior, not the function.",
|
|
100
|
+
"Arrange, act, assert, separated by blank lines.",
|
|
101
|
+
"No network or real clock in unit tests. Use fixtures and fakes.",
|
|
102
|
+
"Never weaken or delete an assertion to make a test pass. Fix the code or ask.",
|
|
103
|
+
"Run the narrowest test first, then the full check.",
|
|
104
|
+
*p["test_rules"],
|
|
105
|
+
],
|
|
106
|
+
)
|
|
107
|
+
return {".agents/rules/source.md": source, ".agents/rules/tests.md": tests}
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def canonical_files(cfg: Config) -> dict[str, str]:
|
|
111
|
+
t = _templates()
|
|
112
|
+
subs = {
|
|
113
|
+
"{{name}}": cfg.name,
|
|
114
|
+
"{{description}}": cfg.description
|
|
115
|
+
or "<One sentence: what this project does and who it is for.>",
|
|
116
|
+
"{{layout}}": layout_lines(cfg),
|
|
117
|
+
"{{workflow}}": workflow_lines(cfg),
|
|
118
|
+
"{{date}}": _dt.date.today().isoformat(),
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
def render(s: str) -> str:
|
|
122
|
+
for k, v in subs.items():
|
|
123
|
+
s = s.replace(k, v)
|
|
124
|
+
return s
|
|
125
|
+
|
|
126
|
+
files: dict[str, str] = {"AGENTS.md": render(t["AGENTS.md"])}
|
|
127
|
+
files.update(starter_rules(cfg))
|
|
128
|
+
for name in ("researcher", "test-runner", "reviewer"):
|
|
129
|
+
files[f".agents/agents/{name}.md"] = t[f"agents/agents/{name}.md"]
|
|
130
|
+
|
|
131
|
+
if cfg.module("docs"):
|
|
132
|
+
files[".agents/rules/docs.md"] = t["agents/rules/docs.md"]
|
|
133
|
+
for rel in (
|
|
134
|
+
"architecture.md",
|
|
135
|
+
"glossary.md",
|
|
136
|
+
"agent-context.md",
|
|
137
|
+
"decisions/0001-record-architecture-decisions.md",
|
|
138
|
+
):
|
|
139
|
+
files[f"docs/{rel}"] = render(t[f"docs/{rel}"])
|
|
140
|
+
files[".agents/skills/adr/SKILL.md"] = t["agents/skills/adr/SKILL.md"]
|
|
141
|
+
files[".agents/skills/adr/template.md"] = t["agents/skills/adr/template.md"]
|
|
142
|
+
|
|
143
|
+
if cfg.module("work"):
|
|
144
|
+
files["work/handoff.md"] = t["work/handoff.md"]
|
|
145
|
+
files["work/plans/.gitkeep"] = GITKEEP
|
|
146
|
+
files["work/scratch/.gitkeep"] = GITKEEP
|
|
147
|
+
files[".agents/skills/plan-task/SKILL.md"] = t["agents/skills/plan-task/SKILL.md"]
|
|
148
|
+
files[".agents/skills/plan-task/template.md"] = t["agents/skills/plan-task/template.md"]
|
|
149
|
+
files[".agents/skills/handoff/SKILL.md"] = t["agents/skills/handoff/SKILL.md"]
|
|
150
|
+
|
|
151
|
+
if cfg.module("ai_app"):
|
|
152
|
+
files[".agents/rules/ai-assets.md"] = t["agents/rules/ai-assets.md"]
|
|
153
|
+
files["prompts/README.md"] = t["ai_app/prompts/README.md"]
|
|
154
|
+
files["evals/README.md"] = t["ai_app/evals/README.md"]
|
|
155
|
+
files["data/README.md"] = t["ai_app/data/README.md"]
|
|
156
|
+
for d in ("evals/datasets", "evals/graders", "evals/results", "data/raw"):
|
|
157
|
+
files[f"{d}/.gitkeep"] = GITKEEP
|
|
158
|
+
|
|
159
|
+
files[".env.example"] = (
|
|
160
|
+
"# Copy to .env and fill in. .env is gitignored and blocked from agent reads.\n"
|
|
161
|
+
)
|
|
162
|
+
return files
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# One entry point for "is it green?" (generated by ctxplate from [commands] in
|
|
3
|
+
# .agents/contextplate.toml; edit that file and run `ctxplate sync`).
|
|
4
|
+
#
|
|
5
|
+
# Output is deliberately terse so agents read less: one line per passing step,
|
|
6
|
+
# the last 30 lines of each failure.
|
|
7
|
+
#
|
|
8
|
+
# ./scripts/check.sh # everything
|
|
9
|
+
# ./scripts/check.sh test # only steps whose name contains "test"
|
|
10
|
+
|
|
11
|
+
set -u
|
|
12
|
+
cd "$(dirname "$0")/.." || exit 1
|
|
13
|
+
|
|
14
|
+
filter="${1:-}"
|
|
15
|
+
failed=0
|
|
16
|
+
ran=0
|
|
17
|
+
log="$(mktemp)"
|
|
18
|
+
trap 'rm -f "$log"' EXIT
|
|
19
|
+
|
|
20
|
+
step() { # step <name> <command>
|
|
21
|
+
local name="$1" cmd="$2"
|
|
22
|
+
[[ -n "$filter" && "$name" != *"$filter"* ]] && return 0
|
|
23
|
+
ran=$((ran + 1))
|
|
24
|
+
if (eval "$cmd") >"$log" 2>&1; then
|
|
25
|
+
echo "ok $name"
|
|
26
|
+
else
|
|
27
|
+
echo "FAIL $name ($cmd)"
|
|
28
|
+
tail -n 30 "$log" | sed 's/^/ /'
|
|
29
|
+
failed=$((failed + 1))
|
|
30
|
+
fi
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
{{steps}}
|
|
34
|
+
|
|
35
|
+
if [ "$ran" -eq 0 ]; then
|
|
36
|
+
[ -n "$filter" ] && echo "No steps matched \"$filter\"."
|
|
37
|
+
exit 0
|
|
38
|
+
fi
|
|
39
|
+
if [ "$failed" -eq 0 ]; then
|
|
40
|
+
echo "PASS ($ran steps)"
|
|
41
|
+
else
|
|
42
|
+
echo "FAILED ($failed of $ran steps)"
|
|
43
|
+
exit 1
|
|
44
|
+
fi
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# ruff: noqa
|
|
3
|
+
# fmt: off
|
|
4
|
+
"""PostToolUse formatter (generated by ctxplate; edit [format] in .agents/contextplate.toml).
|
|
5
|
+
|
|
6
|
+
Runs the first formatter whose glob matches the edited file. Silent and
|
|
7
|
+
non-blocking: a missing formatter or a formatter error never interrupts the agent.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import re
|
|
13
|
+
import shlex
|
|
14
|
+
import shutil
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def expand_braces(pattern):
|
|
21
|
+
m = re.search(r"\{([^{}]*)\}", pattern)
|
|
22
|
+
if not m:
|
|
23
|
+
return [pattern]
|
|
24
|
+
out = []
|
|
25
|
+
for option in m.group(1).split(","):
|
|
26
|
+
out.extend(expand_braces(pattern[: m.start()] + option + pattern[m.end():]))
|
|
27
|
+
return out
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def glob_match(name, pattern):
|
|
31
|
+
for p in expand_braces(pattern):
|
|
32
|
+
rx = re.escape(p).replace(r"\*\*", ".*").replace(r"\*", "[^/]*").replace(r"\?", "[^/]")
|
|
33
|
+
if re.fullmatch(rx, name):
|
|
34
|
+
return True
|
|
35
|
+
return False
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def main():
|
|
39
|
+
try:
|
|
40
|
+
payload = json.load(sys.stdin)
|
|
41
|
+
except (ValueError, OSError):
|
|
42
|
+
return 0
|
|
43
|
+
path = (payload.get("tool_input") or {}).get("file_path")
|
|
44
|
+
if not path or not os.path.isfile(path):
|
|
45
|
+
return 0
|
|
46
|
+
try:
|
|
47
|
+
formatters = json.loads((Path(__file__).parent / "config.json").read_text(encoding="utf-8")).get("format", {})
|
|
48
|
+
except (OSError, ValueError):
|
|
49
|
+
return 0
|
|
50
|
+
root = os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()
|
|
51
|
+
try:
|
|
52
|
+
rel = Path(path).resolve().relative_to(Path(root).resolve()).as_posix()
|
|
53
|
+
except ValueError:
|
|
54
|
+
return 0 # never format files outside the project
|
|
55
|
+
name = rel.rsplit("/", 1)[-1]
|
|
56
|
+
for pattern, command in formatters.items():
|
|
57
|
+
if glob_match(name, pattern) or glob_match(rel, pattern):
|
|
58
|
+
# Split the template before substituting so paths with spaces stay one argument.
|
|
59
|
+
# Use forward slashes in [format] commands; they work on every OS.
|
|
60
|
+
args = [a.replace("{file}", path) for a in shlex.split(command)]
|
|
61
|
+
exe = shutil.which(args[0]) if args else None
|
|
62
|
+
if not exe:
|
|
63
|
+
break # formatter not installed: stay silent
|
|
64
|
+
args[0] = exe # resolves npx -> npx.cmd on Windows
|
|
65
|
+
try:
|
|
66
|
+
subprocess.run(args, cwd=root, capture_output=True, timeout=60, check=False)
|
|
67
|
+
except (OSError, subprocess.SubprocessError):
|
|
68
|
+
pass
|
|
69
|
+
break
|
|
70
|
+
return 0
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
if __name__ == "__main__":
|
|
74
|
+
sys.exit(main())
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# ruff: noqa
|
|
3
|
+
# fmt: off
|
|
4
|
+
"""PreToolUse guard (generated by ctxplate; edit .agents/contextplate.toml instead).
|
|
5
|
+
|
|
6
|
+
Blocks agent edits to protected files and to files ctxplate generates.
|
|
7
|
+
Exit code 2 blocks the tool call and sends the stderr message back to the agent.
|
|
8
|
+
Standard library only. Reads .agents/hooks/config.json next to this script.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import sys
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def expand_braces(pattern):
|
|
19
|
+
m = re.search(r"\{([^{}]*)\}", pattern)
|
|
20
|
+
if not m:
|
|
21
|
+
return [pattern]
|
|
22
|
+
out = []
|
|
23
|
+
for option in m.group(1).split(","):
|
|
24
|
+
out.extend(expand_braces(pattern[: m.start()] + option + pattern[m.end():]))
|
|
25
|
+
return out
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def to_regex(pattern):
|
|
29
|
+
i, n, out = 0, len(pattern), []
|
|
30
|
+
while i < n:
|
|
31
|
+
c = pattern[i]
|
|
32
|
+
if c == "*":
|
|
33
|
+
if pattern[i : i + 3] == "**/":
|
|
34
|
+
out.append("(?:.*/)?")
|
|
35
|
+
i += 3
|
|
36
|
+
continue
|
|
37
|
+
if pattern[i : i + 2] == "**":
|
|
38
|
+
out.append(".*")
|
|
39
|
+
i += 2
|
|
40
|
+
continue
|
|
41
|
+
out.append("[^/]*")
|
|
42
|
+
elif c == "?":
|
|
43
|
+
out.append("[^/]")
|
|
44
|
+
elif c == "[":
|
|
45
|
+
j = pattern.find("]", i + 1)
|
|
46
|
+
if j == -1:
|
|
47
|
+
out.append(re.escape(c))
|
|
48
|
+
else:
|
|
49
|
+
out.append("[" + pattern[i + 1 : j].replace("!", "^", 1) + "]")
|
|
50
|
+
i = j
|
|
51
|
+
else:
|
|
52
|
+
out.append(re.escape(c))
|
|
53
|
+
i += 1
|
|
54
|
+
return re.compile("".join(out) + r"\Z")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def match(relpath, pattern):
|
|
58
|
+
relpath = relpath.replace("\\", "/")
|
|
59
|
+
while relpath.startswith("./"):
|
|
60
|
+
relpath = relpath[2:]
|
|
61
|
+
for p in expand_braces(pattern):
|
|
62
|
+
anchored = "/" in p.rstrip("/")
|
|
63
|
+
p = p.lstrip("/")
|
|
64
|
+
if p.endswith("/"):
|
|
65
|
+
p += "**"
|
|
66
|
+
target = relpath if anchored else relpath.rsplit("/", 1)[-1]
|
|
67
|
+
if to_regex(p).match(target) or (not anchored and to_regex(p).match(relpath)):
|
|
68
|
+
return True
|
|
69
|
+
return False
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def matches_any(relpath, patterns):
|
|
73
|
+
result = False
|
|
74
|
+
for p in patterns:
|
|
75
|
+
neg = p.startswith("!")
|
|
76
|
+
if match(relpath, p[1:] if neg else p):
|
|
77
|
+
result = not neg
|
|
78
|
+
return result
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def relative(path, root):
|
|
82
|
+
try:
|
|
83
|
+
return Path(path).resolve().relative_to(Path(root).resolve()).as_posix()
|
|
84
|
+
except (ValueError, OSError):
|
|
85
|
+
return str(path).replace("\\", "/")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def main():
|
|
89
|
+
try:
|
|
90
|
+
payload = json.load(sys.stdin)
|
|
91
|
+
except (ValueError, OSError):
|
|
92
|
+
return 0
|
|
93
|
+
tool_input = payload.get("tool_input") or {}
|
|
94
|
+
path = tool_input.get("file_path") or tool_input.get("path") or tool_input.get("notebook_path")
|
|
95
|
+
if not path:
|
|
96
|
+
return 0
|
|
97
|
+
try:
|
|
98
|
+
cfg = json.loads((Path(__file__).parent / "config.json").read_text(encoding="utf-8"))
|
|
99
|
+
except (OSError, ValueError):
|
|
100
|
+
return 0
|
|
101
|
+
root = os.environ.get("CLAUDE_PROJECT_DIR") or payload.get("cwd") or os.getcwd()
|
|
102
|
+
rel = relative(path, root)
|
|
103
|
+
if rel in set(cfg.get("generated", [])):
|
|
104
|
+
print(
|
|
105
|
+
f"Blocked: {rel} is generated by ctxplate. Edit its source in .agents/ "
|
|
106
|
+
"(or .agents/contextplate.toml), then run `ctxplate sync`.",
|
|
107
|
+
file=sys.stderr,
|
|
108
|
+
)
|
|
109
|
+
return 2
|
|
110
|
+
if matches_any(rel, cfg.get("no_edit", [])):
|
|
111
|
+
print(
|
|
112
|
+
f"Blocked: {rel} is protected ([protect].no_edit in .agents/contextplate.toml). "
|
|
113
|
+
"If this change is really needed, ask the user to make it.",
|
|
114
|
+
file=sys.stderr,
|
|
115
|
+
)
|
|
116
|
+
return 2
|
|
117
|
+
return 0
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
if __name__ == "__main__":
|
|
121
|
+
sys.exit(main())
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# ruff: noqa
|
|
3
|
+
# fmt: off
|
|
4
|
+
"""SessionStart hook (generated by ctxplate; edit .agents/contextplate.toml instead).
|
|
5
|
+
|
|
6
|
+
Prints a compact snapshot that the harness adds to the agent's context at
|
|
7
|
+
session start, after /clear, and after compaction: git state, the handoff
|
|
8
|
+
note, and active plans. Never fails: any error just prints less.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import re
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def git(*args):
|
|
20
|
+
try:
|
|
21
|
+
r = subprocess.run(["git", *args], capture_output=True, text=True, timeout=5, check=False)
|
|
22
|
+
return r.stdout.strip() if r.returncode == 0 else ""
|
|
23
|
+
except (OSError, subprocess.SubprocessError):
|
|
24
|
+
return ""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def main():
|
|
28
|
+
try:
|
|
29
|
+
sys.stdin.read()
|
|
30
|
+
except OSError:
|
|
31
|
+
pass
|
|
32
|
+
root = Path(os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd())
|
|
33
|
+
try:
|
|
34
|
+
os.chdir(root)
|
|
35
|
+
except OSError:
|
|
36
|
+
return 0
|
|
37
|
+
try:
|
|
38
|
+
cfg = json.loads((Path(__file__).parent / "config.json").read_text(encoding="utf-8")).get("session", {})
|
|
39
|
+
except (OSError, ValueError):
|
|
40
|
+
cfg = {}
|
|
41
|
+
max_lines = int(cfg.get("max_lines", 40))
|
|
42
|
+
|
|
43
|
+
out = ["## Session snapshot (auto-injected)"]
|
|
44
|
+
if git("rev-parse", "--is-inside-work-tree") == "true":
|
|
45
|
+
branch = git("branch", "--show-current") or "detached"
|
|
46
|
+
dirty = len([line for line in git("status", "--porcelain").splitlines() if line.strip()])
|
|
47
|
+
out.append(f"Branch: {branch} | Uncommitted files: {dirty}")
|
|
48
|
+
log = git("log", "--oneline", "-5")
|
|
49
|
+
if log:
|
|
50
|
+
out.append("Recent commits:")
|
|
51
|
+
out.extend(f"- {line}" for line in log.splitlines())
|
|
52
|
+
|
|
53
|
+
handoff = cfg.get("handoff")
|
|
54
|
+
if handoff and (root / handoff).is_file():
|
|
55
|
+
text = (root / handoff).read_text(encoding="utf-8", errors="replace")
|
|
56
|
+
text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL)
|
|
57
|
+
lines = [line for line in text.splitlines() if line.strip()]
|
|
58
|
+
if lines:
|
|
59
|
+
out.append("")
|
|
60
|
+
out.append(f"## {handoff}")
|
|
61
|
+
out.extend(lines[:max_lines])
|
|
62
|
+
|
|
63
|
+
plans_dir = cfg.get("plans")
|
|
64
|
+
if plans_dir and (root / plans_dir).is_dir():
|
|
65
|
+
active = []
|
|
66
|
+
for p in sorted((root / plans_dir).glob("*.md")):
|
|
67
|
+
head = p.read_text(encoding="utf-8", errors="replace")[:400]
|
|
68
|
+
if re.search(r"(?m)^status:\s*active\s*$", head):
|
|
69
|
+
active.append(p.relative_to(root).as_posix())
|
|
70
|
+
if active:
|
|
71
|
+
out.append("")
|
|
72
|
+
out.append("Active plans (read before continuing): " + ", ".join(active))
|
|
73
|
+
|
|
74
|
+
print("\n".join(out))
|
|
75
|
+
return 0
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
if __name__ == "__main__":
|
|
79
|
+
sys.exit(main())
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# {{name}}
|
|
2
|
+
|
|
3
|
+
{{description}}
|
|
4
|
+
|
|
5
|
+
<!-- ctxplate:begin commands -->
|
|
6
|
+
<!-- ctxplate:end commands -->
|
|
7
|
+
|
|
8
|
+
## Layout
|
|
9
|
+
{{layout}}
|
|
10
|
+
|
|
11
|
+
## Conventions
|
|
12
|
+
|
|
13
|
+
- Follow the pattern in neighboring files before introducing a new one.
|
|
14
|
+
- Small, focused changes. One concern per commit.
|
|
15
|
+
- New behavior needs a test. Bug fixes start with a failing test.
|
|
16
|
+
- Secrets live in `.env` (never committed). Read them from environment variables.
|
|
17
|
+
- <Add the 3 to 7 conventions an agent cannot infer from the code. Delete this line when done.>
|
|
18
|
+
|
|
19
|
+
## Workflow
|
|
20
|
+
{{workflow}}
|
|
21
|
+
|
|
22
|
+
## Boundaries
|
|
23
|
+
|
|
24
|
+
- Never edit protected files (secrets, lockfiles, raw data); see `[protect]` in `.agents/contextplate.toml`.
|
|
25
|
+
- Never commit, push, or delete branches unless asked.
|
|
26
|
+
- Ask before adding a dependency or changing a public interface.
|
|
27
|
+
|
|
28
|
+
<!-- ctxplate:begin index -->
|
|
29
|
+
<!-- ctxplate:end index -->
|