agent-manifesto-kit 1.8.2 → 1.8.4

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.
Files changed (56) hide show
  1. package/README.md +29 -2
  2. package/collection/bundles/game-dev/README.md +69 -0
  3. package/collection/bundles/game-dev/RECOMMENDS.md +24 -0
  4. package/collection/bundles/game-dev/agents/game-code-reviewer.md +36 -0
  5. package/collection/bundles/game-dev/agents/game-image-generator.md +34 -0
  6. package/collection/bundles/game-dev/agents/game-visual-reviewer.md +34 -0
  7. package/collection/bundles/game-dev/skills/game-code/SKILL.md +54 -0
  8. package/collection/bundles/game-dev/skills/game-code/agents/openai.yaml +4 -0
  9. package/collection/bundles/game-dev/skills/game-code/references/engine-godot.md +45 -0
  10. package/collection/bundles/game-dev/skills/game-code/references/engine-threejs.md +47 -0
  11. package/collection/bundles/game-dev/skills/game-delegation/SKILL.md +58 -0
  12. package/collection/bundles/game-dev/skills/game-delegation/agents/openai.yaml +4 -0
  13. package/collection/bundles/game-dev/skills/game-dev-setup/SKILL.md +103 -0
  14. package/collection/bundles/game-dev/skills/game-dev-setup/agents/openai.yaml +4 -0
  15. package/collection/bundles/game-dev/skills/game-dev-setup/assets/agents-section.md +20 -0
  16. package/collection/bundles/game-dev/skills/game-dev-setup/references/config.md +46 -0
  17. package/collection/bundles/game-dev/skills/game-dev-setup/scripts/audit.py +202 -0
  18. package/collection/bundles/game-dev/skills/game-dev-setup/scripts/balance.py +197 -0
  19. package/collection/bundles/game-dev/skills/game-dev-setup/scripts/check.py +62 -0
  20. package/collection/bundles/game-dev/skills/game-dev-setup/scripts/delegate.py +350 -0
  21. package/collection/bundles/game-dev/skills/game-dev-setup/scripts/gamedev_config.py +163 -0
  22. package/collection/bundles/game-dev/skills/game-dev-setup/scripts/install.py +172 -0
  23. package/collection/bundles/game-dev/skills/game-dev-setup/scripts/instruction_size.py +75 -0
  24. package/collection/bundles/game-dev/skills/game-dev-setup/scripts/prompts/code_review.md +19 -0
  25. package/collection/bundles/game-dev/skills/game-dev-setup/scripts/prompts/image.md +5 -0
  26. package/collection/bundles/game-dev/skills/game-dev-setup/scripts/prompts/visual_review.md +13 -0
  27. package/collection/bundles/game-dev/skills/game-dev-setup/scripts/pyramid.py +84 -0
  28. package/collection/bundles/game-dev/skills/game-dev-setup/scripts/test_game_dev.py +309 -0
  29. package/collection/bundles/game-dev/skills/game-planning/SKILL.md +80 -0
  30. package/collection/bundles/game-dev/skills/game-planning/agents/openai.yaml +4 -0
  31. package/collection/bundles/game-dev/skills/game-testing/SKILL.md +58 -0
  32. package/collection/bundles/game-dev/skills/game-testing/agents/openai.yaml +4 -0
  33. package/collection/bundles/kit-adopt/conventions/recommended-companions.md +1 -1
  34. package/collection/skills/astro-preview/SKILL.md +97 -41
  35. package/collection/skills/astro-preview/references/manifest.md +42 -0
  36. package/collection/skills/astro-preview/scripts/portal.py +686 -0
  37. package/collection/skills/astro-preview/scripts/test_portal.py +576 -0
  38. package/collection/skills/concept-asset-builder/SKILL.md +14 -5
  39. package/collection/skills/concept-asset-builder/assets/templates/agent_brief.md +5 -2
  40. package/collection/skills/concept-asset-builder/references/field-lessons.md +9 -0
  41. package/collection/skills/concept-asset-builder/scripts/blender/render_views.py +4 -2
  42. package/collection/skills/concept-asset-builder/scripts/codex_review.sh +4 -1
  43. package/collection/skills/concept-asset-builder/scripts/godot/capture.gd +5 -2
  44. package/collection/skills/concept-asset-builder/scripts/init_workspace.sh +1 -1
  45. package/collection/skills/concept-asset-builder/scripts/measure_silhouette.py +18 -4
  46. package/collection/skills/concept-asset-builder/scripts/overlay_masks.py +25 -0
  47. package/collection/skills/concept-asset-builder/scripts/test_tools.py +44 -0
  48. package/collection/skills/concept-asset-builder/scripts/threejs/studio.js +4 -2
  49. package/collection/skills/concept-asset-builder/scripts/wear_stats.py +35 -1
  50. package/collection/skills/mixamo/SKILL.md +109 -0
  51. package/collection/skills/mixamo/agents/openai.yaml +4 -0
  52. package/collection/skills/mixamo/scripts/mixamo.py +264 -0
  53. package/collection/skills/mixamo/scripts/test_mixamo.py +108 -0
  54. package/collection/skills/sfx-creator/SKILL.md +160 -0
  55. package/collection/skills/sfx-creator/agents/openai.yaml +4 -0
  56. package/package.json +1 -1
