GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / automation/repd

Renewable Energy Planning Database (REPD) Hashguard and 1 more file

A Python command-line tool in the automation folder of GlobalGrid2050 that reads manifest (`read_manifest`), writes manifest (`write_manifest`) and lists worktree files (`list_worktree_files`), using SHA-256.

700 lines of Python from globalgrid2050, in 2 files. Topic: Electricity markets and data pipelines. Section 824 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Renewable Energy Planning Database (REPD) Fetch storage · globalgrid2050 / automation/repd/fetch.py lines 1–288
  2. Renewable Energy Planning Database (REPD) Hashguard storage · globalgrid2050 / automation/repd/hashguard.py lines 1–412

Renewable Energy Planning Database (REPD) Fetch

A Python command-line tool in the automation folder of GlobalGrid2050 that fetches fetch receipt and the REPD register, using SHA-256.

storageglobalgrid2050 / automation/repd/fetch.py · lines 1–288 of 288 · Entry point · pattern compare_hashes (shared by 2 files)

What it does
It fetches fetch receipt and the REPD register. Defines 19 functions or classes, including FetchRefused, Response, redirected, utc_now, sha256. Uses libraries __future__, argparse, hashlib, json, sys. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register.
Inputs & outputs
In: JSON file fetch_receipt.json; command-line arguments.
Downstream impact
Used directly by 3 files: Renewable Energy Planning Database (REPD) Detect (globalgrid2050); Renewable Energy Planning Database (REPD) Monthly (globalgrid2050); Test Detect Fetch (globalgrid2050). Reached from 3 other entry points, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); GlobalGrid2050 Renewable Energy Planning Database (REPD) Monthly Workflow (globalgrid2050); Test Monthly (globalgrid2050).
What it achieves
It fetches refused (`FetchRefused`), checks response (`check_response`) and hashes tree (`hash_tree`). Download a REPD release (CSV + XLSX) described by a release descriptor. It accepts `--descriptor`, `--out` and `--from-dir`.
Why it matters
Imported by Renewable Energy Planning Database (REPD) Detect and Renewable Energy Planning Database (REPD) Monthly. Checked by Test Detect Fetch.
Application
globalgrid2050 · automation/repd · Python CLI
Uses
Automation — Renewable Energy Planning Database (REPD) (relative import), __future__, argparse, hashlib, json, sys, time, dataclasses, datetime
Used by
imported by Renewable Energy Planning Database (REPD) Detect (relative import), imported by Renewable Energy Planning Database (REPD) Monthly (import), imported by Test Detect Fetch (import)
Produces
FetchRefused, Response, utc_now, sha256, file_name, urllib_fetcher, local_fetcher, check_response, hash_tree, compare_hashes, fetch_release, main
Defines here
FetchRefused, Response, redirected, utc_now, sha256, file_name, _Recorder, __init__, redirect_request, urllib_fetcher, fetch, local_fetcher, fetch, check_response, hash_tree, compare_hashes, _write_once, fetch_release, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/repd/fetch.py:1-288 · blob c9ed70924a4583518bcb61557e4cfe909303a454 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Download a REPD release (CSV + XLSX) described by a release descriptor.

Reuses scripts/repd_sources_v6.py:fetch_bytes (same User-Agent, three attempts,
exponential back-off, empty-body rejection) but records the redirect chain,
because GOV.UK serves a *replaced* attachment's old URL as a redirect to the new
file: in November 2026 the July (Q2) URLs returned the October (Q3) bytes.

Guards, all fail closed:
  * every response records requested URL, each (status, url) hop, final URL,
    bytes, sha256 and retrieval time;
  * a redirect whose final file name names a different quarter is refused;
  * bytes whose sha256 is pinned by ANOTHER release descriptor are refused;
  * a pinned expected sha256 / byte count must match;
  * CSV must not be HTML (old assets of removed quarters redirect to the page),
    XLSX must be a zip.
Raw bytes go to <out>/raw/<file name>; <out>/fetch_receipt.json records everything.
Existing files in <out> are never overwritten with different bytes.

The network is reached only through an injectable `fetcher(url) -> Response`.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import sys
import time
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Callable, Optional
from urllib.parse import unquote, urlparse
from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener

try:
    from . import config
except ImportError:  # run as a plain script
    sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
    from automation.repd import config  # type: ignore

