hoatv2211/GameStudio-CodexKIT / skills/studio-project-scaffold
studio-project-scaffold
VerifiedUse when running gamestudio init, status, or uninit, or bootstrapping a new or adopted game repository with AGENTS.md, HANDOFF.md, .agents/CONTRACT.md, project governance, a subsystem registry, or a per-project adapter report, plan digest, named reviewer, backup root, generated agent overlay, apply, uninstall, and .codex/config.toml preservation.
scripts/project_scaffold.py
View on GitHub# Generated by scripts/sync_skill_resources.py. Do not edit manually.
from __future__ import annotations
import argparse
import hashlib
import json
import os
import shutil
import sys
import uuid
import yaml
from pathlib import Path, PurePosixPath
from typing import Iterable
try:
from scripts.agent_overlay import plan_agent_overlay
from scripts.codegraph_adapter import CommandRunner, inspect_codegraph
from scripts.project_complexity import analyze_project_complexity
from scripts.project_profile import render_validation_matrix, render_workspace_map
from scripts.project_skill_overlay import plan_project_skill_overlay
from scripts.safe_mutation import apply_mutation, report_mutation
except ModuleNotFoundError:
from agent_overlay import plan_agent_overlay
from codegraph_adapter import CommandRunner, inspect_codegraph
from project_complexity import analyze_project_complexity
from project_profile import render_validation_matrix, render_workspace_map
from project_skill_overlay import plan_project_skill_overlay
from safe_mutation import apply_mutation, report_mutation
GENERATED_HEADER = "Generated by scripts/project_scaffold.py. Do not edit manually."
DEFAULT_EXCLUDED_DIRECTORIES = {
".agents",
".archive",
".cache",
".git",
"archive",
"bin",
"Library",
"Logs",
"node_modules",
"obj",
"Temp",
}
def _is_reparse_point(path: Path) -> bool:
try:
attributes = getattr(path.lstat(), "st_file_attributes", 0)
except OSError:
return True
return path.is_symlink() or bool(attributes & 0x400)
def _manifest_owned_path(root: Path, relative: object) -> tuple[str, Path]:
if not isinstance(relative, str) or not relative.strip():
raise ValueError("managed install manifest contains an invalid path")
normalized = relative.replace("\\", "/")
portable = PurePosixPath(normalized)
if portable.is_absolute() or any(part in {"", ".", ".."} for part in portable.parts):
raise ValueError(f"managed install manifest path escapes project root: {relative}")
target = root.joinpath(*portable.parts)
try:
target.relative_to(root)
except ValueError as error:
raise ValueError(f"managed install manifest path escapes project root: {relative}") from error
return portable.as_posix(), target
def _walk(root: Path, exclusions: Iterable[str] = ()) -> Iterable[tuple[Path, tuple[str, ...], tuple[str, ...]]]:
excluded = {name.casefold() for name in DEFAULT_EXCLUDED_DIRECTORIES}
excluded.update(name.casefold() for name in exclusions)
for current, directory_names, file_names in os.walk(root, topdown=True, followlinks=False):
current_path = Path(current)
kept: list[str] = []
for name in directory_names:
candidate = current_path / name
if name.casefold() in excluded or _is_reparse_point(candidate):
continue
kept.append(name)
directory_names[:] = kept
yield current_path, tuple(kept), tuple(file_names)
def _files(root: Path, exclusions: Iterable[str] = ()) -> Iterable[Path]:
for current, _directory_names, file_names in _walk(root, exclusions):
for name in file_names:
yield current / name
def _valid_git_marker(repository: Path) -> bool:
marker = repository / ".git"
if marker.is_dir():
return (marker / "HEAD").is_file()
if not marker.is_file():
return False
try:
first_line = marker.read_text(encoding="utf-8", errors="replace").splitlines()[0]
except (OSError, IndexError):
return False
if not first_line.casefold().startswith("gitdir:"):
return False
target_text = first_line.split(":", 1)[1].strip()
if not target_text:
return False
target = Path(target_text)
if not target.is_absolute():
target = repository / target
return target.is_dir() and (target / "HEAD").is_file()
def detect_git_roots(root: Path | str, exclusions: Iterable[str] = ()) -> list[str]:
root_path = Path(root).resolve()
git_roots: list[str] = []
excluded = {name.casefold() for name in DEFAULT_EXCLUDED_DIRECTORIES if name != ".git"}
excluded.update(name.casefold() for name in exclusions)
for current, directory_names, file_names in os.walk(root_path, topdown=True, followlinks=False):
current_path = Path(current)
if (".git" in directory_names or ".git" in file_names) and _valid_git_marker(current_path):
relative = current_path.relative_to(root_path).as_posix()
git_roots.append(relative if relative != "." else ".")
kept: list[str] = []
for name in directory_names:
candidate = current_path / name
if name == ".git" or name.casefold() in excluded or _is_reparse_point(candidate):
continue
kept.append(name)
directory_names[:] = kept
return sorted(set(git_roots))
def detect_subsystems(root: Path | str, exclusions: Iterable[str] = ()) -> set[str]:
root_path = Path(root).resolve()
subsystems: set[str] = set()
for current, directory_names, file_names in _walk(root_path, exclusions):
if "Assets" in directory_names and "ProjectSettings" in directory_names:
subsystems.add("unity")
for name in file_names:
path = current / name
suffix = path.suffix.casefold()
if suffix in {".csproj", ".sln", ".vcxproj"} or name == "CMakeLists.txt":
subsystems.add("server")
if suffix == ".lua":
subsystems.add("lua")
if name in {"pom.xml", "build.gradle", "build.gradle.kts"} or suffix == ".gradle":
subsystems.add("java")
if suffix == ".sql" or "database" in {part.casefold() for part in path.parts}:
subsystems.add("database")
return subsystems
def draft_project_profile(root: Path | str) -> dict[str, object]:
root_path = Path(root).resolve()
git_roots = detect_git_roots(root_path)
repository_paths = git_roots or ["."]
repositories: list[dict[str, object]] = []
for relative in repository_paths:
repository_root = root_path if relative == "." else root_path / relative
repository_id = "workspace" if relative == "." else relative.replace("/", "-").casefold()
subsystems = sorted(detect_subsystems(repository_root)) or ["unclassified"]
repositories.append(
{
"id": repository_id,
"path": relative,
"git_root": relative in git_roots,
"subsystems": subsystems,
"owner_skill": "studio-project-intake",
"validation": [],
}
)
return {
"schema_version": 1,
"workspace": {
"name": root_path.name,
"root_git": "." in git_roots,
"default_concurrency": min(2, max(0, len(repositories) - 1)),
},
"repositories": repositories,
"exclusions": sorted(
name
for name in DEFAULT_EXCLUDED_DIRECTORIES
if name not in {".agents", ".git"}
),
"agents": {"specialists": []},
"cross_project_contracts": [],
"studio_experience": {
"default_role": "developer",
"preferred_mode": "basic",
"enabled_intents": [
"diagnose",
"verify",
"plan-change",
"ship",
"handle-incident",
],
},
}
def _agent_entries(subsystems: list[str]) -> list[dict[str, str]]:
entries = [{"id": "orchestrator", "scope": "shared governance and integration"}]
entries.extend({"id": subsystem, "scope": f"{subsystem} subsystem"} for subsystem in subsystems)
return entries
def _profile_subsystems(profile: dict[str, object]) -> list[str]:
repositories = profile.get("repositories", [])
return sorted(
{
subsystem
for repository in repositories
for subsystem in repository.get("subsystems", [])
if subsystem != "unclassified"
}
)
def _profile_git_roots(profile: dict[str, object]) -> list[str]:
return sorted(
str(repository["path"])
for repository in profile.get("repositories", [])
if repository.get("git_root")
)
def scaffold_files(
root: Path | str,
profile: dict[str, object] | None = None,
local_skill_ids: Iterable[str] = (),
) -> dict[Path, str]:
root_path = Path(root).resolve()
profile = draft_project_profile(root_path) if profile is None else profile
subsystems = _profile_subsystems(profile)
subsystem_text = ", ".join(subsystems) if subsystems else "unclassified"
skill_root = root_path / ".agents" / "skills"
existing_local_skills = (
{
directory.name
for directory in skill_root.iterdir()
if directory.is_dir() and (directory / "SKILL.md").is_file()
}
if skill_root.exists()
else set()
)
local_skills = sorted(existing_local_skills.union(local_skill_ids))
agents = f"""<!-- {GENERATED_HEADER} -->
# Project Agent Contract
- Detected subsystems: {subsystem_text}.
- Read-only inspection is the default.
- One writer owns each file or generated output.
- Preserve external, vendor, binary, generated, and credential paths.
- Use Verified, Snapshot, Unverified, and BLOCKED evidence labels.
- For three or more similar records, files, or assets, assess a tool or batch workflow before manual processing.
- Prefer reuse or extend an existing tool; do not build a helper for a small one-off task without evidence of reuse value.
- Repeated-work tools must be deterministic, bounded, validated, safely rerunnable, and use a manifest or structured log. Mutating tools require dry-run; long pipelines require resumable progress; repeated operations require idempotent or completed-state handling.
- Quarantine recoverable item failures, repair the owning rule or converter by failure cluster, and fail fast when shared integrity is invalid.
- Automation does not expand approval: commit, service, database, Unity mutation, publish, credential, and destructive gates remain in force.
- Do not commit, publish, start services, import databases, or perform destructive cleanup without explicit approval.
"""
contract = f"""<!-- {GENERATED_HEADER} -->
# Agent Ownership Contract
The orchestrator owns shared governance and final verification. Subsystem agents own only exact declared paths. Reviewers are read-only. Generated files are changed through their source. External projects remain read-only unless separately authorized.
"""
handoff = f"""<!-- {GENERATED_HEADER} -->
# HANDOFF
## Goal
Unverified.
## Scope Ownership and Do-Not-Touch
- Snapshot: detected subsystems are {subsystem_text}.
## Files Touched
None.
## Commands and Tests
None.
## Verified
None.
## Snapshot
Initial scaffold only.
## Unverified
Runtime topology, versions, ports, schemas, and owners require project intake.
## BLOCKED
Live verification has not run.
## Next Actions
1. Run project intake.
2. Verify subsystem owners.
3. Replace snapshot assumptions with commands.
## Reactivation Prompt
Inspect this repository read-only, verify the scaffold snapshot, and create a bounded task packet.
"""
registry = {
"_generated": GENERATED_HEADER,
"schema_version": 1,
"subsystems": subsystems,
"agents": _agent_entries(subsystems),
"skills": local_skills,
}
return {
root_path / "AGENTS.md": agents,
root_path / "HANDOFF.md": handoff,
root_path / ".agents" / "CONTRACT.md": contract,
root_path / ".agents" / "project-profile.yaml": yaml.safe_dump(
profile, sort_keys=False
),
root_path / ".agents" / "references" / "workspace-map.md": render_workspace_map(profile),
root_path / ".agents" / "references" / "validation-matrix.md": render_validation_matrix(profile),
root_path / ".agents" / "registry.json": json.dumps(registry, indent=2) + "\n",
}
def _sha256_text(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def _plan_digest(mutation_report: dict[str, object]) -> str:
operations = sorted(
(
{
"path": str(item["path"]).replace("\\", "/"),
"action": item["action"],
"before_sha256": item["before_sha256"],
"after_sha256": item["after_sha256"],
}
for item in mutation_report["operations"]
),
key=lambda item: item["path"],
)
payload = {"root": mutation_report["root"], "operations": operations}
encoded = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
return hashlib.sha256(encoded).hexdigest()
def _validate_scaffold_backup(
root: Path,
backup_root: Path | str,
operations: Iterable[dict[str, str]],
) -> Path:
if not str(backup_root).strip():
raise ValueError("scaffold backup root is required for scaffold apply")
backup = Path(backup_root).resolve()
try:
backup.relative_to(root)
except ValueError as error:
raise ValueError(
"scaffold backup root must remain inside the project root"
) from error
if backup == root:
raise ValueError("scaffold backup root must be below the project root")
for operation in operations:
target = (root / operation["path"]).resolve()
if target == backup or target in backup.parents or backup in target.parents:
raise ValueError(
f"scaffold backup root overlaps scaffold output: {operation['path']}"
)
for parent in target.parents:
if parent == root:
break
if parent == backup or parent in backup.parents or backup in parent.parents:
raise ValueError(
f"scaffold backup root overlaps scaffold output: {operation['path']}"
)
return backup
def _install_manifest_content(root: Path, operations: list[dict[str, str]]) -> str:
files = [
{"path": operation["path"], "sha256": _sha256_text(operation["content"])}
for operation in sorted(operations, key=lambda item: item["path"])
if operation["path"] != ".agents/gamestudio-install.json"
]
payload = {
"_generated": GENERATED_HEADER,
"schema_version": 1,
"root": str(root.resolve()),
"files": files,
}
return json.dumps(payload, indent=2) + "\n"
def _agent_template_root() -> Path:
script_path = Path(__file__).resolve()
candidates = (
script_path.parent.parent / "templates" / "agents",
script_path.parent.parent / "skills" / "studio-project-scaffold" / "templates" / "agents",
)
for candidate in candidates:
if candidate.is_dir():
return candidate
raise FileNotFoundError("studio-project-scaffold agent templates are unavailable")
def _scaffold_operations(
root: Path,
profile: dict[str, object] | None = None,
) -> tuple[
list[dict[str, str]],
list[str],
dict[str, object],
dict[str, object],
dict[str, object],
]:
project_profile = draft_project_profile(root) if profile is None else profile
skill_plan = plan_project_skill_overlay(root, project_profile)
agent_plan = plan_agent_overlay(
root,
template_root=_agent_template_root(),
profile=project_profile,
known_skills={"studio-project-intake", *skill_plan["skill_ids"]},
project_skills=skill_plan["skills"],
)
operations: list[dict[str, str]] = [
*skill_plan["operations"],
*agent_plan["operations"],
]
preserved: list[str] = [
*skill_plan["preserved"],
*agent_plan["preserved"],
]
for path, content in scaffold_files(
root,
project_profile,
local_skill_ids=skill_plan["skill_ids"],
).items():
relative = path.relative_to(root).as_posix()
if path.exists():
preserved.append(relative)
continue
operations.append({"path": relative, "content": content})
manifest_relative = ".agents/gamestudio-install.json"
manifest_path = root / manifest_relative
existing_manifest = (
manifest_path.read_text(encoding="utf-8", errors="replace")
if manifest_path.is_file()
else ""
)
if manifest_path.exists() and GENERATED_HEADER not in existing_manifest:
preserved.append(manifest_relative)
skill_plan["collisions"].append(
{"path": manifest_relative, "kind": "unmanaged-install-manifest"}
)
else:
operations.append(
{
"path": manifest_relative,
"content": _install_manifest_content(root, operations),
}
)
operations.sort(key=lambda operation: operation["path"])
return operations, sorted(set(preserved)), project_profile, skill_plan, agent_plan
def scaffold_project(
root: Path | str,
*,
codegraph_runner: CommandRunner | None = None,
codegraph_preference: str | None = None,
) -> dict[str, object]:
root_path = Path(root).resolve()
operations, preserved, profile, skill_plan, agent_plan = _scaffold_operations(root_path)
report = report_mutation(root_path, operations)
plan_digest = _plan_digest(report)
complexity = analyze_project_complexity(
root_path,
git_roots=_profile_git_roots(profile),
subsystems=_profile_subsystems(profile),
)
codegraph = inspect_codegraph(
root_path,
runner=codegraph_runner,
preference=codegraph_preference,
)
return {
"status": "REPORT_ONLY",
"root": str(root_path),
"plan_digest": plan_digest,
"proposed": sorted(operation["path"] for operation in operations),
"preserved": preserved,
"subsystems": _profile_subsystems(profile),
"git_roots": _profile_git_roots(profile),
"complexity": complexity.to_dict(),
"codegraph": codegraph.to_dict(),
"project_skills": skill_plan,
"project_agents": agent_plan,
"collisions": sorted(
[*skill_plan["collisions"], *agent_plan["collisions"]],
key=lambda collision: collision["path"],
),
"mutation_report": report,
}
def apply_scaffold(
root: Path | str,
*,
reviewer: str,
backup_root: Path | str,
approved_plan_digest: str,
codegraph_runner: CommandRunner | None = None,
codegraph_preference: str | None = None,
) -> dict[str, object]:
if not isinstance(reviewer, str):
raise ValueError("reviewer must be a string for scaffold apply")
reviewer_value = reviewer.strip()
if not reviewer_value:
raise ValueError("reviewer is required for scaffold apply")
if not isinstance(approved_plan_digest, str):
raise ValueError("approved plan digest must be a string for scaffold apply")
approved_plan_digest_value = approved_plan_digest.strip()
if not approved_plan_digest_value:
raise ValueError("approved plan digest is required for scaffold apply")
root_path = Path(root).resolve()
operations, preserved, profile, skill_plan, agent_plan = _scaffold_operations(root_path)
mutation_report = report_mutation(root_path, operations)
plan_digest = _plan_digest(mutation_report)
if approved_plan_digest_value != plan_digest:
raise ValueError("scaffold plan changed since report; review the new plan digest")
backup_path = _validate_scaffold_backup(root_path, backup_root, operations)
manifest_path = apply_mutation(
root_path,
operations,
backup_path,
expected_operations=mutation_report["operations"],
)
complexity = analyze_project_complexity(
root_path,
git_roots=_profile_git_roots(profile),
subsystems=_profile_subsystems(profile),
)
codegraph = inspect_codegraph(
root_path,
runner=codegraph_runner,
preference=codegraph_preference,
)
restore_script = Path(__file__).resolve().with_name("safe_mutation.py")
return {
"status": "PASS",
"root": str(root_path),
"plan_digest": plan_digest,
"created": sorted(operation["path"] for operation in operations),
"preserved": preserved,
"subsystems": _profile_subsystems(profile),
"git_roots": _profile_git_roots(profile),
"complexity": complexity.to_dict(),
"codegraph": codegraph.to_dict(),
"project_skills": skill_plan,
"project_agents": agent_plan,
"collisions": sorted(
[*skill_plan["collisions"], *agent_plan["collisions"]],
key=lambda collision: collision["path"],
),
"reviewer": reviewer_value,
"manifest": str(manifest_path),
"restore_argv": [
sys.executable,
str(restore_script),
"--mode",
"restore",
"--root",
str(root_path),
"--manifest",
str(manifest_path),
],
}
def _load_install_manifest(root: Path) -> dict[str, object] | None:
path = root / ".agents" / "gamestudio-install.json"
if _is_reparse_point(path):
raise ValueError("managed install manifest is a symlink or reparse point")
if not path.is_file():
return None
data = json.loads(path.read_text(encoding="utf-8"))
if not isinstance(data, dict) or data.get("_generated") != GENERATED_HEADER:
raise ValueError("unmanaged or invalid GameStudio install manifest")
return data
def scaffold_status(root: Path | str) -> dict[str, object]:
root_path = Path(root).resolve()
manifest = _load_install_manifest(root_path)
if manifest is None:
return {"status": "NOT_INITIALIZED", "root": str(root_path), "owned": [], "drift": []}
owned: list[str] = []
drift: list[str] = []
for item in manifest.get("files", []):
relative, target = _manifest_owned_path(root_path, item.get("path"))
if not _is_reparse_point(target) and target.is_file() and hashlib.sha256(target.read_bytes()).hexdigest() == item["sha256"]:
owned.append(relative)
else:
drift.append(relative)
return {
"status": "DRIFTED" if drift else "HEALTHY",
"root": str(root_path),
"owned": sorted(owned),
"drift": sorted(drift),
}
def uninit_scaffold(
root: Path | str,
*,
apply: bool = False,
reviewer: str | None = None,
backup_root: Path | str | None = None,
) -> dict[str, object]:
root_path = Path(root).resolve()
manifest = _load_install_manifest(root_path)
if manifest is None:
return {"status": "NOT_INITIALIZED", "root": str(root_path), "removable": [], "preserved_drift": []}
removable: list[str] = []
drift: list[str] = []
for item in manifest.get("files", []):
relative, target = _manifest_owned_path(root_path, item.get("path"))
if _is_reparse_point(target):
drift.append(relative)
elif target.is_file() and hashlib.sha256(target.read_bytes()).hexdigest() == item["sha256"]:
removable.append(relative)
else:
drift.append(relative)
preview = {
"status": "REPORT_ONLY",
"root": str(root_path),
"removable": sorted(removable),
"preserved_drift": sorted(drift),
}
if not apply:
return preview
if not reviewer or not reviewer.strip() or backup_root is None:
raise ValueError("uninit apply requires reviewer and backup_root")
backup_path = Path(backup_root).resolve() / f"gamestudio-uninit-{uuid.uuid4().hex}"
if backup_path == root_path:
raise ValueError("uninit backup root must be disjoint from project root")
copied: list[tuple[Path, Path]] = []
targets = [*removable, ".agents/gamestudio-install.json"]
try:
for relative in targets:
_normalized, source = _manifest_owned_path(root_path, relative)
if _is_reparse_point(source):
raise ValueError(f"owned scaffold path is a symlink or reparse point: {relative}")
if not source.is_file():
continue
destination = backup_path / relative
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, destination)
copied.append((source, destination))
for source, _destination in copied:
source.unlink()
for relative in sorted(targets, key=lambda value: len(Path(value).parts), reverse=True):
parent = (root_path / relative).parent
while parent != root_path and parent.is_dir():
try:
parent.rmdir()
except OSError:
break
parent = parent.parent
except BaseException:
for source, destination in reversed(copied):
if destination.is_file() and not source.exists():
source.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(destination, source)
raise
return {
"status": "PARTIAL" if drift else "PASS",
"root": str(root_path),
"reviewer": reviewer.strip(),
"removed": sorted(removable),
"preserved_drift": sorted(drift),
"backup": str(backup_path),
}
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Bootstrap project-local game studio governance.")
parser.add_argument("root", nargs="?", default=".")
parser.add_argument("--apply", action="store_true")
parser.add_argument("--reviewer")
parser.add_argument("--backup-root")
parser.add_argument("--plan-digest")
args = parser.parse_args(argv)
if args.apply:
if not args.reviewer or not args.backup_root or not args.plan_digest:
parser.error("--apply requires --reviewer, --backup-root, and --plan-digest")
report = apply_scaffold(
Path(args.root),
reviewer=args.reviewer,
backup_root=Path(args.backup_root),
approved_plan_digest=args.plan_digest,
)
else:
report = scaffold_project(Path(args.root))
print(json.dumps(report, indent=2))
return 0
if __name__ == "__main__":
sys.exit(main())
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 470k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |