Skip to content

hoatv2211/GameStudio-CodexKIT / skills/studio-project-scaffold

studio-project-scaffold

Verified

Use 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.

FileKindSize
SKILL.mdskill md8.5 KB
agents/openai.yamlconfig259 B
references/code-intelligence-providers.yamlconfig1.8 KB
schemas/studio-evidence-card.schema.jsonconfig3.1 KB
schemas/studio-task-packet.schema.jsonconfig4.8 KB
scripts/agent_overlay.pyscript25.0 KB
scripts/code_intelligence.pyscript62.3 KB
scripts/codegraph_adapter.pyscript18.7 KB
scripts/gamestudio_cli.pyscript8.0 KB
scripts/project_complexity.pyscript13.1 KB
scripts/project_profile.pyscript19.7 KB
scripts/project_scaffold.pyscript26.1 KB
scripts/project_skill_overlay.pyscript10.7 KB
scripts/safe_mutation.pyscript61.6 KB
scripts/studio_experience.pyscript27.3 KB
templates/agents/implementer.tomlconfig1.1 KB
templates/agents/investigator.tomlconfig918 B
templates/agents/verifier.tomlconfig1.4 KB
templates/specialists/asset-pipeline-specialist.tomlconfig1.2 KB
templates/specialists/audio-engineer.tomlconfig1.2 KB
templates/specialists/build-release-engineer.tomlconfig1.8 KB
templates/specialists/cpp-game-server.tomlconfig1.2 KB
templates/specialists/csharp-backend.tomlconfig1.1 KB
templates/specialists/game-data-engineer.tomlconfig1.2 KB
templates/specialists/game-security-engineer.tomlconfig1.2 KB
templates/specialists/game-showcase-capture-producer.tomlconfig1.6 KB
templates/specialists/golang-services.tomlconfig1.2 KB
templates/specialists/level-content-designer.tomlconfig1.2 KB
templates/specialists/liveops-sre.tomlconfig1.3 KB
templates/specialists/lua-gameplay.tomlconfig1.2 KB
templates/specialists/narrative-designer.tomlconfig1.3 KB
templates/specialists/producer.tomlconfig1.2 KB
templates/specialists/product-analyst.tomlconfig1.2 KB
templates/specialists/qa-automation.tomlconfig1.2 KB
templates/specialists/systems-game-designer.tomlconfig1.1 KB
templates/specialists/technical-artist.tomlconfig1.2 KB
templates/specialists/ui-localization-specialist.tomlconfig1.4 KB
templates/specialists/ui-motion-artist.tomlconfig1.8 KB
templates/specialists/unity-csharp-client.tomlconfig1.3 KB

scripts/codegraph_adapter.py

View on GitHub
# Generated by scripts/sync_skill_resources.py. Do not edit manually.

from __future__ import annotations

import hashlib
import hmac
import json
import subprocess
from dataclasses import asdict, dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Callable, Protocol


STATE_MARKER = "Generated by scripts/codegraph_adapter.py. Do not edit manually."
CODEGRAPH_PACKAGE = "@colbymchenry/codegraph@latest"
VALID_PREFERENCES = {"skip_once", "never_suggest"}
BROKEN_INDEX_STATES = {"broken", "error", "failed", "partial"}
STALE_INDEX_STATES = {"indexing", "stale"}


class CommandResult(Protocol):
    returncode: int
    stdout: str
    stderr: str


CommandRunner = Callable[..., CommandResult]


@dataclass(frozen=True)
class CodeGraphStatus:
    state: str
    blocking: bool
    detail: str
    version: str | None
    existing_index: bool
    index_ownership: str | None
    status_argv: tuple[str, ...]
    raw_status: dict[str, Any] | None = None

    def to_dict(self) -> dict[str, object]:
        return asdict(self)


def _default_runner(argv: list[str], *, cwd: Path) -> subprocess.CompletedProcess[str]:
    return subprocess.run(
        argv,
        cwd=cwd,
        capture_output=True,
        text=True,
        check=False,
        shell=False,
    )