USER_AGENT = "GlobalGrid2050/6.0 (+https://globalgrid2050.com/)"  # as repd_sources_v6.fetch_bytes


class FetchRefused(RuntimeError):
    pass


@dataclass
class Response:
    requested_url: str
    final_url: str
    status_chain: list            # [[status, url], ...] first hop .. final 200
    body: bytes
    content_type: str = ""

    @property
    def redirected(self) -> bool:
        return self.final_url != self.requested_url or len(self.status_chain) > 1


Fetcher = Callable[[str], Response]


def utc_now() -> str:
    return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")


def sha256(raw: bytes) -> str:
    return hashlib.sha256(raw).hexdigest()


def file_name(url: str) -> str:
    return unquote(urlparse(url).path.rsplit("/", 1)[-1])


# ---------------------------------------------------------------- default fetcher
class _Recorder(HTTPRedirectHandler):
    def __init__(self):
        self.hops: list = []

    def redirect_request(self, req, fp, code, msg, headers, newurl):
        self.hops.append([code, req.full_url])
        return super().redirect_request(req, fp, code, msg, headers, newurl)


def urllib_fetcher(use_env_proxy: bool = True, attempts: int = 3, timeout: int = 75) -> Fetcher:
    """Live fetcher (not used in tests against gov.uk). Retry policy copied from fetch_bytes."""
    def fetch(url: str) -> Response:
        last = None
        for attempt in range(attempts):
            rec = _Recorder()
            handlers = [rec] if use_env_proxy else [rec, ProxyHandler({})]
            opener = build_opener(*handlers)
            try:
                with opener.open(Request(url, headers={"User-Agent": USER_AGENT}), timeout=timeout) as r:
                    body = r.read()
                    if not body:
                        raise RuntimeError("empty response")
                    final = r.geturl()
                    return Response(url, final, rec.hops + [[r.status, final]], body,
                                    r.headers.get("Content-Type", ""))
            except Exception as exc:  # noqa: BLE001 - mirror fetch_bytes
                last = exc
                if attempt < attempts - 1:
                    time.sleep(2 ** attempt)
        raise RuntimeError(f"Unable to retrieve official source after {attempts} attempts: {url}: {last}")
    return fetch


def local_fetcher(directory, redirects: Optional[dict] = None) -> Fetcher:
    """Offline fetcher: serves <directory>/<url file name>. `redirects` maps a URL to
    the URL it should 301 to (used to replay the replaced-attachment trap)."""
    directory = Path(directory)
    redirects = redirects or {}

    def fetch(url: str) -> Response:
        chain, cur, seen = [], url, set()
        while cur in redirects:
            if cur in seen:
                raise RuntimeError(f"redirect loop at {cur}")
            seen.add(cur)
            chain.append([301, cur])
            cur = redirects[cur]
        path = directory / file_name(cur)
        if not path.is_file():
            raise RuntimeError(f"local fetcher: no file {path} for {cur}")
        chain.append([200, cur])
        return Response(url, cur, chain, path.read_bytes(), "")
    return fetch