@@ -0,0 +1,686 @@
1
+ #!/usr/bin/env python3
2
+ """Astro Preview portal upkeep for a project: manifest, wiki pages, the wiki hook and the wiki updater.
3
+
4
+ Standard library only. The wiki lives in the project (`docs/wiki/*.md` by default) next to `.astro/portal.json`;
5
+ Astro Preview only reads them. `update` runs a cheaper Claude model in a throw-away snapshot of HEAD, copies back
6
+ only the wiki folder and commits it alone, so user work in the checkout is never touched.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import datetime as dt
12
+ import hashlib
13
+ import json
14
+ import os
15
+ import re
16
+ import shutil
17
+ import subprocess
18
+ import sys
19
+ import tempfile
20
+ import time
21
+ from pathlib import Path
22
+
23
+ MANIFEST = Path(".astro") / "portal.json"
24
+ STATE = ".state.json"
25
+ DEFAULT_MODEL = "claude-sonnet-5-5"
26
+ EFFORTS = ("low", "medium", "high")
27
+ # Each project gets its own marked block, so several projects in one repository keep their hooks.
28
+ HOOK_BEGIN = "# >>> astro-preview wiki"
29
+ HOOK_END = "# <<< astro-preview wiki"
30
+ HOOKS = ("post-commit", "post-merge")
31
+ SKILL_DIR = Path(__file__).resolve().parents[1]
32
+ LOCK_TTL = 2 * 3600
33
+ AGENT_TIMEOUT = 30 * 60
34
+
35
+ TEMPLATES = {
36
+ "game": [
37
+ ("01-idea", "Idea", "Pitch: what the game is, who it is for and why it is fun."),
38
+ ("02-concepts", "Concepts & Art", "Setting, visual style, key references and the vocabulary of the world."),
39
+ ("03-mechanics", "Core Mechanics", "Player verbs, rules, resources, win and loss conditions."),
40
+ ("04-game-loop", "Game Loop", "Moment-to-moment, session and long-term loops; progression."),
41
+ ("05-entities", "Characters & Entities", "Units, characters, enemies, items and their roles."),
42
+ ("06-levels", "Levels & World", "Maps, levels and environments and how they are built."),
43
+ ("07-controls", "Controls", "Input scheme per platform."),
44
+ ("08-audio", "Audio", "Audio direction and where the approved sounds live."),
45
+ ("09-technology", "Technology", "Engine, stack, project structure, how to build and run."),
46
+ ],
47
+ "app": [
48
+ ("01-idea", "Idea", "What the application is for, who uses it and why."),
49
+ ("02-concepts", "Domain Concepts", "The things the application operates on and their relationships."),
50
+ ("03-features", "Features", "Capabilities available today."),
51
+ ("04-user-flows", "User Flows", "The main scenarios step by step."),
52
+ ("05-architecture", "Architecture", "Modules, data flow, storage and runtime boundaries."),
53
+ ("06-technology", "Technology", "Stack, project structure, how to build and run."),
54
+ ],
55
+ }
56
+
57
+
58
+ class PortalError(Exception):
59
+ pass
60
+
61
+
62
+ # ---------------------------------------------------------------- helpers
63
+
64
+ def git(root: Path, *args: str, check: bool = True, env: dict | None = None) -> str:
65
+ result = subprocess.run(["git", "-C", str(root), *args], capture_output=True, text=True,
66
+ env={**os.environ, **(env or {})})
67
+ if check and result.returncode:
68
+ raise PortalError(f"git {' '.join(args)}: {result.stderr.strip() or result.stdout.strip()}")
69
+ return result.stdout.strip() if result.returncode == 0 else ""
70
+
71
+
72
+ def relative_ok(value: str) -> bool:
73
+ return (bool(value) and len(value) <= 256 and "\\" not in value and not value.startswith("/")
74
+ and all(part and not part.startswith(".") and part != ".." for part in value.split("/")))
75
+
76
+
77
+ def project_root(path: str | None, create: bool = False) -> Path:
78
+ """The project folder: the one given (as Astro registers it), or the nearest folder up to the git top level
79
+ that holds a manifest. A project may be a subfolder of its repository."""
80
+ start = Path(path or os.getcwd()).resolve()
81
+ if create or (start / MANIFEST).is_file():
82
+ return start
83
+ top = git(start, "rev-parse", "--show-toplevel", check=False)
84
+ if top:
85
+ for folder in [start, *start.parents]:
86
+ if (folder / MANIFEST).is_file():
87
+ return folder
88
+ if folder == Path(top).resolve():
89
+ break
90
+ return start
91
+
92
+
93
+ def read_manifest_raw(root: Path) -> dict | None:
94
+ path = root / MANIFEST
95
+ if not path.is_file() or path.is_symlink():
96
+ return None
97
+ try:
98
+ value = json.loads(path.read_text(encoding="utf-8"))
99
+ except (OSError, ValueError) as error:
100
+ raise PortalError(f"{MANIFEST}: invalid JSON ({error})") from error
101
+ if not isinstance(value, dict):
102
+ raise PortalError(f"{MANIFEST}: must be a JSON object")
103
+ return value
104
+
105
+
106
+ def load_manifest(root: Path) -> dict | None:
107
+ """The manifest with defaults, validated like Astro Preview's reader; None when the project has none."""
108
+ raw = read_manifest_raw(root)
109
+ if raw is None:
110
+ return None
111
+ if raw.get("version", 1) != 1:
112
+ raise PortalError(f"{MANIFEST}: unsupported version")
113
+ if raw.get("type") not in TEMPLATES:
114
+ raise PortalError(f"{MANIFEST}: type must be game or app")
115
+ data = {"version": 1, "type": raw["type"], "wiki": raw.get("wiki", "docs/wiki"),
116
+ "sounds": raw.get("sounds", []), "autoUpdate": raw.get("autoUpdate", True),
117
+ "model": raw.get("model", DEFAULT_MODEL), "effort": raw.get("effort", "medium")}
118
+ if "title" in raw:
119
+ data["title"] = raw["title"]
120
+ if "run" in raw:
121
+ data["run"] = raw["run"]
122
+ if not relative_ok(data["wiki"]):
123
+ raise PortalError(f"{MANIFEST}: wiki must be a relative path")
124
+ if not isinstance(data["sounds"], list) or len(data["sounds"]) > 16 or \
125
+ not all(isinstance(s, str) and relative_ok(s) for s in data["sounds"]):
126
+ raise PortalError(f"{MANIFEST}: sounds must be relative paths")
127
+ if "run" in data and (not isinstance(data["run"], str) or not data["run"].strip() or len(data["run"]) > 500
128
+ or "\n" in data["run"] or "\r" in data["run"]):
129
+ raise PortalError(f"{MANIFEST}: run must be one line")
130
+ if not isinstance(data["autoUpdate"], bool):
131
+ raise PortalError(f"{MANIFEST}: autoUpdate must be true or false")
132
+ if not isinstance(data["model"], str) or not re.fullmatch(r"[a-z0-9][a-z0-9.-]{0,63}", data["model"]):
133
+ raise PortalError(f"{MANIFEST}: model is invalid")
134
+ if data["effort"] not in EFFORTS:
135
+ raise PortalError(f"{MANIFEST}: effort must be low, medium or high")
136
+ return data
137
+
138
+
139
+ def require_manifest(root: Path) -> dict:
140
+ manifest = load_manifest(root)
141
+ if manifest is None:
142
+ raise PortalError(f"No {MANIFEST} in {root}; run `portal.py init --type game|app` first")
143
+ return manifest
144
+
145
+
146
+ def write_json(path: Path, value: dict) -> None:
147
+ path.parent.mkdir(parents=True, exist_ok=True)
148
+ tmp = path.with_name(path.name + ".tmp")
149
+ tmp.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
150
+ os.replace(tmp, path)
151
+
152
+
153
+ def read_state(root: Path, manifest: dict) -> dict:
154
+ try:
155
+ value = json.loads((root / manifest["wiki"] / STATE).read_text(encoding="utf-8"))
156
+ return value if isinstance(value, dict) else {}
157
+ except (OSError, ValueError):
158
+ return {}
159
+
160
+
161
+ def wiki_pages(root: Path, manifest: dict) -> list[Path]:
162
+ folder = root / manifest["wiki"]
163
+ if not folder.is_dir():
164
+ return []
165
+ return sorted(p for p in folder.iterdir() if p.is_file() and not p.is_symlink() and p.suffix.lower() == ".md"
166
+ and not p.name.startswith("."))
167
+
168
+
169
+ def changes_since(root: Path, manifest: dict, base: str | None) -> list[str] | None:
170
+ """One-line commits after `base` that touch anything outside the wiki; None when `base` is unknown."""
171
+ if not isinstance(base, str) or not re.fullmatch(r"[0-9a-f]{7,64}", base):
172
+ return None
173
+ if subprocess.run(["git", "-C", str(root), "merge-base", "--is-ancestor", base, "HEAD"],
174
+ capture_output=True).returncode:
175
+ return None
176
+ out = git(root, "log", "--format=%h %s", f"{base}..HEAD", "--", ".", f":(exclude){manifest['wiki']}",
177
+ check=False)
178
+ return [line for line in out.splitlines() if line]
179
+
180
+
181
+ def stale(root: Path, manifest: dict) -> bool | None:
182
+ commit = read_state(root, manifest).get("commit")
183
+ if not isinstance(commit, str) or not git(root, "rev-parse", "HEAD", check=False):
184
+ return None
185
+ changes = changes_since(root, manifest, commit)
186
+ return None if changes is None else bool(changes)
187
+
188
+
189
+ def common_git_dir(root: Path) -> Path:
190
+ return Path(git(root, "rev-parse", "--path-format=absolute", "--git-common-dir"))
191
+
192
+
193
+ def hooks_dir(root: Path) -> Path:
194
+ return Path(git(root, "rev-parse", "--path-format=absolute", "--git-path", "hooks"))
195
+
196
+
197
+ # ---------------------------------------------------------------- init / toggle
198
+
199
+ def cmd_init(args) -> int:
200
+ root = project_root(args.project, create=True)
201
+ if args.type not in TEMPLATES:
202
+ raise PortalError("--type must be game or app")
203
+ wiki = args.wiki or "docs/wiki"
204
+ sounds = [s.strip() for s in (args.sounds or "").split(",") if s.strip()]
205
+ if not relative_ok(wiki) or not all(relative_ok(s) for s in sounds):
206
+ raise PortalError("--wiki and --sounds must be relative paths inside the project")
207
+ if args.run and ("\n" in args.run or "\r" in args.run or len(args.run) > 500):
208
+ raise PortalError("--run must be one line")
209
+ created = []
210
+ manifest_path = root / MANIFEST
211
+ if not manifest_path.exists():
212
+ data = {"version": 1, "type": args.type}
213
+ if args.title:
214
+ data["title"] = args.title
215
+ data.update({"wiki": wiki, "sounds": sounds})
216
+ if args.run:
217
+ data["run"] = args.run
218
+ data.update({"autoUpdate": True, "model": DEFAULT_MODEL, "effort": "medium"})
219
+ write_json(manifest_path, data)
220
+ created.append(str(MANIFEST))
221
+ manifest = require_manifest(root)
222
+ folder = root / manifest["wiki"]
223
+ folder.mkdir(parents=True, exist_ok=True)
224
+ for slug, title, hint in TEMPLATES[manifest["type"]]:
225
+ page = folder / f"{slug}.md"
226
+ if not page.exists():
227
+ page.write_text(f"# {title}\n\n_To fill: {hint}_\n", encoding="utf-8")
228
+ created.append(str(page.relative_to(root)))
229
+ print("\n".join(created) if created else "Nothing to create; the portal files already exist.")
230
+ return 0
231
+
232
+
233
+ def set_auto_update(root: Path, value: bool) -> None:
234
+ raw = read_manifest_raw(root)
235
+ if raw is None:
236
+ raise PortalError(f"No {MANIFEST} in {root}")
237
+ raw["autoUpdate"] = value
238
+ write_json(root / MANIFEST, raw)
239
+
240
+
241
+ def cmd_enable(args) -> int:
242
+ set_auto_update(project_root(args.project), True)
243
+ print("Wiki auto-update enabled")
244
+ return 0
245
+
246
+
247
+ def cmd_disable(args) -> int:
248
+ set_auto_update(project_root(args.project), False)
249
+ print("Wiki auto-update disabled")
250
+ return 0
251
+
252
+
253
+ # ---------------------------------------------------------------- hooks
254
+
255
+ def shell_quote(value: str) -> str:
256
+ return "'" + value.replace("'", "'\\''") + "'"
257
+
258
+
259
+ def hook_line(root: Path) -> str:
260
+ script = shell_quote(os.path.abspath(__file__))
261
+ return (f"[ -f {script} ] && python3 {script} update --project {shell_quote(str(root))} "
262
+ f"--hook --background >/dev/null 2>&1 || true")
263
+
264
+
265
+ def markers(root: Path) -> tuple[str, str]:
266
+ root = root.resolve()
267
+ return f"{HOOK_BEGIN} {root} >>>", f"{HOOK_END} {root} <<<"
268
+
269
+
270
+ def hook_block(root: Path) -> str:
271
+ begin, end = markers(root)
272
+ return (f"{begin}\n"
273
+ f"# Updates the wiki in the background after commits and merges on main (portal.py; see SKILL.md).\n"
274
+ f"{hook_line(root)}\n"
275
+ f"{end}\n")
276
+
277
+
278
+ def strip_block(text: str, root: Path) -> str:
279
+ begin, end = markers(root)
280
+ return re.sub(rf"\n?{re.escape(begin)}\n.*?{re.escape(end)}\n?", "\n", text, flags=re.S).rstrip("\n") \
281
+ + ("\n" if text.strip() else "")
282
+
283
+
284
+ def cmd_hook(args) -> int:
285
+ root = project_root(args.project)
286
+ folder = hooks_dir(root)
287
+ if args.action == "install" and not args.force:
288
+ managed = git(root, "config", "--get", "core.hooksPath", check=False)
289
+ if managed:
290
+ raise PortalError(f"core.hooksPath is set to {managed} (a hook manager); add this line to its "
291
+ f"post-commit and post-merge hooks instead, or pass --force:\n{hook_line(root)}")
292
+ for name in HOOKS:
293
+ path = folder / name
294
+ first = path.read_text(encoding="utf-8").split("\n", 1)[0] if path.is_file() else ""
295
+ if first.startswith("#!") and not re.search(r"\b(sh|bash|zsh|dash)\b", first):
296
+ raise PortalError(f"{path} is not a shell script ({first}); call this from it instead, or pass "
297
+ f"--force:\n{hook_line(root)}")
298
+ folder.mkdir(parents=True, exist_ok=True)
299
+ for name in HOOKS:
300
+ path = folder / name
301
+ text = path.read_text(encoding="utf-8") if path.exists() else ""
302
+ mine = markers(root)[0] in text
303
+ base = strip_block(text, root) if mine else text
304
+ if args.action == "install":
305
+ if not base.strip():
306
+ base = "#!/bin/sh\n"
307
+ path.write_text(base.rstrip("\n") + "\n" + hook_block(root), encoding="utf-8")
308
+ path.chmod(path.stat().st_mode | 0o111)
309
+ elif mine:
310
+ if base.strip() in ("", "#!/bin/sh"):
311
+ path.unlink()
312
+ else:
313
+ path.write_text(base, encoding="utf-8")
314
+ print(f"Hooks {'installed' if args.action == 'install' else 'removed'} in {folder}")
315
+ return 0
316
+
317
+
318
+ def hook_installed(root: Path) -> bool:
319
+ try:
320
+ folder = hooks_dir(root)
321
+ except PortalError:
322
+ return False
323
+ begin = markers(root)[0]
324
+ return any((folder / n).is_file() and begin in (folder / n).read_text(encoding="utf-8") for n in HOOKS)
325
+
326
+
327
+ # ---------------------------------------------------------------- update
328
+
329
+ def build_prompt(root: Path, manifest: dict, full: bool = False) -> str:
330
+ wiki = manifest["wiki"]
331
+ pages = [f"{wiki}/{p.name}" for p in wiki_pages(root, manifest)]
332
+ state = read_state(root, manifest)
333
+ changes = None if full else changes_since(root, manifest, state.get("commit"))
334
+ sections = "\n".join(f"- {slug}.md: {title} ({hint})" for slug, title, hint in TEMPLATES[manifest["type"]])
335
+ if changes is None:
336
+ scope = ("This is the first update (or the previous one is unknown): read the README, the docs and the "
337
+ "source tree and fill every page from what the project really contains.")
338
+ else:
339
+ listed = "\n".join(changes[:200]) or "(none)"
340
+ stat = git(root, "diff", "--stat", f"{state['commit']}..HEAD", "--", ".", f":(exclude){wiki}", check=False)
341
+ stat = "\n".join(stat.splitlines()[:300])
342
+ scope = ("Update the wiki for the commits made since the last update. Read the changed files to understand "
343
+ f"them.\n\nCommits:\n{listed}\n\nChanged files:\n{stat}")
344
+ kind = "game" if manifest["type"] == "game" else "application"
345
+ return f"""You maintain the project wiki of this {kind} for the Astro Preview portal.
346
+
347
+ The current directory is a read-only snapshot of the repository at HEAD. Edit only Markdown files inside `{wiki}/`;
348
+ anything else you change is discarded. Do not create, delete or modify files outside `{wiki}/`.
349
+
350
+ Wiki pages now:
351
+ {chr(10).join(pages) or '(none)'}
352
+
353
+ Expected sections for a {kind} (one page each, keep the file names):
354
+ {sections}
355
+
356
+ {scope}
357
+
358
+ Rules:
359
+ - Write in English, concise and factual. Describe what the project contains today; never invent features.
360
+ - Keep every page under 8,000 characters; link to the project's own docs instead of copying them.
361
+ - Prefer the existing pages; add a page only when a topic clearly does not fit any of them.
362
+ - Each page starts with a `# Title` heading. Replace `_To fill: ..._` placeholders once the facts are known; leave
363
+ a page's placeholder when the project has nothing on that topic yet.
364
+ - Keep existing accurate text; update what changed; remove what is no longer true.
365
+ - Show the {kind}, do not only describe it. Embed the project's real visuals with Markdown image syntax and paths
366
+ relative to the page, one per line, for example `![Hero concept](../../art/concepts/hero.png)`; wrap a path that
367
+ contains spaces or punctuation such as ! [ ] ( ) in angle brackets: `![Key art](<../../art/key art.png>)`. Images (.png .jpg .jpeg .webp .gif) show
368
+ at full size; 3D models (.glb .gltf .blend .fbx .obj) show as preview cards. Consecutive image lines without blank
369
+ lines between them form a gallery. Give every image a short caption as its alt text.
370
+ - Use only files that exist in the repository: find them with Glob (for example `**/*.{{png,jpg,webp,glb,blend}}`)
371
+ and skip hidden, build and dependency folders (node_modules, dist, .godot, .git). Prefer final or approved art
372
+ over experiments; pick a representative set of up to about 12 per page.
373
+ - Visuals belong on Concepts & Art (concept art, key art, style references, palette), Characters & Entities (each
374
+ character, unit, enemy or item with its sprite, render or model) and Levels & World (maps, environments, tiles,
375
+ screenshots); add a screenshot to the Idea page when one exists. For an application use screenshots and diagrams.
376
+ - Do not touch `{wiki}/{STATE}`; it is written for you.
377
+ - Reply with one short line saying which pages changed.
378
+ """
379
+
380
+
381
+ def agent_command(manifest: dict, prompt: str) -> list[str]:
382
+ wiki = manifest["wiki"]
383
+ return [os.environ.get("ASTRO_CLAUDE", "claude"), "-p", prompt,
384
+ "--model", manifest["model"], "--effort", manifest["effort"],
385
+ "--no-session-persistence", "--disallowedTools", "WebFetch", "WebSearch", "Bash",
386
+ "--allowedTools", "Read", "Glob", "Grep", f"Edit({wiki}/**)"]
387
+
388
+
389
+ def lock_path(root: Path) -> Path:
390
+ """One lock per project, so projects sharing a repository update independently."""
391
+ key = hashlib.sha256(str(root.resolve()).encode()).hexdigest()[:12]
392
+ return common_git_dir(root) / f"astro-wiki-{key}.lock"
393
+
394
+
395
+ class Lock:
396
+ def __init__(self, root: Path):
397
+ self.path = lock_path(root)
398
+ self.held = False
399
+
400
+ def __enter__(self):
401
+ for _ in range(2):
402
+ try:
403
+ fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
404
+ os.write(fd, str(os.getpid()).encode())
405
+ os.close(fd)
406
+ self.held = True
407
+ return self
408
+ except FileExistsError:
409
+ try:
410
+ if time.time() - self.path.stat().st_mtime > LOCK_TTL:
411
+ self.path.unlink()
412
+ continue
413
+ except FileNotFoundError:
414
+ continue
415
+ return self
416
+ return self
417
+
418
+ def __exit__(self, *exc):
419
+ if self.held:
420
+ self.path.unlink(missing_ok=True)
421
+
422
+
423
+ def wiki_dirty(root: Path, wiki: str) -> bool:
424
+ return bool(git(root, "status", "--porcelain", "--untracked-files=all", "--", wiki, check=False))
425
+
426
+
427
+ def sync_wiki(source: Path, target: Path, tracked: set[Path], journal: list[tuple[Path, bytes | None]]) -> None:
428
+ """Copy the agent's regular files into the checkout, recording original contents in `journal` before each
429
+ change. Only files tracked at the snapshot's commit may be deleted; ignored or untracked files and anything
430
+ behind a symlink in the checkout are left alone."""
431
+
432
+ def behind_symlink(rel: Path) -> bool:
433
+ return any((target / Path(*rel.parts[:i])).is_symlink() for i in range(1, len(rel.parts) + 1))
434
+
435
+ wanted = {p.relative_to(source) for p in source.rglob("*") if p.is_file() and not p.is_symlink()
436
+ and p.name != STATE}
437
+ for rel in sorted(tracked - wanted):
438
+ path = target / rel
439
+ if path.name != STATE and not behind_symlink(rel) and path.is_file():
440
+ journal.append((path, path.read_bytes()))
441
+ path.unlink()
442
+ for rel in sorted(wanted):
443
+ if behind_symlink(rel):
444
+ continue
445
+ dest = target / rel
446
+ journal.append((dest, dest.read_bytes() if dest.is_file() else None))
447
+ dest.parent.mkdir(parents=True, exist_ok=True)
448
+ shutil.copyfile(source / rel, dest)
449
+
450
+
451
+ def roll_back(journal: list[tuple[Path, bytes | None]]) -> None:
452
+ for path, original in reversed(journal):
453
+ if original is None:
454
+ path.unlink(missing_ok=True)
455
+ else:
456
+ path.write_bytes(original)
457
+
458
+
459
+ def git_state(root: Path) -> tuple[str, str, bool]:
460
+ """Branch (empty when detached), HEAD and whether a merge or rebase is in progress."""
461
+ g = Path(git(root, "rev-parse", "--path-format=absolute", "--git-dir"))
462
+ busy = (g / "rebase-merge").exists() or (g / "rebase-apply").exists() or (g / "MERGE_HEAD").exists()
463
+ return git(root, "symbolic-ref", "--quiet", "--short", "HEAD", check=False), git(root, "rev-parse", "HEAD"), busy
464
+
465
+
466
+ def ensure_unchanged(root: Path, wiki: str, branch: str, head: str) -> None:
467
+ """The checkout may have moved on while the agent worked; never overwrite or misplace someone's work."""
468
+ now_branch, now_head, busy = git_state(root)
469
+ if busy:
470
+ raise PortalError("a merge or rebase started during the update; nothing was written")
471
+ if now_branch != branch or (not branch and now_head != head):
472
+ raise PortalError("the branch changed during the update; nothing was written")
473
+ if subprocess.run(["git", "-C", str(root), "diff", "--quiet", head, "HEAD", "--", wiki]).returncode:
474
+ raise PortalError(f"{wiki} was committed during the update; nothing was written")
475
+ if wiki_dirty(root, wiki):
476
+ raise PortalError(f"{wiki} changed during the update; nothing was written")
477
+
478
+
479
+ def hook_allowed(root: Path, manifest: dict | None) -> str | None:
480
+ """Why the hook must not run now, or None."""
481
+ if os.environ.get("ASTRO_WIKI_HOOK") or os.environ.get("ROADMAP_HOOK"):
482
+ return "nested hook call"
483
+ if manifest is None or not manifest["autoUpdate"]:
484
+ return "auto-update is off"
485
+ gd = git(root, "rev-parse", "--path-format=absolute", "--git-dir", check=False)
486
+ if not gd or gd != str(common_git_dir(root)):
487
+ return "not the main checkout"
488
+ if git(root, "symbolic-ref", "--quiet", "--short", "HEAD", check=False) not in ("main", "master"):
489
+ return "not on main"
490
+ g = Path(gd)
491
+ if (g / "rebase-merge").exists() or (g / "rebase-apply").exists() or (g / "MERGE_HEAD").exists():
492
+ return "rebase or merge in progress"
493
+ return None
494
+
495
+
496
+ def update_once(root: Path, manifest: dict, commit: bool, full: bool = False) -> bool:
497
+ """Runs one update; returns True when the wiki was rewritten."""
498
+ wiki = manifest["wiki"]
499
+ branch, head, _ = git_state(root)
500
+ state = read_state(root, manifest)
501
+ changes = changes_since(root, manifest, state.get("commit"))
502
+ if changes == [] and not full:
503
+ print("Wiki is up to date")
504
+ return False
505
+ if wiki_dirty(root, wiki):
506
+ raise PortalError(f"{wiki} has uncommitted changes; commit or discard them before updating the wiki")
507
+ prompt = build_prompt(root, manifest, full)
508
+ prefix = git(root, "rev-parse", "--show-prefix", check=False)
509
+ snapshot = Path(tempfile.mkdtemp(prefix="astro-wiki-"))
510
+ worktree = snapshot / "repo"
511
+ quiet = {"GIT_LFS_SKIP_SMUDGE": "1"}
512
+ try:
513
+ # No LFS downloads and no project checkout hooks for the throw-away snapshot.
514
+ git(root, "-c", "core.hooksPath=/dev/null", "worktree", "add", "--detach", "-q", str(worktree), head,
515
+ env=quiet)
516
+ project = worktree / prefix
517
+ result = subprocess.run(agent_command(manifest, prompt), cwd=project, capture_output=True, text=True,
518
+ stdin=subprocess.DEVNULL,
519
+ timeout=AGENT_TIMEOUT, env={**os.environ, "ASTRO_WIKI_HOOK": "1"})
520
+ if result.returncode:
521
+ raise PortalError(f"Wiki agent failed ({result.returncode}): "
522
+ f"{result.stdout[-1500:].strip()}\n{result.stderr[-1500:].strip()}")
523
+ print(result.stdout.strip()[-1000:])
524
+ tracked = {Path(p).relative_to(wiki) for p in git(root, "ls-tree", "-r", "--name-only", head, "--", wiki,
525
+ check=False).splitlines() if p}
526
+ ensure_unchanged(root, wiki, branch, head)
527
+ state_path = root / wiki / STATE
528
+ journal: list[tuple[Path, bytes | None]] = []
529
+ try:
530
+ sync_wiki(project / wiki, root / wiki, tracked, journal)
531
+ journal.append((state_path, state_path.read_bytes() if state_path.is_file() else None))
532
+ write_json(state_path, {"commit": head,
533
+ "updatedAt": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
534
+ "model": manifest["model"], "effort": manifest["effort"]})
535
+ if commit:
536
+ env = {"ASTRO_WIKI_HOOK": "1"}
537
+ git(root, "add", "--all", "--", wiki, env=env)
538
+ if subprocess.run(["git", "-C", str(root), "diff", "--cached", "--quiet", "HEAD", "--",
539
+ wiki]).returncode:
540
+ git(root, "commit", "--no-verify", "-q", "-m", f"Wiki: update for {head[:7]}", "--", wiki,
541
+ env=env)
542
+ print(f"Committed the wiki update for {head[:7]}")
543
+ except BaseException:
544
+ # Put back exactly what this run wrote so the next run is not blocked by half-written files.
545
+ roll_back(journal)
546
+ if commit:
547
+ git(root, "reset", "-q", "--", wiki, check=False)
548
+ raise
549
+ finally:
550
+ git(root, "worktree", "remove", "--force", str(worktree), check=False)
551
+ shutil.rmtree(snapshot, ignore_errors=True)
552
+ return True
553
+
554
+
555
+ def cmd_update(args) -> int:
556
+ root = project_root(args.project)
557
+ if args.hook:
558
+ try:
559
+ manifest = load_manifest(root)
560
+ except PortalError:
561
+ return 0
562
+ reason = hook_allowed(root, manifest)
563
+ if reason:
564
+ return 0
565
+ if changes_since(root, manifest, read_state(root, manifest).get("commit")) == []:
566
+ return 0
567
+ if args.background:
568
+ log = common_git_dir(root) / "astro-wiki.log"
569
+ with open(log, "a", encoding="utf-8") as out:
570
+ out.write(f"--- {dt.datetime.now().isoformat(timespec='seconds')} update\n")
571
+ out.flush()
572
+ subprocess.Popen([sys.executable, os.path.abspath(__file__), "update", "--hook",
573
+ "--project", str(root)], cwd=root, stdin=subprocess.DEVNULL, stdout=out,
574
+ stderr=subprocess.STDOUT, start_new_session=True)
575
+ return 0
576
+ else:
577
+ manifest = require_manifest(root)
578
+ with Lock(root) as lock:
579
+ if not lock.held:
580
+ print("Another wiki update is running")
581
+ return 0
582
+ # Commits made while the agent worked are picked up by another round.
583
+ for round_ in range(3):
584
+ if args.hook and hook_allowed(root, load_manifest(root)):
585
+ return 0
586
+ # Only the first round rebuilds everything; later rounds catch commits made meanwhile.
587
+ if not update_once(root, manifest, commit=not args.no_commit, full=args.full and round_ == 0):
588
+ break
589
+ if args.no_commit:
590
+ break
591
+ return 0
592
+
593
+
594
+ # ---------------------------------------------------------------- status / register
595
+
596
+ def cmd_status(args) -> int:
597
+ root = project_root(args.project)
598
+ manifest = load_manifest(root)
599
+ data = {"root": str(root), "manifest": manifest, "hook": hook_installed(root),
600
+ "pages": [p.name for p in wiki_pages(root, manifest)] if manifest else [],
601
+ "stale": stale(root, manifest) if manifest else None,
602
+ "state": read_state(root, manifest) if manifest else {}}
603
+ if args.json:
604
+ print(json.dumps(data, indent=2))
605
+ else:
606
+ print(f"Project: {root}")
607
+ if not manifest:
608
+ print(f"No {MANIFEST}")
609
+ return 0
610
+ print(f"Type: {manifest['type']}; wiki: {manifest['wiki']} ({len(data['pages'])} pages)")
611
+ print(f"Auto-update: {'on' if manifest['autoUpdate'] else 'off'}; hook: "
612
+ f"{'installed' if data['hook'] else 'not installed'}; model: {manifest['model']} ({manifest['effort']})")
613
+ print(f"Stale: {data['stale']}")
614
+ return 0
615
+
616
+
617
+ def astro_root(explicit: str | None) -> Path:
618
+ """The Astro Preview checkout: --astro-dir, then $ASTRO_PREVIEW_DIR, then the checkout this skill lives in."""
619
+ value = explicit or os.environ.get("ASTRO_PREVIEW_DIR")
620
+ if value:
621
+ return Path(value).expanduser().resolve()
622
+ inside = SKILL_DIR.parents[2]
623
+ if (inside / "bin" / "viewer.mjs").is_file():
624
+ return inside
625
+ raise PortalError("Astro Preview checkout unknown; pass --astro-dir or set ASTRO_PREVIEW_DIR")
626
+
627
+
628
+ def cmd_register(args) -> int:
629
+ root = project_root(args.project)
630
+ name = args.name or (load_manifest(root) or {}).get("title") or root.name
631
+ cli = astro_root(args.astro_dir) / "bin" / "viewer.mjs"
632
+ if not cli.is_file():
633
+ raise PortalError(f"Astro Preview CLI not found at {cli}; pass --astro-dir or set ASTRO_PREVIEW_DIR")
634
+ return subprocess.run(["node", str(cli), "project", "add", name, "--root", str(root), "--json"]).returncode
635
+
636
+
637
+ # ---------------------------------------------------------------- main
638
+
639
+ # Hooks run with these set relative to the checkout; they would redirect every git call made here.
640
+ HOOK_GIT_ENV = ("GIT_DIR", "GIT_INDEX_FILE", "GIT_WORK_TREE", "GIT_PREFIX", "GIT_COMMON_DIR",
641
+ "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_QUARANTINE_PATH")
642
+
643
+
644
+ def main(argv: list[str] | None = None) -> int:
645
+ for key in HOOK_GIT_ENV:
646
+ os.environ.pop(key, None)
647
+ parser = argparse.ArgumentParser(prog="portal.py", description=__doc__.splitlines()[0])
648
+ sub = parser.add_subparsers(dest="command", required=True)
649
+
650
+ def command(name, func, help_text):
651
+ p = sub.add_parser(name, help=help_text)
652
+ p.set_defaults(func=func)
653
+ p.add_argument("--project", help="project folder (default: the current git repository)")
654
+ return p
655
+
656
+ p = command("init", cmd_init, "create .astro/portal.json and wiki template pages (never overwrites)")
657
+ p.add_argument("--type", required=True)
658
+ p.add_argument("--title")
659
+ p.add_argument("--wiki")
660
+ p.add_argument("--sounds", help="comma-separated approved audio folders")
661
+ p.add_argument("--run", help="run command, executed from the project root")
662
+ command("enable", cmd_enable, "turn wiki auto-update on")
663
+ command("disable", cmd_disable, "turn wiki auto-update off")
664
+ p = command("hook", cmd_hook, "install or remove the post-commit/post-merge wiki hook")
665
+ p.add_argument("action", choices=("install", "remove"))
666
+ p.add_argument("--force", action="store_true", help="install despite core.hooksPath or a non-sh hook")
667
+ p = command("update", cmd_update, "update the wiki now with the manifest's model")
668
+ p.add_argument("--hook", action="store_true", help="hook mode: only on main in the main checkout")
669
+ p.add_argument("--background", action="store_true", help="with --hook: detach and log to .git/astro-wiki.log")
670
+ p.add_argument("--no-commit", action="store_true", help="write the pages without committing them")
671
+ p.add_argument("--full", action="store_true", help="rewrite the whole wiki from the repository, even if up to date")
672
+ p = command("status", cmd_status, "show manifest, hook and staleness")
673
+ p.add_argument("--json", action="store_true")
674
+ p = command("register", cmd_register, "register the project in Astro Preview's catalog")
675
+ p.add_argument("--name")
676
+ p.add_argument("--astro-dir", help="Astro Preview checkout (default: $ASTRO_PREVIEW_DIR)")
677
+ args = parser.parse_args(argv)
678
+ try:
679
+ return args.func(args)
680
+ except PortalError as error:
681
+ print(f"portal.py: {error}", file=sys.stderr)
682
+ return 1
683
+
684
+
685
+ if __name__ == "__main__":
686
+ sys.exit(main())