PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
audit_agent_setup.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2"""Audit and synchronize the repository-portable agent instruction setup."""
3
4from __future__ import annotations
5
6import argparse
7import shutil
8import subprocess
9import sys
10from pathlib import Path
11
12
13REPO_ROOT = Path(__file__).resolve().parents[2]
14CANONICAL_ROOT = REPO_ROOT / ".agents" / "skills"
15CLAUDE_ROOT = REPO_ROOT / ".claude" / "skills"
16EXPECTED_SKILLS = {
17 "picurv-capability-change",
18 "picurv-solver-debugging",
19 "picurv-case-design",
20 "picurv-test-design",
21 "picurv-spatial-kernel-change",
22 "picurv-technical-communication",
23}
24LOCAL_SETTINGS = ".claude/settings.local.json"
25LOCAL_SETTINGS_PATTERN = "/.claude/settings.local.json"
26
27
28def frontmatter(path: Path) -> dict[str, str]:
29 """!
30 @brief Parse the simple YAML front matter used by a skill file.
31 @param[in] path Skill file to inspect.
32 @return Parsed scalar front-matter fields.
33 """
34
35 lines = path.read_text(encoding="utf-8").splitlines()
36 if not lines or lines[0] != "---":
37 return {}
38 fields: dict[str, str] = {}
39 for line in lines[1:]:
40 if line == "---":
41 return fields
42 if ":" in line:
43 key, value = line.split(":", 1)
44 fields[key.strip()] = value.strip()
45 return {}
46
47
48def skill_entries(root: Path) -> dict[str, Path]:
49 """!
50 @brief Return skill directories directly below one discovery root.
51 @param[in] root Skill discovery directory.
52 @return Mapping from directory name to path, including symlinked directories.
53 """
54
55 if not root.is_dir():
56 return {}
57 return {
58 child.name: child
59 for child in root.iterdir()
60 if child.is_dir() or child.is_symlink()
61 }
62
63
64def entry_names(root: Path) -> set[str]:
65 """!
66 @brief Return every direct child name under a skill discovery root.
67 @param[in] root Skill discovery directory.
68 @return Child-name set, including unexpected files and links.
69 """
70
71 return {child.name for child in root.iterdir()} if root.is_dir() else set()
72
73
74def remove_entry(path: Path) -> None:
75 """!
76 @brief Remove one skill-tree entry without following a directory symlink.
77 @param[in] path Exact materialized or symlinked skill path.
78 @return None.
79 """
80
81 if path.is_symlink() or path.is_file():
82 path.unlink()
83 elif path.is_dir():
84 shutil.rmtree(path)
85
86
87def synchronize() -> None:
88 """!
89 @brief Materialize byte-identical Claude skill copies from the canonical tree.
90 @return None.
91 @throws RuntimeError when the canonical skill set is incomplete or unexpected.
92 """
93
94 canonical = skill_entries(CANONICAL_ROOT)
95 canonical_names = entry_names(CANONICAL_ROOT)
96 if canonical_names != EXPECTED_SKILLS:
97 missing = sorted(EXPECTED_SKILLS - canonical_names)
98 extra = sorted(canonical_names - EXPECTED_SKILLS)
99 raise RuntimeError(f"canonical skill set differs: missing={missing}, extra={extra}")
100
101 CLAUDE_ROOT.mkdir(parents=True, exist_ok=True)
102 for path in list(CLAUDE_ROOT.iterdir()):
103 remove_entry(path)
104 for name in sorted(EXPECTED_SKILLS):
105 shutil.copytree(canonical[name], CLAUDE_ROOT / name, symlinks=False)
106
107
108def git(*args: str) -> subprocess.CompletedProcess[str]:
109 """!
110 @brief Run Git with machine-global excludes disabled.
111 @param[in] args Arguments following `git`.
112 @return Completed process with captured text output.
113 """
114
115 return subprocess.run(
116 ["git", "-c", "core.excludesFile=/dev/null", "-C", str(REPO_ROOT), *args],
117 capture_output=True,
118 text=True,
119 check=False,
120 )
121
122
123def audit() -> list[str]:
124 """!
125 @brief Validate shared instructions, skill discovery copies, and local-settings hygiene.
126 @return Human-readable violations; an empty list means the audit passed.
127 """
128
129 errors: list[str] = []
130 agents = REPO_ROOT / "AGENTS.md"
131 claude = REPO_ROOT / "CLAUDE.md"
132
133 if not agents.is_file() or agents.is_symlink():
134 errors.append("AGENTS.md must be a tracked regular file, not a symlink")
135 if not claude.is_file() or claude.is_symlink():
136 errors.append("CLAUDE.md must be a regular file, not a symlink")
137 elif "@AGENTS.md" not in {line.strip() for line in claude.read_text(encoding="utf-8").splitlines()}:
138 errors.append("CLAUDE.md must import the canonical @AGENTS.md instructions")
139
140 canonical = skill_entries(CANONICAL_ROOT)
141 copies = skill_entries(CLAUDE_ROOT)
142 canonical_names = entry_names(CANONICAL_ROOT)
143 copy_names = entry_names(CLAUDE_ROOT)
144 if canonical_names != EXPECTED_SKILLS:
145 errors.append(
146 "canonical skill set mismatch: "
147 f"missing={sorted(EXPECTED_SKILLS - canonical_names)}, "
148 f"extra={sorted(canonical_names - EXPECTED_SKILLS)}"
149 )
150 if copy_names != EXPECTED_SKILLS:
151 errors.append(
152 "Claude skill set mismatch: "
153 f"missing={sorted(EXPECTED_SKILLS - copy_names)}, "
154 f"extra={sorted(copy_names - EXPECTED_SKILLS)}; run make sync-agent-skills"
155 )
156
157 for name in sorted(EXPECTED_SKILLS & set(canonical)):
158 source_dir = canonical[name]
159 source = source_dir / "SKILL.md"
160 if source_dir.is_symlink() or not source.is_file() or source.is_symlink():
161 errors.append(f"canonical skill {name} must contain a regular SKILL.md")
162 continue
163 metadata = frontmatter(source)
164 if metadata.get("name") != name:
165 errors.append(f"{source.relative_to(REPO_ROOT)} front-matter name must be {name!r}")
166 if not metadata.get("description"):
167 errors.append(f"{source.relative_to(REPO_ROOT)} requires a non-empty description")
168
169 target_dir = copies.get(name)
170 target = target_dir / "SKILL.md" if target_dir else None
171 if target_dir is None:
172 continue
173 if target_dir.is_symlink() or target is None or not target.is_file() or target.is_symlink():
174 errors.append(f"Claude skill {name} must be a materialized regular-file copy")
175 continue
176 source_files = sorted(
177 path.relative_to(source_dir) for path in source_dir.rglob("*") if path.is_file()
178 )
179 target_files = sorted(
180 path.relative_to(target_dir) for path in target_dir.rglob("*") if path.is_file()
181 )
182 if source_files != target_files:
183 errors.append(f"Claude skill {name} file set differs; run make sync-agent-skills")
184 continue
185 for relative in source_files:
186 if (source_dir / relative).read_bytes() != (target_dir / relative).read_bytes():
187 errors.append(
188 f"Claude skill {name}/{relative} differs byte-for-byte; "
189 "run make sync-agent-skills"
190 )
191
192 tracked = git("ls-files", "--error-unmatch", "--", LOCAL_SETTINGS)
193 if tracked.returncode == 0:
194 errors.append(f"{LOCAL_SETTINGS} is machine-local and must not be tracked")
195 ignored = git("check-ignore", "-v", "--", LOCAL_SETTINGS)
196 if ignored.returncode != 0:
197 errors.append(f"{LOCAL_SETTINGS} must be ignored by the repository .gitignore")
198 else:
199 fields = ignored.stdout.rstrip().split("\t", 1)[0].rsplit(":", 2)
200 source = fields[0] if len(fields) == 3 else ""
201 pattern = fields[2] if len(fields) == 3 else ""
202 if Path(source).name != ".gitignore" or pattern != LOCAL_SETTINGS_PATTERN:
203 errors.append(
204 f"{LOCAL_SETTINGS} must use the exact repository ignore pattern "
205 f"{LOCAL_SETTINGS_PATTERN!r}, not a user-global or incidental rule"
206 )
207
208 return errors
209
210
211def parse_args(argv: list[str]) -> argparse.Namespace:
212 """!
213 @brief Parse audit command-line arguments.
214 @param[in] argv Arguments excluding the executable name.
215 @return Parsed command-line namespace.
216 """
217
218 parser = argparse.ArgumentParser(
219 description="Audit or synchronize PICurv's portable shared agent setup."
220 )
221 parser.add_argument(
222 "--sync",
223 action="store_true",
224 help="replace Claude skill entries with materialized copies of canonical .agents skills",
225 )
226 return parser.parse_args(argv)
227
228
229def main(argv: list[str] | None = None) -> int:
230 """!
231 @brief Synchronize when requested, then fail closed on portability drift.
232 @param[in] argv Optional arguments excluding the executable name.
233 @return Zero on success and one on any setup violation.
234 """
235
236 args = parse_args(sys.argv[1:] if argv is None else argv)
237 try:
238 if args.sync:
240 except (OSError, RuntimeError) as error:
241 print(f"Agent setup synchronization failed: {error}", file=sys.stderr)
242 return 1
243
244 errors = audit()
245 if errors:
246 for error in errors:
247 print(f"ERROR: {error}", file=sys.stderr)
248 return 1
249 action = "synchronized and audited" if args.sync else "audited"
250 print(f"Agent setup {action}: shared instructions and {len(EXPECTED_SKILLS)} skills are portable.")
251 return 0
252
253
254if __name__ == "__main__":
255 raise SystemExit(main())
int main(list[str]|None argv=None)
Synchronize when requested, then fail closed on portability drift.
dict[str, str] frontmatter(Path path)
Parse the simple YAML front matter used by a skill file.
subprocess.CompletedProcess[str] git(*str args)
Run Git with machine-global excludes disabled.
argparse.Namespace parse_args(list[str] argv)
Parse audit command-line arguments.
dict[str, Path] skill_entries(Path root)
Return skill directories directly below one discovery root.
set[str] entry_names(Path root)
Return every direct child name under a skill discovery root.
list[str] audit()
Validate shared instructions, skill discovery copies, and local-settings hygiene.
None synchronize()
Materialize byte-identical Claude skill copies from the canonical tree.
None remove_entry(Path path)
Remove one skill-tree entry without following a directory symlink.
Head of a generic C-style linked list.
Definition variables.h:504