def _numeric_total(value: object) -> int:
    if isinstance(value, bool):
        return 0
    if isinstance(value, (int, float)):
        return max(0, int(value))
    if isinstance(value, list):
        return len(value)
    if isinstance(value, dict):
        return sum(_numeric_total(item) for item in value.values())
    return 0


def _index_payload(payload: dict[str, Any]) -> dict[str, Any]:
    index = payload.get("index")
    return index if isinstance(index, dict) else {}


def _worktree_payload(payload: dict[str, Any]) -> dict[str, Any]:
    worktree = payload.get("worktree")
    return worktree if isinstance(worktree, dict) else {}


def inspect_codegraph(
    root: Path | str,
    *,
    runner: CommandRunner | None = None,
    preference: str | None = None,
) -> CodeGraphStatus:
    root_path = Path(root).resolve()
    existing_index = (root_path / ".codegraph").is_dir()
    ownership = "USER_OWNED" if existing_index else None
    argv = ["codegraph", "status", str(root_path), "--json", "--no-color"]

    if preference == "never_suggest":
        return CodeGraphStatus(
            state="USER_DISABLED",
            blocking=False,
            detail="CodeGraph advice disabled by project-owned preference.",
            version=None,
            existing_index=existing_index,
            index_ownership=ownership,
            status_argv=tuple(argv),
        )

    command_runner = runner or _default_runner
    try:
        completed = command_runner(argv, cwd=root_path)
    except (FileNotFoundError, OSError) as error:
        return CodeGraphStatus(
            state="UNAVAILABLE",
            blocking=False,
            detail=str(error) or "CodeGraph CLI is unavailable.",
            version=None,
            existing_index=existing_index,
            index_ownership=ownership,
            status_argv=tuple(argv),
        )
    except Exception as error:
        return CodeGraphStatus(
            state="INITIALIZED_BROKEN",
            blocking=False,
            detail=f"CodeGraph status probe failed: {error}",
            version=None,
            existing_index=existing_index,
            index_ownership=ownership,
            status_argv=tuple(argv),
        )

    if completed.returncode != 0:
        detail = (completed.stderr or completed.stdout or "CodeGraph status failed.").strip()
        return CodeGraphStatus(
            state="INITIALIZED_BROKEN",
            blocking=False,
            detail=detail,
            version=None,
            existing_index=existing_index,
            index_ownership=ownership,
            status_argv=tuple(argv),
        )

    try:
        payload = json.loads(completed.stdout)
    except (json.JSONDecodeError, TypeError) as error:
        return CodeGraphStatus(
            state="INITIALIZED_BROKEN",
            blocking=False,
            detail=f"Invalid CodeGraph status JSON: {error}",
            version=None,
            existing_index=existing_index,
            index_ownership=ownership,
            status_argv=tuple(argv),
        )
    if not isinstance(payload, dict):
        return CodeGraphStatus(
            state="INITIALIZED_BROKEN",
            blocking=False,
            detail="Invalid CodeGraph status JSON object.",
            version=None,
            existing_index=existing_index,
            index_ownership=ownership,
            status_argv=tuple(argv),
        )

    version = payload.get("version")
    version_text = str(version) if version is not None else None
    if payload.get("initialized") is not True:
        return CodeGraphStatus(
            state="AVAILABLE_NOT_INITIALIZED",
            blocking=False,
            detail="CodeGraph CLI is available but this project is not initialized.",
            version=version_text,
            existing_index=existing_index,
            index_ownership=ownership,
            status_argv=tuple(argv),
            raw_status=payload,
        )

    index = _index_payload(payload)
    worktree = _worktree_payload(payload)
    index_state = str(index.get("state", "complete")).casefold()
    if index_state in BROKEN_INDEX_STATES or bool(worktree.get("worktreeMismatch")):
        state = "INITIALIZED_BROKEN"
        detail = "CodeGraph reports a broken or mismatched index."
    else:
        pending_changes = _numeric_total(payload.get("pendingChanges"))
        pending_refs = _numeric_total(index.get("pendingRefs")) + _numeric_total(
            worktree.get("pendingRefs")
        )
        stale = (
            bool(index.get("reindexRecommended"))
            or pending_changes > 0
            or pending_refs > 0
            or index_state in STALE_INDEX_STATES
        )
        if stale:
            state = "INITIALIZED_STALE"
            detail = "CodeGraph index exists but refresh signals are present."
        else:
            state = "INITIALIZED_HEALTHY"
            detail = "CodeGraph index reports healthy."

    return CodeGraphStatus(
        state=state,
        blocking=False,
        detail=detail,
        version=version_text,
        existing_index=existing_index,
        index_ownership=ownership,
        status_argv=tuple(argv),
        raw_status=payload,
    )