# ---------------------------------------------------------------- guards
def check_response(resp: Response, role: str, desc: config.ReleaseDescriptor, registry: dict) -> dict:
    """Return the receipt entry, or raise FetchRefused. `registry` = config.known_hashes()."""
    digest = sha256(resp.body)
    entry = {
        "role": role,
        "requested_url": resp.requested_url,
        "final_url": resp.final_url,
        "status_chain": resp.status_chain,
        "redirected": resp.redirected,
        "content_type": resp.content_type,
        "bytes": len(resp.body),
        "sha256": digest,
        "retrieved_at": utc_now(),
        "expected_sha256": getattr(desc.expected, f"{role}_sha256"),
        "expected_bytes": getattr(desc.expected, f"{role}_bytes"),
    }
    where = f"{desc.release_id} {role.upper()} ({resp.requested_url} -> {resp.final_url}, sha256 {digest})"
    if not resp.status_chain or resp.status_chain[-1][0] != 200:
        raise FetchRefused(f"{where}: final status is not 200: {resp.status_chain}")
    head = resp.body[:512].lstrip().lower()
    if head.startswith((b"<!doctype", b"<html")):
        raise FetchRefused(f"{where}: received an HTML page, not a data file "
                           "(old assets of removed quarters redirect to the publication page)")
    if role == "xlsx" and not resp.body.startswith(b"PK\x03\x04"):
        raise FetchRefused(f"{where}: XLSX body is not a zip container")
    want_yq = config.quarter_from_label(desc.label)
    final_yq = config.quarter_from_filename(resp.final_url)
    if resp.redirected and final_yq is not None and final_yq != want_yq:
        raise FetchRefused(
            f"{where}: redirected to a file for {config.quarter_text(*final_yq)}; refusing to label it "
            f"{desc.quarter}. GOV.UK redirects a replaced attachment's old URL to its replacement, so the "
            f"{desc.label} bytes are no longer served at this URL.")
    owner = registry.get(digest)
    if owner and owner[0] != desc.release_id:
        raise FetchRefused(f"{where}: these bytes are pinned by release {owner[0]} ({owner[1]}); "
                           f"refusing to label them {desc.release_id}")
    if entry["expected_sha256"] and entry["expected_sha256"] != digest:
        raise FetchRefused(f"{where}: sha256 differs from pinned {entry['expected_sha256']}")
    if entry["expected_bytes"] is not None and entry["expected_bytes"] != len(resp.body):
        raise FetchRefused(f"{where}: {len(resp.body)} bytes, pinned {entry['expected_bytes']}")
    entry["sha256_verified"] = bool(entry["expected_sha256"])
    entry["warnings"] = []
    if not entry["expected_sha256"]:
        entry["warnings"].append("no pinned sha256: bytes accepted on URL/quarter evidence only; pin after review")
    if resp.redirected:
        entry["warnings"].append("redirected: final URL recorded; same quarter so accepted")
    return entry


# ---------------------------------------------------------------- hash guard
def hash_tree(paths, exclude=None) -> dict[str, str]:
    """sha256 of every file under the given files/dirs (excluding `exclude` subtree)."""
    exclude = Path(exclude).resolve() if exclude else None
    out = {}
    for p in map(Path, paths):
        files = [p] if p.is_file() else sorted(x for x in p.rglob("*") if x.is_file())
        for f in files:
            r = f.resolve()
            if exclude and (r == exclude or exclude in r.parents) or ".git" in r.parts:
                continue
            out[str(r)] = sha256(r.read_bytes())
    return out


def compare_hashes(before: dict, after: dict) -> list[str]:
    diffs = [f"changed: {k}" for k in before if k in after and before[k] != after[k]]
    diffs += [f"removed: {k}" for k in before if k not in after]
    diffs += [f"added: {k}" for k in after if k not in before]
    return diffs


# ---------------------------------------------------------------- main entry
def _write_once(path: Path, data: bytes) -> None:
    if path.exists():
        if sha256(path.read_bytes()) != sha256(data):
            raise FetchRefused(f"{path} exists with different bytes; refusing to overwrite (use a new --out)")
        return
    tmp = path.with_name(path.name + ".part")
    tmp.write_bytes(data)
    tmp.replace(path)


