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/agent_overlay.py
View on GitHub# Generated by scripts/sync_skill_resources.py. Do not edit manually.
from __future__ import annotations
import hashlib
import fnmatch
import json
import re
import stat
import tomllib
import unicodedata
from pathlib import Path, PurePosixPath, PureWindowsPath
from typing import Any, Iterable
try:
from scripts.project_profile import load_project_profile, validate_project_profile
except ModuleNotFoundError:
from project_profile import load_project_profile, validate_project_profile
MARKER = "Generated by scripts/generate_adapters.py. Do not edit manually."
ROLE_ID_PATTERN = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
REQUIRED_TEMPLATE_FIELDS = ("name", "description", "developer_instructions")
WINDOWS_FORBIDDEN_ROLE_CHARACTERS = set('<>:"|?*')
RESERVED_WINDOWS_BASENAMES = {
"con",
"prn",
"aux",
"nul",
"conin$",
"conout$",
*(f"com{number}" for number in range(1, 10)),
*(f"lpt{number}" for number in range(1, 10)),
}
RESERVED_NUMBERED_WINDOWS_BASENAME = re.compile(
r"^(?:com|lpt)(?:[1-9¹²³])$",
re.IGNORECASE,
)
def _validate_role_id(value: object, *, label: str) -> str:
if not isinstance(value, str) or not value:
raise ValueError(f"invalid {label} role id: {value}")
basename = value.split(".", 1)[0].rstrip(" .").casefold()
if (
"/" in value
or "\\" in value
or value.endswith((".", " "))
or any(character in WINDOWS_FORBIDDEN_ROLE_CHARACTERS for character in value)
or any(unicodedata.category(character) == "Cc" for character in value)
or basename in RESERVED_WINDOWS_BASENAMES
or RESERVED_NUMBERED_WINDOWS_BASENAME.fullmatch(basename)
or ROLE_ID_PATTERN.fullmatch(value) is None
):
raise ValueError(f"invalid {label} role id: {value}")
return value
def _has_generated_header(text: str) -> bool:
lines = text.splitlines()
return bool(lines) and lines[0] == f"# {MARKER}"
def _sha256_text(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def _is_reparse_point(path: Path) -> bool:
try:
info = path.lstat()
except FileNotFoundError:
return False
attributes = getattr(info, "st_file_attributes", 0)
reparse_flag = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
return path.is_symlink() or bool(attributes & reparse_flag)
def _safe_project_path(project: Path, relative: str) -> Path:
normalized = relative.replace("\\", "/")
pure = PurePosixPath(normalized)
windows = PureWindowsPath(relative)
parts = pure.parts
is_agent_root = parts == (".codex", "agents")
is_agent = len(parts) == 3 and parts[:2] == (".codex", "agents")
is_activation = parts == (".codex", "agents.generated.toml")
if (
pure.is_absolute()
or windows.is_absolute()
or windows.drive
or not parts
or "." in parts
or ".." in parts
or not (is_agent_root or is_agent or is_activation)
):
raise ValueError(f"unsafe agent overlay path: {relative}")
project_root = project.resolve()
candidate = project_root.joinpath(*parts)
current = project_root
if _is_reparse_point(current):
raise ValueError(f"project root is a symlink or reparse point: {current}")
for part in parts:
current = current / part
if current.exists() and _is_reparse_point(current):
raise ValueError(f"symlink or reparse point is not allowed: {current}")
owned_root = project_root / ".codex"
resolved = candidate.resolve()
try:
resolved.relative_to(owned_root.resolve())
except ValueError as error:
raise ValueError(f"agent overlay path escapes its owned scope: {relative}") from error
return candidate
def _load_generic_roles(template_root: Path) -> list[dict[str, str]]:
roles: list[dict[str, str]] = []
role_ids: set[str] = set()
for template in template_root.glob("*.toml"):
content = template.read_text(encoding="utf-8")
parsed = tomllib.loads(content)
role_id = _validate_role_id(parsed.get("name"), label="generic")
if role_id in role_ids:
raise ValueError(f"duplicate generic role id: {role_id}")
role_ids.add(role_id)
for field in REQUIRED_TEMPLATE_FIELDS:
value = parsed.get(field)
if not isinstance(value, str) or not value.strip():
raise ValueError(f"generic role {role_id} requires {field}")
roles.append(
{
"id": role_id,
"description": parsed["description"],
"content": f"# {MARKER}\n\n{content}",
}
)
return sorted(roles, key=lambda role: role["id"])
def _load_specialist_templates(template_root: Path) -> dict[str, dict[str, Any]]:
templates: dict[str, dict[str, Any]] = {}
if not template_root.is_dir():
return templates
for template_path in sorted(template_root.glob("*.toml")):
parsed = tomllib.loads(template_path.read_text(encoding="utf-8"))
role_id = _validate_role_id(parsed.get("name"), label="specialist template")
if role_id in templates:
raise ValueError(f"duplicate specialist template id: {role_id}")
for field in (
"name",
"description",
"developer_instructions",
"discipline",
"required_skills",
"owned_scope_patterns",
"read_scope_patterns",
"forbidden_actions",
"validation_commands",
"concurrency_group",
):
if field not in parsed:
raise ValueError(f"specialist template {role_id} requires {field}")
templates[role_id] = parsed
return templates
def _activation_text(roles: list[dict[str, Any]]) -> str:
lines = [f"# {MARKER}", ""]
for role in roles:
role_id = role["id"]
lines.extend(
[
f"[agents.{role_id}]",
f"description = {json.dumps(role['description'])}",
f"config_file = {json.dumps(f'./agents/{role_id}.toml')}",
"",
]
)
return "\n".join(lines)
def _unmanaged_agent_paths(
project: Path,
*,
planned_paths: set[str],
) -> list[str]:
agents_root = _safe_project_path(project, ".codex/agents")
if not agents_root.exists():
return []
preserved: list[str] = []
for candidate in sorted(agents_root.iterdir(), key=lambda path: path.name):
if _is_reparse_point(candidate) or not candidate.is_file():
continue
if candidate.suffix.casefold() != ".toml":
continue
relative = PurePosixPath(".codex", "agents", candidate.name).as_posix()
if relative in planned_paths:
continue
existing = candidate.read_text(encoding="utf-8", errors="replace")
if not _has_generated_header(existing):
preserved.append(relative)
return preserved
def _specialist_role(
specialist: dict[str, Any],
repository: dict[str, Any],
canonical: dict[str, Any] | None = None,
) -> dict[str, Any]:
role_id = str(specialist["id"])
repository_id = str(repository["id"])
repository_path = str(repository["path"])
constraints = [str(item) for item in specialist["constraints"]]
description = str(
canonical.get("description")
if canonical is not None
else f"Project specialist for {repository_id} ({repository_path})."
)
required_skills: list[str] = []
owned_scope_patterns = list(specialist.get("owned_scope_patterns", []))
read_scope_patterns = list(specialist.get("read_scope_patterns", []))
concurrency_group = specialist.get("concurrency_group")
metadata_fields: list[str] = []
if canonical is not None:
required_skills = list(canonical["required_skills"])
required_skills.extend(
str(item) for item in specialist.get("required_project_skills", [])
)
owned_scope_patterns = specialist.get(
"owned_scope_patterns", canonical["owned_scope_patterns"]
)
read_scope_patterns = specialist.get(
"read_scope_patterns", canonical["read_scope_patterns"]
)
concurrency_group = specialist.get(
"concurrency_group", canonical["concurrency_group"]
)
metadata_fields.extend(
(
f"discipline = {json.dumps(canonical['discipline'])}",
f"required_skills = {json.dumps(sorted(set(required_skills)))}",
f"forbidden_actions = {json.dumps(canonical['forbidden_actions'])}",
f"validation_commands = {json.dumps(canonical['validation_commands'])}",
)
)
if owned_scope_patterns:
metadata_fields.extend(
(
f"owned_scope_patterns = {json.dumps(owned_scope_patterns)}",
f"read_scope_patterns = {json.dumps(read_scope_patterns)}",
)
)
if concurrency_group:
metadata_fields.append(
f"concurrency_group = {json.dumps(concurrency_group)}"
)
metadata = "\n".join(metadata_fields)
canonical_instructions = (
str(canonical.get("developer_instructions", "")).strip()
if canonical is not None
else ""
)
instruction_text = "\n".join(
[
f"Own only repository {repository_id} at {repository_path} and the exact files assigned by the main thread.",
"Preserve project-profile ownership, validation, generated-file, and do-not-touch rules.",
canonical_instructions,
*constraints,
"Do not revert concurrent edits, expand into sibling repositories, or create child agents.",
"Return changed paths, commands, exit codes, artifacts, and remaining rollout risk.",
]
)
reasoning_effort = specialist["reasoning_effort"]
sandbox_mode = (
canonical.get("sandbox_mode", "workspace-write")
if canonical
else "workspace-write"
)
content = "\n".join(
[
f"# {MARKER}",
"",
f"name = {json.dumps(role_id)}",
f"description = {json.dumps(description)}",
f"model_reasoning_effort = '{reasoning_effort}'",
f"sandbox_mode = '{sandbox_mode}'",
metadata,
f"developer_instructions = {json.dumps(instruction_text)}",
"",
]
)
return {
"id": role_id,
"description": description,
"content": content,
"kind": "specialist",
"repository_id": repository_id,
"owned_scope_patterns": list(owned_scope_patterns),
"read_scope_patterns": list(read_scope_patterns),
"concurrency_group": concurrency_group,
"sandbox_mode": sandbox_mode,
}
def _scope_prefix(value: str) -> str:
normalized = value.replace("\\", "/").strip("/")
wildcard = min(
(
index
for index in (
normalized.find("*"),
normalized.find("?"),
normalized.find("["),
)
if index >= 0
),
default=len(normalized),
)
return normalized[:wildcard].rstrip("/").casefold()
def _scope_patterns_overlap(left: str, right: str) -> bool:
left_prefix = _scope_prefix(left)
right_prefix = _scope_prefix(right)
return bool(
left_prefix
and right_prefix
and (
left_prefix == right_prefix
or left_prefix.startswith(right_prefix + "/")
or right_prefix.startswith(left_prefix + "/")
)
)
def _glob_matches_path(pattern: str, path: str) -> bool:
pattern_parts = pattern.replace("\\", "/").strip("/").casefold().split("/")
path_parts = path.replace("\\", "/").strip("/").casefold().split("/")
memo: dict[tuple[int, int], bool] = {}
def matches(pattern_index: int, path_index: int) -> bool:
key = (pattern_index, path_index)
if key in memo:
return memo[key]
if pattern_index == len(pattern_parts):
result = path_index == len(path_parts)
elif pattern_parts[pattern_index] == "**":
result = matches(pattern_index + 1, path_index) or (
path_index < len(path_parts) and matches(pattern_index, path_index + 1)
)
else:
result = bool(
path_index < len(path_parts)
and fnmatch.fnmatchcase(path_parts[path_index], pattern_parts[pattern_index])
and matches(pattern_index + 1, path_index + 1)
)
memo[key] = result
return result
return matches(0, 0)
def _assignment_path(value: object) -> str:
if not isinstance(value, str) or not value.strip():
raise ValueError("agent write assignment path must be a non-empty string")
normalized = value.replace("\\", "/")
pure = PurePosixPath(normalized)
windows = PureWindowsPath(value)
if (
pure.is_absolute()
or windows.is_absolute()
or windows.drive
or "." in pure.parts
or ".." in pure.parts
or any(character in normalized for character in "*?[]")
):
raise ValueError(f"agent write assignment must be one exact relative path: {value}")
return pure.as_posix()
def review_effective_agent_scopes(
roles: Iterable[dict[str, Any]],
active_assignments: Iterable[dict[str, object]] | None = None,
) -> dict[str, object]:
resolved = sorted(
(role for role in roles if role.get("kind") == "specialist"),
key=lambda role: str(role["id"]),
)
overlaps: list[dict[str, object]] = []
for index, left in enumerate(resolved):
for right in resolved[index + 1 :]:
if left.get("repository_id") != right.get("repository_id"):
continue
pairs = sorted(
{
(left_scope, right_scope)
for left_scope in left.get("owned_scope_patterns", [])
for right_scope in right.get("owned_scope_patterns", [])
if _scope_patterns_overlap(left_scope, right_scope)
}
)
if pairs:
overlaps.append(
{
"roles": sorted([str(left["id"]), str(right["id"])]),
"repository": left["repository_id"],
"classification": "capability-overlap",
"blocks_activation": False,
"pattern_pairs": [list(pair) for pair in pairs],
}
)
report: dict[str, object] = {
"status": "PASS",
"assignment_status": "NOT_PROVIDED",
"resolved_scopes": [
{
"role_id": str(role["id"]),
"repository": role["repository_id"],
"owned_scope_patterns": list(role.get("owned_scope_patterns", [])),
"read_scope_patterns": list(role.get("read_scope_patterns", [])),
"concurrency_group": role.get("concurrency_group"),
}
for role in resolved
],
"capability_overlaps": overlaps,
"assignment_conflicts": [],
"assignments": [],
}
if active_assignments is None:
return report
assignments = list(active_assignments)
role_by_id = {str(role["id"]): role for role in resolved}
path_owners: dict[str, set[str]] = {}
normalized_assignments: list[dict[str, object]] = []
seen_role_paths: set[tuple[str, str]] = set()
for index, assignment in enumerate(assignments):
if not isinstance(assignment, dict) or set(assignment) != {
"role_id",
"write_paths",
}:
raise ValueError(f"active assignment {index} requires role_id and write_paths")
role_id = assignment.get("role_id")
paths = assignment.get("write_paths")
if not isinstance(role_id, str) or role_id not in role_by_id:
raise ValueError(
"active assignment references an unknown managed specialist: "
f"{role_id}"
)
if not isinstance(paths, list) or not paths:
raise ValueError(f"active assignment write_paths must be non-empty: {role_id}")
scopes = role_by_id[role_id].get("owned_scope_patterns", [])
if not scopes:
raise ValueError(f"active assignment has no effective owned scope: {role_id}")
normalized_paths: list[str] = []
for raw_path in paths:
path = _assignment_path(raw_path)
if not any(_glob_matches_path(scope, path) for scope in scopes):
raise ValueError(
"active assignment is outside effective owned scope: "
f"{role_id}: {path}"
)
key = (role_id, path.casefold())
if key in seen_role_paths:
raise ValueError(f"duplicate active agent write assignment: {role_id}: {path}")
seen_role_paths.add(key)
normalized_paths.append(path)
path_owners.setdefault(path.casefold(), set()).add(role_id)
normalized_assignments.append(
{"role_id": role_id, "write_paths": sorted(normalized_paths)}
)
conflicts = [
{"path": path, "roles": sorted(owners)}
for path, owners in sorted(path_owners.items())
if len(owners) > 1
]
if conflicts:
detail = "; ".join(
f"{conflict['path']}: {', '.join(conflict['roles'])}" for conflict in conflicts
)
raise ValueError(f"simultaneous agent write assignment conflict: {detail}")
report["assignment_status"] = "PASS"
report["assignments"] = sorted(
normalized_assignments, key=lambda assignment: str(assignment["role_id"])
)
return report
PROJECT_SKILL_SPECIALISTS = {
"project-unity-client": "unity-csharp-client",
"project-dotnet-server": "csharp-backend",
"project-cpp-server": "cpp-game-server",
"project-go-services": "golang-services",
"project-lua-gameplay": "lua-gameplay",
"project-data-pipeline": "game-data-engineer",
}
def _project_skill_scopes(
skill_id: str, repository_path: str
) -> tuple[list[str], list[str]]:
prefix = "**" if repository_path == "." else repository_path.rstrip("/")
owned = {
"project-unity-client": [f"{prefix}/Assets/**", f"{prefix}/ProjectSettings/**"],
"project-dotnet-server": [f"{prefix}/**/*.cs", f"{prefix}/**/*.csproj"],
"project-cpp-server": [
f"{prefix}/**/*.c",
f"{prefix}/**/*.cpp",
f"{prefix}/**/*.h",
f"{prefix}/**/*.hpp",
],
"project-go-services": [
f"{prefix}/**/*.go",
f"{prefix}/go.mod",
f"{prefix}/go.sum",
],
"project-lua-gameplay": [f"{prefix}/**/*.lua"],
"project-data-pipeline": [
f"{prefix}/**/*.sql",
f"{prefix}/**/data/**",
f"{prefix}/**/database/**",
],
}[skill_id]
return owned, [f"{prefix}/**"]
def _inferred_specialists(
project_skills: Iterable[dict[str, Any]],
repositories: dict[str, dict[str, Any]],
) -> list[dict[str, Any]]:
inferred: list[dict[str, Any]] = []
for skill in sorted(project_skills, key=lambda item: str(item.get("id", ""))):
skill_id = str(skill.get("id", ""))
template_id = PROJECT_SKILL_SPECIALISTS.get(skill_id)
if template_id is None:
continue
repository_ids = sorted(str(value) for value in skill.get("repositories", []))
for repository_id in repository_ids:
repository = repositories.get(repository_id)
if repository is None:
continue
role_id = template_id if len(repository_ids) == 1 else f"{template_id}-{repository_id}"
owned, read = _project_skill_scopes(skill_id, str(repository["path"]))
inferred.append(
{
"id": role_id,
"template_id": template_id,
"repository": repository_id,
"reasoning_effort": "high",
"constraints": [f"Route project-local decisions through {skill_id}."],
"owned_scope_patterns": owned,
"read_scope_patterns": read,
"required_project_skills": [skill_id],
"concurrency_group": f"{template_id}-{repository_id}-writer",
}
)
return inferred
def plan_agent_overlay(
project: Path | str,
*,
template_root: Path | str,
profile_path: Path | str | None = None,
profile: dict[str, Any] | None = None,
known_skills: Iterable[str] = (),
project_skills: Iterable[dict[str, Any]] = (),
active_assignments: Iterable[dict[str, object]] | None = None,
) -> dict[str, object]:
project_path = Path(project)
generic_roles = _load_generic_roles(Path(template_root))
roles: list[dict[str, Any]] = list(generic_roles)
generic_role_ids = {role["id"] for role in generic_roles}
specialist_templates = _load_specialist_templates(Path(template_root).parent / "specialists")
if profile_path is not None and profile is not None:
raise ValueError("provide profile_path or profile, not both")
active_profile = profile
if profile_path is not None and Path(profile_path).is_file():
active_profile = load_project_profile(profile_path, known_skills=known_skills)
elif active_profile is not None:
errors = validate_project_profile(active_profile, known_skills=known_skills)
if errors:
raise ValueError("; ".join(errors))
if active_profile is not None:
repositories = {
str(repository["id"]): repository for repository in active_profile["repositories"]
}
configured = list(active_profile.get("agents", {}).get("specialists", []))
configured.extend(_inferred_specialists(project_skills, repositories))
seen_specialists: set[str] = set()
for specialist in configured:
specialist_id = _validate_role_id(specialist.get("id"), label="specialist")
if specialist_id in generic_role_ids:
raise ValueError(f"specialist id collides with generic role: {specialist_id}")
if specialist_id in seen_specialists:
continue
seen_specialists.add(specialist_id)
repository = repositories[str(specialist["repository"])]
template_id = str(specialist.get("template_id", specialist_id))
roles.append(
_specialist_role(
specialist,
repository,
specialist_templates.get(template_id),
)
)
roles.sort(key=lambda role: role["id"])
operations: list[dict[str, str]] = []
planned_paths = {
PurePosixPath(".codex", "agents", f"{role['id']}.toml").as_posix()
for role in roles
}
preserved = _unmanaged_agent_paths(project_path, planned_paths=planned_paths)
collisions: list[dict[str, str]] = []
managed_roles: list[dict[str, Any]] = []
for role in roles:
relative = PurePosixPath(".codex", "agents", f"{role['id']}.toml").as_posix()
destination = _safe_project_path(project_path, relative)
existing = (
destination.read_text(encoding="utf-8", errors="replace")
if destination.exists()
else ""
)
if destination.exists() and not _has_generated_header(existing):
preserved.append(relative)
collisions.append(
{
"path": relative,
"kind": "unmanaged-agent",
"role_id": role["id"],
}
)
continue
operations.append({"path": relative, "content": role["content"]})
managed_roles.append(role)
scope_review = review_effective_agent_scopes(managed_roles, active_assignments)
activation_relative = ".codex/agents.generated.toml"
activation_destination = _safe_project_path(project_path, activation_relative)
activation_existing = (
activation_destination.read_text(encoding="utf-8", errors="replace")
if activation_destination.exists()
else ""
)
activated_roles: list[str] = []
if activation_destination.exists() and not _has_generated_header(activation_existing):
preserved.append(activation_relative)
collisions.append({"path": activation_relative, "kind": "unmanaged-activation"})
else:
operations.append(
{"path": activation_relative, "content": _activation_text(managed_roles)}
)
activated_roles = [role["id"] for role in managed_roles]
operations.sort(key=lambda operation: operation["path"])
return {
"operations": operations,
"preserved": sorted(preserved),
"collisions": sorted(collisions, key=lambda collision: collision["path"]),
"owned_files": [
{"path": operation["path"], "sha256": _sha256_text(operation["content"])}
for operation in operations
],
"activated_roles": activated_roles,
"scope_review": scope_review,
}
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 |