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/doctor.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""`ctxplate doctor`: health checks for agent context."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import shutil
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from . import writer
|
|
11
|
+
from .adapters import build_context, build_outputs
|
|
12
|
+
from .config import Config
|
|
13
|
+
from .model import PORTABLE_SKILL_KEYS, SKILL_NAME_RE
|
|
14
|
+
|
|
15
|
+
PLACEHOLDER = re.compile(r"<(?:Add|One sentence|Delete|[A-Z][a-z]+ [a-z])[^>\n]{2,}>")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class Report:
|
|
20
|
+
items: list[tuple[str, str]] = field(default_factory=list) # (level, message)
|
|
21
|
+
|
|
22
|
+
def ok(self, msg: str) -> None:
|
|
23
|
+
self.items.append(("ok", msg))
|
|
24
|
+
|
|
25
|
+
def warn(self, msg: str) -> None:
|
|
26
|
+
self.items.append(("warn", msg))
|
|
27
|
+
|
|
28
|
+
def fail(self, msg: str) -> None:
|
|
29
|
+
self.items.append(("fail", msg))
|
|
30
|
+
|
|
31
|
+
def has(self, level: str) -> bool:
|
|
32
|
+
return any(lvl == level for lvl, _ in self.items)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def estimate_tokens(text: str) -> int:
|
|
36
|
+
return (len(text) + 3) // 4
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def always_on_text(root: Path, cfg: Config, rules) -> str:
|
|
40
|
+
parts = []
|
|
41
|
+
agents = root / "AGENTS.md"
|
|
42
|
+
if agents.exists():
|
|
43
|
+
parts.append(agents.read_text(encoding="utf-8"))
|
|
44
|
+
claude = root / "CLAUDE.md"
|
|
45
|
+
if "claude" in cfg.harnesses and claude.exists():
|
|
46
|
+
text = claude.read_text(encoding="utf-8")
|
|
47
|
+
parts.append("\n".join(line for line in text.splitlines() if not line.startswith("@")))
|
|
48
|
+
parts.extend(r.body for r in rules if r.always)
|
|
49
|
+
return re.sub(r"<!--.*?-->", "", "\n".join(parts), flags=re.S)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def run(root: Path, cfg: Config) -> Report:
|
|
53
|
+
rep = Report()
|
|
54
|
+
for w in cfg.warnings:
|
|
55
|
+
rep.warn(f"config: {w}")
|
|
56
|
+
|
|
57
|
+
if not (root / "AGENTS.md").exists():
|
|
58
|
+
rep.fail("AGENTS.md is missing. Run `ctxplate sync` or create it.")
|
|
59
|
+
|
|
60
|
+
try:
|
|
61
|
+
ctx = build_context(root, cfg)
|
|
62
|
+
except ValueError as e:
|
|
63
|
+
rep.fail(str(e))
|
|
64
|
+
return rep
|
|
65
|
+
|
|
66
|
+
# drift
|
|
67
|
+
try:
|
|
68
|
+
result = writer.sync(root, build_outputs(ctx), dry_run=True)
|
|
69
|
+
except ValueError as e:
|
|
70
|
+
rep.fail(f"cannot render outputs: {e}")
|
|
71
|
+
result = None
|
|
72
|
+
if result is not None:
|
|
73
|
+
pending = [a for a in result.actions if a.kind in ("create", "update", "delete")]
|
|
74
|
+
conflicts = [a for a in result.actions if a.kind == "conflict"]
|
|
75
|
+
if pending:
|
|
76
|
+
rep.warn(f"{len(pending)} generated file(s) out of date. Run `ctxplate sync`.")
|
|
77
|
+
if conflicts:
|
|
78
|
+
rep.warn(
|
|
79
|
+
"edited generated files: "
|
|
80
|
+
+ ", ".join(a.path for a in conflicts)
|
|
81
|
+
+ ". Move the change into .agents/, then `ctxplate sync --force`."
|
|
82
|
+
)
|
|
83
|
+
if not pending and not conflicts:
|
|
84
|
+
rep.ok("generated files are in sync")
|
|
85
|
+
for w in ctx.warnings:
|
|
86
|
+
rep.warn(w)
|
|
87
|
+
|
|
88
|
+
# budget
|
|
89
|
+
tokens = estimate_tokens(always_on_text(root, cfg, ctx.rules))
|
|
90
|
+
if tokens > cfg.budget_tokens:
|
|
91
|
+
rep.warn(
|
|
92
|
+
f"always-loaded context is about {tokens} tokens (budget {cfg.budget_tokens}). Move detail into rules, skills, or docs."
|
|
93
|
+
)
|
|
94
|
+
else:
|
|
95
|
+
rep.ok(f"always-loaded context is about {tokens} tokens (budget {cfg.budget_tokens})")
|
|
96
|
+
|
|
97
|
+
# placeholders
|
|
98
|
+
for rel in ("AGENTS.md", "docs/architecture.md", "docs/glossary.md"):
|
|
99
|
+
p = root / rel
|
|
100
|
+
if p.exists():
|
|
101
|
+
hits = PLACEHOLDER.findall(p.read_text(encoding="utf-8"))
|
|
102
|
+
if hits:
|
|
103
|
+
rep.warn(f"{rel} has {len(hits)} unfilled placeholder(s), e.g. {hits[0][:60]}")
|
|
104
|
+
|
|
105
|
+
# skills
|
|
106
|
+
for s in ctx.skills:
|
|
107
|
+
where = f".agents/skills/{s.dir.name}"
|
|
108
|
+
if not SKILL_NAME_RE.match(s.name) or len(s.name) > 64:
|
|
109
|
+
rep.fail(
|
|
110
|
+
f"{where}: skill name `{s.name}` must be lowercase letters, digits, and hyphens (max 64)"
|
|
111
|
+
)
|
|
112
|
+
if s.name != s.dir.name:
|
|
113
|
+
rep.warn(
|
|
114
|
+
f"{where}: name `{s.name}` differs from its folder name; some tools require them to match"
|
|
115
|
+
)
|
|
116
|
+
if not s.description:
|
|
117
|
+
rep.fail(
|
|
118
|
+
f"{where}: missing description (agents use it to decide when to load the skill)"
|
|
119
|
+
)
|
|
120
|
+
elif len(s.description) > 1024:
|
|
121
|
+
rep.warn(f"{where}: description is over 1024 characters")
|
|
122
|
+
extra = sorted(set(s.meta) - PORTABLE_SKILL_KEYS)
|
|
123
|
+
if extra:
|
|
124
|
+
rep.warn(
|
|
125
|
+
f"{where}: non-portable frontmatter {extra}; put tool-specific hints under `metadata`"
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
for a in ctx.agents:
|
|
129
|
+
if not a.description:
|
|
130
|
+
rep.fail(f"{a.source}: missing description")
|
|
131
|
+
if a.model not in ("inherit", "fast", "strong"):
|
|
132
|
+
rep.warn(
|
|
133
|
+
f"{a.source}: model `{a.model}` is not a neutral tier; use fast, strong, or inherit, or set `<harness>.model`"
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
for r in ctx.rules:
|
|
137
|
+
if r.always:
|
|
138
|
+
rep.warn(
|
|
139
|
+
f"{r.source}: has no `paths`, so it loads every session; consider moving it into AGENTS.md or scoping it"
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
if cfg.module("hooks") and "claude" in cfg.harnesses and not shutil.which(cfg.python):
|
|
143
|
+
rep.warn(f"hook interpreter `{cfg.python}` not found on PATH; set [hooks].python")
|
|
144
|
+
|
|
145
|
+
if not rep.has("warn") and not rep.has("fail"):
|
|
146
|
+
rep.ok("no issues found")
|
|
147
|
+
return rep
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Minimal, dependency-free YAML frontmatter reader and writer.
|
|
2
|
+
|
|
3
|
+
Supports the subset used by agent instruction files: scalars, quoted strings,
|
|
4
|
+
flow lists ``[a, b]``, block lists, one level of nested maps, flow maps
|
|
5
|
+
``{a: b}``, and block scalars (``|`` / ``>``). Anything fancier raises
|
|
6
|
+
FrontmatterError so callers can fall back gracefully.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
|
|
14
|
+
_FM_RE = re.compile(r"\A?---[ \t]*\r?\n(.*?)(?:\r?\n)?---[ \t]*(?:\r?\n|\Z)", re.S)
|
|
15
|
+
_PLAIN_SAFE = re.compile(r"^[A-Za-z0-9_./(][^\n#]*$")
|
|
16
|
+
_RESERVED = {"true", "false", "yes", "no", "on", "off", "null", "~", ""}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class FrontmatterError(ValueError):
|
|
20
|
+
pass
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def split(text: str) -> tuple[dict | None, str]:
|
|
24
|
+
"""Return (metadata, body). metadata is None when there is no frontmatter."""
|
|
25
|
+
m = _FM_RE.match(text)
|
|
26
|
+
if not m:
|
|
27
|
+
return None, text
|
|
28
|
+
return parse(m.group(1)), text[m.end() :]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def parse(src: str) -> dict:
|
|
32
|
+
data: dict = {}
|
|
33
|
+
lines = src.splitlines()
|
|
34
|
+
i = 0
|
|
35
|
+
while i < len(lines):
|
|
36
|
+
line = lines[i]
|
|
37
|
+
stripped = line.strip()
|
|
38
|
+
if not stripped or stripped.startswith("#"):
|
|
39
|
+
i += 1
|
|
40
|
+
continue
|
|
41
|
+
if line[0] in " \t":
|
|
42
|
+
raise FrontmatterError(f"unexpected indentation: {line!r}")
|
|
43
|
+
key, sep, rest = line.partition(":")
|
|
44
|
+
if not sep:
|
|
45
|
+
raise FrontmatterError(f"expected 'key: value', got {line!r}")
|
|
46
|
+
key = _unquote_key(key.strip())
|
|
47
|
+
rest = rest.strip()
|
|
48
|
+
if rest and not rest.startswith(("|", ">")):
|
|
49
|
+
data[key] = _value(rest)
|
|
50
|
+
i += 1
|
|
51
|
+
continue
|
|
52
|
+
block: list[str] = []
|
|
53
|
+
j = i + 1
|
|
54
|
+
while j < len(lines) and (not lines[j].strip() or lines[j][0] in " \t"):
|
|
55
|
+
block.append(lines[j])
|
|
56
|
+
j += 1
|
|
57
|
+
i = j
|
|
58
|
+
items = [b for b in block if b.strip() and not b.strip().startswith("#")]
|
|
59
|
+
if rest.startswith(("|", ">")):
|
|
60
|
+
data[key] = _block_scalar(
|
|
61
|
+
block, folded=rest.startswith(">"), keep=not rest.endswith("-")
|
|
62
|
+
)
|
|
63
|
+
elif not items:
|
|
64
|
+
data[key] = None
|
|
65
|
+
elif items[0].strip().startswith("-"):
|
|
66
|
+
out = []
|
|
67
|
+
for b in items:
|
|
68
|
+
s = b.strip()
|
|
69
|
+
if not s.startswith("-"):
|
|
70
|
+
raise FrontmatterError(f"mixed list/map under {key!r}")
|
|
71
|
+
out.append(_value(s[1:].strip()))
|
|
72
|
+
data[key] = out
|
|
73
|
+
else:
|
|
74
|
+
sub = {}
|
|
75
|
+
for b in items:
|
|
76
|
+
k2, s2, r2 = b.strip().partition(":")
|
|
77
|
+
if not s2:
|
|
78
|
+
raise FrontmatterError(f"expected 'key: value' under {key!r}, got {b!r}")
|
|
79
|
+
sub[_unquote_key(k2.strip())] = _value(r2.strip()) if r2.strip() else None
|
|
80
|
+
data[key] = sub
|
|
81
|
+
return data
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _unquote_key(k: str) -> str:
|
|
85
|
+
if len(k) >= 2 and k[0] == k[-1] and k[0] in "\"'":
|
|
86
|
+
return k[1:-1]
|
|
87
|
+
return k
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _block_scalar(block: list[str], folded: bool, keep: bool) -> str:
|
|
91
|
+
content = [b for b in block if b.strip()]
|
|
92
|
+
if not content:
|
|
93
|
+
return ""
|
|
94
|
+
indent = min(len(b) - len(b.lstrip()) for b in content)
|
|
95
|
+
lines = [b[indent:] if b.strip() else "" for b in block]
|
|
96
|
+
while lines and not lines[-1]:
|
|
97
|
+
lines.pop()
|
|
98
|
+
text = " ".join(lines) if folded else "\n".join(lines)
|
|
99
|
+
return text + ("\n" if keep else "")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _split_top(s: str, sep: str = ",") -> list[str]:
|
|
103
|
+
parts, buf, depth, quote = [], [], 0, None
|
|
104
|
+
for ch in s:
|
|
105
|
+
if quote:
|
|
106
|
+
buf.append(ch)
|
|
107
|
+
if ch == quote:
|
|
108
|
+
quote = None
|
|
109
|
+
continue
|
|
110
|
+
if ch in "\"'":
|
|
111
|
+
quote = ch
|
|
112
|
+
elif ch in "[{":
|
|
113
|
+
depth += 1
|
|
114
|
+
elif ch in "]}":
|
|
115
|
+
depth -= 1
|
|
116
|
+
elif ch == sep and depth == 0:
|
|
117
|
+
parts.append("".join(buf).strip())
|
|
118
|
+
buf = []
|
|
119
|
+
continue
|
|
120
|
+
buf.append(ch)
|
|
121
|
+
if "".join(buf).strip():
|
|
122
|
+
parts.append("".join(buf).strip())
|
|
123
|
+
return parts
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _value(s: str):
|
|
127
|
+
s = s.strip()
|
|
128
|
+
if s.startswith("[") and s.endswith("]"):
|
|
129
|
+
return [_value(p) for p in _split_top(s[1:-1])]
|
|
130
|
+
if s.startswith("{") and s.endswith("}"):
|
|
131
|
+
out = {}
|
|
132
|
+
for p in _split_top(s[1:-1]):
|
|
133
|
+
k, _, v = p.partition(":")
|
|
134
|
+
out[_unquote_key(k.strip())] = _value(v.strip())
|
|
135
|
+
return out
|
|
136
|
+
return _scalar(s)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _scalar(s: str):
|
|
140
|
+
if not s:
|
|
141
|
+
return None
|
|
142
|
+
if s[0] == '"':
|
|
143
|
+
end = _closing_quote(s, '"')
|
|
144
|
+
return json.loads(s[: end + 1])
|
|
145
|
+
if s[0] == "'":
|
|
146
|
+
end = _closing_quote(s, "'")
|
|
147
|
+
return s[1:end].replace("''", "'")
|
|
148
|
+
if " #" in s:
|
|
149
|
+
s = s.split(" #", 1)[0].rstrip()
|
|
150
|
+
low = s.lower()
|
|
151
|
+
if low in ("true", "yes", "on"):
|
|
152
|
+
return True
|
|
153
|
+
if low in ("false", "no", "off"):
|
|
154
|
+
return False
|
|
155
|
+
if low in ("null", "~"):
|
|
156
|
+
return None
|
|
157
|
+
if re.fullmatch(r"-?\d+", s):
|
|
158
|
+
return int(s)
|
|
159
|
+
return s
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _closing_quote(s: str, q: str) -> int:
|
|
163
|
+
i = 1
|
|
164
|
+
while i < len(s):
|
|
165
|
+
if q == '"' and s[i] == "\\":
|
|
166
|
+
i += 2
|
|
167
|
+
continue
|
|
168
|
+
if s[i] == q:
|
|
169
|
+
if q == "'" and i + 1 < len(s) and s[i + 1] == "'":
|
|
170
|
+
i += 2
|
|
171
|
+
continue
|
|
172
|
+
return i
|
|
173
|
+
i += 1
|
|
174
|
+
raise FrontmatterError(f"unterminated string: {s!r}")
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
# ---------------------------------------------------------------- writing
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def fmt_scalar(v) -> str:
|
|
181
|
+
if v is True:
|
|
182
|
+
return "true"
|
|
183
|
+
if v is False:
|
|
184
|
+
return "false"
|
|
185
|
+
if isinstance(v, int):
|
|
186
|
+
return str(v)
|
|
187
|
+
s = str(v)
|
|
188
|
+
if (
|
|
189
|
+
_PLAIN_SAFE.match(s)
|
|
190
|
+
and s.lower() not in _RESERVED
|
|
191
|
+
and ": " not in s
|
|
192
|
+
and not s.endswith((":", " "))
|
|
193
|
+
and not re.fullmatch(r"-?\d+(\.\d+)?", s)
|
|
194
|
+
):
|
|
195
|
+
return s
|
|
196
|
+
return json.dumps(s, ensure_ascii=False)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def dump(meta: dict) -> str:
|
|
200
|
+
"""Render a frontmatter block (including the --- fences)."""
|
|
201
|
+
lines = []
|
|
202
|
+
for k, v in meta.items():
|
|
203
|
+
if v is None:
|
|
204
|
+
continue
|
|
205
|
+
if isinstance(v, dict):
|
|
206
|
+
if not v:
|
|
207
|
+
continue
|
|
208
|
+
lines.append(f"{k}:")
|
|
209
|
+
for k2, v2 in v.items():
|
|
210
|
+
if v2 is None:
|
|
211
|
+
continue
|
|
212
|
+
if isinstance(v2, list):
|
|
213
|
+
lines.append(f" {k2}: [{', '.join(fmt_scalar(x) for x in v2)}]")
|
|
214
|
+
else:
|
|
215
|
+
lines.append(f" {k2}: {fmt_scalar(v2)}")
|
|
216
|
+
elif isinstance(v, list):
|
|
217
|
+
lines.append(f"{k}:")
|
|
218
|
+
lines.extend(f" - {json.dumps(str(x), ensure_ascii=False)}" for x in v)
|
|
219
|
+
else:
|
|
220
|
+
lines.append(f"{k}: {fmt_scalar(v)}")
|
|
221
|
+
return "---\n" + "\n".join(lines) + "\n---\n"
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def compose(meta: dict, body: str) -> str:
|
|
225
|
+
body = body.lstrip("\n")
|
|
226
|
+
return dump(meta) + ("\n" if body else "") + body
|
contextplate/globs.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Gitignore-style glob matching with brace expansion.
|
|
2
|
+
|
|
3
|
+
Rules:
|
|
4
|
+
- A pattern without "/" (ignoring a trailing one) matches the file name at any depth.
|
|
5
|
+
- A pattern with "/" is anchored at the project root.
|
|
6
|
+
- ``**`` matches across directories, ``*`` and ``?`` within one segment.
|
|
7
|
+
- A leading ``!`` negates; the last matching pattern wins.
|
|
8
|
+
|
|
9
|
+
The same logic is mirrored in templates/hooks/guard.py, which must stay
|
|
10
|
+
dependency-free. tests/test_globs.py runs one table against both.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import re
|
|
16
|
+
from functools import lru_cache
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def expand_braces(pattern: str) -> list[str]:
|
|
20
|
+
m = re.search(r"\{([^{}]*)\}", pattern)
|
|
21
|
+
if not m:
|
|
22
|
+
return [pattern]
|
|
23
|
+
head, tail = pattern[: m.start()], pattern[m.end() :]
|
|
24
|
+
out: list[str] = []
|
|
25
|
+
for option in m.group(1).split(","):
|
|
26
|
+
out.extend(expand_braces(head + option + tail))
|
|
27
|
+
return out
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@lru_cache(maxsize=512)
|
|
31
|
+
def _compile(pattern: str) -> re.Pattern:
|
|
32
|
+
i, n, out = 0, len(pattern), []
|
|
33
|
+
while i < n:
|
|
34
|
+
c = pattern[i]
|
|
35
|
+
if c == "*":
|
|
36
|
+
if pattern[i : i + 3] == "**/":
|
|
37
|
+
out.append("(?:.*/)?")
|
|
38
|
+
i += 3
|
|
39
|
+
continue
|
|
40
|
+
if pattern[i : i + 2] == "**":
|
|
41
|
+
out.append(".*")
|
|
42
|
+
i += 2
|
|
43
|
+
continue
|
|
44
|
+
out.append("[^/]*")
|
|
45
|
+
elif c == "?":
|
|
46
|
+
out.append("[^/]")
|
|
47
|
+
elif c == "[":
|
|
48
|
+
j = pattern.find("]", i + 1)
|
|
49
|
+
if j == -1:
|
|
50
|
+
out.append(re.escape(c))
|
|
51
|
+
else:
|
|
52
|
+
out.append("[" + pattern[i + 1 : j].replace("!", "^", 1) + "]")
|
|
53
|
+
i = j
|
|
54
|
+
else:
|
|
55
|
+
out.append(re.escape(c))
|
|
56
|
+
i += 1
|
|
57
|
+
return re.compile("".join(out) + r"\Z")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def match(relpath: str, pattern: str) -> bool:
|
|
61
|
+
relpath = relpath.replace("\\", "/")
|
|
62
|
+
while relpath.startswith("./"):
|
|
63
|
+
relpath = relpath[2:]
|
|
64
|
+
for p in expand_braces(pattern):
|
|
65
|
+
anchored = "/" in p.rstrip("/")
|
|
66
|
+
p = p.lstrip("/")
|
|
67
|
+
if p.endswith("/"):
|
|
68
|
+
p += "**"
|
|
69
|
+
target = relpath if anchored else relpath.rsplit("/", 1)[-1]
|
|
70
|
+
if _compile(p).match(target):
|
|
71
|
+
return True
|
|
72
|
+
if not anchored and _compile(p).match(relpath):
|
|
73
|
+
return True
|
|
74
|
+
return False
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def matches_any(relpath: str, patterns: list[str]) -> bool:
|
|
78
|
+
"""Gitignore semantics: later patterns override earlier ones; '!' re-includes."""
|
|
79
|
+
result = False
|
|
80
|
+
for p in patterns:
|
|
81
|
+
neg = p.startswith("!")
|
|
82
|
+
if match(relpath, p[1:] if neg else p):
|
|
83
|
+
result = not neg
|
|
84
|
+
return result
|
contextplate/model.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Load canonical, harness-neutral content from .agents/."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from . import frontmatter
|
|
10
|
+
from .globs import expand_braces
|
|
11
|
+
|
|
12
|
+
NEUTRAL_TOOLS = ("read", "search", "web", "shell", "edit")
|
|
13
|
+
MODEL_TIERS = ("inherit", "fast", "strong")
|
|
14
|
+
SKILL_NAME_RE = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$")
|
|
15
|
+
# Agent Skills spec fields allowed at top level of SKILL.md for portability.
|
|
16
|
+
PORTABLE_SKILL_KEYS = {
|
|
17
|
+
"name",
|
|
18
|
+
"description",
|
|
19
|
+
"license",
|
|
20
|
+
"compatibility",
|
|
21
|
+
"metadata",
|
|
22
|
+
"allowed-tools",
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class Rule:
|
|
28
|
+
name: str
|
|
29
|
+
description: str
|
|
30
|
+
paths: list[str]
|
|
31
|
+
body: str
|
|
32
|
+
source: str
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def always(self) -> bool:
|
|
36
|
+
return not self.paths
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def expanded_paths(self) -> list[str]:
|
|
40
|
+
out: list[str] = []
|
|
41
|
+
for p in self.paths:
|
|
42
|
+
for x in expand_braces(p):
|
|
43
|
+
if x not in out:
|
|
44
|
+
out.append(x)
|
|
45
|
+
return out
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass
|
|
49
|
+
class Skill:
|
|
50
|
+
name: str
|
|
51
|
+
dir: Path
|
|
52
|
+
meta: dict
|
|
53
|
+
body: str
|
|
54
|
+
files: list[Path] = field(default_factory=list) # supporting files, relative to dir
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def description(self) -> str:
|
|
58
|
+
return str(self.meta.get("description", ""))
|
|
59
|
+
|
|
60
|
+
def neutral(self, key: str, default=None):
|
|
61
|
+
"""Neutral, harness-agnostic hints live in `metadata` (Agent Skills spec)."""
|
|
62
|
+
md = self.meta.get("metadata") or {}
|
|
63
|
+
return md.get(key, default)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass
|
|
67
|
+
class Agent:
|
|
68
|
+
name: str
|
|
69
|
+
description: str
|
|
70
|
+
tools: list[str] | None
|
|
71
|
+
model: str
|
|
72
|
+
body: str
|
|
73
|
+
overrides: dict[str, dict] # harness -> {key: value}, from "claude.memory: project" style keys
|
|
74
|
+
source: str
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def read_only(self) -> bool:
|
|
78
|
+
return self.tools is not None and "edit" not in self.tools and "shell" not in self.tools
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class ContentError(ValueError):
|
|
82
|
+
pass
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _rel(p: Path, root: Path) -> str:
|
|
86
|
+
return p.relative_to(root).as_posix()
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def load_rules(root: Path) -> list[Rule]:
|
|
90
|
+
base = root / ".agents" / "rules"
|
|
91
|
+
rules: list[Rule] = []
|
|
92
|
+
if not base.is_dir():
|
|
93
|
+
return rules
|
|
94
|
+
for f in sorted(base.rglob("*.md")):
|
|
95
|
+
text = f.read_text(encoding="utf-8")
|
|
96
|
+
try:
|
|
97
|
+
meta, body = frontmatter.split(text)
|
|
98
|
+
except frontmatter.FrontmatterError as e:
|
|
99
|
+
raise ContentError(f"{_rel(f, root)}: {e}") from e
|
|
100
|
+
meta = meta or {}
|
|
101
|
+
paths = meta.get("paths") or []
|
|
102
|
+
if isinstance(paths, str):
|
|
103
|
+
paths = [p.strip() for p in paths.split(",") if p.strip()]
|
|
104
|
+
name = f.relative_to(base).with_suffix("").as_posix().replace("/", "-")
|
|
105
|
+
desc = str(meta.get("description") or _first_heading(body) or name)
|
|
106
|
+
rules.append(
|
|
107
|
+
Rule(
|
|
108
|
+
name=name,
|
|
109
|
+
description=desc,
|
|
110
|
+
paths=[str(p) for p in paths],
|
|
111
|
+
body=body,
|
|
112
|
+
source=_rel(f, root),
|
|
113
|
+
)
|
|
114
|
+
)
|
|
115
|
+
return rules
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def load_skills(root: Path) -> list[Skill]:
|
|
119
|
+
base = root / ".agents" / "skills"
|
|
120
|
+
skills: list[Skill] = []
|
|
121
|
+
if not base.is_dir():
|
|
122
|
+
return skills
|
|
123
|
+
for d in sorted(p for p in base.iterdir() if p.is_dir()):
|
|
124
|
+
f = d / "SKILL.md"
|
|
125
|
+
if not f.exists():
|
|
126
|
+
continue
|
|
127
|
+
try:
|
|
128
|
+
meta, body = frontmatter.split(f.read_text(encoding="utf-8"))
|
|
129
|
+
except frontmatter.FrontmatterError as e:
|
|
130
|
+
raise ContentError(f"{_rel(f, root)}: {e}") from e
|
|
131
|
+
meta = meta or {}
|
|
132
|
+
files = sorted(
|
|
133
|
+
p.relative_to(d) for p in d.rglob("*") if p.is_file() and p.name != "SKILL.md"
|
|
134
|
+
)
|
|
135
|
+
skills.append(
|
|
136
|
+
Skill(name=str(meta.get("name") or d.name), dir=d, meta=meta, body=body, files=files)
|
|
137
|
+
)
|
|
138
|
+
return skills
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def load_agents(root: Path) -> list[Agent]:
|
|
142
|
+
base = root / ".agents" / "agents"
|
|
143
|
+
agents: list[Agent] = []
|
|
144
|
+
if not base.is_dir():
|
|
145
|
+
return agents
|
|
146
|
+
for f in sorted(base.glob("*.md")):
|
|
147
|
+
try:
|
|
148
|
+
meta, body = frontmatter.split(f.read_text(encoding="utf-8"))
|
|
149
|
+
except frontmatter.FrontmatterError as e:
|
|
150
|
+
raise ContentError(f"{_rel(f, root)}: {e}") from e
|
|
151
|
+
meta = meta or {}
|
|
152
|
+
tools = meta.get("tools")
|
|
153
|
+
if isinstance(tools, str):
|
|
154
|
+
tools = [t.strip() for t in tools.split(",") if t.strip()]
|
|
155
|
+
if tools is not None:
|
|
156
|
+
unknown = [t for t in tools if t not in NEUTRAL_TOOLS]
|
|
157
|
+
if unknown:
|
|
158
|
+
raise ContentError(
|
|
159
|
+
f"{_rel(f, root)}: unknown tools {unknown}; use {', '.join(NEUTRAL_TOOLS)}"
|
|
160
|
+
)
|
|
161
|
+
model = str(meta.get("model") or "inherit")
|
|
162
|
+
overrides: dict[str, dict] = {}
|
|
163
|
+
for k, v in meta.items():
|
|
164
|
+
if "." in k:
|
|
165
|
+
h, _, key = k.partition(".")
|
|
166
|
+
overrides.setdefault(h, {})[key] = v
|
|
167
|
+
agents.append(
|
|
168
|
+
Agent(
|
|
169
|
+
name=str(meta.get("name") or f.stem),
|
|
170
|
+
description=str(meta.get("description") or ""),
|
|
171
|
+
tools=tools,
|
|
172
|
+
model=model,
|
|
173
|
+
body=body,
|
|
174
|
+
overrides=overrides,
|
|
175
|
+
source=_rel(f, root),
|
|
176
|
+
)
|
|
177
|
+
)
|
|
178
|
+
return agents
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _first_heading(body: str) -> str:
|
|
182
|
+
for line in body.splitlines():
|
|
183
|
+
if line.startswith("#"):
|
|
184
|
+
return line.lstrip("#").strip()
|
|
185
|
+
return ""
|