def fetch_release(desc: config.ReleaseDescriptor, out_dir, fetcher: Fetcher,
                  registry: Optional[dict] = None) -> dict:
    """Fetch CSV + XLSX, check both, then write raw bytes and fetch_receipt.json.
    Nothing is written unless BOTH files pass."""
    desc.validate()
    registry = config.known_hashes(config.load_all()) if registry is None else registry
    out = Path(out_dir)
    entries = []
    for role in ("csv", "xlsx"):
        url = getattr(desc, f"{role}_url")
        resp = fetcher(url)
        entries.append((check_response(resp, role, desc, registry), resp.body))
    raw = out / "raw"
    raw.mkdir(parents=True, exist_ok=True)
    files = []
    for entry, body in entries:
        target = raw / file_name(entry["final_url"])
        _write_once(target, body)
        entry["path"] = str(target.relative_to(out))
        files.append(entry)
    receipt = {
        "schema": "globalgrid2050.repd-fetch-receipt.v1",
        "release_id": desc.release_id,
        "label": desc.label,
        "quarter": desc.quarter,
        "fetched_at": utc_now(),
        "descriptor": desc.to_dict(),
        "files": files,
        "status": "FETCHED_VERIFIED" if all(f["sha256_verified"] for f in files) else "FETCHED_UNPINNED",
    }
    rp = out / "fetch_receipt.json"
    rp.write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8")
    return receipt


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--descriptor", required=True, help="release descriptor JSON")
    ap.add_argument("--out", required=True, help="staging directory (raw/ + fetch_receipt.json)")
    ap.add_argument("--from-dir", help="offline: serve files by URL file name from this directory")
    ap.add_argument("--redirect", action="append", default=[], metavar="OLD_URL=NEW_URL",
                    help="offline only: replay a 301 from OLD_URL to NEW_URL (repeatable)")
    ap.add_argument("--releases-dir", default=str(config.RELEASES_DIR),
                    help="descriptors whose pinned hashes form the known-release registry")
    ap.add_argument("--guard", action="append", default=[],
                    help="file/dir that must be byte-identical before and after (repeatable)")
    a = ap.parse_args(argv)
    desc = config.load(a.descriptor)
    if a.redirect and not a.from_dir:
        ap.error("--redirect needs --from-dir")
    redirects = dict(r.split("=", 1) for r in a.redirect)
    fetcher = local_fetcher(a.from_dir, redirects) if a.from_dir else urllib_fetcher()
    descs = config.load_all(a.releases_dir)
    descs[desc.release_id] = desc
    before = hash_tree(a.guard, exclude=a.out) if a.guard else {}
    try:
        receipt = fetch_release(desc, a.out, fetcher, config.known_hashes(descs))
    except FetchRefused as exc:
        print(f"REFUSED: {exc}", file=sys.stderr)
        return 3
    if a.guard:
        diffs = compare_hashes(before, hash_tree(a.guard, exclude=a.out))
        if diffs:
            print("HASH GUARD FAILED (previous work changed):\n  " + "\n  ".join(diffs), file=sys.stderr)
            return 4
        print(f"hash guard: {len(before)} protected files unchanged")
    for f in receipt["files"]:
        print(f"{f['role']}: {f['bytes']} bytes sha256 {f['sha256']} <- {f['final_url']}")
    print(receipt["status"])
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Renewable Energy Planning Database (REPD) Hashguard

A Python command-line tool in the automation folder of GlobalGrid2050 that reads manifest (`read_manifest`), writes manifest (`write_manifest`) and lists worktree files (`list_worktree_files`), using SHA-256.

storageglobalgrid2050 / automation/repd/hashguard.py · lines 1–412 of 430 · Entry point · pattern read_manifest (shared by 2 files)

What it does
It loads data. Defines 22 functions or classes, including GuardError, _unquote, read_manifest, write_manifest, id_kind. Uses libraries argparse, datetime, fnmatch, hashlib, json. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'repd'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: command-line arguments. Out: JSON file.
Downstream impact
Used directly by 1 file: Test Hashguard (globalgrid2050). Reached from 1 other entry point, including GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It guards error (`GuardError`) and is built from the id kind helper (`id_kind`) and the is git worktree helper (`is_git_worktree`). "no truncation of previous work" guard. It accepts `--git`, `--rev` and `--root`.
Why it matters
Checked by Test Hashguard.
Application
globalgrid2050 · automation/repd · Python CLI
Uses
argparse, datetime, fnmatch, hashlib, json, os, subprocess, sys
Used by
imported by Test Hashguard (sys.path import)
Produces
GuardError, read_manifest, write_manifest, id_kind, is_git_worktree, raw_blob_id, sha256_id, git_hash_paths, snapshot_git, snapshot_sha256, list_worktree_files, Snap
Defines here
GuardError, _unquote, read_manifest, write_manifest, id_kind, _git, is_git_worktree, raw_blob_id, sha256_id, git_hash_paths, _exists, snapshot_git, snapshot_sha256, list_worktree_files, Snap, __init__, snapshot_worktree, load_allow, allowed, compare, _parse_git_spec, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/repd/hashguard.py:1-412 · blob 08cab909d0ff987eab2e5e5035339051ebd383a3 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
#!/usr/bin/env python3
"""hashguard.py - "no truncation of previous work" guard.

A snapshot is a manifest of (id, size, path) for files that must not change:
  * git mode    : `git ls-tree -r -l <rev>`  -> git blob id, blob size, path  (every tracked file)
  * sha256 mode : a given list of paths      -> "sha256:<hex>", byte size, path
The on-disk format is the same three-column TSV as /home/claude/monitor/*.blobmanifest.tsv
(`<id>\\t<size>\\t<path>`, no header, paths unquoted, sorted by path).

compare fails (exit 1) when any path of the BEFORE snapshot changed, shrank or disappeared in AFTER,
unless the path matches an explicit allow-list pattern. Paths that exist only in AFTER are additions:
reported, never failed.  AFTER can be another snapshot file, a git revision, or a working tree.

Usage
  python3 -I hashguard.py snapshot --git REPO [--rev HEAD] --out before.tsv
  python3 -I hashguard.py snapshot --root DIR (--paths-file LIST | --paths P [P ...]) --out before.tsv
  python3 -I hashguard.py compare --before before.tsv
          (--after after.tsv | --after-git REPO[@REV] | --worktree DIR [--full-hash])
          [--allow GLOB ...] [--allow-file FILE] [--json report.json] [--max-list N]

Allow-list patterns are fnmatch globs over the repo-relative path ('*' also crosses '/'); a pattern ending
in '/' allows everything under that directory.  Blank lines and '#' comments are ignored in --allow-file.

Working-tree mode (git repo, default): tracked files take their blob id from the index unless
`git status` reports them modified, in which case the file is hashed with `git hash-object` (so
.gitattributes filters apply, giving ids comparable with ls-tree).  --full-hash re-hashes every file.
Untracked, non-ignored files are additions. Ignored files are not examined.
Outside a git repo every file is hashed as a raw git blob (sha1 of "blob <n>\\0" + bytes).

Exit status: 0 = no violation; 1 = at least one pre-existing file changed/shrank/disappeared outside the
allow-list; 2 = could not run (bad arguments, unreadable manifest, git failure, mixed id kinds).
"""
import argparse
import datetime
import fnmatch
import hashlib
import json
import os
import subprocess
import sys

