Skip to content

Commit 295eb22

Browse files
marcelsafinCopilot
andauthored
feat(extensions): port update-agent-context to Python (#3387)
* feat(extensions): port update-agent-context to Python Ports the agent-context extension updater to a single Python script, per #3281 and the check-prerequisites PoC pattern from #3302. The bash version already ran its core logic through embedded Python heredocs, so the port lifts that logic into a standalone script. Parity tests run bash and Python side by side and compare output and resulting context-file bytes. Co-authored-by: Copilot <[email protected]> * fix(extensions): match bash case-insensitivity on MSYS, test unparseable config gate Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Copilot <[email protected]>
1 parent 5a901a6 commit 295eb22

2 files changed

Lines changed: 833 additions & 0 deletions

File tree

Lines changed: 352 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,352 @@
1+
#!/usr/bin/env python3
2+
"""Refresh the managed Spec Kit section in the coding agent's context file(s).
3+
4+
Python port of ``update-agent-context.sh`` / ``update-agent-context.ps1``.
5+
6+
Reads ``context_files`` or ``context_file``, plus ``context_markers.{start,end}``,
7+
from the agent-context extension config:
8+
.specify/extensions/agent-context/agent-context-config.yml
9+
10+
Usage: update_agent_context.py [plan_path]
11+
12+
When ``plan_path`` is omitted, the script derives it from
13+
``.specify/feature.json`` (written by /speckit-specify). Falls back to the most
14+
recently modified ``specs/*/plan.md`` only when feature.json is absent or its
15+
plan does not exist yet.
16+
"""
17+
18+
from __future__ import annotations
19+
20+
import json
21+
import os
22+
import re
23+
import sys
24+
from pathlib import Path
25+
26+
DEFAULT_START = "<!-- SPECKIT START -->"
27+
DEFAULT_END = "<!-- SPECKIT END -->"
28+
29+
30+
def _err(message: str) -> None:
31+
print(message, file=sys.stderr)
32+
33+
34+
def _get_str(obj: object, *keys: str) -> str:
35+
node = obj
36+
for key in keys:
37+
if isinstance(node, dict) and key in node:
38+
node = node[key]
39+
else:
40+
return ""
41+
return node if isinstance(node, str) else ""
42+
43+
44+
def _collect_context_files(data: dict, project_root: str) -> list[str]:
45+
"""Resolve the managed context files from config, mirroring the bash logic."""
46+
context_files: list[str] = []
47+
seen: set[str] = set()
48+
case_insensitive = sys.platform.startswith(("win32", "cygwin", "msys"))
49+
50+
def add(value: object) -> None:
51+
if not isinstance(value, str):
52+
return
53+
candidate = value.strip()
54+
if not candidate:
55+
return
56+
key = candidate.casefold() if case_insensitive else candidate
57+
if key in seen:
58+
return
59+
context_files.append(candidate)
60+
seen.add(key)
61+
62+
raw_files = data.get("context_files")
63+
if isinstance(raw_files, list):
64+
for value in raw_files:
65+
add(value)
66+
if not context_files:
67+
add(_get_str(data, "context_file"))
68+
if not context_files:
69+
# Self-seed: when the config declares no target, derive one from the
70+
# active integration recorded in init-options.json, mapped through the
71+
# bundled agent-context-defaults.json file. Independent of the Specify
72+
# CLI by design.
73+
integration_key = ""
74+
try:
75+
with open(
76+
f"{project_root}/.specify/init-options.json", "r", encoding="utf-8"
77+
) as fh:
78+
opts = json.load(fh)
79+
if isinstance(opts, dict):
80+
value = opts.get("integration") or opts.get("ai") or ""
81+
integration_key = value if isinstance(value, str) else ""
82+
except Exception:
83+
integration_key = ""
84+
if integration_key:
85+
defaults_path = (
86+
f"{project_root}/.specify/extensions/agent-context/"
87+
"agent-context-defaults.json"
88+
)
89+
mapping = {}
90+
try:
91+
with open(defaults_path, "r", encoding="utf-8") as fh:
92+
loaded = json.load(fh)
93+
agents = loaded.get("agents", {}) if isinstance(loaded, dict) else {}
94+
mapping = agents if isinstance(agents, dict) else {}
95+
except Exception:
96+
_err(
97+
"agent-context: unable to read %s; cannot self-seed the context "
98+
"file. Set context_file in the extension config." % defaults_path
99+
)
100+
mapping = {}
101+
add(mapping.get(integration_key, "") or "")
102+
if not context_files:
103+
_err(
104+
"agent-context: no default context file is known for integration "
105+
"%s. Set context_file in the extension config to choose one."
106+
% integration_key
107+
)
108+
return context_files
109+
110+
111+
def _validate_context_file(project_root: str, context_file: str) -> str | None:
112+
"""Return an error message when the path escapes the project root."""
113+
if context_file.startswith("/") or re.match(r"^[A-Za-z]:", context_file):
114+
return (
115+
"agent-context: context files must be project-relative paths; "
116+
f"got '{context_file}'."
117+
)
118+
if "\\" in context_file:
119+
return (
120+
"agent-context: context files must not contain backslash separators; "
121+
f"got '{context_file}'."
122+
)
123+
if ".." in context_file.split("/"):
124+
return (
125+
"agent-context: context files must not contain '..' path segments; "
126+
f"got '{context_file}'."
127+
)
128+
root = Path(project_root).resolve()
129+
target = (root / context_file).resolve()
130+
try:
131+
target.relative_to(root)
132+
except ValueError:
133+
return (
134+
"agent-context: context file path resolves outside the project root; "
135+
f"got '{context_file}'."
136+
)
137+
return None
138+
139+
140+
def _resolve_plan_path(project_root: str) -> str:
141+
"""Derive the plan path: feature.json first, then the mtime fallback."""
142+
plan_path = ""
143+
feature_json = Path(project_root) / ".specify" / "feature.json"
144+
if feature_json.is_file():
145+
feature_dir = ""
146+
try:
147+
with open(feature_json, "r", encoding="utf-8") as fh:
148+
data = json.load(fh)
149+
value = data.get("feature_directory", "")
150+
feature_dir = value if isinstance(value, str) else ""
151+
except Exception:
152+
feature_dir = ""
153+
# Normalize backslashes (written by PS on Windows) before path ops.
154+
feature_dir = feature_dir.replace("\\", "/").rstrip("/")
155+
if feature_dir:
156+
# feature_directory may be relative or absolute (absolute paths
157+
# outside the project root are preserved as-is), including
158+
# drive-qualified paths (C:/...) written by PowerShell on Windows.
159+
if feature_dir.startswith("/") or re.match(r"^[A-Za-z]:/", feature_dir):
160+
candidate = Path(feature_dir) / "plan.md"
161+
else:
162+
candidate = Path(project_root) / feature_dir / "plan.md"
163+
if candidate.is_file():
164+
# Resolve symlinks before comparing so paths like /var/… vs
165+
# /private/var/… (macOS) are treated as equivalent.
166+
root = Path(project_root).resolve()
167+
resolved = candidate.resolve()
168+
try:
169+
plan_path = resolved.relative_to(root).as_posix()
170+
except ValueError:
171+
plan_path = resolved.as_posix()
172+
173+
if not plan_path:
174+
root = Path(project_root).resolve()
175+
plans = sorted(
176+
(root / "specs").glob("*/plan.md"),
177+
key=lambda p: p.stat().st_mtime,
178+
reverse=True,
179+
)
180+
if plans:
181+
try:
182+
plan_path = plans[0].relative_to(root).as_posix()
183+
except ValueError:
184+
plan_path = ""
185+
return plan_path
186+
187+
188+
def _build_section(marker_start: str, marker_end: str, plan_path: str) -> str:
189+
lines = [
190+
marker_start,
191+
"For additional context about technologies to be used, project structure,",
192+
"shell commands, and other important information, read the current plan",
193+
]
194+
if plan_path:
195+
lines.append(f"at {plan_path}")
196+
lines.append(marker_end)
197+
return "\n".join(lines) + "\n"
198+
199+
200+
def ensure_mdc_frontmatter(content: str) -> str:
201+
"""Ensure ``.mdc`` content has YAML frontmatter with ``alwaysApply: true``.
202+
203+
Cursor only auto-loads ``.mdc`` rule files that carry frontmatter with
204+
``alwaysApply: true``. Prepend it when missing, or repair the value while
205+
preserving any existing frontmatter comments/formatting.
206+
"""
207+
leading_ws = len(content) - len(content.lstrip())
208+
leading = content[:leading_ws]
209+
stripped = content[leading_ws:]
210+
211+
if not stripped.startswith("---"):
212+
return "---\nalwaysApply: true\n---\n\n" + content
213+
214+
match = re.match(
215+
r"^(---[ \t]*\r?\n)(.*?)(\r?\n---[ \t]*)(\r?\n|$)(.*)",
216+
stripped,
217+
re.DOTALL,
218+
)
219+
if not match:
220+
return "---\nalwaysApply: true\n---\n\n" + content
221+
222+
opening, fm_text, closing, sep, rest = match.groups()
223+
newline = "\r\n" if "\r\n" in opening else "\n"
224+
225+
if re.search(r"(?m)^[ \t]*alwaysApply[ \t]*:[ \t]*true[ \t]*(?:#.*)?$", fm_text):
226+
return content
227+
228+
if re.search(r"(?m)^[ \t]*alwaysApply[ \t]*:", fm_text):
229+
fm_text = re.sub(
230+
r"(?m)^([ \t]*)alwaysApply[ \t]*:.*?([ \t]*(?:#.*)?)$",
231+
r"\1alwaysApply: true\2",
232+
fm_text,
233+
count=1,
234+
)
235+
elif fm_text.strip():
236+
fm_text = fm_text + newline + "alwaysApply: true"
237+
else:
238+
fm_text = "alwaysApply: true"
239+
240+
return f"{leading}{opening}{fm_text}{closing}{sep}{rest}"
241+
242+
243+
def _upsert_section(
244+
ctx_path: str, marker_start: str, marker_end: str, section: str
245+
) -> None:
246+
"""Insert or replace the managed section, then normalize and write."""
247+
if os.path.exists(ctx_path):
248+
with open(ctx_path, "r", encoding="utf-8-sig") as fh:
249+
content = fh.read()
250+
s = content.find(marker_start)
251+
e = content.find(marker_end, s if s != -1 else 0)
252+
if s != -1 and e != -1 and e > s:
253+
end_of_marker = e + len(marker_end)
254+
if end_of_marker < len(content) and content[end_of_marker] == "\r":
255+
end_of_marker += 1
256+
if end_of_marker < len(content) and content[end_of_marker] == "\n":
257+
end_of_marker += 1
258+
new_content = content[:s] + section + content[end_of_marker:]
259+
elif s != -1:
260+
new_content = content[:s] + section
261+
elif e != -1:
262+
end_of_marker = e + len(marker_end)
263+
if end_of_marker < len(content) and content[end_of_marker] == "\r":
264+
end_of_marker += 1
265+
if end_of_marker < len(content) and content[end_of_marker] == "\n":
266+
end_of_marker += 1
267+
new_content = section + content[end_of_marker:]
268+
else:
269+
if content and not content.endswith("\n"):
270+
content += "\n"
271+
new_content = (content + "\n" + section) if content else section
272+
else:
273+
new_content = section
274+
275+
new_content = new_content.replace("\r\n", "\n").replace("\r", "\n")
276+
if ctx_path.casefold().endswith(".mdc"):
277+
new_content = ensure_mdc_frontmatter(new_content)
278+
with open(ctx_path, "wb") as fh:
279+
fh.write(new_content.encode("utf-8"))
280+
281+
282+
def main(argv: list[str] | None = None) -> int:
283+
args = sys.argv[1:] if argv is None else argv
284+
project_root = os.getcwd()
285+
ext_config = (
286+
f"{project_root}/.specify/extensions/agent-context/agent-context-config.yml"
287+
)
288+
289+
if not os.path.isfile(ext_config):
290+
_err(f"agent-context: {ext_config} not found; nothing to do.")
291+
return 0
292+
293+
try:
294+
import yaml
295+
except ImportError:
296+
_err(
297+
"agent-context: PyYAML is required to parse extension config but is "
298+
"not available in the current Python environment.\n"
299+
" To resolve: pip install pyyaml (or install it into the environment "
300+
"used by python3).\n"
301+
" Context file will not be updated until PyYAML is importable."
302+
)
303+
_err("agent-context: skipping update (see above for details).")
304+
return 0
305+
306+
try:
307+
with open(ext_config, "r", encoding="utf-8") as fh:
308+
data = yaml.safe_load(fh)
309+
except Exception as exc:
310+
_err(
311+
f"agent-context: unable to parse {ext_config} ({exc}); "
312+
"cannot update context."
313+
)
314+
_err("agent-context: skipping update (see above for details).")
315+
return 0
316+
if not isinstance(data, dict):
317+
data = {}
318+
319+
context_files = _collect_context_files(data, project_root)
320+
if not context_files:
321+
_err(
322+
"agent-context: context_files/context_file not set in extension config; "
323+
"nothing to do."
324+
)
325+
return 0
326+
327+
for context_file in context_files:
328+
error = _validate_context_file(project_root, context_file)
329+
if error:
330+
_err(error)
331+
return 1
332+
333+
marker_start = _get_str(data, "context_markers", "start") or DEFAULT_START
334+
marker_end = _get_str(data, "context_markers", "end") or DEFAULT_END
335+
336+
plan_path = args[0] if args else ""
337+
if not plan_path:
338+
plan_path = _resolve_plan_path(project_root)
339+
340+
section = _build_section(marker_start, marker_end, plan_path)
341+
342+
for context_file in context_files:
343+
ctx_path = os.path.join(project_root, context_file)
344+
os.makedirs(os.path.dirname(ctx_path) or ".", exist_ok=True)
345+
_upsert_section(ctx_path, marker_start, marker_end, section)
346+
print(f"agent-context: updated {context_file}")
347+
348+
return 0
349+
350+
351+
if __name__ == "__main__":
352+
sys.exit(main())

0 commit comments

Comments
 (0)