#!/usr/bin/env python3
PK       N]¢iŸŽW   W      __main__.pyfrom deadroom_audit.plugins.codepillar.standalone import main
raise SystemExit(main())
PK       N]               deadroom_audit/__init__.pyPK       N]Aû>YL  L     deadroom_audit/core.py"""Findings, checks and reports.

A check is a deterministic function of its input. Its result is a Finding that carries the evidence.
Report text written by a model may only explain findings (see explain.py); it never creates them.
"""
from __future__ import annotations

import json
from dataclasses import dataclass, field
from typing import Any, Dict, Iterable, List, Optional

STATUSES = ("pass", "info", "warn", "fail", "error")
SEVERITIES = ("low", "medium", "high")

# Points taken off a 100-point score per non-passing finding. An error counts as a high-severity
# failure because a check that did not run proves nothing.
PENALTY = {"fail": {"low": 5, "medium": 10, "high": 20}, "warn": {"low": 2, "medium": 4, "high": 8}}
ERROR_PENALTY = 20


@dataclass(frozen=True)
class Finding:
    check_id: str
    status: str
    severity: str
    title: str
    evidence: Dict[str, Any] = field(default_factory=dict)
    claim_key: Optional[str] = None  # the claim in claims.jsonl that this check enforces

    def __post_init__(self):
        if self.status not in STATUSES:
            raise ValueError(f"status must be one of {STATUSES}, got {self.status!r}")
        if self.severity not in SEVERITIES:
            raise ValueError(f"severity must be one of {SEVERITIES}, got {self.severity!r}")

    def to_dict(self) -> Dict[str, Any]:
        return {"check_id": self.check_id, "status": self.status, "severity": self.severity,
                "title": self.title, "evidence": self.evidence, "claim_key": self.claim_key}


class Check:
    """Subclass with an id, a title and run(ctx) returning a list of Findings."""
    id = "check"
    title = "Check"
    claim_key: Optional[str] = None

    def run(self, ctx: Any) -> List[Finding]:  # pragma: no cover - interface
        raise NotImplementedError


def run_checks(checks: Iterable[Check], ctx: Any) -> List[Finding]:
    """Run every check; a crash becomes an error finding instead of a silent pass."""
    out: List[Finding] = []
    for c in checks:
        try:
            out.extend(c.run(ctx))
        except Exception as exc:  # noqa: BLE001 - the point is to capture anything
            out.append(Finding(c.id, "error", "high", f"{c.title}: check did not complete",
                               {"exception": f"{type(exc).__name__}: {exc}"}, getattr(c, "claim_key", None)))
    return out


@dataclass
class Report:
    subject: str
    kind: str
    findings: List[Finding]
    generated_at: str
    engine_version: str = "0.1.0"
    explanation: Optional[str] = None  # model-written, gated by explain.check_explanation

    def sorted_findings(self) -> List[Finding]:
        return sorted(self.findings, key=lambda x: (x.check_id, x.status, x.title))

    def summary(self) -> Dict[str, int]:
        s = {k: 0 for k in STATUSES}
        for x in self.findings:
            s[x.status] += 1
        return s

    def score(self) -> int:
        total = 100
        for x in self.findings:
            if x.status == "error":
                total -= ERROR_PENALTY
            elif x.status in PENALTY:
                total -= PENALTY[x.status][x.severity]
        return max(0, total)

    def to_dict(self) -> Dict[str, Any]:
        return {"subject": self.subject, "kind": self.kind, "generated_at": self.generated_at,
                "engine_version": self.engine_version, "score": self.score(), "summary": self.summary(),
                "findings": [x.to_dict() for x in self.sorted_findings()],
                "explanation": self.explanation}

    def to_json(self) -> str:
        return json.dumps(self.to_dict(), indent=2, sort_keys=True, ensure_ascii=False) + "\n"
PK       N]            "   deadroom_audit/plugins/__init__.pyPK       N]            -   deadroom_audit/plugins/codepillar/__init__.pyPK       N]è³¯ÈB  B  *   deadroom_audit/plugins/codepillar/csvio.py"""Hostile-input-safe CSV reading and writing for the preflight.