SCHEMA = 'globalgrid2050.hashguard-report.v1'


class GuardError(Exception):
    pass


# ------------------------------------------------------------------ manifest I/O
def _unquote(p):
    if len(p) >= 2 and p[0] == '"' and p[-1] == '"':  # git C-style quoting
        return p[1:-1].encode('latin-1', 'backslashreplace').decode('unicode_escape').encode('latin-1').decode('utf-8')
    return p


def read_manifest(path):
    """-> {path: (id, size_or_None)}"""
    out = {}
    with open(path, encoding='utf-8', newline='') as f:
        for n, line in enumerate(f, 1):
            line = line.rstrip('\n').rstrip('\r')
            if not line or line.startswith('#'):
                continue
            parts = line.split('\t', 2)
            if len(parts) != 3:
                raise GuardError(f'{path}:{n}: expected "<id>\\t<size>\\t<path>", got {line[:80]!r}')
            oid, size, p = parts
            p = _unquote(p)
            if p in out:
                raise GuardError(f'{path}:{n}: duplicate path {p!r}')
            out[p] = (oid, None if size in ('-', '') else int(size))
    return out


def write_manifest(snap, path):
    with open(path, 'w', encoding='utf-8', newline='') as f:
        for p in sorted(snap):
            if '\t' in p or '\n' in p:
                raise GuardError(f'path contains tab/newline, cannot write manifest: {p!r}')
            oid, size = snap[p]
            f.write(f'{oid}\t{"-" if size is None else size}\t{p}\n')


def id_kind(snap):
    kinds = {('sha256' if oid.startswith('sha256:') else 'git') for oid, _ in snap.values()}
    if len(kinds) > 1:
        raise GuardError('manifest mixes git blob ids and sha256 ids')
    return kinds.pop() if kinds else 'git'


# ------------------------------------------------------------------ hashing helpers
def _git(repo, *args, input_bytes=None):
    try:
        # GIT_OPTIONAL_LOCKS=0: `git status` must not refresh/write the index of the repo being guarded
        env = dict(os.environ, GIT_OPTIONAL_LOCKS='0')
        r = subprocess.run(['git', '-C', repo, *args], input=input_bytes, capture_output=True, check=True, env=env)
    except FileNotFoundError:
        raise GuardError('git executable not found')
    except subprocess.CalledProcessError as e:
        raise GuardError(f'git {" ".join(args)} failed in {repo}: {e.stderr.decode(errors="replace").strip()}')
    return r.stdout


def is_git_worktree(root):
    try:
        return _git(root, 'rev-parse', '--is-inside-work-tree').strip() == b'true' and \
            os.path.realpath(_git(root, 'rev-parse', '--show-toplevel').decode().strip()) == os.path.realpath(root)
    except GuardError:
        return False


