File size: 2,909 Bytes
7fd88a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/env python3
"""Generate the deterministic package manifest (v16).

The manifest records SHA-256 prefixes and sizes for maintained Markdown, Python,
TOML, YAML, JSON and the VERSION file. It is written only after explicit CLI
execution; --help has no filesystem side effects. The ``agent_version`` field is
read from the package VERSION file (v15 hard-coded "15.0.0" here, which is how
the v14 manifest had drifted to "11.0.0").
"""

from __future__ import annotations

import argparse
import hashlib
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(Path(__file__).resolve().parent))
from agent_version import read_version  # noqa: E402

TRACK_EXT = {".md", ".py", ".json", ".toml", ".yaml", ".yml"}
TRACK_NAMES = {"VERSION"}
SKIP_DIRS = {"__pycache__", ".cache", ".pytest_cache"}
# LEDGER.md and DECISIONS.md are append-only audit logs that must record the
# manifest regeneration itself (and the final test run after it); tracking them
# would make the manifest unsatisfiable by construction. Everything else is tracked.
SKIP_FILES = {"LEDGER.md", "DECISIONS.md"}


def build_manifest(root: Path = ROOT) -> dict:
    """Return the manifest without writing files."""
    files = {}
    for path in sorted(root.rglob("*")):
        if not path.is_file() or path.name == "manifest.json":
            continue
        if path.parent == root and path.name in SKIP_FILES:
            continue
        if any(part in SKIP_DIRS for part in path.relative_to(root).parts):
            continue
        if path.suffix not in TRACK_EXT and path.name not in TRACK_NAMES:
            continue
        data = path.read_bytes()
        files[str(path.relative_to(root))] = {
            "sha256": hashlib.sha256(data).hexdigest()[:16],
            "size": len(data),
        }
    return {"agent_version": read_version(), "files": files}


def write_manifest(output: Path, root: Path = ROOT) -> dict:
    """Write a manifest atomically and return its data."""
    manifest = build_manifest(root)
    temporary = output.with_suffix(output.suffix + ".tmp")
    temporary.write_text(json.dumps(manifest, indent=1, sort_keys=True) + "\n",
                         encoding="utf-8")
    temporary.replace(output)
    return manifest


def build_parser() -> argparse.ArgumentParser:
    """Build the side-effect-free CLI parser."""
    parser = argparse.ArgumentParser(
        description=f"Generate the package manifest (agent version {read_version()})")
    parser.add_argument("--output", type=Path, default=ROOT / "manifest.json")
    return parser


def main() -> int:
    """Generate the manifest requested by the CLI."""
    args = build_parser().parse_args()
    manifest = write_manifest(args.output)
    print(f"{args.output}: {len(manifest['files'])} files tracked")
    return 0


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