def _normalized_language_tokens(
    values: object,
    *,
    require_list: bool,
) -> tuple[str, ...]:
    if require_list:
        if (
            not isinstance(values, list)
            or not values
            or any(not isinstance(item, str) or not item.strip() for item in values)
        ):
            return ()
    elif (
        isinstance(values, (str, bytes, dict))
        or not isinstance(values, (list, tuple))
        or any(not isinstance(item, str) or not item.strip() for item in values)
    ):
        raise ValueError("required_languages must contain nonblank strings")
    return tuple(dict.fromkeys(item.strip().casefold() for item in values))


def to_code_intelligence_status(
    status: CodeGraphStatus,
    *,
    repository: str,
    revision: str | None,
    worktree_identity: str | None,
    required_languages: tuple[str, ...] = (),
):
    """Map legacy status data into the shared read-only status contract."""

    try:
        from scripts.code_intelligence import (
            CodeIntelligenceStatus,
            normalize_index_state,
        )
    except ModuleNotFoundError:
        from code_intelligence import CodeIntelligenceStatus, normalize_index_state

    raw = status.raw_status if isinstance(status.raw_status, dict) else {}
    index = _index_payload(raw)
    worktree = _worktree_payload(raw)
    index_revision = index.get("revision") or raw.get("revision")
    index_worktree_identity = (
        worktree.get("identity")
        or worktree.get("digest")
        or raw.get("worktreeIdentity")
    )
    required = _normalized_language_tokens(required_languages, require_list=False)
    supported = _normalized_language_tokens(raw.get("languages"), require_list=True)
    missing = tuple(language for language in required if language not in supported)

    normalized_state = normalize_index_state(status.state)
    limitations = [status.detail]
    normalized_version = (
        status.version.strip()
        if isinstance(status.version, str) and status.version.strip()
        else None
    )
    if normalized_state == "FRESH" and normalized_version is None:
        normalized_state = "BROKEN"
        limitations.append(
            "Legacy CodeGraph fresh status lacks a resolved provider version."
        )
    elif normalized_state == "FRESH" and not status.existing_index:
        normalized_state = "NOT_INITIALIZED"
        limitations.append(
            "Legacy CodeGraph fresh status lacks the local .codegraph index artifact."
        )
    elif normalized_state == "FRESH" and (
        not isinstance(index_revision, str)
        or not isinstance(revision, str)
        or index_revision != revision
    ):
        normalized_state = "STALE_HEAD"
        limitations.append(
            "Legacy CodeGraph index revision does not match the current revision."
        )
    elif normalized_state == "FRESH" and (
        not isinstance(index_worktree_identity, str)
        or not isinstance(worktree_identity, str)
        or index_worktree_identity != worktree_identity
    ):
        normalized_state = "STALE_WORKTREE"
        limitations.append(
            "Legacy CodeGraph index worktree identity does not match the current worktree."
        )
    if normalized_state == "FRESH" and missing:
        normalized_state = "PARTIAL_LANGUAGE"
        limitations.append(
            "Legacy CodeGraph status does not prove required language coverage."
        )

    return CodeIntelligenceStatus(
        provider="codegraph",
        provider_version=normalized_version,
        repository=repository,
        revision=revision,
        worktree_identity=worktree_identity,
        index_revision=(
            str(index_revision) if index_revision is not None else None
        ),
        index_worktree_identity=(
            str(index_worktree_identity)
            if index_worktree_identity is not None
            else None
        ),
        index_state=normalized_state,
        capabilities=("status", "context", "dependency-path", "impact"),
        required_languages=required,
        supported_languages=supported,
        missing_languages=missing,
        artifact_paths=(".codegraph/",) if status.existing_index else (),
        side_effects=(),
        limitations=tuple(dict.fromkeys(limitations)),
    )