def raw_blob_id(path):
    size = os.path.getsize(path)
    h = hashlib.sha1(b'blob %d\0' % size)
    with open(path, 'rb') as f:
        for b in iter(lambda: f.read(1 << 20), b''):
            h.update(b)
    return h.hexdigest()


def sha256_id(path):
    h = hashlib.sha256()
    with open(path, 'rb') as f:
        for b in iter(lambda: f.read(1 << 20), b''):
            h.update(b)
    return 'sha256:' + h.hexdigest()


def git_hash_paths(root, paths, filters=True):
    """git blob ids for repo-relative paths that exist as regular files.
    filters=True applies .gitattributes (eol/clean) as `git add` would; False hashes the raw bytes."""
    if not paths:
        return {}
    args = ['hash-object', '--stdin-paths'] + ([] if filters else ['--no-filters'])
    out = _git(root, *args, input_bytes=('\n'.join(paths) + '\n').encode('utf-8'))
    ids = out.decode().split()
    if len(ids) != len(paths):
        raise GuardError('git hash-object returned an unexpected number of ids')
    return dict(zip(paths, ids))


def _exists(root, p):
    fp = os.path.join(root, p)
    return os.path.isfile(fp) or os.path.islink(fp)


# ------------------------------------------------------------------ snapshots
def snapshot_git(repo, rev='HEAD'):
    out = _git(repo, 'ls-tree', '-r', '-l', '-z', rev)
    snap = {}
    for rec in out.split(b'\0'):
        if not rec:
            continue
        meta, p = rec.split(b'\t', 1)
        mode, typ, oid, size = meta.split()
        if typ != b'blob':  # submodule commits: keep the id, size unknown
            snap[p.decode('utf-8')] = (oid.decode(), None)
            continue
        snap[p.decode('utf-8')] = (oid.decode(), int(size))
    return snap


def snapshot_sha256(root, paths):
    snap = {}
    for p in paths:
        p = p.strip()
        if p.startswith('./'):
            p = p[2:]
        if not p:
            continue
        fp = os.path.join(root, p)
        if not os.path.isfile(fp):
            raise GuardError(f'cannot snapshot {p!r}: not a file under {root}')
        snap[p] = (sha256_id(fp), os.path.getsize(fp))
    return snap


def list_worktree_files(root):
    if is_git_worktree(root):
        out = _git(root, 'ls-files', '-co', '--exclude-standard', '-z')
        return [p.decode('utf-8') for p in out.split(b'\0') if p and _exists(root, p.decode('utf-8'))]
    files = []
    for d, dirs, fs in os.walk(root):
        dirs[:] = [x for x in dirs if x != '.git']
        for f in fs:
            files.append(os.path.relpath(os.path.join(d, f), root).replace(os.sep, '/'))
    return files


class Snap(dict):
    """{path: (id, size)} plus .alt {path: second acceptable id}: a working-tree file whose raw bytes and
    filtered (.gitattributes-normalised) bytes hash differently matches BEFORE if either id equals it.
    This happens for blobs committed with CRLF before `* text=auto eol=lf` was added."""
    def __init__(self, *a, **k):
        super().__init__(*a, **k)
        self.alt = {}


