#!/usr/bin/env python3 """Build stable context packs from manifests. Rules: - files are explicit; missing required file => fail - sorted paths, no timestamps => stable prefix - token estimate = chars / 4 (documented heuristic) - secret-like patterns => abort - atomic publish via os.replace """ import argparse import json import os import re import sys from pathlib import Path import yaml ROOT = Path(__file__).resolve().parents[2] CONTEXT = ROOT / "ops" / "context" MANIFESTS = CONTEXT / "manifests" PACKS = CONTEXT / "packs" SECRET_PATTERNS = [ re.compile(r"(?i)(password|passwd|token|api[_-]?key|secret)\s*[:=]\s*\S{4,}"), re.compile(r"sk-[A-Za-z0-9]{10,}"), re.compile(r"-----BEGIN (RSA |OPENSSH |EC )?PRIVATE KEY-----"), ] def scan(text): return any(p.search(text) for p in SECRET_PATTERNS) def load_manifest(path): data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} files = data.get("files") or [] if not files: raise ValueError(f"{path.name}: no files") return data, files def main(): ap = argparse.ArgumentParser() ap.add_argument("--all", action="store_true") args = ap.parse_args() PACKS.mkdir(parents=True, exist_ok=True) manifests = sorted(MANIFESTS.glob("*.yaml")) if not manifests: sys.exit("no manifests") logs = [] for mpath in manifests: data, files = load_manifest(mpath) name = data.get("name") or mpath.stem limit = int(data.get("limit") or 0) parts = [f"# PACK {name}", f"# files: {len(files)}", ""] total = 0 for rel in files: p = ROOT / rel if not p.is_file(): sys.exit(f"missing required file: {rel}") text = p.read_text(encoding="utf-8", errors="replace") if scan(text): sys.exit(f"secret-like content in: {rel}") total += len(text) parts += [f"## {rel}", "", text.rstrip(), ""] text = "\n".join(parts) tokens = len(text) // 4 if limit and tokens > limit: sys.exit(f"{name}: estimate {tokens} > limit {limit}") out = PACKS / f"{name}.md" tmp = out.with_suffix(".tmp") tmp.write_text(text, encoding="utf-8") os.replace(tmp, out) logs.append({"pack": name, "files": len(files), "chars": len(text), "est_tokens": tokens, "limit": limit}) (PACKS / "BUILD-LOG.json").write_text(json.dumps(logs, ensure_ascii=False, indent=2), encoding="utf-8") print(json.dumps(logs, ensure_ascii=False, indent=2)) if __name__ == "__main__": main()