@elvis1513/auto-coding-skill 4.1.6 → 4.1.9

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.
@@ -0,0 +1,424 @@
1
+ #!/usr/bin/env python3
2
+ """Generate and verify the bounded auto-coding-skill install manifest."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import re
11
+ import stat
12
+ import sys
13
+ import tomllib
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from scaffold_templates import MANAGED_FRAMEWORK_DOCS, templates_for
18
+
19
+
20
+ SCHEMA_VERSION = 1
21
+ MANIFEST_PATH = Path(".agents/managed-install.json")
22
+ SKIPPED_NAMES = {"__pycache__", ".DS_Store"}
23
+ SKIPPED_SUFFIXES = {".pyc", ".pyo", ".pyd"}
24
+ STRATEGIES = {"exact", "normalized-agent", "managed-workflow"}
25
+
26
+
27
+ def _is_generated_noise(path: Path) -> bool:
28
+ return any(part in SKIPPED_NAMES for part in path.parts) or path.suffix.lower() in SKIPPED_SUFFIXES
29
+
30
+
31
+ def _files(root: Path) -> list[Path]:
32
+ if not root.exists():
33
+ return []
34
+ return sorted(
35
+ (path for path in root.rglob("*") if path.is_file() and not _is_generated_noise(path.relative_to(root))),
36
+ key=lambda path: path.relative_to(root).as_posix(),
37
+ )
38
+
39
+
40
+ def _sha256(data: bytes) -> str:
41
+ return hashlib.sha256(data).hexdigest()
42
+
43
+
44
+ def _is_escaped(text: str, index: int) -> bool:
45
+ slashes = 0
46
+ index -= 1
47
+ while index >= 0 and text[index] == "\\":
48
+ slashes += 1
49
+ index -= 1
50
+ return slashes % 2 == 1
51
+
52
+
53
+ def _next_multiline_state(line: str, initial: str) -> str:
54
+ state = initial
55
+ quote = ""
56
+ index = 0
57
+ while index < len(line):
58
+ if state:
59
+ close = line.find(state, index)
60
+ if close < 0:
61
+ return state
62
+ if state == '\"\"\"' and _is_escaped(line, close):
63
+ index = close + 3
64
+ continue
65
+ state = ""
66
+ index = close + 3
67
+ continue
68
+ if quote:
69
+ if line[index] == quote and (quote == "'" or not _is_escaped(line, index)):
70
+ quote = ""
71
+ index += 1
72
+ continue
73
+ if line[index] == "#":
74
+ return state
75
+ triple = line[index:index + 3]
76
+ if triple in {'\"\"\"', "'''"}:
77
+ state = triple
78
+ index += 3
79
+ continue
80
+ if line[index] in {'\"', "'"}:
81
+ quote = line[index]
82
+ index += 1
83
+ return state
84
+
85
+
86
+ def normalize_managed_agent(text: str) -> str:
87
+ """Remove the one supported top-level model override, preserving all other bytes."""
88
+ try:
89
+ parsed = tomllib.loads(text)
90
+ except tomllib.TOMLDecodeError as exc:
91
+ raise ValueError(f"invalid managed agent TOML: {exc}") from exc
92
+ if "model" in parsed and (not isinstance(parsed["model"], str) or not parsed["model"].strip()):
93
+ raise ValueError("model must be a non-empty TOML string")
94
+ lines = text.replace("\r\n", "\n").split("\n")
95
+ matches: list[int] = []
96
+ multiline = ""
97
+ in_table = False
98
+ pattern = re.compile(r"^\s*(?:model|\"model\"|'model')\s*=\s*(.+)$")
99
+ for index, line in enumerate(lines):
100
+ if not multiline:
101
+ trimmed = line.lstrip()
102
+ if trimmed.startswith("[") and not trimmed.startswith("[#"):
103
+ in_table = True
104
+ if not in_table and pattern.match(line):
105
+ matches.append(index)
106
+ multiline = _next_multiline_state(line, multiline)
107
+ if len(matches) > 1:
108
+ raise ValueError("model is defined more than once")
109
+ if matches:
110
+ del lines[matches[0]]
111
+ return "\n".join(lines)
112
+
113
+
114
+ def managed_workflow_region(text: str) -> str:
115
+ normalized = text.replace("\r\n", "\n")
116
+ start = list(re.finditer(
117
+ r"<!--\s*auto-coding-skill:managed-workflow:start\s+version=[0-9]+\.[0-9]+\.[0-9]+\s*-->",
118
+ normalized,
119
+ ))
120
+ end = list(re.finditer(r"<!--\s*auto-coding-skill:managed-workflow:end\s*-->", normalized))
121
+ if len(start) != 1 or len(end) != 1 or start[0].start() >= end[0].start():
122
+ raise ValueError("managed workflow markers are missing or malformed")
123
+ return normalized[start[0].start():end[0].end()]
124
+
125
+
126
+ def _entry(
127
+ *,
128
+ target: str,
129
+ source: str,
130
+ strategy: str,
131
+ data: bytes,
132
+ executable: bool,
133
+ scope: str,
134
+ version: str,
135
+ ) -> dict[str, Any]:
136
+ return {
137
+ "path": target,
138
+ "source": source,
139
+ "ownership": strategy,
140
+ "sha256": _sha256(data),
141
+ "executable": executable,
142
+ "scope": scope,
143
+ "version": version,
144
+ }
145
+
146
+
147
+ def build_manifest(skill_root: Path, agents_root: Path, version: str) -> dict[str, Any]:
148
+ entries: list[dict[str, Any]] = []
149
+ for source_path in _files(skill_root):
150
+ rel = source_path.relative_to(skill_root).as_posix()
151
+ entries.append(_entry(
152
+ target=f".agents/skills/auto-coding-skill/{rel}",
153
+ source=f"skill/{rel}",
154
+ strategy="exact",
155
+ data=source_path.read_bytes(),
156
+ executable=bool(source_path.stat().st_mode & 0o111),
157
+ scope="shared",
158
+ version=version,
159
+ ))
160
+ for source_path in _files(agents_root):
161
+ rel = source_path.relative_to(agents_root).as_posix()
162
+ normalized = normalize_managed_agent(source_path.read_text(encoding="utf-8")).encode("utf-8")
163
+ entries.append(_entry(
164
+ target=f".agents/agents/{rel}",
165
+ source=f"agents/{rel}",
166
+ strategy="normalized-agent",
167
+ data=normalized,
168
+ executable=bool(source_path.stat().st_mode & 0o111),
169
+ scope="shared",
170
+ version=version,
171
+ ))
172
+
173
+ exact_project_sources = {
174
+ "AGENTS.md": skill_root / "data/templates/bridges/AGENTS.md",
175
+ "docs/tools/autopipeline/ap.py": skill_root / "data/templates/tools/ap.py",
176
+ }
177
+ for target, source_path in exact_project_sources.items():
178
+ rel = source_path.relative_to(skill_root).as_posix()
179
+ entries.append(_entry(
180
+ target=target,
181
+ source=f"skill/{rel}",
182
+ strategy="exact",
183
+ data=source_path.read_bytes(),
184
+ executable=bool(source_path.stat().st_mode & 0o111),
185
+ scope="project",
186
+ version=version,
187
+ ))
188
+
189
+ engineering = skill_root / "data/templates/ENGINEERING.md"
190
+ entries.append(_entry(
191
+ target="docs/ENGINEERING.md",
192
+ source="skill/data/templates/ENGINEERING.md#managed-workflow",
193
+ strategy="managed-workflow",
194
+ data=managed_workflow_region(engineering.read_text(encoding="utf-8")).encode("utf-8"),
195
+ executable=bool(engineering.stat().st_mode & 0o111),
196
+ scope="project",
197
+ version=version,
198
+ ))
199
+
200
+ templates = templates_for("all")
201
+ for target in sorted(MANAGED_FRAMEWORK_DOCS):
202
+ entries.append(_entry(
203
+ target=target,
204
+ source=f"generated:scaffold_templates:{target}",
205
+ strategy="exact",
206
+ data=templates[target].encode("utf-8"),
207
+ executable=False,
208
+ scope="project",
209
+ version=version,
210
+ ))
211
+
212
+ entries.sort(key=lambda item: item["path"])
213
+ if len({item["path"] for item in entries}) != len(entries):
214
+ raise ValueError("managed install manifest contains duplicate paths")
215
+ return {
216
+ "schema_version": SCHEMA_VERSION,
217
+ "skill_version": version,
218
+ "manifest_path": MANIFEST_PATH.as_posix(),
219
+ "entries": entries,
220
+ "managed_namespaces": [
221
+ {"path": ".agents/skills/auto-coding-skill", "scope": "shared"},
222
+ {"path": "docs/tools/autopipeline", "scope": "project"},
223
+ ],
224
+ "preserved": [
225
+ ".agents/archive/**",
226
+ ".agents/agents/* (except paths listed in entries)",
227
+ "docs/project/**",
228
+ "docs/architecture/adr/[0-9]*.md",
229
+ "docs/design/*.md",
230
+ "docs/interfaces/*.md",
231
+ "docs/deployment/deploy-records/*.md",
232
+ "docs/reviews/*.md",
233
+ ],
234
+ }
235
+
236
+
237
+ def render_manifest(manifest: dict[str, Any]) -> str:
238
+ return json.dumps(manifest, ensure_ascii=False, separators=(",", ":")) + "\n"
239
+
240
+
241
+ def _safe_relative_path(raw: Any) -> Path:
242
+ if not isinstance(raw, str) or not raw or "\\" in raw:
243
+ raise ValueError("path must be a non-empty POSIX relative path")
244
+ path = Path(raw)
245
+ if path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts):
246
+ raise ValueError("path must not be absolute or contain traversal")
247
+ return path
248
+
249
+
250
+ def _load_manifest(path: Path) -> dict[str, Any]:
251
+ try:
252
+ value = json.loads(path.read_text(encoding="utf-8"))
253
+ except FileNotFoundError as exc:
254
+ raise ValueError(f"missing manifest: {path}") from exc
255
+ except (OSError, json.JSONDecodeError) as exc:
256
+ raise ValueError(f"invalid manifest {path}: {exc}") from exc
257
+ if not isinstance(value, dict) or value.get("schema_version") != SCHEMA_VERSION:
258
+ raise ValueError("managed install manifest schema_version must be 1")
259
+ return value
260
+
261
+
262
+ def verify_managed_install(
263
+ repo: Path,
264
+ *,
265
+ mode: str = "project",
266
+ expected_version: str | None = None,
267
+ manifest_path: Path | None = None,
268
+ ) -> dict[str, Any]:
269
+ repo = repo.resolve()
270
+ errors: list[str] = []
271
+ manifest_file = manifest_path or repo / MANIFEST_PATH
272
+ try:
273
+ manifest = _load_manifest(manifest_file)
274
+ except ValueError as exc:
275
+ return {"ok": False, "version": "", "checked": 0, "errors": [str(exc)]}
276
+
277
+ version = manifest.get("skill_version")
278
+ if not isinstance(version, str) or not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version):
279
+ errors.append("manifest skill_version must be a semantic version")
280
+ version = ""
281
+ if expected_version and version != expected_version:
282
+ errors.append(f"manifest version {version or '<invalid>'} does not match expected {expected_version}")
283
+ if manifest.get("manifest_path") != MANIFEST_PATH.as_posix():
284
+ errors.append(f"manifest_path must be {MANIFEST_PATH.as_posix()}")
285
+
286
+ raw_entries = manifest.get("entries")
287
+ if not isinstance(raw_entries, list):
288
+ return {"ok": False, "version": version, "checked": 0, "errors": errors + ["manifest entries must be a list"]}
289
+
290
+ entries: list[tuple[dict[str, Any], Path]] = []
291
+ seen: set[str] = set()
292
+ for index, entry in enumerate(raw_entries):
293
+ label = f"entries[{index}]"
294
+ if not isinstance(entry, dict):
295
+ errors.append(f"{label} must be an object")
296
+ continue
297
+ try:
298
+ rel = _safe_relative_path(entry.get("path"))
299
+ except ValueError as exc:
300
+ errors.append(f"{label}: {exc}")
301
+ continue
302
+ rel_text = rel.as_posix()
303
+ if rel_text in seen:
304
+ errors.append(f"duplicate managed path: {rel_text}")
305
+ continue
306
+ seen.add(rel_text)
307
+ if entry.get("ownership") not in STRATEGIES:
308
+ errors.append(f"{rel_text}: unknown ownership strategy")
309
+ if entry.get("scope") not in {"shared", "project"}:
310
+ errors.append(f"{rel_text}: scope must be shared or project")
311
+ if entry.get("version") != version:
312
+ errors.append(f"{rel_text}: entry version does not match manifest")
313
+ if not isinstance(entry.get("sha256"), str) or not re.fullmatch(r"[0-9a-f]{64}", entry["sha256"]):
314
+ errors.append(f"{rel_text}: invalid sha256")
315
+ if not isinstance(entry.get("executable"), bool):
316
+ errors.append(f"{rel_text}: executable must be boolean")
317
+ entries.append((entry, rel))
318
+
319
+ active_scopes = {"shared"} | ({"project"} if mode == "project" else set())
320
+ checked = 0
321
+ active_paths: set[str] = set()
322
+ for entry, rel in entries:
323
+ if entry.get("scope") not in active_scopes:
324
+ continue
325
+ target = repo / rel
326
+ rel_text = rel.as_posix()
327
+ active_paths.add(rel_text)
328
+ if target.is_symlink():
329
+ errors.append(f"{rel_text}: managed target must not be a symlink")
330
+ continue
331
+ if not target.is_file():
332
+ errors.append(f"{rel_text}: managed file is missing")
333
+ continue
334
+ checked += 1
335
+ try:
336
+ strategy = entry.get("ownership")
337
+ if strategy == "exact":
338
+ material = target.read_bytes()
339
+ elif strategy == "normalized-agent":
340
+ material = normalize_managed_agent(target.read_text(encoding="utf-8")).encode("utf-8")
341
+ elif strategy == "managed-workflow":
342
+ material = managed_workflow_region(target.read_text(encoding="utf-8")).encode("utf-8")
343
+ else:
344
+ continue
345
+ except (OSError, UnicodeError, ValueError) as exc:
346
+ errors.append(f"{rel_text}: cannot normalize managed content: {exc}")
347
+ continue
348
+ if _sha256(material) != entry.get("sha256"):
349
+ errors.append(f"{rel_text}: managed content drift")
350
+ if os.name != "nt":
351
+ actual_executable = bool(stat.S_IMODE(target.stat().st_mode) & 0o111)
352
+ if actual_executable != entry.get("executable"):
353
+ errors.append(f"{rel_text}: executable bit drift")
354
+
355
+ namespaces = manifest.get("managed_namespaces")
356
+ if not isinstance(namespaces, list):
357
+ errors.append("managed_namespaces must be a list")
358
+ namespaces = []
359
+ for index, namespace in enumerate(namespaces):
360
+ if not isinstance(namespace, dict) or namespace.get("scope") not in active_scopes:
361
+ continue
362
+ try:
363
+ rel = _safe_relative_path(namespace.get("path"))
364
+ except ValueError as exc:
365
+ errors.append(f"managed_namespaces[{index}]: {exc}")
366
+ continue
367
+ root = repo / rel
368
+ if not root.is_dir():
369
+ errors.append(f"{rel.as_posix()}: managed namespace is missing")
370
+ continue
371
+ expected = {path for path in active_paths if path.startswith(rel.as_posix() + "/")}
372
+ actual = {
373
+ candidate.relative_to(repo).as_posix()
374
+ for candidate in root.rglob("*")
375
+ if (candidate.is_file() or candidate.is_symlink())
376
+ and not _is_generated_noise(candidate.relative_to(root))
377
+ }
378
+ for extra in sorted(actual - expected):
379
+ errors.append(f"{extra}: unexpected file in managed namespace")
380
+
381
+ return {"ok": not errors, "version": version, "checked": checked, "errors": errors}
382
+
383
+
384
+ def _main(argv: list[str]) -> int:
385
+ parser = argparse.ArgumentParser(description=__doc__)
386
+ commands = parser.add_subparsers(dest="command", required=True)
387
+ generate = commands.add_parser("generate")
388
+ generate.add_argument("--skill-root", required=True)
389
+ generate.add_argument("--agents-root", required=True)
390
+ generate.add_argument("--version", required=True)
391
+ generate.add_argument("--output")
392
+ verify = commands.add_parser("verify")
393
+ verify.add_argument("--repo", required=True)
394
+ verify.add_argument("--mode", choices=("project", "global"), default="project")
395
+ verify.add_argument("--expected-version")
396
+ verify.add_argument("--manifest")
397
+ verify.add_argument("--json", action="store_true")
398
+ args = parser.parse_args(argv)
399
+ if args.command == "generate":
400
+ rendered = render_manifest(build_manifest(Path(args.skill_root), Path(args.agents_root), args.version))
401
+ if args.output:
402
+ Path(args.output).write_text(rendered, encoding="utf-8")
403
+ else:
404
+ sys.stdout.write(rendered)
405
+ return 0
406
+ result = verify_managed_install(
407
+ Path(args.repo),
408
+ mode=args.mode,
409
+ expected_version=args.expected_version,
410
+ manifest_path=Path(args.manifest) if args.manifest else None,
411
+ )
412
+ if args.json:
413
+ print(json.dumps(result, ensure_ascii=False))
414
+ elif result["ok"]:
415
+ print(f"[install-integrity] OK version={result['version']} files={result['checked']}")
416
+ else:
417
+ print("[install-integrity] FAILED", file=sys.stderr)
418
+ for error in result["errors"]:
419
+ print(f"- {error}", file=sys.stderr)
420
+ return 0 if result["ok"] else 2
421
+
422
+
423
+ if __name__ == "__main__":
424
+ raise SystemExit(_main(sys.argv[1:]))
@@ -156,6 +156,15 @@ Only executed checks may be marked PASS.
156
156
  }
157
157
 
158
158
 
159
+ MANAGED_FRAMEWORK_DOCS = frozenset({
160
+ "docs/architecture/structure-standard.md",
161
+ "docs/architecture/adr/_TEMPLATE-ADR.md",
162
+ "docs/deployment/deploy-records/_TEMPLATE-DEPLOY-RECORD.md",
163
+ "docs/design/_TEMPLATE-DD.md",
164
+ "docs/reviews/_TEMPLATE-REVIEW.md",
165
+ })
166
+
167
+
159
168
  def scaffold_groups() -> list[str]:
160
169
  return sorted(TEMPLATES)
161
170
 
@@ -30,6 +30,10 @@ const files = payload?.[0]?.files?.map(item => String(item.path || "")) || [];
30
30
  const forbidden = files.filter(file =>
31
31
  /(^|\/)__pycache__(\/|$)/.test(file) || /\.py[cod]$/i.test(file),
32
32
  );
33
+ if (!files.includes("cli/assets/managed-install.json")) {
34
+ process.stderr.write("Managed install manifest is missing from the package\n");
35
+ process.exit(1);
36
+ }
33
37
  if (forbidden.length > 0) {
34
38
  process.stderr.write(`Generated Python cache leaked into package:\n- ${forbidden.join("\n- ")}\n`);
35
39
  process.exit(1);