def snapshot_worktree(root, kind='git', paths=None, full_hash=False):
    """Current state of a working tree, in the id kind of the snapshot it will be compared with.
    paths: restrict hashing to these (sha256 kind); additions are still discovered by listing."""
    snap = Snap()
    alts = snap.alt
    if kind == 'sha256':
        for p in (paths if paths is not None else list_worktree_files(root)):
            fp = os.path.join(root, p)
            if os.path.isfile(fp):
                snap[p] = (sha256_id(fp), os.path.getsize(fp))
        if paths is not None:  # additions: list only, ids not computed
            for p in list_worktree_files(root):
                snap.setdefault(p, ('unhashed', os.path.getsize(os.path.join(root, p))))
        return snap
    if not is_git_worktree(root):
        for p in list_worktree_files(root):
            fp = os.path.join(root, p)
            snap[p] = (raw_blob_id(fp), os.path.getsize(fp))
        return snap
    if full_hash:
        files = list_worktree_files(root)
        regular = [p for p in files if os.path.isfile(os.path.join(root, p)) and not os.path.islink(os.path.join(root, p))]
        ids = git_hash_paths(root, regular, filters=False)
        alt = git_hash_paths(root, regular, filters=True)
        for p in files:
            fp = os.path.join(root, p)
            if os.path.islink(fp):
                snap[p] = (hashlib.sha1(b'blob %d\0' % len(os.readlink(fp).encode()) + os.readlink(fp).encode()).hexdigest(),
                           len(os.readlink(fp).encode()))
            else:
                snap[p] = (ids[p], os.path.getsize(fp))
                if alt[p] != ids[p]:
                    alts[p] = alt[p]
        return snap
    # fast path: index ids + re-hash only what git status reports as dirty / untracked
    idx = {}
    for rec in _git(root, 'ls-files', '-s', '-z').split(b'\0'):
        if not rec:
            continue
        meta, p = rec.split(b'\t', 1)
        mode, oid, stage = meta.split()
        idx[p.decode('utf-8')] = (oid.decode(), mode.decode())
    dirty, untracked = set(), set()
    st = _git(root, 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--no-renames').split(b'\0')
    for rec in st:
        if len(rec) < 4:
            continue
        xy, p = rec[:2].decode(), rec[3:].decode('utf-8')
        (untracked if xy == '??' else dirty).add(p)
    # `git status` never reports files flagged assume-unchanged (ls-files -v: lower-case tag) or
    # skip-worktree (tag S/s; every path outside a sparse checkout's cone carries it). A file with
    # either flag that is present on disk is therefore re-hashed, as if git status had called it dirty.
    for rec in _git(root, 'ls-files', '-v', '-z').split(b'\0'):
        if len(rec) < 3:
            continue
        tag, p = rec[:1].decode(), rec[2:].decode('utf-8')
        if (tag.islower() or tag == 'S') and _exists(root, p):
            dirty.add(p)
    rehash = sorted(p for p in (dirty | untracked) if _exists(root, p) and not os.path.islink(os.path.join(root, p)))
    ids = git_hash_paths(root, rehash, filters=False)
    for p, fid in git_hash_paths(root, rehash, filters=True).items():
        if fid != ids[p]:
            alts[p] = fid
    for p, (oid, mode) in idx.items():
        if p in dirty:
            if p in ids:
                snap[p] = (ids[p], os.path.getsize(os.path.join(root, p)))
            # else deleted from the working tree: absent
        elif mode == '160000':
            snap[p] = (oid, None)
        else:  # unchanged per git status: index id, size of the file on disk (or absent if git disagrees)
            fp = os.path.join(root, p)
            snap[p] = (oid, os.path.getsize(fp) if _exists(root, p) else None)
    for p in untracked:
        if p in ids:
            snap[p] = (ids[p], os.path.getsize(os.path.join(root, p)))
    return snap


# ------------------------------------------------------------------ compare
def load_allow(patterns=None, files=None):
    pats = list(patterns or [])
    for f in files or []:
        with open(f, encoding='utf-8') as fh:
            for line in fh:
                line = line.strip()
                if line and not line.startswith('#'):
                    pats.append(line)
    return pats


def allowed(path, patterns):
    for pat in patterns:
        if pat.endswith('/') and path.startswith(pat):
            return pat
        if fnmatch.fnmatchcase(path, pat):
            return pat
    return None


def compare(before, after, allow=(), max_list=None):
    """-> report dict. before/after: {path: (id, size_or_None)}"""
    kb = id_kind(before)
    ka = id_kind({p: v for p, v in after.items() if v[0] != 'unhashed'})
    if kb != ka and after:
        raise GuardError(f'cannot compare a {kb} snapshot with a {ka} snapshot')
    violations, allowed_changes, unchanged = [], [], 0
    for p in sorted(before):
        oid, size = before[p]
        if p not in after:
            item = {'path': p, 'change': 'disappeared', 'before_id': oid, 'before_size': size}
        else:
            aid, asize = after[p]
            if aid == oid or getattr(after, 'alt', {}).get(p) == oid:
                unchanged += 1
                continue
            if asize is None:
                asize = size
            kind = 'shrank' if (size is not None and asize is not None and asize < size) else 'changed'
            item = {'path': p, 'change': kind, 'before_id': oid, 'after_id': aid, 'before_size': size, 'after_size': asize}
        pat = allowed(p, allow)
        if pat:
            item['allowed_by'] = pat
            allowed_changes.append(item)
        else:
            violations.append(item)
    additions = [{'path': p, 'id': after[p][0], 'size': after[p][1]} for p in sorted(set(after) - set(before))]
    cut = (lambda xs: xs[:max_list]) if max_list else (lambda xs: xs)
    by = {}
    for v in violations:
        by[v['change']] = by.get(v['change'], 0) + 1
    return {
        'schema': SCHEMA, 'id_kind': kb,
        'generated_at': datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds'),
        'before_files': len(before), 'after_files': len(after), 'unchanged': unchanged,
        'violations_total': len(violations), 'violations_by_change': by, 'violations': cut(violations),
        'allowed_changes_total': len(allowed_changes), 'allowed_changes': cut(allowed_changes),
        'additions_total': len(additions), 'additions_bytes': sum(a['size'] or 0 for a in additions),
        'additions': cut(additions), 'allow_patterns': list(allow),
        'result': 'FAIL' if violations else 'PASS', 'exit_code': 1 if violations else 0,
    }


def _parse_git_spec(spec):
    if '@' in spec and not os.path.exists(spec):
        repo, rev = spec.rsplit('@', 1)
        return repo, rev or 'HEAD'
    return spec, 'HEAD'


def main(argv=None):
    ap = argparse.ArgumentParser(description='no-truncation hash guard')
    sub = ap.add_subparsers(dest='cmd', required=True)
    s = sub.add_parser('snapshot')
    s.add_argument('--git', help='repository: snapshot every tracked file of --rev')
    s.add_argument('--rev', default='HEAD')
    s.add_argument('--root', help='directory for sha256 mode')
    s.add_argument('--paths-file')
    s.add_argument('--paths', nargs='+')
    s.add_argument('--out', required=True)
    c = sub.add_parser('compare')
    c.add_argument('--before', required=True)
    g = c.add_mutually_exclusive_group(required=True)
    g.add_argument('--after')
    g.add_argument('--after-git', help='REPO or REPO@REV')
    g.add_argument('--worktree')
    c.add_argument('--full-hash', action='store_true')
    c.add_argument('--allow', action='append', default=[])
    c.add_argument('--allow-file', action='append', default=[])
    c.add_argument('--json')
    c.add_argument('--max-list', type=int, default=0, help='truncate lists in the JSON report (0 = all)')
    c.add_argument('--quiet', action='store_true')
    try:
        a = ap.parse_args(argv)
    except SystemExit as e:
        return 2 if e.code else 0
    try:
        if a.cmd == 'snapshot':
            if bool(a.git) == bool(a.root):
                raise GuardError('give exactly one of --git or --root')
            if a.git:
                snap = snapshot_git(a.git, a.rev)
            else:
                paths = list(a.paths or [])
                if a.paths_file:
                    with open(a.paths_file, encoding='utf-8') as f:
                        paths += [ln.strip() for ln in f if ln.strip() and not ln.startswith('#')]
                if not paths:
                    raise GuardError('sha256 mode needs --paths or --paths-file')
                snap = snapshot_sha256(a.root, paths)
            write_manifest(snap, a.out)
            print(f'snapshot: {len(snap)} files, {sum(v[1] or 0 for v in snap.values())} bytes -> {a.out}')
            return 0
        before = read_manifest(a.before)
        kind = id_kind(before)
        if a.after:
            after = read_manifest(a.after)
        elif a.after_git:
            if kind != 'git':
                raise GuardError('a sha256 snapshot can only be compared with a working tree or another sha256 snapshot')
            after = snapshot_git(*_parse_git_spec(a.after_git))
        else:
            after = snapshot_worktree(a.worktree, kind, paths=sorted(before) if kind == 'sha256' else None,
                                      full_hash=a.full_hash)
        allow = load_allow(a.allow, a.allow_file)
        rep = compare(before, after, allow, a.max_list or None)
        rep['before'] = a.before
        rep['after'] = a.after or (('git:' + a.after_git) if a.after_git else ('worktree:' + a.worktree +
                                                                               (' (full hash)' if a.full_hash else '')))
    except (GuardError, OSError, ValueError) as e:
        print(f'ERROR: {e}', file=sys.stderr)
        return 2
    if not a.quiet:
        print(f'{rep["result"]}: {rep["before_files"]} pre-existing files, {rep["unchanged"]} unchanged, '