def _utc_now(now: datetime | None) -> datetime:
    value = now or datetime.now(timezone.utc)
    if value.tzinfo is None:
        raise ValueError("plan time must include a timezone")
    return value.astimezone(timezone.utc)


def _plan_digest(plan: dict[str, object]) -> str:
    unsigned = {key: value for key, value in plan.items() if key != "digest"}
    canonical = json.dumps(unsigned, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def _canonical_install_steps(
    root: Path,
    *,
    existing_index: bool,
    cli_available: bool,
) -> tuple[list[dict[str, object]], list[list[str]]]:
    """Build the only argv surface that a reviewed CodeGraph plan may execute."""
    actions: list[dict[str, object]] = []
    if not cli_available:
        actions.append(
            {
                "id": "install-cli",
                "argv": ["npm", "install", "--global", CODEGRAPH_PACKAGE],
                "owner": "CodeGraph",
            }
        )
    if not existing_index:
        actions.append(
            {
                "id": "initialize-project",
                "argv": ["codegraph", "init", str(root)],
                "owner": "CodeGraph",
            }
        )
    restore_argv: list[list[str]] = []
    if not existing_index:
        restore_argv.append(["codegraph", "uninit", str(root), "--force"])
    if not cli_available:
        restore_argv.append(["npm", "uninstall", "--global", CODEGRAPH_PACKAGE])
    return actions, restore_argv


def create_install_plan(
    root: Path | str,
    *,
    reviewer: str,
    now: datetime | None = None,
    ttl: timedelta = timedelta(minutes=30),
    cli_available: bool = False,
) -> dict[str, object]:
    if not reviewer.strip():
        raise ValueError("reviewer is required for CodeGraph install planning")
    if ttl <= timedelta(0):
        raise ValueError("CodeGraph install plan ttl must be positive")

    root_path = Path(root).resolve()
    created_at = _utc_now(now)
    existing_index = (root_path / ".codegraph").is_dir()
    actions, restore_argv = _canonical_install_steps(
        root_path,
        existing_index=existing_index,
        cli_available=cli_available,
    )

    plan: dict[str, object] = {
        "schema_version": 1,
        "kind": "CODEGRAPH_INSTALL",
        "root": str(root_path),
        "created_at": created_at.isoformat(),
        "expires_at": (created_at + ttl).isoformat(),
        "reviewer": reviewer.strip(),
        "existing_index": existing_index,
        "cli_available": bool(cli_available),
        "existing_index_ownership": "USER_OWNED" if existing_index else None,
        "actions": actions,
        "restore_argv": restore_argv,
        "apply_requires": ["reviewer", "digest", "unexpired_plan"],
    }
    plan["digest"] = _plan_digest(plan)
    return plan


def verify_install_plan(
    plan: dict[str, object],
    *,
    reviewer: str,
    digest: str,
    now: datetime | None = None,
) -> dict[str, object]:
    if plan.get("kind") != "CODEGRAPH_INSTALL":
        raise ValueError("not a CodeGraph install plan")
    try:
        root_path = Path(str(plan["root"])).resolve()
    except (KeyError, TypeError, ValueError) as error:
        raise ValueError("CodeGraph install plan root is invalid") from error
    if str(plan.get("root")) != str(root_path):
        raise ValueError("CodeGraph install plan root is not canonical")
    if not isinstance(plan.get("existing_index"), bool):
        raise ValueError("CodeGraph install plan existing_index is invalid")
    if not isinstance(plan.get("cli_available"), bool):
        raise ValueError("CodeGraph install plan cli_available is invalid")
    canonical_actions, canonical_restore = _canonical_install_steps(
        root_path,
        existing_index=plan["existing_index"],
        cli_available=plan["cli_available"],
    )
    if plan.get("actions") != canonical_actions:
        raise ValueError("CodeGraph install plan actions are not canonical")
    if plan.get("restore_argv") != canonical_restore:
        raise ValueError("CodeGraph install plan restore actions are not canonical")
    if plan.get("apply_requires") != ["reviewer", "digest", "unexpired_plan"]:
        raise ValueError("CodeGraph install plan apply gates are not canonical")
    expected_digest = _plan_digest(plan)
    if not hmac.compare_digest(str(plan.get("digest", "")), expected_digest):
        raise ValueError("CodeGraph install plan content has drifted")
    if not hmac.compare_digest(digest, expected_digest):
        raise ValueError("CodeGraph install plan digest does not match")
    if reviewer.strip() != str(plan.get("reviewer", "")):
        raise ValueError("CodeGraph install plan reviewer does not match")
    try:
        expires_at = datetime.fromisoformat(str(plan["expires_at"]))
    except (KeyError, TypeError, ValueError) as error:
        raise ValueError("CodeGraph install plan expiry is invalid") from error
    if _utc_now(now) > expires_at.astimezone(timezone.utc):
        raise ValueError("CodeGraph install plan has expired")
    return plan


def apply_install_plan(
    plan: dict[str, object],
    *,
    reviewer: str,
    digest: str,
    runner: CommandRunner | None = None,
    now: datetime | None = None,
) -> dict[str, object]:
    verified = verify_install_plan(
        plan,
        reviewer=reviewer,
        digest=digest,
        now=now,
    )
    root_path = Path(str(verified["root"])).resolve()
    canonical_actions, canonical_restore = _canonical_install_steps(
        root_path,
        existing_index=verified["existing_index"],
        cli_available=verified["cli_available"],
    )
    command_runner = runner or _default_runner
    completed_actions: list[dict[str, object]] = []
    for action in canonical_actions:
        argv = action["argv"]
        try:
            completed = command_runner(list(argv), cwd=root_path)
        except OSError as error:
            return {
                "status": "FAIL",
                "root": str(root_path),
                "completed_actions": completed_actions,
                "failed_action": action.get("id"),
                "detail": str(error),
                "restore_argv": canonical_restore,
            }
        record = {
            "id": action.get("id"),
            "argv": list(argv),
            "exit_code": completed.returncode,
            "stdout": completed.stdout,
            "stderr": completed.stderr,
        }
        completed_actions.append(record)
        if completed.returncode != 0:
            return {
                "status": "FAIL",
                "root": str(root_path),
                "completed_actions": completed_actions,
                "failed_action": action.get("id"),
                "detail": (completed.stderr or completed.stdout).strip(),
                "restore_argv": canonical_restore,
            }
    return {
        "status": "PASS",
        "root": str(root_path),
        "reviewer": reviewer.strip(),
        "plan_digest": digest,
        "completed_actions": completed_actions,
        "restore_argv": canonical_restore,
    }


def plan_codegraph_preference(root: Path | str, preference: str) -> dict[str, str]:
    if preference not in VALID_PREFERENCES:
        raise ValueError(f"unsupported CodeGraph preference: {preference}")
    root_path = Path(root).resolve()
    target = root_path / ".agents" / "gamestudio-state.json"
    state: dict[str, object] = {
        "_generated": STATE_MARKER,
        "schema_version": 1,
    }
    if target.exists():
        try:
            loaded = json.loads(target.read_text(encoding="utf-8"))
        except (OSError, json.JSONDecodeError) as error:
            raise ValueError(f"invalid owned GameStudio state: {target}") from error
        if not isinstance(loaded, dict) or loaded.get("_generated") != STATE_MARKER:
            raise ValueError(f"refusing to replace unmanaged GameStudio state: {target}")
        state.update(loaded)

    advice: dict[str, object] = {"mode": preference}
    if preference == "skip_once":
        advice["remaining_runs"] = 1
    state["codegraph_advice"] = advice
    return {
        "path": ".agents/gamestudio-state.json",
        "content": json.dumps(state, indent=2, sort_keys=True) + "\n",
    }
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: 470kUpdated Claude CodeCodexVerifiedInstall
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: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
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 availableStars: 322kUpdated Claude CodeCodexVerifiedInstall