Nothing here executes or evaluates cell content. Limits that are the engine's own (not Shopify's) are named
ENGINE_* and are documented as such in the README.
"""
from __future__ import annotations

import codecs
import csv
import io
import re
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Union

SHOPIFY_FILE_LIMIT = 15 * 1024 * 1024  # shopify-help: import-products page
ENGINE_MAX_FILE_BYTES = 64 * 1024 * 1024
ENGINE_MAX_FIELD_BYTES = 1024 * 1024
ENGINE_MAX_ROWS = 200_000
ENGINE_MAX_COLS = 1_000
EVIDENCE_CLIP = 200

HOSTILE_PREFIXES = ("=", "+", "-", "@", "\t", "\r")
_PLAIN_NUMBER = re.compile(r"^[+-]?\d+(\.\d+)?$")
NUMERIC_COLUMNS = frozenset({"Price", "Compare-at price", "Cost per item", "Inventory quantity",
                             "Weight value (grams)", "Image position", "Packed product length",
                             "Packed product width", "Packed product height"})
_MOJIBAKE = re.compile("Ãƒ[\x80-Â¿]|Ã¢â‚¬")
_VALID_MULTIBYTE = re.compile(rb"[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf4][\x80-\xbf]{3}")
_CTRL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")


class UnsafeExport(Exception):
    """The file is refused: it is not safe or not possible to read."""


def clip(value: Any, n: int = EVIDENCE_CLIP) -> str:
    s = _CTRL.sub("?", str(value))
    return s if len(s) <= n else s[: n - 3] + "..."


def is_hostile(value: str, column: str = "") -> bool:
    if not value or not value.startswith(HOSTILE_PREFIXES):
        return False
    return not (column in NUMERIC_COLUMNS and _PLAIN_NUMBER.match(value))


def escape_cell(value: str, column: str = "") -> str:
    """A leading apostrophe stops a spreadsheet from reading the cell as a formula. Idempotent."""
    return "'" + value if is_hostile(value, column) else value


@dataclass
class ParsedCsv:
    headers: List[str]
    rows: List[List[str]]
    lines: List[int]
    notes: Dict[str, Any] = field(default_factory=dict)


def read_file_bytes(path: Union[str, Path]) -> bytes:
    p = Path(path)
    size = p.stat().st_size
    if size > ENGINE_MAX_FILE_BYTES:
        raise UnsafeExport(f"file is {size} bytes; the engine refuses files over {ENGINE_MAX_FILE_BYTES} bytes")
    with open(p, "rb") as fh:
        data = fh.read(ENGINE_MAX_FILE_BYTES + 1)
    if len(data) > ENGINE_MAX_FILE_BYTES:
        raise UnsafeExport("file grew while being read; refused")
    return data


def decode(data: bytes) -> "tuple[str, Dict[str, Any]]":
    notes: Dict[str, Any] = {"size_bytes": len(data), "bom": False, "utf16": False, "invalid_utf8": False,
                             "mixed_encoding": False, "mojibake_cells": 0}
    if data.startswith((codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)):
        notes["utf16"] = True
        text = data.decode("utf-16", errors="replace")
        return text.lstrip("ï»¿"), notes
    if b"\x00" in data:
        raise UnsafeExport("file contains null bytes; refused")
    if data.startswith(codecs.BOM_UTF8):
        notes["bom"] = True
        data = data[len(codecs.BOM_UTF8):]
    try:
        text = data.decode("utf-8")
    except UnicodeDecodeError:
        notes["invalid_utf8"] = True
        notes["mixed_encoding"] = bool(_VALID_MULTIBYTE.search(data))
        text = data.decode("utf-8", errors="replace") if notes["mixed_encoding"] else data.decode("cp1252", errors="replace")
    notes["mojibake_cells"] = len(_MOJIBAKE.findall(text))
    notes["crlf"] = "\r\n" in text
    return text, notes


def parse_csv_text(text: str, notes: Dict[str, Any]) -> ParsedCsv:
    old = csv.field_size_limit(ENGINE_MAX_FIELD_BYTES)
    rows: List[List[str]] = []
    lines: List[int] = []
    try:
        reader = csv.reader(io.StringIO(text, newline=""), strict=True)
        for rec in reader:
            if not rec:  # a truly empty line
                notes["empty_lines"] = notes.get("empty_lines", 0) + 1
                continue
            rows.append(rec)
            lines.append(reader.line_num)
            if len(rows) > ENGINE_MAX_ROWS + 1:
                raise UnsafeExport(f"more than {ENGINE_MAX_ROWS} rows; refused")
            if len(rec) > ENGINE_MAX_COLS:
                raise UnsafeExport(f"a row has more than {ENGINE_MAX_COLS} cells; refused")
    except csv.Error as exc:
        raise UnsafeExport(f"csv could not be read: {clip(exc)}") from None
    finally:
        csv.field_size_limit(old)
    if not rows:
        raise UnsafeExport("file has no header row")
    return ParsedCsv(headers=rows[0], rows=rows[1:], lines=lines[1:], notes=notes)


def parse_bytes(data: bytes) -> ParsedCsv:
    text, notes = decode(data)
    return parse_csv_text(text, notes)


def unique_keys(headers: List[str]) -> "tuple[List[str], List[str]]":
    """Dict keys for the header cells; a repeated header gets a suffix so no data is overwritten."""
    keys, dups, seen = [], [], {}
    for h in headers:
        if h in seen:
            seen[h] += 1
            keys.append(f"{h}__dup{seen[h]}")
            dups.append(h)
        else:
            seen[h] = 0
            keys.append(h)
    return keys, dups


@dataclass
class Export:
    source: str
    headers: List[str]          # dict keys, in file order
    raw_headers: List[str]
    rows: List[Dict[str, str]]  # each row carries __id, __line, __source
    notes: Dict[str, Any]


def parse_export(data: bytes, source: str) -> Export:
    p = parse_bytes(data)
    keys, dups = unique_keys(p.headers)
    p.notes["duplicate_headers"] = dups
    ragged = []
    rows = []
    for i, (rec, line) in enumerate(zip(p.rows, p.lines), start=1):
        if len(rec) != len(keys):
            ragged.append({"line": line, "cells": len(rec), "expected": len(keys)})
        padded = (rec + [""] * len(keys))[: len(keys)]
        row = dict(zip(keys, padded))
        row["__id"] = f"r{i:06d}"
        row["__line"] = str(line)
        row["__source"] = source
        rows.append(row)
    p.notes["ragged"] = ragged
    return Export(source=source, headers=keys, raw_headers=p.headers, rows=rows, notes=p.notes)


def write_csv(headers: List[str], rows: List[Dict[str, str]]) -> str:
    buf = io.StringIO(newline="")
    w = csv.writer(buf, lineterminator="\n")
    w.writerow([escape_cell(h) for h in headers])
    for r in rows:
        w.writerow([escape_cell(r.get(h, ""), h) for h in headers])
    return buf.getvalue()
PK       N]DH/ {  {  /   deadroom_audit/plugins/codepillar/standalone.py"""Command line for the downloadable Unity scanner (unity-urp-scan.pyz). Standard library only; reads files, sends nothing."""
from __future__ import annotations

import argparse
import json
import sys

from . import unity_scan

ORDER = {"fail": 0, "error": 1, "warn": 2, "info": 3, "pass": 4}


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(prog="unity-urp-scan", description="Read a Unity project folder and list what matters for moving from the Built-In Render Pipeline to URP.")
    ap.add_argument("project", help="path to the Unity project folder (the one that contains Assets and ProjectSettings)")
    ap.add_argument("--json", default="unity-urp-scan.json", help="where to write the scan (default: ./unity-urp-scan.json)")
    a = ap.parse_args(argv)
    try:
        data = unity_scan.scan_project(a.project)
    except (OSError, ValueError) as exc:
        print(f"Could not scan {a.project}: {exc}", file=sys.stderr)
        return 2
    with open(a.json, "w", encoding="utf-8") as fh:
        json.dump(data, fh, indent=1, sort_keys=True)
        fh.write("\n")
    rep = unity_scan.scan_to_report(data)
    ver = (data.get("unity_version") or {}).get("value") or "unknown"
    print(f"Scanned {a.project} (Unity {ver}). Pipeline: {data['pipeline']['detected']}.")
    rd = data["readiness"]
    print("Readiness: " + (f"{rd['score']}/100 (a count of open items, not a prediction of conversion success)" if rd.get("applicable", True)
                           else "not applicable (the project already uses a Scriptable Render Pipeline)"))
    print("\nFindings:")
    for f in sorted(rep.findings, key=lambda x: (ORDER.get(x.status, 9), x.check_id)):
        print(f"  [{f.status}] {f.title}")
    print(f"\nWrote {a.json}. It holds settings, package names, shader counts and folder names, not the source of your scripts or shaders.")
    print("This tool does not send anything over the network; everything stays on your machine.")
    print("It is an operational check and does not promise that a conversion will succeed.")
    return 0 if rep.summary().get("fail", 0) == 0 else 1


if __name__ == "__main__":
    raise SystemExit(main())
PK       N]Íc)šy  šy  /   deadroom_audit/plugins/codepillar/unity_scan.py"""Unity Built-In to URP readiness scanner.

Reads a Unity project FOLDER as text: no editor, no code execution, no YAML loader (Unity YAML has custom tags,
so a line-based reader picks the few keys needed), symlinks are never followed, and file counts and bytes read
are capped. The result is a JSON a customer can upload instead of source. scan_to_report turns that JSON into
findings. Nothing here claims that Unity's converter will succeed.

Only file patterns and YAML keys the spec names are used. Anything the spec marks unsourced is reported with
"verified": false or listed under "unverified", never as fact.
"""
from __future__ import annotations

import json
import os
import re
import stat
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional, Tuple

from deadroom_audit import core

from .csvio import clip

SCHEMA = "deadroom-unity-scan/1"
SCANNER_VERSION = "0.1.0"
MAX_ENTRIES = 100_000            # engine limit: files and folders visited under Assets/
MAX_DEPTH = 40                   # engine limit
MAX_FILE_BYTES = 1024 * 1024     # engine limit: bytes read from any one file
MAX_TOTAL_BYTES = 256 * 1024 * 1024
META_BYTES = 4096
LIST_CAP = 50

URP_PKG = "com.unity.render-pipelines.universal"
HDRP_PKG = "com.unity.render-pipelines.high-definition"
CORE_PKG = "com.unity.render-pipelines.core"
PPV2_PKG = "com.unity.postprocessing"
PACKAGES = {URP_PKG: True, HDRP_PKG: False, CORE_PKG: False, PPV2_PKG: False}   # id -> sourced in the spec

UNSUPPORTED_LIGHTMODES = ("Always", "ForwardAdd", "PrepassBase", "PrepassFinal", "Vertex", "VertexLMRGBM", "VertexLM")
LEGACY_PREFIXES = {"Legacy Shaders/": "unity-docs", "Mobile/": "unity-docs", "Particles/": "unity-docs",
                   "Unlit/": "unverified"}
KNOWN_RISK = {"amplifyshadereditor": {
    "note": "a Unity forum thread reports Amplify Shader Editor shaders stay pink after the converter and must be re-exported from Amplify",
    "source": "unity-forum-search-snippet", "verified": False}}
UNVERIFIED = [
    "ProjectSettings/ProjectVersion.txt key m_EditorVersion is not sourced in the spec",
    "com.unity.render-pipelines.high-definition package id is not sourced in the spec",
    "com.unity.render-pipelines.core package id is not sourced in the spec",
    "com.unity.postprocessing package id is not sourced in the spec",
    "UnityCG.cginc as the Built-In include is not sourced in the spec",
    "PostProcessLayer and PostProcessVolume names as scene text are not sourced in the spec",
    "Volume framework use has no file pattern in the spec",
    "lightmapping and mixed-lighting settings have no file pattern or YAML key in the spec",
    "fixed-function ShaderLab (SetTexture, Material blocks) in URP has no stated rule in the spec",
    "Shader Graph URP target is not readable from the documented sources",
    "which top-level Assets folders are third party cannot be told from folder names alone",
    "the active quality level is not read; per-level pipeline assets are listed instead",
    "m_RenderPipelineGlobalSettingsMap in newer GraphicsSettings files is unverified",
]

NOTE_TRUNC = "scan incomplete: a cap was reached, so counts are lower bounds"


class NotUnityProject(Exception):
    pass


# ---- safe file access ---------------------------------------------------------------------------------------

class _Reader:
    def __init__(self, root: str, max_file: int, max_total: int):
        self.root, self.max_file, self.max_total = root, max_file, max_total
        self.lim = {"entries_visited": 0, "symlinks_skipped": 0, "special_skipped": 0, "binary_skipped": 0,
                    "partial_reads": 0, "unreadable": 0, "bytes_read": 0, "truncated": False,
                    "max_entries": MAX_ENTRIES, "max_file_bytes": max_file, "max_total_bytes": max_total}
        self.notes: List[str] = []

    def read(self, path: str, cap: Optional[int] = None, count_partial: bool = True) -> Optional[str]:
        cap = self.max_file if cap is None else min(cap, self.max_file)
        if self.lim["bytes_read"] >= self.max_total:
            self.lim["truncated"] = True
            return None
        try:
            fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
        except OSError:
            self.lim["unreadable"] += 1
            return None
        try:
            st = os.fstat(fd)
            if not stat.S_ISREG(st.st_mode):
                self.lim["special_skipped"] += 1
                return None
            data = os.read(fd, cap + 1)
            while len(data) < cap + 1:
                more = os.read(fd, cap + 1 - len(data))
                if not more:
                    break
                data += more
        except OSError:
            self.lim["unreadable"] += 1
            return None
        finally:
            os.close(fd)
        if len(data) > cap:
            data = data[:cap]
            if count_partial:
                self.lim["partial_reads"] += 1
        self.lim["bytes_read"] += len(data)
        if self.lim["bytes_read"] > self.max_total:
            self.lim["truncated"] = True
        if b"\x00" in data[:8192]:
            self.lim["binary_skipped"] += 1
            return None
        return data.decode("utf-8", errors="replace")

    def read_rel(self, rel: str, cap: Optional[int] = None) -> Optional[str]:
        """Read a fixed project file, refusing it when any path component is a symlink."""
        p = self.root
        for part in rel.split("/"):
            p = os.path.join(p, part)
            try:
                st = os.lstat(p)
            except OSError:
                return None
            if stat.S_ISLNK(st.st_mode):
                self.lim["symlinks_skipped"] += 1
                self.notes.append(f"{rel}: path contains a symlink; not read")
                return None
        return self.read(p, cap)


# ---- tolerant Unity YAML reading -----------------------------------------------------------------------------

_REF_BODY = re.compile(r"\{([^}]*)\}")
_GUID = re.compile(r"guid:\s*([0-9a-fA-F]{32})")
_FILEID = re.compile(r"fileID:\s*(-?\d+)")


MAX_WRAP_LINES = 3  # Unity wraps a long {fileID, guid, type} mapping onto at most a couple of continuation lines


def join_wrapped(lines: List[str], i: int, value: str) -> str:
    """Unity wraps long flow mappings across lines; join continuation lines until the closing brace.

    Bounded by MAX_WRAP_LINES so a malformed file cannot make us swallow the rest of it."""
    v = value.strip()
    if not v.startswith("{") or "}" in v:
        return v
    for extra in lines[i + 1:i + 1 + MAX_WRAP_LINES]:
        v += " " + extra.strip()
        if "}" in extra:
            break
    return v


def parse_ref(line_value: str) -> Dict[str, Any]:
    m = _REF_BODY.search(line_value)
    body = m.group(1) if m else (line_value.split("{", 1)[1] if "{" in line_value else "")  # unterminated: use what is there
    fid, g = _FILEID.search(body), _GUID.search(body)
    guid = g.group(1).lower() if g else None
    fileid = fid.group(1) if fid else "0"
    return {"assigned": (fileid != "0") or (guid is not None and guid != "0" * 32), "file_id": fileid, "guid": guid}


def parse_graphics(text: Optional[str]) -> Dict[str, Any]:
    if text is not None:
        lines = text.splitlines()
        for i, line in enumerate(lines):
            m = re.match(r"^\s*m_CustomRenderPipeline:\s*(.*)$", line)
            if m:
                return {**parse_ref(join_wrapped(lines, i, m.group(1))), "found_key": True}
    return {"assigned": False, "file_id": "0", "guid": None, "found_key": False}


def parse_quality(text: Optional[str]) -> List[Dict[str, Any]]:
    levels: List[Dict[str, Any]] = []
    cur: Optional[Dict[str, Any]] = None
    all_lines = (text or "").splitlines()
    for idx, line in enumerate(all_lines):
        if re.match(r"^\s*-\s*serializedVersion:", line):
            cur = {"name": None, "assigned": False, "guid": None}
            levels.append(cur)
            continue
        if cur is None:
            continue
        m = re.match(r"^\s+name:\s*(.*)$", line)
        if m and cur["name"] is None:
            cur["name"] = clip(m.group(1).strip(), 100)
            continue
        m = re.match(r"^\s+customRenderPipeline:\s*(.*)$", line)
        if m:
            ref = parse_ref(join_wrapped(all_lines, idx, m.group(1)))
            cur["assigned"], cur["guid"] = ref["assigned"], ref["guid"]
    return levels[:LIST_CAP]


def top_level_keys(text: str) -> List[str]:
    keys, indent = [], None
    in_doc = False
    for line in text.splitlines():
        if line.startswith("--- "):
            if in_doc:
                break
            in_doc = True
            continue
        if not in_doc:
            continue
        m = re.match(r"^(\s+)([A-Za-z_][\w]*):", line)
        if m:
            if indent is None:
                indent = len(m.group(1))
            if len(m.group(1)) == indent:
                keys.append(m.group(2))
        if len(keys) >= 40:
            break
    return keys


# ---- shader classification ----------------------------------------------------------------------------------

_LIGHTMODE = re.compile(r'"LightMode"\s*=\s*"([^"]+)"')
_SHADER_NAME = re.compile(r'^\s*Shader\s+"([^"]+)"', re.M)
_FIXED_T = re.compile(r"\bfixed[1-4]?\b")


def classify_shader(text: str) -> Dict[str, Any]:
    surface = "#pragma surface" in text
    cg, hlsl = "CGPROGRAM" in text, "HLSLPROGRAM" in text
    fixed_fn = bool(re.search(r"\bSetTexture\b", text) or re.search(r"\bMaterial\s*\{", text))
    t = "surface" if surface else "cgprogram" if cg else "hlslprogram" if hlsl else "fixed_function" if fixed_fn else "other"
    nm = _SHADER_NAME.search(text)
    return {"type": t, "name": clip(nm.group(1), 100) if nm else None, "light_modes": sorted(set(_LIGHTMODE.findall(text))),
            "features": {"fixed_types": bool(_FIXED_T.search(text)),
                         "urp_render_pipeline_tag": bool(re.search(r'"RenderPipeline"\s*=\s*"UniversalPipeline"', text)),
                         "unitycg_include": "UnityCG.cginc" in text,
                         "core_hlsl_include": "render-pipelines.universal/ShaderLibrary/Core.hlsl" in text,
                         "cbuffer_unitypermaterial": "CBUFFER_START(UnityPerMaterial)" in text}}


# ---- the scan -----------------------------------------------------------------------------------------------

def scan_project(project_dir, max_entries: int = MAX_ENTRIES, max_file_bytes: int = MAX_FILE_BYTES,
                 max_total_bytes: int = MAX_TOTAL_BYTES) -> Dict[str, Any]:
    root = os.fspath(project_dir)
    try:
        if not stat.S_ISDIR(os.stat(root).st_mode):
            raise NotUnityProject("not a folder")
    except OSError:
        raise NotUnityProject("folder not found") from None
    has_settings = os.path.isfile(os.path.join(root, "ProjectSettings", "ProjectVersion.txt"))
    has_assets = os.path.isdir(os.path.join(root, "Assets"))
    if not (has_settings or has_assets):
        raise NotUnityProject("no ProjectSettings/ProjectVersion.txt or Assets folder: not a Unity project folder")
    rd = _Reader(root, max_file_bytes, max_total_bytes)

    ver = rd.read_rel("ProjectSettings/ProjectVersion.txt", 4096)
    m = re.search(r"^m_EditorVersion:\s*(\S+)", ver or "", re.M)
    version = {"value": clip(m.group(1), 64) if m else None, "source": "ProjectSettings/ProjectVersion.txt m_EditorVersion",
               "sourced": False}

    gtext = rd.read_rel("ProjectSettings/GraphicsSettings.asset")
    qtext = rd.read_rel("ProjectSettings/QualitySettings.asset")
    graphics, levels = parse_graphics(gtext), parse_quality(qtext)
    wanted = {g for g in [graphics["guid"]] + [q["guid"] for q in levels] if g}

    pkgs: Dict[str, Dict[str, Any]] = {k: {"present": False, "version": None, "sourced": s} for k, s in PACKAGES.items()}
    mtext = rd.read_rel("Packages/manifest.json")
    if mtext is not None:
        try:
            deps = json.loads(mtext).get("dependencies", {})
            if isinstance(deps, dict):
                for k in pkgs:
                    if k in deps:
                        pkgs[k].update(present=True, version=clip(deps[k], 64))
        except (ValueError, RecursionError, AttributeError):
            rd.notes.append("Packages/manifest.json could not be parsed (invalid, too deep or truncated)")
    elif has_settings:
        rd.notes.append("Packages/manifest.json was not read")

    shader_files: Dict[str, Dict[str, Any]] = {}        # rel path -> classification
    guid_to_shader: Dict[str, str] = {}
    guid_to_asset: Dict[str, str] = {}
    mat_guids: Dict[Optional[str], int] = {}
    mat_total = 0
    graph = sub = scenes = pp_mentions = 0
    top: Dict[str, Dict[str, Any]] = {}
    per_folder: Dict[str, Dict[str, int]] = {}

    assets = os.path.join(root, "Assets")
    stack: List[Tuple[str, int]] = []
    if has_assets:
        if os.path.islink(assets):
            rd.lim["symlinks_skipped"] += 1
            rd.notes.append("Assets is a symlink; not scanned")
        else:
            stack.append((assets, 0))
    stop = False
    while stack and not stop:
        d, depth = stack.pop()
        try:
            with os.scandir(d) as it:
                entries = sorted(it, key=lambda e: e.name)
        except OSError:
            rd.lim["unreadable"] += 1
            continue
        for e in reversed(entries):   # reversed so the stack pops in name order
            rd.lim["entries_visited"] += 1
            if rd.lim["entries_visited"] > max_entries:
                rd.lim["truncated"] = True
                stop = True
                break
            if e.is_symlink():
                rd.lim["symlinks_skipped"] += 1
                continue
            rel = os.path.relpath(e.path, root).replace(os.sep, "/")
            parts = rel.split("/")
            folder = clip(parts[1], 100) if len(parts) > 2 else "(root)"
            if e.is_dir(follow_symlinks=False):
                if len(parts) == 2:
                    top.setdefault(clip(parts[1], 100), {"name": clip(parts[1], 100), "shaders": 0, "custom_shaders": 0})
                if depth < MAX_DEPTH:
                    stack.append((e.path, depth + 1))
                else:
                    rd.notes.append("a folder deeper than the depth cap was not scanned")
                continue
            if not e.is_file(follow_symlinks=False):
                rd.lim["special_skipped"] += 1
                continue
            low = e.name.lower()
            if low.endswith(".shader"):
                text = rd.read(e.path)
                if text is not None:
                    shader_files[rel] = classify_shader(text)
                    pf = per_folder.setdefault(folder, {"shaders": 0, "custom_shaders": 0})
                    pf["shaders"] += 1
                    pf["custom_shaders"] += shader_files[rel]["type"] != "hlslprogram"
            elif low.endswith(".shadergraph"):
                graph += 1
            elif low.endswith(".shadersubgraph"):
                sub += 1
            elif low.endswith(".mat"):
                mat_total += 1
                text = rd.read(e.path)
                mm = re.search(r"^\s*m_Shader:\s*\{[^}]*guid:\s*([0-9a-fA-F]{32})", text or "", re.M)
                g = mm.group(1).lower() if mm else None
                mat_guids[g] = mat_guids.get(g, 0) + 1
            elif low.endswith((".shader.meta", ".shadergraph.meta", ".shadersubgraph.meta", ".asset.meta")):
                text = rd.read(e.path, META_BYTES, count_partial=False)
                mg = re.search(r"^guid:\s*([0-9a-fA-F]{32})", text or "", re.M)
                if mg:
                    g, base = mg.group(1).lower(), rel[:-5]
                    if low.endswith(".asset.meta"):
                        if g in wanted:
                            guid_to_asset[g] = base
                    else:
                        guid_to_shader[g] = base
            elif low.endswith((".unity", ".prefab")):
                scenes += low.endswith(".unity")
                text = rd.read(e.path)
                if text:
                    pp_mentions += text.count("PostProcessLayer") + text.count("PostProcessVolume")

    for name, st in per_folder.items():
        if name in top:
            top[name].update(st)
        elif name != "(root)":
            top[name] = {"name": name, **st}
    for t in top.values():
        low = t["name"].lower()
        t["known_risk"] = next((v for k, v in KNOWN_RISK.items() if low.startswith(k)), None)

    def asset_info(ref: Dict[str, Any]) -> Dict[str, Any]:
        path = guid_to_asset.get(ref["guid"]) if ref.get("guid") else None
        keys: List[str] = []
        if path:
            txt = rd.read(os.path.join(root, *path.split("/")), 256 * 1024, count_partial=False)
            keys = top_level_keys(txt) if txt else []
        return {"assigned": ref["assigned"], "guid": ref["guid"], "asset_path": path, "asset_top_level_keys": keys}

    g_info = asset_info(graphics)
    q_info = [{"name": q["name"], **{k: v for k, v in asset_info({"assigned": q["assigned"], "guid": q["guid"]}).items()
                                      if k in ("assigned", "guid", "asset_path")}} for q in levels]
    eff = [q["assigned"] or graphics["assigned"] for q in levels] or [graphics["assigned"]]
    has_urp, has_hdrp = pkgs[URP_PKG]["present"], pkgs[HDRP_PKG]["present"]
    if gtext is None and not levels:
        detected = "unknown"
    elif not any(eff):
        detected = "built-in"
    elif not all(eff):
        detected = "srp-per-quality-level"
    elif has_urp and has_hdrp:
        detected = "srp-ambiguous"
    elif has_urp:
        detected = "urp"
    elif has_hdrp:
        detected = "hdrp"
    else:
        detected = "srp-unknown"

    by_type = {"surface": 0, "cgprogram": 0, "hlslprogram": 0, "fixed_function": 0, "other": 0}
    feats = dict.fromkeys(("fixed_types", "urp_render_pipeline_tag", "unitycg_include", "core_hlsl_include",
                           "cbuffer_unitypermaterial"), 0)
    lm: Dict[str, int] = {}
    legacy = dict.fromkeys(LEGACY_PREFIXES, 0)
    for sc in shader_files.values():
        by_type[sc["type"]] += 1
        for k, v in sc["features"].items():
            feats[k] += bool(v)
        for mode in sc["light_modes"]:
            lm[clip(mode, 40)] = lm.get(clip(mode, 40), 0) + 1
        for pre in legacy:
            legacy[pre] += bool(sc["name"] and sc["name"].startswith(pre))
    bad_modes = ("ForwardBase",) + UNSUPPORTED_LIGHTMODES
    files_bad_modes = sum(1 for sc in shader_files.values() if any(x in bad_modes for x in sc["light_modes"]))

    by_shader: Dict[str, int] = {}
    unresolved = on_cg = on_graph = on_fixed = 0
    for g, n in mat_guids.items():
        path = guid_to_shader.get(g) if g else None
        if path is None:
            unresolved += n
            continue
        by_shader[path] = by_shader.get(path, 0) + n
        sc = shader_files.get(path)
        if sc is None:
            on_graph += n
        elif sc["type"] in ("cgprogram", "surface"):
            on_cg += n
        elif sc["type"] == "fixed_function":
            on_fixed += n
    top_sorted = [top[k] for k in sorted(top)][:200]

    out: Dict[str, Any] = {
        "schema": SCHEMA, "scanner_version": SCANNER_VERSION,
        "unity_version": version,
        "pipeline": {"detected": detected, "graphics_default": {**g_info, "found_key": graphics["found_key"]},
                     "quality_levels": q_info,
                     "resolution_rule": "quality level asset wins; else Graphics default; if neither is set Unity uses Built-In (Unity docs)"},
        "packages": pkgs,
        "shaders": {"total": len(shader_files), "by_type": by_type, "shader_graph": graph, "shader_subgraph": sub,
                    "shader_graph_urp_target": "unverified", "features": feats, "light_modes": dict(sorted(lm.items())[:LIST_CAP]),
                    "files_with_builtin_only_light_modes": files_bad_modes, "legacy_prefix_shaders": legacy},
        "materials": {"total": mat_total, "unresolved": unresolved, "on_custom_cg_shaders": on_cg,
                      "on_fixed_function_shaders": on_fixed, "on_shader_graph_or_other": on_graph,
                      "by_shader": dict(sorted(by_shader.items(), key=lambda kv: (-kv[1], kv[0]))[:LIST_CAP]),
                      "note": "materials whose shader guid is not an Assets shader are built-in, package or missing; they cannot be classified"},
        "post_processing": {"ppv2_package": pkgs[PPV2_PKG], "ppv2_component_mentions": pp_mentions,
                            "volume_framework_use": "unverified"},
        "lighting": {"scene_files": scenes, "lightmapping": "unverified",
                     "light_mode_source": "shader LightMode tags (Unity docs)"},
        "assets": {"top_level_folders": top_sorted,
                   "third_party_identification": "unverified: folder names only; the scan cannot tell which folders are third party"},
        "limits": rd.lim, "notes": rd.notes, "unverified": list(UNVERIFIED),
    }
    if rd.lim["truncated"]:
        rd.notes.append(NOTE_TRUNC)
    if rd.lim["partial_reads"] or rd.lim["binary_skipped"] or rd.lim["unreadable"]:
        rd.notes.append("some files were only partly read, binary or unreadable")
    applicable = out["pipeline"]["detected"] not in ("urp", "hdrp")
    out["readiness"] = {"score": scan_to_report(out).score() if applicable else None, "applicable": applicable,
                        "method": ("100 minus a penalty per warning in the report; a count of open items, not a prediction of conversion success"
                                   if applicable else "not applicable: the project already uses a Scriptable Render Pipeline, so there is no Built-In to URP conversion to score")}
    return out


# ---- report -------------------------------------------------------------------------------------------------

UNITY_DOCS = "unity-docs"
SCOPE = "Operational check only. This report does not promise a successful conversion or upgrade."
CONVERTER_HANDLES = ["Rendering Settings (creates a URP asset and a Universal Renderer asset)",
                     "Material Upgrade for materials on Unity's built-in shaders (Standard to URP/Lit, Standard Terrain to URP/Terrain/Lit, Particles/Standard Surface to URP/Particles/Lit, Mobile and Legacy Shaders to URP/Simple Lit)",
                     "Read-only Material Converter", "Animation Clip Converter (only when clips touch material or Post-Processing v2 properties)",
                     "Post-Processing Stack v2 Converter (only when the v2 package is installed)"]
CONVERTER_SKIPS = ["materials with custom shaders (Material Upgrade does not support them)",
                   "custom shaders: they need a manual rewrite or a Shader Graph rebuild",
                   "SpeedTree materials are not regenerated on reimport"]
CUSTOM_STEPS = ["change CGPROGRAM/ENDCG to HLSLPROGRAM/ENDHLSL", "replace fixed types", "include Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl",
                'add the "RenderPipeline" = "UniversalPipeline" tag', "wrap properties in CBUFFER_START(UnityPerMaterial) for the SRP Batcher",
                "rename _MainTex to _BaseMap", "use the TEXTURE2D and SAMPLER macros"]
DEPRECATION = ['"Starting the official Built-In Render Pipeline deprecation process in 6.5"',
               '"The Built-In Render Pipeline will still be available at least through Unity 6.7 LTS"',
               '"we strictly do not recommend it for any new titles"',
               '"The final removal version is not yet decided and will depend on your feedback"']


def _d(v: Any) -> Dict[str, Any]:
    return v if isinstance(v, dict) else {}


def _l(v: Any) -> List[Any]:
    return v if isinstance(v, list) else []


def _n(v: Any) -> int:
    return v if isinstance(v, int) and not isinstance(v, bool) and 0 <= v <= 10**9 else 0


def _s(v: Any, n: int = 100) -> Optional[str]:
    return clip(v, n) if isinstance(v, str) else None


def scan_to_report(scan: Dict[str, Any], now: Optional[str] = None) -> core.Report:
    """Findings from a scan JSON. The JSON is treated as untrusted input; its readiness score is ignored."""
    if not isinstance(scan, dict) or scan.get("schema") != SCHEMA:
        raise ValueError("not a deadroom-unity-scan JSON")
    P = "codepillar.unity."
    out: List[core.Finding] = []

    def add(cid, status, sev, title, **ev):
        out.append(core.Finding(P + cid, status, sev, title, {k: (clip(v) if isinstance(v, str) else v) for k, v in ev.items()}))

    pipe, pk, sh = _d(scan.get("pipeline")), _d(scan.get("packages")), _d(scan.get("shaders"))
    mat, pp, asset, lim = _d(scan.get("materials")), _d(scan.get("post_processing")), _d(scan.get("assets")), _d(scan.get("limits"))
    bt = _d(sh.get("by_type"))
    add("scope", "info", "low", SCOPE, source="engine")
    v = _s(_d(scan.get("unity_version")).get("value"), 64)
    if v:
        add("version", "info", "low", "Unity editor version read from ProjectVersion.txt", version=v, verified=False,
            note="the m_EditorVersion key is not sourced in the spec")
    else:
        add("version", "warn", "low", "Unity editor version not found", verified=False)
    det = _s(pipe.get("detected"), 40) or "unknown"
    if det == "built-in":
        add("pipeline", "warn", "medium", "Project uses the Built-In Render Pipeline", detected=det, source=UNITY_DOCS,
            unity_statements=DEPRECATION, support_note="Unity states support at least until the end of 2028 (2029 with Enterprise or Industry)",
            url="https://unity.com/topics/render-pipelines-strategy-for-2026", verified=True,
            note="statements are Unity's, quoted from its page; this scan does not verify them")
    elif det == "urp":
        add("pipeline", "pass", "low", "Project already uses a URP pipeline: no Built-In to URP conversion is needed", detected=det, source=UNITY_DOCS)
    elif det == "hdrp":
        add("pipeline", "warn", "low", "Project uses a High Definition pipeline package; this is not a Built-In to URP case",
            detected=det, verified=False, note="the HDRP package id is not sourced in the spec")
    else:
        add("pipeline", "warn", "low", "The active pipeline could not be settled from the project files", detected=det,
            verified=False, note="per-quality-level assets, an unknown package set or missing settings files")
    cg, surf, fixed, hl = (_n(bt.get(k)) for k in ("cgprogram", "surface", "fixed_function", "hlslprogram"))
    if cg + surf + fixed:
        add("shaders.custom", "warn", "medium", "Custom shaders in Assets that Unity's converter does not convert",
            cgprogram=cg, surface=surf, fixed_function=fixed, hlslprogram=hl, source=UNITY_DOCS, verified=True,
            guidance=CUSTOM_STEPS, alternative="rebuild the shader in Shader Graph")
    if surf:
        add("shaders.surface", "warn", "medium", "Surface shaders (#pragma surface) are not available in URP", count=surf,
            guidance="remove any #pragma surface directives and write the lighting code yourself", source=UNITY_DOCS,
            verified=False, note="the unavailability rule was seen only as a search snippet; the rewrite guidance is on Unity's upgrade guide")
    if fixed:
        add("shaders.fixedfunction", "warn", "low", "Fixed-function ShaderLab shaders found", count=fixed, verified=False,
            note="the spec has no stated URP rule for SetTexture or Material blocks")
    feats = _d(sh.get("features"))
    if _n(feats.get("fixed_types")):
        add("shaders.fixedtypes", "warn", "low", "Shaders using fixed types, which URP does not support", count=_n(feats.get("fixed_types")),
            source=UNITY_DOCS, verified=True)
    lmn = _n(sh.get("files_with_builtin_only_light_modes"))
    if lmn:
        add("shaders.lightmode", "warn", "medium", "Shaders with LightMode tags URP does not list", files=lmn,
            light_modes={_s(k, 40) or "?": _n(c) for k, c in list(_d(sh.get("light_modes")).items())[:50]},
            unsupported_by_docs=["Always", "ForwardAdd", "PrepassBase", "PrepassFinal", "Vertex", "VertexLMRGBM", "VertexLM"],
            note="ForwardBase is not on URP's supported list; the docs do not name it as unsupported", source=UNITY_DOCS, verified=True)
    if _n(mat.get("on_custom_cg_shaders")):
        add("materials.custom", "warn", "medium", "Materials on custom shaders: the Material Upgrade converter does not support them",
            materials=_n(mat.get("on_custom_cg_shaders")), source=UNITY_DOCS, verified=True)
    if _n(mat.get("unresolved")):
        add("materials.unresolved", "info", "low", "Materials whose shader is not an Assets shader cannot be classified",
            materials=_n(mat.get("unresolved")), total=_n(mat.get("total")), verified=False)
    ppv2 = _d(pp.get("ppv2_package"))
    if ppv2.get("present") is True or _n(pp.get("ppv2_component_mentions")):
        add("postprocessing", "warn", "medium", "Post Processing Stack v2 signals found; URP uses the Volume framework",
            package_present=ppv2.get("present") is True, component_mentions=_n(pp.get("ppv2_component_mentions")),
            verified=False, note="Unity's manual (seen as a search snippet) says URP is not compatible with the v2 package; the converter lists a v2 converter, so treat it as best effort")
    risky = [{"folder": _s(t.get("name")), "note": _s(_d(t.get("known_risk")).get("note"), 200)}
             for t in _l(asset.get("top_level_folders")) if isinstance(t, dict) and _d(t.get("known_risk"))][:20]
    if risky:
        add("thirdparty", "warn", "medium", "Third-party asset folders with a reported URP problem", folders=risky, verified=False,
            note="the report is a forum thread seen as a search snippet; no vendor source was found")
    if lim.get("truncated") is True:
        add("truncated", "warn", "medium", "Scan incomplete: a file, byte or depth cap was reached", entries_visited=_n(lim.get("entries_visited")),
            note="counts are lower bounds")
    skipped = {k: _n(lim.get(k)) for k in ("symlinks_skipped", "binary_skipped", "unreadable", "partial_reads") if _n(lim.get(k))}
    if skipped:
        add("limits", "info", "low", "Some entries were skipped or only partly read", **skipped)
    add("converter", "info", "low", "What Unity's converter handles and what it skips", handles=CONVERTER_HANDLES, skips=CONVERTER_SKIPS,
        irreversible="Unity states the conversion makes irreversible changes: commit or back up first", source=UNITY_DOCS,
        note="whether a given project converts cleanly is not predicted here")
    add("unverified", "info", "low", "Items this scan treats as unverified", items=[_s(x, 200) for x in _l(scan.get("unverified"))[:20]])
    return core.Report(subject=f"unity-{_s(_d(scan.get('unity_version')).get('value'), 30) or 'project'}", kind="unity-urp", findings=out,
                       generated_at=now or datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"))
PK       N]¢iŸŽW   W              ¤   __main__.pyPK       N]                       ¤—   deadroom_audit/__init__.pyPK       N]Aû>YL  L             ¤Ï   deadroom_audit/core.pyPK       N]            "           ¤O  deadroom_audit/plugins/__init__.pyPK       N]            -           ¤�  deadroom_audit/plugins/codepillar/__init__.pyPK       N]è³¯ÈB  B  *           ¤Ú  deadroom_audit/plugins/codepillar/csvio.pyPK       N]DH/ {  {  /           ¤d)  deadroom_audit/plugins/codepillar/standalone.pyPK       N]Íc)šy  šy  /           ¤,2  deadroom_audit/plugins/codepillar/unity_scan.pyPK      ‚  ¬    