package_agent_handoff.py 104 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802
  1. #!/usr/bin/env python3
  2. """Create a comprehensive, sanitized CPLD workspace handoff archive."""
  3. from __future__ import annotations
  4. import argparse
  5. import gzip
  6. import hashlib
  7. import importlib.util
  8. import io
  9. import json
  10. import os
  11. import re
  12. import shutil
  13. import stat
  14. import subprocess
  15. import sys
  16. import tarfile
  17. import tempfile
  18. import tomllib
  19. import unicodedata
  20. import uuid
  21. import zipfile
  22. from collections import Counter
  23. from contextlib import contextmanager
  24. from dataclasses import dataclass
  25. from datetime import datetime, timezone
  26. from pathlib import Path
  27. from typing import BinaryIO, Callable, Iterable, Iterator, cast
  28. ROOT = Path(__file__).resolve().parents[1]
  29. ARCHIVE_ROOT = "CPLD"
  30. METADATA_ROOT = f"{ARCHIVE_ROOT}/HANDOFF-METADATA"
  31. SECRET_SCAN_OVERLAP = 512
  32. MAX_ARCHIVE_DEPTH = 3
  33. MAX_ARCHIVE_MEMBERS = 100_000
  34. MAX_ARCHIVE_UNCOMPRESSED_BYTES = 8 * 1024 * 1024 * 1024
  35. SECRET_PATTERNS = (
  36. (
  37. "private key",
  38. re.compile(
  39. rb"-----BEGIN "
  40. + rb"(?:ENCRYPTED |RSA |DSA |EC |OPENSSH )?"
  41. + rb"PRIVATE KEY-----"
  42. + rb"|-----BEGIN PGP "
  43. + rb"PRIVATE KEY BLOCK-----"
  44. ),
  45. ),
  46. (
  47. "GitHub token",
  48. re.compile(
  49. rb"(?<![A-Za-z0-9_])(?:gh[pousr]_[A-Za-z0-9]{36,255}"
  50. rb"|github_pat_[A-Za-z0-9_]{60,255})(?![A-Za-z0-9_])"
  51. ),
  52. ),
  53. (
  54. "AWS secret access key",
  55. re.compile(
  56. rb"(?<![A-Za-z0-9_])aws_"
  57. + rb"(?:secret_access_key|secret_key)[\"']?\s*[:=]\s*[\"']?"
  58. + rb"[A-Za-z0-9/+=]{40}(?![A-Za-z0-9/+=])",
  59. re.IGNORECASE,
  60. ),
  61. ),
  62. (
  63. "AWS session token",
  64. re.compile(
  65. rb"(?<![A-Za-z0-9_])aws_"
  66. + rb"(?:session_token|security_token)[\"']?\s*[:=]\s*[\"']?"
  67. + rb"[A-Za-z0-9/+=]{32,2048}(?![A-Za-z0-9/+=])",
  68. re.IGNORECASE,
  69. ),
  70. ),
  71. (
  72. "OpenAI API key",
  73. re.compile(
  74. rb"(?<![A-Za-z0-9_-])sk-(?:proj-|svcacct-)?[A-Za-z0-9_-]{32,255}"
  75. rb"(?![A-Za-z0-9_-])"
  76. ),
  77. ),
  78. (
  79. "Slack token",
  80. re.compile(rb"(?<![A-Za-z0-9-])xox[baprs]-[A-Za-z0-9-]{20,255}(?![A-Za-z0-9-])"),
  81. ),
  82. )
  83. SAFE_PACKAGE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,119}$")
  84. TD_BUILD_EVIDENCE_SUFFIXES = {".qor", ".area", ".timing", ".rpt", ".log", ".logw"}
  85. LEGACY_HANDOFF_PROFILES = frozenset({"full", "code-only"})
  86. REVIEW_PROFILES = frozenset({"review-compact", "review-debug", "archive-local"})
  87. HANDOFF_PROFILES = LEGACY_HANDOFF_PROFILES | REVIEW_PROFILES
  88. UNIFIED_LAYOUT_PROFILES = REVIEW_PROFILES
  89. DEFAULT_HANDOFF_PROFILE = "review-compact"
  90. CODE_ONLY_ROOT_EXCLUSIONS = {
  91. "reference": "reference_material",
  92. }
  93. CODE_ONLY_GENERATED_VISUAL_ASSETS = frozenset(
  94. {
  95. "board-copper.svg",
  96. "board-silkscreen.svg",
  97. "board-mask-edge.svg",
  98. }
  99. )
  100. BOARD_VIEWER_DERIVED_ASSETS = CODE_ONLY_GENERATED_VISUAL_ASSETS | {
  101. "board-data.json",
  102. "build-info.json",
  103. "import-report.json",
  104. }
  105. REVIEW_HEAVY_ORIGINAL_SUFFIXES = {".pdf", ".brd", ".dsn"}
  106. REVIEW_ORIGINAL_ROOT_EXCLUSIONS = {
  107. "reference/original/board": "reference_original_board",
  108. "reference/original/schematics": "reference_original_schematics",
  109. "reference/original/diagrams": "reference_original_diagrams",
  110. "reference/original/local_archives": "reference_original_archives",
  111. }
  112. SIZE_BUDGET_MIN_BYTES = 256 * 1024
  113. SIZE_BUDGET_MIN_SHARE = 0.01
  114. WINDOWS_RESERVED_NAMES = {
  115. "con",
  116. "prn",
  117. "aux",
  118. "nul",
  119. *(f"com{index}" for index in range(1, 10)),
  120. *(f"lpt{index}" for index in range(1, 10)),
  121. }
  122. WINDOWS_INVALID_FILENAME_CHARS = frozenset('<>:"/\\|?*')
  123. class PackagingError(RuntimeError):
  124. """Raised when a handoff archive cannot be produced safely."""
  125. @dataclass(frozen=True)
  126. class Candidate:
  127. absolute: Path
  128. relative: str
  129. size: int
  130. mtime_ns: int
  131. device: int
  132. inode: int
  133. mode: int
  134. @dataclass
  135. class CandidateSnapshot:
  136. stream: BinaryIO
  137. inventory: dict[str, object]
  138. @dataclass
  139. class ArchiveScanBudget:
  140. member_count: int = 0
  141. uncompressed_bytes: int = 0
  142. @dataclass(frozen=True)
  143. class ScanContext:
  144. changxin_version: str | None
  145. profile: str = "full"
  146. def utc_now() -> str:
  147. return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
  148. def find_7z() -> Path | None:
  149. discovered = shutil.which("7z") or shutil.which("7zz")
  150. candidates = [
  151. Path(discovered) if discovered else None,
  152. Path(r"C:\Program Files\7-Zip\7z.exe"),
  153. Path(r"C:\Program Files (x86)\7-Zip\7z.exe"),
  154. ]
  155. for candidate in candidates:
  156. if candidate is not None and candidate.is_file():
  157. return candidate.resolve(strict=True)
  158. return None
  159. def build_7zip_create_command(archive_path: Path, staging_root: Path) -> list[str]:
  160. del staging_root
  161. return [
  162. "a",
  163. "-tzip",
  164. "-mm=Deflate",
  165. "-mx=9",
  166. "-mmt",
  167. "-y",
  168. "-r",
  169. str(archive_path),
  170. "CPLD\\*",
  171. ]
  172. def run_7zip(seven_zip: Path, arguments: list[str], *, cwd: Path) -> str:
  173. try:
  174. completed = subprocess.run(
  175. [str(seven_zip), *arguments],
  176. cwd=cwd,
  177. stdout=subprocess.PIPE,
  178. stderr=subprocess.STDOUT,
  179. text=True,
  180. encoding="utf-8",
  181. errors="replace",
  182. timeout=300,
  183. check=False,
  184. )
  185. except (OSError, subprocess.TimeoutExpired) as exc:
  186. raise PackagingError("unable to run 7-Zip") from exc
  187. if completed.returncode != 0:
  188. detail = completed.stdout.strip().splitlines()
  189. suffix = f": {detail[-1]}" if detail else ""
  190. raise PackagingError(f"7-Zip failed{suffix}")
  191. return completed.stdout
  192. def rename_archive_entries(
  193. seven_zip: Path,
  194. archive_path: Path,
  195. renames: list[tuple[str, str]],
  196. ) -> None:
  197. for offset in range(0, len(renames), 64):
  198. batch = renames[offset : offset + 64]
  199. arguments = ["rn", "-y", str(archive_path)]
  200. for old_name, new_name in batch:
  201. arguments.extend((old_name, new_name))
  202. run_7zip(seven_zip, arguments, cwd=archive_path.parent)
  203. def validate_windows_component(component: str, relative: str) -> str:
  204. if component.endswith((" ", ".")):
  205. raise PackagingError(f"path component has a Windows-unsafe trailing character: {relative}")
  206. if any(ord(character) < 32 or character in WINDOWS_INVALID_FILENAME_CHARS for character in component):
  207. raise PackagingError(f"path component contains a Windows-invalid character: {relative}")
  208. normalized = component.casefold()
  209. if normalized.split(".", 1)[0] in WINDOWS_RESERVED_NAMES:
  210. raise PackagingError(f"Windows reserved device name is not portable: {relative}")
  211. return normalized
  212. def normalize_relative(parts: Iterable[str]) -> str:
  213. try:
  214. relative = unicodedata.normalize("NFC", "/".join(parts))
  215. relative.encode("utf-8", errors="strict")
  216. except UnicodeError as exc:
  217. raise PackagingError("path is not valid UTF-8") from exc
  218. components = relative.split("/")
  219. if not relative or relative.startswith("/") or any(part in {"", ".", ".."} for part in components):
  220. raise PackagingError(f"unsafe relative path: {relative!r}")
  221. for component in components:
  222. validate_windows_component(component, relative)
  223. return relative
  224. def windows_collision_key(relative: str) -> str:
  225. components = []
  226. for component in unicodedata.normalize("NFC", relative).split("/"):
  227. if not component:
  228. raise PackagingError(f"path component is empty after Windows normalization: {relative}")
  229. normalized = validate_windows_component(component, relative)
  230. components.append(normalized)
  231. return "/".join(components)
  232. def is_under(relative: str, prefix: str) -> bool:
  233. return relative == prefix or relative.startswith(prefix + "/")
  234. def load_scan_context(root: Path, *, profile: str = "full") -> ScanContext:
  235. pyproject = root / "tools" / "changxin-temp-uart" / "pyproject.toml"
  236. version: str | None = None
  237. try:
  238. raw_payload = read_stable_regular_bytes(
  239. pyproject,
  240. "Changxin pyproject",
  241. max_bytes=1024 * 1024,
  242. )
  243. payload = tomllib.loads(raw_payload.decode("utf-8-sig", errors="strict"))
  244. value = payload.get("project", {}).get("version")
  245. if isinstance(value, str) and value.strip():
  246. version = value.strip()
  247. except (PackagingError, UnicodeError, tomllib.TOMLDecodeError):
  248. version = None
  249. return ScanContext(version, profile=profile)
  250. def secret_path_reason(relative: str, *, is_dir: bool) -> str | None:
  251. if is_dir:
  252. return None
  253. name = relative.rsplit("/", 1)[-1].casefold()
  254. parts = relative.casefold().split("/")
  255. suffix = Path(name).suffix.casefold()
  256. if name == ".env" or (
  257. name.startswith(".env.")
  258. and not name.endswith((".example", ".sample", ".template", ".dist"))
  259. ):
  260. return "secret_environment_file"
  261. if name in {"id_rsa", "id_dsa", "id_ecdsa", "id_ed25519"} or name.startswith("id_rsa."):
  262. return "private_key_file"
  263. if name in {".netrc", "_netrc", ".pypirc", ".npmrc", ".git-credentials"}:
  264. return "credential_configuration_file"
  265. if len(parts) >= 2 and parts[-2:] == [".aws", "credentials"]:
  266. return "cloud_credential_file"
  267. if len(parts) >= 2 and parts[-2:] == [".docker", "config.json"]:
  268. return "container_registry_credential_file"
  269. if len(parts) >= 2 and parts[-2:] == ["gcloud", "application_default_credentials.json"]:
  270. return "cloud_credential_file"
  271. if suffix in {".key", ".pfx", ".p12", ".lic"}:
  272. return "credential_or_license_file"
  273. return None
  274. def common_file_exclusion_reason(relative: str) -> str | None:
  275. lower = relative.casefold()
  276. name = lower.rsplit("/", 1)[-1]
  277. suffix = Path(name).suffix.casefold()
  278. if suffix in {".pyc", ".pyo"}:
  279. return "python_bytecode"
  280. if suffix in {".tmp", ".partial", ".part", ".swp", ".swo"} or name.endswith("~"):
  281. return "atomic_or_editor_temporary_file"
  282. if suffix == ".dmp" or name.startswith("minidump-"):
  283. return "crash_dump"
  284. if name == "a.out" or (name.startswith("tmp_last_pkg") and name.endswith(".txt")):
  285. return "temporary_build_artifact"
  286. if name in {".ds_store", "thumbs.db", "desktop.ini"}:
  287. return "os_metadata_cache"
  288. if name in {".coverage", "coverage.xml"}:
  289. return "coverage_cache"
  290. if name.startswith(".coverage."):
  291. return "coverage_cache"
  292. if lower.startswith("td/td_") and suffix in {".log", ".logw"}:
  293. return "td_root_runtime_log"
  294. if "/" not in lower and lower.startswith("td_") and suffix in {".log", ".logw"}:
  295. return "td_root_runtime_log"
  296. generated_binary_suffixes = {
  297. ".bit",
  298. ".bid",
  299. ".data",
  300. ".db",
  301. ".sqlite",
  302. ".timing",
  303. ".rpt",
  304. ".area",
  305. ".qor",
  306. ".vvp",
  307. }
  308. if name in {"status.sqlite", "logfile.txt"} and "/tests/formal/" in f"/{lower}/":
  309. return "formal_workdir_artifact"
  310. if suffix in generated_binary_suffixes:
  311. return "generated_binary_artifact"
  312. if suffix == ".exe":
  313. return "vendor_executable"
  314. # Vendor tool installers / release archives must never enter analysis packages.
  315. # Covers root OSS CAD suite .tgz, Anlogic TD/BW release zips, and similar.
  316. if name.startswith(("bw_release_", "td_release_", "oss-cad-suite")) and (
  317. suffix in {".zip", ".tgz", ".tar", ".gz", ".7z", ".rar"}
  318. or name.endswith((".tar.gz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz"))
  319. ):
  320. return "vendor_toolchain_archive"
  321. if "license" in name and suffix in {".zip", ".tgz", ".7z", ".rar"}:
  322. return "license_archive"
  323. if name.endswith((".lic",)) or name in {"anlogic.lic"}:
  324. return "credential_or_license_file"
  325. return None
  326. def exclusion_reason(relative: str, *, is_dir: bool, context: ScanContext) -> str | None:
  327. lower = relative.casefold()
  328. parts = lower.split("/")
  329. raw_parts = relative.split("/")
  330. name = parts[-1]
  331. if parts[0] == "handoff-metadata":
  332. raise PackagingError(f"source uses reserved package path: {relative}")
  333. secret_reason = secret_path_reason(relative, is_dir=is_dir)
  334. if secret_reason:
  335. return secret_reason
  336. explicit_roots = {
  337. ".git": "raw_git_metadata",
  338. ".codegraph": "external_codegraph_cache",
  339. ".omo": "agent_session_runtime",
  340. ".hypothesis": "hypothesis_cache",
  341. ".pytest_cache": "pytest_cache",
  342. ".chatgpt-handoff": "chatgpt_handoff_runtime_not_in_compact",
  343. ".playwright-upload-cache": "playwright_upload_cache",
  344. "workspace": "deprecated_workspace",
  345. "_archive": "deprecated_archive",
  346. "unused": "unused_workspace_area",
  347. "log": "runtime_log_directory",
  348. "dist": "generated_handoff_output",
  349. "anlogic_cd": "vendor_installer_payload",
  350. "receipts/local": "local_runtime_receipt",
  351. "j6-binary921-deliverables": "generated_delivery_package",
  352. "j6tmp-v2-tailfix-package": "generated_delivery_package",
  353. "cpld-deliverables": "generated_delivery_package",
  354. "runs": "run_state_directory",
  355. }
  356. for prefix, reason in explicit_roots.items():
  357. if is_under(lower, prefix):
  358. return reason
  359. if lower in {"td/project/.lock.f", "td/project/.recent_user_depot.ini"}:
  360. return "td_gui_runtime_state"
  361. if is_under(lower, "td/project/log"):
  362. return "td_gui_runtime_log"
  363. if is_under(lower, "td/project") and len(parts) >= 3 and parts[2].endswith("_runs"):
  364. return "td_gui_runtime_run"
  365. if any(component.endswith("_Runs") for component in raw_parts):
  366. return "generated_run_directory"
  367. if lower == "tests/cocotb/results.xml":
  368. return "cocotb_transient_result"
  369. if not is_dir:
  370. common_reason = common_file_exclusion_reason(relative)
  371. if common_reason:
  372. return common_reason
  373. cache_components = {
  374. ".git": "raw_git_metadata",
  375. ".codegraph": "external_codegraph_cache",
  376. ".codex": "codex_local_runtime",
  377. "__pycache__": "python_bytecode_cache",
  378. ".pytest_cache": "pytest_cache",
  379. ".hypothesis": "hypothesis_cache",
  380. ".mypy_cache": "mypy_cache",
  381. ".ruff_cache": "ruff_cache",
  382. ".tox": "tox_environment",
  383. ".nox": "nox_environment",
  384. ".venv": "virtual_environment",
  385. "venv": "virtual_environment",
  386. "htmlcov": "coverage_report",
  387. "sim_build": "simulation_build",
  388. "obj_dir": "verilator_build",
  389. "node_modules": "node_modules_runtime",
  390. ".playwright-browsers": "browser_runtime_cache",
  391. "build": "build_output",
  392. "runs": "run_state_directory",
  393. }
  394. for component in parts:
  395. if component in cache_components:
  396. return cache_components[component]
  397. if component.endswith(".egg-info"):
  398. return "python_package_metadata"
  399. if component == "dist":
  400. return "generated_delivery_output"
  401. if component == ".logs":
  402. return "td_generated_run_directory"
  403. if is_under(lower, ".codex"):
  404. return "codex_local_runtime"
  405. if is_under(lower, "tools/changxin-temp-uart/build"):
  406. return "python_package_build_copy"
  407. if is_under(lower, "tools/changxin-temp-uart/pyinstaller-build"):
  408. return "pyinstaller_build_cache"
  409. if is_under(lower, "tools/changxin-temp-uart/pyinstaller-spec"):
  410. return "pyinstaller_spec_cache"
  411. if lower in {
  412. "tools/changxin-temp-uart/pyinstaller-entry.py",
  413. "tools/changxin-temp-uart/linux-onefile-build.json",
  414. "tools/changxin-temp-uart/changxin-temp-uart-static",
  415. }:
  416. return "pyinstaller_generated_output"
  417. if lower == "tools/changxin-temp-uart/dist":
  418. return None
  419. if is_under(lower, "tools/changxin-temp-uart/dist"):
  420. return None
  421. if is_under(lower, "td/build"):
  422. return "td_build_output"
  423. if lower == "tmp":
  424. return None
  425. if is_under(lower, "tmp"):
  426. transient_tmp_roots = {
  427. "tmp/rtl_sim": "compiled_rtl_simulation",
  428. "tmp/cocotb": "cocotb_runtime",
  429. "tmp/detector_selftest": "detector_selftest_runtime",
  430. "tmp/toolchain_probe": "toolchain_probe_runtime",
  431. "tmp/edge-headless-profile": "browser_runtime_profile",
  432. "tmp/td": "td_runtime_snapshot",
  433. "tmp/refactor": "compiled_refactor_probe",
  434. }
  435. for prefix, reason in transient_tmp_roots.items():
  436. if is_under(lower, prefix):
  437. return reason
  438. for evidence_prefix in (
  439. "tmp/resource_audit",
  440. "tmp/pwm_executor_probe",
  441. ):
  442. if is_under(lower, evidence_prefix):
  443. evidence_parts = parts[len(evidence_prefix.split("/")) :]
  444. if "td_user_env" in evidence_parts:
  445. return "td_staged_source_or_runtime_copy"
  446. return None
  447. if len(parts) == 2 and parts[1].startswith("pytest-"):
  448. return "temporary_test_runtime"
  449. return None
  450. return None
  451. def code_only_exclusion_reason(relative: str, *, is_dir: bool) -> str | None:
  452. lower = relative.casefold()
  453. name = lower.rsplit("/", 1)[-1]
  454. for prefix, reason in CODE_ONLY_ROOT_EXCLUSIONS.items():
  455. if is_under(lower, prefix):
  456. return reason
  457. if not is_dir and is_under(lower, "tools/board-viewer/generated"):
  458. if name in CODE_ONLY_GENERATED_VISUAL_ASSETS:
  459. return "generated_board_viewer_visual_asset"
  460. return None
  461. def is_board_viewer_fixture_path(relative: str) -> bool:
  462. return is_under(relative.casefold(), "tests/board_viewer/fixtures")
  463. def is_review_profile(profile: str) -> bool:
  464. return profile in REVIEW_PROFILES
  465. def uses_unified_layout(profile: str) -> bool:
  466. return profile in UNIFIED_LAYOUT_PROFILES
  467. def delivery_policy_for_profile(profile: str) -> str:
  468. if profile == "code-only":
  469. return "code-only"
  470. if profile in REVIEW_PROFILES:
  471. return profile
  472. return "inclusion-first"
  473. def review_exclusion_reason(relative: str, *, is_dir: bool, profile: str) -> str | None:
  474. """Extra exclusions for review-* / archive-local unified packages."""
  475. lower = relative.casefold()
  476. name = lower.rsplit("/", 1)[-1]
  477. if name.startswith(".run_id"):
  478. return "run_id_marker"
  479. if name in {"evidence-batch-summary.txt"}:
  480. return "stale_run_summary"
  481. # Adversarial payload blobs are generated in temp during tests; never ship them
  482. # long-term inside review-compact / review-debug volumes.
  483. if is_under(lower, "tests/fixtures/package_adversarial/payloads"):
  484. if profile in {"review-compact", "review-debug"}:
  485. return "adversarial_fixture_payload"
  486. for prefix, reason in REVIEW_ORIGINAL_ROOT_EXCLUSIONS.items():
  487. if is_under(lower, prefix):
  488. return reason
  489. if is_board_viewer_fixture_path(relative):
  490. return None
  491. if not is_dir:
  492. suffix = Path(name).suffix.casefold()
  493. if suffix in REVIEW_HEAVY_ORIGINAL_SUFFIXES:
  494. return "heavy_design_original_not_packaged"
  495. if name.endswith((".lic",)) or name in {"anlogic.lic"}:
  496. return "credential_or_license_file"
  497. if "license" in name and suffix in {".zip", ".tgz", ".7z", ".rar", ".txt", ".pdf"}:
  498. return "license_material"
  499. # review-compact / review-debug: never ship vendor toolchain installers.
  500. # archive-local leaves this to shared common_file_exclusion_reason (may still
  501. # exclude; do not broaden compact policy by skipping here).
  502. if profile in {"review-compact", "review-debug"}:
  503. common_reason = common_file_exclusion_reason(relative)
  504. if common_reason in {
  505. "vendor_toolchain_archive",
  506. "vendor_executable",
  507. "license_archive",
  508. }:
  509. return common_reason
  510. return None
  511. def make_exclusion_resolver(profile: str) -> Callable[..., str | None]:
  512. if profile not in HANDOFF_PROFILES:
  513. raise PackagingError(f"unsupported handoff profile: {profile}")
  514. def resolve(relative: str, *, is_dir: bool, context: ScanContext) -> str | None:
  515. if profile == "code-only":
  516. code_only_reason = code_only_exclusion_reason(relative, is_dir=is_dir)
  517. if code_only_reason:
  518. return code_only_reason
  519. base = exclusion_reason(relative, is_dir=is_dir, context=context)
  520. if base:
  521. return base
  522. if is_review_profile(profile):
  523. return review_exclusion_reason(relative, is_dir=is_dir, profile=profile)
  524. return None
  525. return resolve
  526. def stat_is_reparse_point(file_stat: os.stat_result) -> bool:
  527. attributes = int(getattr(file_stat, "st_file_attributes", 0))
  528. reparse_flag = int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0))
  529. return stat.S_ISLNK(file_stat.st_mode) or bool(reparse_flag and attributes & reparse_flag)
  530. def is_reparse_point(entry: os.DirEntry[str], file_stat: os.stat_result) -> bool:
  531. return entry.is_symlink() or stat_is_reparse_point(file_stat)
  532. def invalid_receipt_reason(path: Path, relative: str, size: int) -> str | None:
  533. if not relative.casefold().startswith("receipts/") or not relative.casefold().endswith(".json"):
  534. return None
  535. if size == 0:
  536. return "empty_receipt"
  537. if size <= 32:
  538. try:
  539. if path.read_bytes().strip().lower() == b"null":
  540. return "null_receipt"
  541. except OSError as exc:
  542. raise PackagingError(f"unable to inspect receipt {relative}: {exc}") from exc
  543. return None
  544. def scan_tree(
  545. root: Path,
  546. *,
  547. exclusion_resolver: Callable[..., str | None] | None = None,
  548. profile: str = "full",
  549. ) -> tuple[list[Candidate], list[dict[str, str]], ScanContext]:
  550. context = load_scan_context(root, profile=profile)
  551. resolve_exclusion = exclusion_resolver or exclusion_reason
  552. included: list[Candidate] = []
  553. excluded: list[dict[str, str]] = []
  554. collision_paths: dict[str, str] = {}
  555. def record_exclusion(relative: str, reason: str) -> None:
  556. excluded.append({"path": relative, "rule": reason})
  557. def walk(directory: Path, relative_parts: tuple[str, ...]) -> None:
  558. try:
  559. with os.scandir(directory) as iterator:
  560. entries = sorted(
  561. list(iterator),
  562. key=lambda item: unicodedata.normalize("NFC", item.name).casefold(),
  563. )
  564. except OSError as exc:
  565. relative = "/".join(relative_parts) or "."
  566. raise PackagingError(f"unable to enumerate {relative}: {exc}") from exc
  567. for entry in entries:
  568. relative = normalize_relative((*relative_parts, entry.name))
  569. scan_secret_markers(relative.encode("utf-8"), b"", "[source path]")
  570. try:
  571. file_stat = os.lstat(entry.path)
  572. except OSError as exc:
  573. raise PackagingError(f"unable to inspect {relative}: {exc}") from exc
  574. is_directory = stat.S_ISDIR(file_stat.st_mode)
  575. reason = resolve_exclusion(relative, is_dir=is_directory, context=context)
  576. if is_reparse_point(entry, file_stat):
  577. if reason:
  578. record_exclusion(relative, reason)
  579. continue
  580. raise PackagingError(f"undeclared reparse point refuses packaging: {relative}")
  581. if reason:
  582. record_exclusion(relative, reason)
  583. continue
  584. if is_directory:
  585. walk(Path(entry.path), (*relative_parts, entry.name))
  586. continue
  587. if not stat.S_ISREG(file_stat.st_mode):
  588. raise PackagingError(f"unsupported non-regular file: {relative}")
  589. receipt_reason = invalid_receipt_reason(Path(entry.path), relative, file_stat.st_size)
  590. if receipt_reason:
  591. record_exclusion(relative, receipt_reason)
  592. continue
  593. key = windows_collision_key(relative)
  594. previous = collision_paths.get(key)
  595. if previous is not None:
  596. raise PackagingError(f"Windows ZIP path collision: {previous} and {relative}")
  597. collision_paths[key] = relative
  598. if int(file_stat.st_dev) == 0 or int(file_stat.st_ino) == 0:
  599. raise PackagingError(f"filesystem does not expose a stable file identity: {relative}")
  600. included.append(
  601. Candidate(
  602. Path(entry.path),
  603. relative,
  604. file_stat.st_size,
  605. file_stat.st_mtime_ns,
  606. int(file_stat.st_dev),
  607. int(file_stat.st_ino),
  608. int(file_stat.st_mode),
  609. )
  610. )
  611. walk(root, ())
  612. included.sort(key=lambda item: windows_collision_key(item.relative))
  613. excluded.sort(key=lambda item: (windows_collision_key(item["path"]), item["rule"]))
  614. return included, excluded, context
  615. def sha256_file(path: Path) -> str:
  616. digest = hashlib.sha256()
  617. with path.open("rb") as handle:
  618. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  619. digest.update(chunk)
  620. return digest.hexdigest()
  621. def scan_secret_markers(chunk: bytes, tail: bytes, relative: str) -> bytes:
  622. combined = tail + chunk
  623. for label, pattern in SECRET_PATTERNS:
  624. if pattern.search(combined):
  625. raise PackagingError(f"high-confidence {label} secret found in {relative}")
  626. return combined[-SECRET_SCAN_OVERLAP:]
  627. def candidate_stat_matches(file_stat: os.stat_result, candidate: Candidate) -> bool:
  628. return (
  629. stat.S_ISREG(file_stat.st_mode)
  630. and not stat_is_reparse_point(file_stat)
  631. and int(file_stat.st_dev) == candidate.device
  632. and int(file_stat.st_ino) == candidate.inode
  633. and (os.name == "nt" or int(file_stat.st_mode) == candidate.mode)
  634. and file_stat.st_size == candidate.size
  635. and file_stat.st_mtime_ns == candidate.mtime_ns
  636. )
  637. @contextmanager
  638. def open_candidate(candidate: Candidate) -> Iterator[BinaryIO]:
  639. try:
  640. before = os.lstat(candidate.absolute)
  641. except OSError as exc:
  642. raise PackagingError(f"unable to inspect {candidate.relative} before packaging: {exc}") from exc
  643. if not candidate_stat_matches(before, candidate):
  644. raise PackagingError(f"source changed after enumeration: {candidate.relative}")
  645. flags = os.O_RDONLY
  646. flags |= int(getattr(os, "O_BINARY", 0))
  647. flags |= int(getattr(os, "O_NOINHERIT", 0))
  648. flags |= int(getattr(os, "O_NOFOLLOW", 0))
  649. try:
  650. file_descriptor = os.open(candidate.absolute, flags)
  651. except OSError as exc:
  652. raise PackagingError(f"unable to open {candidate.relative} without following links: {exc}") from exc
  653. source: BinaryIO | None = None
  654. try:
  655. try:
  656. opened = os.fstat(file_descriptor)
  657. except OSError as exc:
  658. raise PackagingError(f"unable to inspect opened source {candidate.relative}: {exc}") from exc
  659. if not candidate_stat_matches(opened, candidate):
  660. raise PackagingError(f"source identity changed while opening: {candidate.relative}")
  661. source = os.fdopen(file_descriptor, "rb", closefd=True)
  662. file_descriptor = -1
  663. try:
  664. yield source
  665. try:
  666. opened_after = os.fstat(source.fileno())
  667. except OSError as exc:
  668. raise PackagingError(f"unable to inspect opened source {candidate.relative} after reading: {exc}") from exc
  669. finally:
  670. source.close()
  671. if not candidate_stat_matches(opened_after, candidate):
  672. raise PackagingError(f"source changed while reading: {candidate.relative}")
  673. finally:
  674. if file_descriptor >= 0:
  675. os.close(file_descriptor)
  676. try:
  677. after = os.lstat(candidate.absolute)
  678. except OSError as exc:
  679. raise PackagingError(f"unable to inspect {candidate.relative} after packaging: {exc}") from exc
  680. if not candidate_stat_matches(after, candidate):
  681. raise PackagingError(f"source changed during packaging: {candidate.relative}")
  682. @contextmanager
  683. def snapshot_candidate(
  684. candidate: Candidate,
  685. *,
  686. allow_disk: bool,
  687. ) -> Iterator[CandidateSnapshot]:
  688. snapshot = cast(BinaryIO, tempfile.TemporaryFile()) if allow_disk else cast(BinaryIO, io.BytesIO())
  689. try:
  690. digest = hashlib.sha256()
  691. total = 0
  692. secret_tail = b""
  693. with open_candidate(candidate) as source:
  694. while True:
  695. chunk = source.read(1024 * 1024)
  696. if not chunk:
  697. break
  698. secret_tail = scan_secret_markers(chunk, secret_tail, candidate.relative)
  699. snapshot.write(chunk)
  700. digest.update(chunk)
  701. total += len(chunk)
  702. if total != candidate.size:
  703. raise PackagingError(f"source size changed during packaging: {candidate.relative}")
  704. snapshot.seek(0)
  705. yield CandidateSnapshot(
  706. stream=snapshot,
  707. inventory={"path": candidate.relative, "size": total, "sha256": digest.hexdigest()},
  708. )
  709. except MemoryError as exc:
  710. raise PackagingError(f"insufficient memory to audit source file: {candidate.relative}") from exc
  711. finally:
  712. snapshot.close()
  713. def archive_kind(name: str) -> str | None:
  714. lower = name.casefold()
  715. if lower.endswith((".zip", ".whl", ".jar", ".apk", ".nupkg")):
  716. return "zip"
  717. if lower.endswith((".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz", ".tar")):
  718. return "tar"
  719. if lower.endswith(".gz"):
  720. return "gzip"
  721. if lower.endswith((".rar", ".7z")):
  722. return "unsupported"
  723. return None
  724. def detect_archive_kind(source: BinaryIO, name: str) -> str | None:
  725. position = source.tell()
  726. try:
  727. source.seek(0)
  728. prefix = source.read(512)
  729. source.seek(0)
  730. if zipfile.is_zipfile(source):
  731. return "zip"
  732. hint = archive_kind(name)
  733. if prefix.startswith((b"7z\xbc\xaf'\x1c", b"Rar!\x1a\x07", b"(\xb5/\xfd", b"\x04\x22\x4d\x18")):
  734. return "unsupported"
  735. if prefix.startswith((b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08")):
  736. return "zip"
  737. if prefix.startswith(b"\x1f\x8b"):
  738. return "tar" if hint == "tar" else "gzip"
  739. if prefix.startswith((b"BZh", b"\xfd7zXZ\x00")):
  740. return "tar"
  741. if len(prefix) >= 262 and prefix[257:262] == b"ustar":
  742. return "tar"
  743. if prefix.startswith((b"!<arch>\n", b"MSCF", b"xar!")):
  744. return "unsupported"
  745. return hint
  746. finally:
  747. source.seek(position)
  748. def archive_member_label(archive_label: str, member_name: str) -> str:
  749. normalized = unicodedata.normalize("NFC", member_name)
  750. if (
  751. "\\" in normalized
  752. or "\x00" in normalized
  753. or normalized.startswith("/")
  754. or re.match(r"^[A-Za-z]:", normalized)
  755. ):
  756. raise PackagingError(f"unsafe archive member path in {archive_label}")
  757. normalized = normalized.removesuffix("/")
  758. if not normalized:
  759. raise PackagingError(f"unsafe archive member path in {archive_label}")
  760. parts = normalized.split("/")
  761. if any(part in {"", ".", ".."} for part in parts):
  762. raise PackagingError(f"unsafe archive member path in {archive_label}")
  763. scan_secret_markers(normalized.encode("utf-8"), b"", f"{archive_label} member path")
  764. return f"{archive_label}!/{normalized}"
  765. def scan_archive_metadata(value: str | bytes, label: str) -> None:
  766. try:
  767. payload = value if isinstance(value, bytes) else value.encode("utf-8", errors="strict")
  768. except UnicodeError as exc:
  769. raise PackagingError(f"archive metadata is not valid UTF-8 in {label}") from exc
  770. scan_secret_markers(payload, b"", label)
  771. def account_archive_member(budget: ArchiveScanBudget, label: str) -> None:
  772. budget.member_count += 1
  773. if budget.member_count > MAX_ARCHIVE_MEMBERS:
  774. raise PackagingError(f"archive scan resource limit exceeded in {label}")
  775. def ensure_archive_bytes_available(budget: ArchiveScanBudget, size: int, label: str) -> None:
  776. if size < 0 or budget.uncompressed_bytes + size > MAX_ARCHIVE_UNCOMPRESSED_BYTES:
  777. raise PackagingError(f"archive scan resource limit exceeded in {label}")
  778. def scan_archive_member_stream(
  779. source: BinaryIO,
  780. *,
  781. member_name: str,
  782. label: str,
  783. depth: int,
  784. budget: ArchiveScanBudget,
  785. allow_disk: bool,
  786. ) -> None:
  787. sensitive_reason = secret_path_reason(member_name.removesuffix("/"), is_dir=False)
  788. if sensitive_reason is not None:
  789. raise PackagingError(
  790. f"credential or license path found in archive member: {label} ({sensitive_reason})"
  791. )
  792. nested = cast(BinaryIO, tempfile.TemporaryFile()) if allow_disk else cast(BinaryIO, io.BytesIO())
  793. try:
  794. secret_tail = b""
  795. while True:
  796. chunk = source.read(1024 * 1024)
  797. if not chunk:
  798. break
  799. ensure_archive_bytes_available(budget, len(chunk), label)
  800. budget.uncompressed_bytes += len(chunk)
  801. secret_tail = scan_secret_markers(chunk, secret_tail, label)
  802. nested.write(chunk)
  803. nested.seek(0)
  804. if detect_archive_kind(nested, member_name) is not None:
  805. scan_archive_stream(
  806. nested,
  807. name=member_name,
  808. label=label,
  809. depth=depth + 1,
  810. budget=budget,
  811. allow_disk=allow_disk,
  812. )
  813. except MemoryError as exc:
  814. raise PackagingError(f"insufficient memory to audit archive member: {label}") from exc
  815. finally:
  816. nested.close()
  817. def scan_archive_stream(
  818. source: BinaryIO,
  819. *,
  820. name: str,
  821. label: str,
  822. depth: int,
  823. budget: ArchiveScanBudget,
  824. allow_disk: bool,
  825. ) -> None:
  826. kind = detect_archive_kind(source, name)
  827. if kind is None:
  828. return
  829. if kind == "unsupported":
  830. raise PackagingError(f"unsupported archive format cannot be secret-scanned: {label}")
  831. if depth > MAX_ARCHIVE_DEPTH:
  832. raise PackagingError(f"archive scan resource limit exceeded in {label}")
  833. try:
  834. if kind == "zip":
  835. with zipfile.ZipFile(source) as archive:
  836. scan_archive_metadata(archive.comment, f"{label} archive comment")
  837. for zip_member in archive.infolist():
  838. account_archive_member(budget, label)
  839. member_label = archive_member_label(label, zip_member.filename)
  840. member_mode = (zip_member.external_attr >> 16) & 0xFFFF
  841. member_type = stat.S_IFMT(member_mode)
  842. scan_archive_metadata(zip_member.comment, f"{member_label} comment")
  843. scan_archive_metadata(zip_member.extra, f"{member_label} extra metadata")
  844. if zip_member.flag_bits & 0x1:
  845. raise PackagingError(f"unsafe archive member type in {member_label}")
  846. if zip_member.is_dir():
  847. if (
  848. zip_member.file_size != 0
  849. or zip_member.compress_size != 0
  850. or member_type not in {0, stat.S_IFDIR}
  851. ):
  852. raise PackagingError(f"unsafe archive member type in {member_label}")
  853. continue
  854. if member_type not in {0, stat.S_IFREG}:
  855. raise PackagingError(f"unsafe archive member type in {member_label}")
  856. ensure_archive_bytes_available(budget, zip_member.file_size, member_label)
  857. with archive.open(zip_member, "r") as zip_member_source:
  858. scan_archive_member_stream(
  859. cast(BinaryIO, zip_member_source),
  860. member_name=zip_member.filename,
  861. label=member_label,
  862. depth=depth,
  863. budget=budget,
  864. allow_disk=allow_disk,
  865. )
  866. return
  867. if kind == "tar":
  868. with tarfile.open(fileobj=source, mode="r:*") as archive:
  869. for key, value in archive.pax_headers.items():
  870. scan_archive_metadata(key, f"{label} global pax key")
  871. scan_archive_metadata(value, f"{label} global pax value")
  872. for tar_member in archive:
  873. account_archive_member(budget, label)
  874. member_label = archive_member_label(label, tar_member.name)
  875. for field_name, value in (
  876. ("linkname", tar_member.linkname),
  877. ("uname", tar_member.uname),
  878. ("gname", tar_member.gname),
  879. ):
  880. scan_archive_metadata(value, f"{member_label} {field_name}")
  881. for key, value in tar_member.pax_headers.items():
  882. scan_archive_metadata(key, f"{member_label} pax key")
  883. scan_archive_metadata(value, f"{member_label} pax value")
  884. if tar_member.isdir():
  885. if tar_member.size != 0:
  886. raise PackagingError(f"unsafe archive member type in {member_label}")
  887. continue
  888. if not tar_member.isfile():
  889. raise PackagingError(f"unsafe archive member type in {member_label}")
  890. ensure_archive_bytes_available(budget, tar_member.size, member_label)
  891. tar_member_source = archive.extractfile(tar_member)
  892. if tar_member_source is None:
  893. raise PackagingError(f"unable to inspect archive member in {member_label}")
  894. with tar_member_source:
  895. scan_archive_member_stream(
  896. cast(BinaryIO, tar_member_source),
  897. member_name=tar_member.name,
  898. label=member_label,
  899. depth=depth,
  900. budget=budget,
  901. allow_disk=allow_disk,
  902. )
  903. return
  904. with gzip.GzipFile(fileobj=source, mode="rb") as gzip_member_source:
  905. scan_archive_member_stream(
  906. cast(BinaryIO, gzip_member_source),
  907. member_name=name.removesuffix(".gz"),
  908. label=f"{label}!/<gzip>",
  909. depth=depth,
  910. budget=budget,
  911. allow_disk=allow_disk,
  912. )
  913. except PackagingError:
  914. raise
  915. except (OSError, EOFError, RuntimeError, tarfile.TarError, zipfile.BadZipFile) as exc:
  916. raise PackagingError(f"unable to inspect archive safely: {label} ({type(exc).__name__})") from exc
  917. def scan_candidate_archive(candidate: Candidate) -> None:
  918. with snapshot_candidate(candidate, allow_disk=True) as snapshot:
  919. scan_archive_stream(
  920. snapshot.stream,
  921. name=candidate.relative,
  922. label=candidate.relative,
  923. depth=0,
  924. budget=ArchiveScanBudget(),
  925. allow_disk=True,
  926. )
  927. def audit_candidates(candidates: Iterable[Candidate]) -> list[dict[str, object]]:
  928. inventory = []
  929. for candidate in candidates:
  930. inventory.append(stream_candidate(candidate))
  931. return inventory
  932. def zip_info(name: str, mode: int = stat.S_IFREG | 0o644) -> zipfile.ZipInfo:
  933. info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0))
  934. info.compress_type = zipfile.ZIP_DEFLATED
  935. info.create_system = 3
  936. info.flag_bits |= 0x800 # UTF-8 filenames
  937. info.external_attr = ((stat.S_IFREG | (mode & 0o777)) & 0xFFFF) << 16
  938. return info
  939. def stream_candidate(
  940. candidate: Candidate,
  941. target: BinaryIO | None = None,
  942. *,
  943. allow_disk: bool = True,
  944. ) -> dict[str, object]:
  945. with snapshot_candidate(candidate, allow_disk=allow_disk) as snapshot:
  946. scan_archive_stream(
  947. snapshot.stream,
  948. name=candidate.relative,
  949. label=candidate.relative,
  950. depth=0,
  951. budget=ArchiveScanBudget(),
  952. allow_disk=allow_disk,
  953. )
  954. if target is not None:
  955. snapshot.stream.seek(0)
  956. shutil.copyfileobj(snapshot.stream, target, length=1024 * 1024)
  957. return snapshot.inventory
  958. def hash_candidate(candidate: Candidate) -> dict[str, object]:
  959. digest = hashlib.sha256()
  960. total = 0
  961. secret_tail = b""
  962. with open_candidate(candidate) as source:
  963. for chunk in iter(lambda: source.read(1024 * 1024), b""):
  964. secret_tail = scan_secret_markers(chunk, secret_tail, candidate.relative)
  965. digest.update(chunk)
  966. total += len(chunk)
  967. if total != candidate.size:
  968. raise PackagingError(f"source size changed during packaging: {candidate.relative}")
  969. return {"path": candidate.relative, "size": total, "sha256": digest.hexdigest()}
  970. def write_candidate(archive: zipfile.ZipFile, candidate: Candidate) -> dict[str, object]:
  971. entry_name = f"{ARCHIVE_ROOT}/{candidate.relative}"
  972. try:
  973. with archive.open(zip_info(entry_name, candidate.mode), "w", force_zip64=True) as target:
  974. return stream_candidate(candidate, target)
  975. except OSError as exc:
  976. raise PackagingError(f"unable to package {candidate.relative}: {exc}") from exc
  977. def stage_candidate(
  978. staging_root: Path,
  979. candidate: Candidate,
  980. staging_name: str | None = None,
  981. ) -> dict[str, object]:
  982. target = staging_root / ARCHIVE_ROOT / (
  983. staging_name if staging_name is not None else Path(*candidate.relative.split("/"))
  984. )
  985. target.parent.mkdir(parents=True, exist_ok=True)
  986. try:
  987. with target.open("wb") as destination:
  988. return stream_candidate(candidate, target=destination)
  989. except OSError as exc:
  990. raise PackagingError(f"unable to stage {candidate.relative}: {exc}") from exc
  991. def write_bytes_entry(archive: zipfile.ZipFile, name: str, payload: bytes) -> None:
  992. scan_secret_markers(payload, b"", name)
  993. with archive.open(zip_info(name), "w", force_zip64=True) as handle:
  994. handle.write(payload)
  995. def json_bytes(payload: object) -> bytes:
  996. return (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
  997. def path_contains_reparse_point(root: Path, candidate: Path) -> bool:
  998. root_absolute = Path(os.path.abspath(root))
  999. candidate_absolute = Path(os.path.abspath(candidate))
  1000. try:
  1001. relative = candidate_absolute.relative_to(root_absolute)
  1002. except ValueError:
  1003. return True
  1004. current = root_absolute
  1005. for component in relative.parts:
  1006. current /= component
  1007. try:
  1008. file_stat = os.lstat(current)
  1009. except OSError:
  1010. return True
  1011. if stat_is_reparse_point(file_stat):
  1012. return True
  1013. return False
  1014. def resolve_git_dir(root: Path) -> Path | None:
  1015. marker = root / ".git"
  1016. try:
  1017. marker_stat = os.lstat(marker)
  1018. except OSError:
  1019. return None
  1020. if stat_is_reparse_point(marker_stat):
  1021. return None
  1022. root_resolved = root.resolve(strict=True)
  1023. if stat.S_ISDIR(marker_stat.st_mode):
  1024. try:
  1025. candidate = marker.resolve(strict=True)
  1026. candidate.relative_to(root_resolved)
  1027. except (OSError, RuntimeError, ValueError):
  1028. return None
  1029. return candidate
  1030. if stat.S_ISREG(marker_stat.st_mode):
  1031. try:
  1032. text = read_stable_regular_bytes(marker, ".git marker", max_bytes=4096).decode(
  1033. "utf-8",
  1034. errors="strict",
  1035. ).strip()
  1036. except (PackagingError, UnicodeError):
  1037. return None
  1038. if text.startswith("gitdir:"):
  1039. raw_candidate = root / text.split(":", 1)[1].strip()
  1040. try:
  1041. candidate = raw_candidate.resolve(strict=True)
  1042. candidate.relative_to(root_resolved)
  1043. except (OSError, RuntimeError, ValueError):
  1044. return None
  1045. if path_contains_reparse_point(root_resolved, raw_candidate):
  1046. return None
  1047. try:
  1048. candidate_stat = os.lstat(candidate)
  1049. except OSError:
  1050. return None
  1051. return candidate if stat.S_ISDIR(candidate_stat.st_mode) and not stat_is_reparse_point(candidate_stat) else None
  1052. return None
  1053. def read_head_metadata(git_dir: Path) -> tuple[str | None, str | None]:
  1054. try:
  1055. head = read_stable_regular_bytes(git_dir / "HEAD", "Git HEAD", max_bytes=4096).decode(
  1056. "ascii",
  1057. errors="strict",
  1058. ).strip()
  1059. except (PackagingError, UnicodeError):
  1060. return None, None
  1061. if not head.startswith("ref: "):
  1062. return None, head if re.fullmatch(r"[0-9a-fA-F]{40}", head) else None
  1063. ref = head[5:].strip()
  1064. ref_parts = ref.split("/")
  1065. if (
  1066. not ref.startswith("refs/")
  1067. or "\\" in ref
  1068. or any(part in {"", ".", ".."} for part in ref_parts)
  1069. or ".." in ref
  1070. or "@{" in ref
  1071. or ref.endswith((".", "/", ".lock"))
  1072. or re.fullmatch(r"[A-Za-z0-9._/-]+", ref) is None
  1073. ):
  1074. return None, None
  1075. branch = ref.removeprefix("refs/heads/") if ref.startswith("refs/heads/") else ref
  1076. ref_file = git_dir.joinpath(*ref_parts)
  1077. commit: str | None = None
  1078. if os.path.lexists(ref_file):
  1079. if path_contains_reparse_point(git_dir, ref_file):
  1080. return branch, None
  1081. try:
  1082. commit = read_stable_regular_bytes(ref_file, f"Git ref {ref}", max_bytes=4096).decode(
  1083. "ascii",
  1084. errors="strict",
  1085. ).strip()
  1086. except (PackagingError, UnicodeError):
  1087. return branch, None
  1088. if commit is None:
  1089. commit = None
  1090. packed_refs = git_dir / "packed-refs"
  1091. if os.path.lexists(packed_refs) and not path_contains_reparse_point(git_dir, packed_refs):
  1092. try:
  1093. packed_text = read_stable_regular_bytes(
  1094. packed_refs,
  1095. "Git packed-refs",
  1096. max_bytes=16 * 1024 * 1024,
  1097. ).decode("ascii", errors="strict")
  1098. except (PackagingError, UnicodeError):
  1099. packed_text = ""
  1100. for line in packed_text.splitlines():
  1101. if not line or line.startswith(("#", "^")):
  1102. continue
  1103. sha, _, packed_ref = line.partition(" ")
  1104. if packed_ref == ref:
  1105. commit = sha
  1106. break
  1107. if commit and not re.fullmatch(r"[0-9a-fA-F]{40}", commit):
  1108. commit = None
  1109. return branch, commit
  1110. def run_capture(command: list[str], *, cwd: Path, timeout: int = 60) -> tuple[int, bytes]:
  1111. try:
  1112. completed = subprocess.run(
  1113. command,
  1114. cwd=cwd,
  1115. stdout=subprocess.PIPE,
  1116. stderr=subprocess.STDOUT,
  1117. timeout=timeout,
  1118. check=False,
  1119. )
  1120. except (OSError, subprocess.TimeoutExpired):
  1121. return 1, b""
  1122. return completed.returncode, completed.stdout
  1123. def collect_git_provenance(root: Path) -> tuple[dict[str, object], dict[str, bytes]]:
  1124. git_dir = resolve_git_dir(root)
  1125. if git_dir is None:
  1126. return {"status": "not_a_git_worktree", "branch": None, "head": None, "tool": None}, {}
  1127. branch, head = read_head_metadata(git_dir)
  1128. tool: str | None = None
  1129. status_command: list[str] | None = None
  1130. git = shutil.which("git")
  1131. if git:
  1132. tool = "git"
  1133. status_command = [
  1134. git,
  1135. "--no-optional-locks",
  1136. "-c",
  1137. "core.fsmonitor=false",
  1138. "-c",
  1139. "core.untrackedCache=false",
  1140. "status",
  1141. "--short",
  1142. "--branch",
  1143. "--untracked-files=all",
  1144. ]
  1145. elif importlib.util.find_spec("dulwich") is not None:
  1146. tool = "dulwich"
  1147. status_command = [sys.executable, "-I", "-m", "dulwich", "status"]
  1148. if status_command is None:
  1149. return {"status": "blocked_missing_git_tool", "branch": branch, "head": head, "tool": None}, {}
  1150. status_code, status_payload = run_capture(status_command, cwd=root)
  1151. artifacts: dict[str, bytes] = {}
  1152. if status_code == 0:
  1153. artifacts[f"{METADATA_ROOT}/git-status.txt"] = status_payload
  1154. capture_status = "pass" if status_code == 0 else "partial"
  1155. return {
  1156. "status": capture_status,
  1157. "branch": branch,
  1158. "head": head,
  1159. "tool": tool,
  1160. "status_captured": status_code == 0,
  1161. }, artifacts
  1162. def _git_bytes(git: str, args: list[str], *, cwd: Path) -> bytes | None:
  1163. code, payload = run_capture([git, *args], cwd=cwd)
  1164. if code != 0:
  1165. return None
  1166. return payload
  1167. SHA256_HEX_RE = re.compile(r"^[0-9a-f]{64}$")
  1168. COMMIT_FULL_RE = re.compile(r"^[0-9a-f]{40}$")
  1169. def _resolve_commit_full(root: Path, commit: str | None = None) -> str | None:
  1170. if commit and COMMIT_FULL_RE.fullmatch(commit.strip().casefold()):
  1171. return commit.strip().casefold()
  1172. git = shutil.which("git")
  1173. if git is None:
  1174. return None
  1175. code, payload = run_capture([git, "rev-parse", "HEAD"], cwd=root)
  1176. if code != 0:
  1177. return None
  1178. text = payload.decode("ascii", errors="replace").strip().casefold()
  1179. return text if COMMIT_FULL_RE.fullmatch(text) else None
  1180. def _collect_td_report_bindings(
  1181. report_paths: Iterable[Path],
  1182. ) -> list[dict[str, object]]:
  1183. rows: list[dict[str, object]] = []
  1184. for path in report_paths:
  1185. resolved = path.expanduser().resolve(strict=False)
  1186. if not resolved.is_file():
  1187. rows.append(
  1188. {
  1189. "path": str(path),
  1190. "status": "missing",
  1191. "sha256": None,
  1192. "bytes": None,
  1193. }
  1194. )
  1195. continue
  1196. rows.append(
  1197. {
  1198. "path": str(resolved),
  1199. "status": "present",
  1200. "sha256": sha256_file(resolved),
  1201. "bytes": resolved.stat().st_size,
  1202. "name": resolved.name,
  1203. }
  1204. )
  1205. rows.sort(key=lambda row: str(row.get("path", "")).casefold())
  1206. return rows
  1207. def discover_bitstream_candidates(
  1208. root: Path,
  1209. *,
  1210. evidence_root: Path | None = None,
  1211. ) -> list[Path]:
  1212. """Locate candidate bitstreams for optional binding (does not require TD rebuild)."""
  1213. candidates: list[Path] = []
  1214. search_roots = []
  1215. if evidence_root is not None:
  1216. search_roots.append(evidence_root.expanduser().resolve(strict=False))
  1217. search_roots.extend(
  1218. [
  1219. root / "evidence" / "bitstream",
  1220. root / "td" / "build",
  1221. ]
  1222. )
  1223. env_bit = os.environ.get("PRODU2_BITSTREAM_PATH", "").strip()
  1224. if env_bit:
  1225. candidates.append(Path(env_bit).expanduser())
  1226. for base in search_roots:
  1227. if not base.is_dir():
  1228. continue
  1229. candidates.extend(sorted(base.rglob("*.bit")))
  1230. named = base / "prod2u_p4_normal_v3.bit"
  1231. if named.is_file():
  1232. candidates.append(named)
  1233. fw = base / "fw.bit"
  1234. if fw.is_file():
  1235. candidates.append(fw)
  1236. # Deduplicate while preserving order.
  1237. seen: set[str] = set()
  1238. unique: list[Path] = []
  1239. for path in candidates:
  1240. key = str(path.resolve(strict=False))
  1241. if key in seen:
  1242. continue
  1243. seen.add(key)
  1244. if path.is_file():
  1245. unique.append(path)
  1246. return unique
  1247. def build_td_source_closure_binding(
  1248. root: Path,
  1249. *,
  1250. bitstream_path: Path | None = None,
  1251. td_report_paths: Iterable[Path] | None = None,
  1252. evidence_root: Path | None = None,
  1253. commit: str | None = None,
  1254. require_bitstream: bool = False,
  1255. ) -> dict[str, object]:
  1256. """Build TD source-closure binding; bind real bitstream when supplied.
  1257. Without a bitstream the status remains ``hook_ready`` (or ``hook_partial``).
  1258. When a bitstream (+ optional TD reports) is provided, status becomes ``bound``
  1259. with full commit SHA, source-manifest SHA, project SHA, and bitstream SHA-256.
  1260. Integrators supply the real tip bitstream later; this path must not stay
  1261. forever deferred once artifacts exist.
  1262. """
  1263. root = root.expanduser().resolve(strict=True)
  1264. manifest = root / "src" / "generated" / "td-source-manifest.json"
  1265. project = root / "projects" / "prod2u-door-temp" / "project.json"
  1266. commit_full = _resolve_commit_full(root, commit)
  1267. binding: dict[str, object] = {
  1268. "schema": "cpld-td-source-closure-binding-v1",
  1269. "status": "hook_ready",
  1270. "note": (
  1271. "Binding path accepts a real bitstream + full commit + source-manifest + "
  1272. "TD reports. When those artifacts are absent, status stays hook_ready; "
  1273. "it must not remain deferred once the integrator supplies them."
  1274. ),
  1275. "commit_full": commit_full,
  1276. "commit_short": commit_full[:8] if commit_full else None,
  1277. "td_source_manifest_path": "src/generated/td-source-manifest.json",
  1278. "td_source_manifest_sha256": None,
  1279. "project_config_path": "projects/prod2u-door-temp/project.json",
  1280. "project_config_sha256": None,
  1281. "bitstream": None,
  1282. "td_reports": [],
  1283. "bitstream_binding": "deferred_to_evidence_receipt",
  1284. # Legacy alias kept for older consumers still looking for the hook schema.
  1285. "legacy_schema_alias": "cpld-td-source-closure-binding-hook-v1",
  1286. }
  1287. if manifest.is_file():
  1288. binding["td_source_manifest_sha256"] = sha256_file(manifest)
  1289. else:
  1290. binding["status"] = "hook_partial"
  1291. if project.is_file():
  1292. binding["project_config_sha256"] = sha256_file(project)
  1293. else:
  1294. binding["status"] = "hook_partial"
  1295. resolved_bit = bitstream_path
  1296. if resolved_bit is None:
  1297. discovered = discover_bitstream_candidates(root, evidence_root=evidence_root)
  1298. if len(discovered) == 1:
  1299. resolved_bit = discovered[0]
  1300. elif len(discovered) > 1 and evidence_root is not None:
  1301. # Prefer evidence_root hits when multiple exist.
  1302. evidence_hits = [
  1303. path
  1304. for path in discovered
  1305. if str(path.resolve(strict=False)).startswith(
  1306. str(evidence_root.expanduser().resolve(strict=False))
  1307. )
  1308. ]
  1309. if len(evidence_hits) == 1:
  1310. resolved_bit = evidence_hits[0]
  1311. report_list = list(td_report_paths or [])
  1312. if not report_list and evidence_root is not None:
  1313. evidence = evidence_root.expanduser().resolve(strict=False)
  1314. for pattern in (
  1315. "**/td-primary-receipt.json",
  1316. "**/final_td_report.json",
  1317. "**/original-final_td_report.json",
  1318. "**/TD-PROVENANCE.json",
  1319. ):
  1320. report_list.extend(sorted(evidence.glob(pattern)))
  1321. binding["td_reports"] = _collect_td_report_bindings(report_list)
  1322. if resolved_bit is None:
  1323. if require_bitstream:
  1324. binding["status"] = "bind_failed"
  1325. binding["bitstream_binding"] = "missing_bitstream"
  1326. binding["note"] = "require_bitstream=true but no bitstream was provided or discovered"
  1327. return binding
  1328. bit_path = resolved_bit.expanduser().resolve(strict=False)
  1329. if not bit_path.is_file():
  1330. binding["status"] = "bind_failed"
  1331. binding["bitstream_binding"] = "missing_bitstream"
  1332. binding["bitstream"] = {"path": str(resolved_bit), "status": "missing"}
  1333. return binding
  1334. digest = sha256_file(bit_path)
  1335. if not SHA256_HEX_RE.fullmatch(digest):
  1336. binding["status"] = "bind_failed"
  1337. binding["bitstream_binding"] = "invalid_bitstream_sha256"
  1338. return binding
  1339. binding["bitstream"] = {
  1340. "path": str(bit_path),
  1341. "name": bit_path.name,
  1342. "sha256": digest,
  1343. "bytes": bit_path.stat().st_size,
  1344. "status": "present",
  1345. }
  1346. if (
  1347. commit_full
  1348. and binding.get("td_source_manifest_sha256")
  1349. and binding.get("project_config_sha256")
  1350. ):
  1351. binding["status"] = "bound"
  1352. binding["bitstream_binding"] = "bound"
  1353. binding["note"] = (
  1354. "Bound to real bitstream SHA-256, full commit, project config, "
  1355. "td-source-manifest, and any supplied TD reports."
  1356. )
  1357. else:
  1358. binding["status"] = "bind_partial"
  1359. binding["bitstream_binding"] = "partial"
  1360. binding["note"] = (
  1361. "Bitstream hashed but commit/manifest/project identity incomplete; "
  1362. "not a final closure binding."
  1363. )
  1364. return binding
  1365. def build_td_source_closure_binding_hook(
  1366. root: Path,
  1367. *,
  1368. bitstream_path: Path | None = None,
  1369. td_report_paths: Iterable[Path] | None = None,
  1370. evidence_root: Path | None = None,
  1371. commit: str | None = None,
  1372. require_bitstream: bool = False,
  1373. ) -> dict[str, object]:
  1374. """Compatibility wrapper: bind when artifacts exist, else hook_ready."""
  1375. return build_td_source_closure_binding(
  1376. root,
  1377. bitstream_path=bitstream_path,
  1378. td_report_paths=td_report_paths,
  1379. evidence_root=evidence_root,
  1380. commit=commit,
  1381. require_bitstream=require_bitstream,
  1382. )
  1383. def run_post_staging_reference_inventory_hook(
  1384. repo_root: Path,
  1385. *,
  1386. staging_complete: bool,
  1387. enabled: bool = True,
  1388. ) -> dict[str, object]:
  1389. """Refresh REFERENCE-INVENTORY only after staging completes (packager order).
  1390. Lane E owns inventory generator honesty / evidence-grade docs. Lane D only
  1391. enforces call order: inventory refresh must not run before staging finishes.
  1392. """
  1393. repo_root = repo_root.expanduser().resolve(strict=True)
  1394. report: dict[str, object] = {
  1395. "schema": "cpld-reference-inventory-post-staging-hook-v1",
  1396. "staging_complete": staging_complete,
  1397. "enabled": enabled,
  1398. "status": "not_run",
  1399. "command": None,
  1400. "note": (
  1401. "Packager order: finish reference staging, then refresh inventory, "
  1402. "then finalize the reference volume."
  1403. ),
  1404. }
  1405. if not enabled:
  1406. report["status"] = "skipped_disabled"
  1407. return report
  1408. if not staging_complete:
  1409. report["status"] = "blocked_staging_incomplete"
  1410. report["note"] = "Refusing inventory refresh before staging_complete=true"
  1411. return report
  1412. refresh_py = repo_root / "tools" / "board-viewer" / "refresh_reference_inventory.py"
  1413. if not refresh_py.is_file():
  1414. report["status"] = "blocked_missing_refresher"
  1415. return report
  1416. command = [sys.executable, "-B", str(refresh_py), "--root", str(repo_root)]
  1417. report["command"] = command
  1418. code, payload = run_capture(command, cwd=repo_root, timeout=300)
  1419. report["returncode"] = code
  1420. report["output_tail"] = payload.decode("utf-8", errors="replace")[-2000:]
  1421. report["status"] = "pass" if code == 0 else "fail"
  1422. return report
  1423. _SANITIZED_SNAPSHOT_SKIP_PREFIXES = (
  1424. "reference/original/",
  1425. "node_modules/",
  1426. ".venv/",
  1427. "venv/",
  1428. "__pycache__/",
  1429. ".git/",
  1430. "tmp/",
  1431. "tools/board-viewer/node_modules/",
  1432. )
  1433. _SANITIZED_SNAPSHOT_SKIP_SUFFIXES = (
  1434. ".pdf",
  1435. ".brd",
  1436. ".dsn",
  1437. ".zip",
  1438. ".7z",
  1439. ".rar",
  1440. ".bundle",
  1441. )
  1442. _SANITIZED_SNAPSHOT_FIXTURE_KEEP = "tests/board_viewer/fixtures/"
  1443. def allow_sanitized_snapshot_path(relative: str) -> bool:
  1444. """Filter tracked paths for the optional synthetic single-commit snapshot."""
  1445. rel = relative.replace("\\", "/").lstrip("./")
  1446. lower = rel.casefold()
  1447. if any(lower.startswith(prefix) for prefix in _SANITIZED_SNAPSHOT_SKIP_PREFIXES):
  1448. return False
  1449. if lower.startswith(_SANITIZED_SNAPSHOT_FIXTURE_KEEP.casefold()):
  1450. return True
  1451. if any(lower.endswith(suffix) for suffix in _SANITIZED_SNAPSHOT_SKIP_SUFFIXES):
  1452. return False
  1453. name = lower.rsplit("/", 1)[-1]
  1454. if name.startswith(".run_id"):
  1455. return False
  1456. return True
  1457. def create_sanitized_git_snapshot(
  1458. root: Path,
  1459. *,
  1460. git: str,
  1461. original_head: str | None,
  1462. temp_root: Path,
  1463. meta_prefix: str = "meta/git",
  1464. file_rels: Iterable[str] | None = None,
  1465. ) -> tuple[dict[str, object], dict[str, bytes]]:
  1466. """Build a synthetic single-commit git bundle with synthetic→original mapping.
  1467. The synthetic commit must never be presented as the original tip.
  1468. """
  1469. work = temp_root / "sanitized-git-snapshot-work"
  1470. if work.exists():
  1471. shutil.rmtree(work)
  1472. work.mkdir(parents=True, exist_ok=True)
  1473. code, _ = run_capture([git, "init", "-q"], cwd=work)
  1474. if code != 0:
  1475. status = {
  1476. "requested": True,
  1477. "status": "fail_git_init",
  1478. "original_commit": original_head,
  1479. "impersonates_original_tip": False,
  1480. }
  1481. return status, {f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)}
  1482. for cfg_key, cfg_val in (
  1483. ("user.name", "Prod2U Sanitized Snapshot"),
  1484. ("user.email", "sanitized-snapshot@invalid.local"),
  1485. ):
  1486. run_capture([git, "config", cfg_key, cfg_val], cwd=work)
  1487. selected: list[str] = []
  1488. if file_rels is None:
  1489. ls_files = _git_bytes(git, ["ls-files", "-z"], cwd=root)
  1490. if ls_files is None:
  1491. status = {
  1492. "requested": True,
  1493. "status": "fail_ls_files",
  1494. "original_commit": original_head,
  1495. "impersonates_original_tip": False,
  1496. }
  1497. return status, {
  1498. f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)
  1499. }
  1500. file_rels = [
  1501. raw.decode("utf-8", errors="surrogateescape")
  1502. for raw in ls_files.split(b"\0")
  1503. if raw
  1504. ]
  1505. for rel in file_rels:
  1506. if not allow_sanitized_snapshot_path(rel):
  1507. continue
  1508. src = root / Path(*rel.split("/"))
  1509. if not src.is_file():
  1510. continue
  1511. dest = work / Path(*rel.split("/"))
  1512. dest.parent.mkdir(parents=True, exist_ok=True)
  1513. shutil.copy2(src, dest)
  1514. selected.append(rel.replace("\\", "/"))
  1515. selected.sort()
  1516. if not selected:
  1517. status = {
  1518. "requested": True,
  1519. "status": "fail_empty_snapshot",
  1520. "original_commit": original_head,
  1521. "impersonates_original_tip": False,
  1522. "file_count": 0,
  1523. }
  1524. return status, {f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)}
  1525. code, _ = run_capture([git, "add", "-A"], cwd=work)
  1526. if code != 0:
  1527. status = {
  1528. "requested": True,
  1529. "status": "fail_git_add",
  1530. "original_commit": original_head,
  1531. "impersonates_original_tip": False,
  1532. }
  1533. return status, {f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)}
  1534. message = (
  1535. f"synthetic sanitized snapshot of {original_head or 'unknown'}\n\n"
  1536. "This is a synthetic single-commit snapshot for detached review.\n"
  1537. "It does NOT impersonate the original tip commit.\n"
  1538. )
  1539. code, _ = run_capture([git, "commit", "-q", "-m", message], cwd=work)
  1540. if code != 0:
  1541. status = {
  1542. "requested": True,
  1543. "status": "fail_git_commit",
  1544. "original_commit": original_head,
  1545. "impersonates_original_tip": False,
  1546. }
  1547. return status, {f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)}
  1548. synthetic_raw = _git_bytes(git, ["rev-parse", "HEAD"], cwd=work)
  1549. synthetic = (
  1550. synthetic_raw.decode("utf-8", errors="replace").strip()
  1551. if synthetic_raw is not None
  1552. else None
  1553. )
  1554. if not synthetic or synthetic == original_head:
  1555. status = {
  1556. "requested": True,
  1557. "status": "fail_synthetic_identity",
  1558. "original_commit": original_head,
  1559. "synthetic_commit": synthetic,
  1560. "impersonates_original_tip": False,
  1561. "note": "Synthetic commit must be distinct from original tip.",
  1562. }
  1563. return status, {f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)}
  1564. bundle_path = temp_root / "sanitized-snapshot.bundle"
  1565. code, verify = run_capture(
  1566. [git, "bundle", "create", str(bundle_path), "HEAD"],
  1567. cwd=work,
  1568. )
  1569. if code != 0 or not bundle_path.is_file():
  1570. status = {
  1571. "requested": True,
  1572. "status": "fail_bundle_create",
  1573. "original_commit": original_head,
  1574. "synthetic_commit": synthetic,
  1575. "impersonates_original_tip": False,
  1576. "detail": verify.decode("utf-8", errors="replace")[:500],
  1577. }
  1578. return status, {f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)}
  1579. mapping = {
  1580. "schema": "cpld-sanitized-git-snapshot-mapping-v1",
  1581. "synthetic_commit": synthetic,
  1582. "original_commit": original_head,
  1583. "impersonates_original_tip": False,
  1584. "file_count": len(selected),
  1585. "files": selected,
  1586. "note": (
  1587. "Synthetic→original mapping only. Consumers must treat synthetic_commit "
  1588. "as a packaging artifact, never as the repository tip."
  1589. ),
  1590. }
  1591. status = {
  1592. "requested": True,
  1593. "status": "pass",
  1594. "synthetic_commit": synthetic,
  1595. "original_commit": original_head,
  1596. "impersonates_original_tip": False,
  1597. "bundle_path": f"{meta_prefix}/sanitized-snapshot.bundle",
  1598. "mapping_path": f"{meta_prefix}/sanitized-snapshot-mapping.json",
  1599. "file_count": len(selected),
  1600. "note": (
  1601. "Optional sanitized synthetic single-commit snapshot. "
  1602. "Records synthetic→original mapping and must not impersonate the original tip."
  1603. ),
  1604. }
  1605. artifacts = {
  1606. f"{meta_prefix}/sanitized-snapshot.bundle": bundle_path.read_bytes(),
  1607. f"{meta_prefix}/sanitized-snapshot-mapping.json": json_bytes(mapping),
  1608. f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status),
  1609. }
  1610. return status, artifacts
  1611. def collect_review_git_provenance(
  1612. root: Path,
  1613. *,
  1614. include_sanitized_git_snapshot: bool = False,
  1615. meta_prefix: str = "meta/git",
  1616. temp_root: Path | None = None,
  1617. ) -> tuple[dict[str, object], dict[str, bytes]]:
  1618. """Git provenance for review-* packages: no full bundle; commit/status/log/tree/hashes."""
  1619. git_dir = resolve_git_dir(root)
  1620. artifacts: dict[str, bytes] = {}
  1621. if git_dir is None:
  1622. metadata: dict[str, object] = {
  1623. "status": "not_a_git_worktree",
  1624. "branch": None,
  1625. "head": None,
  1626. "tool": None,
  1627. "full_bundle": False,
  1628. "sanitized_git_snapshot": {
  1629. "requested": include_sanitized_git_snapshot,
  1630. "status": "not_applicable",
  1631. },
  1632. }
  1633. artifacts[f"{meta_prefix}/sanitized-snapshot-status.json"] = json_bytes(
  1634. metadata["sanitized_git_snapshot"]
  1635. )
  1636. return metadata, artifacts
  1637. branch, head = read_head_metadata(git_dir)
  1638. git = shutil.which("git")
  1639. if not git:
  1640. return {
  1641. "status": "blocked_missing_git_tool",
  1642. "branch": branch,
  1643. "head": head,
  1644. "tool": None,
  1645. "full_bundle": False,
  1646. "sanitized_git_snapshot": {
  1647. "requested": include_sanitized_git_snapshot,
  1648. "status": "blocked_missing_git_tool",
  1649. },
  1650. }, {
  1651. f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(
  1652. {
  1653. "requested": include_sanitized_git_snapshot,
  1654. "status": "blocked_missing_git_tool",
  1655. }
  1656. )
  1657. }
  1658. status_payload = _git_bytes(
  1659. git,
  1660. [
  1661. "--no-optional-locks",
  1662. "-c",
  1663. "core.fsmonitor=false",
  1664. "-c",
  1665. "core.untrackedCache=false",
  1666. "status",
  1667. "--short",
  1668. "--branch",
  1669. "--untracked-files=all",
  1670. ],
  1671. cwd=root,
  1672. )
  1673. log_payload = _git_bytes(
  1674. git,
  1675. ["log", "-20", "--format=%H %ad %s", "--date=iso-strict"],
  1676. cwd=root,
  1677. )
  1678. rev_parse = _git_bytes(git, ["rev-parse", "HEAD"], cwd=root)
  1679. if rev_parse is not None:
  1680. head = rev_parse.decode("utf-8", errors="replace").strip() or head
  1681. ls_files = _git_bytes(git, ["ls-files", "-z"], cwd=root)
  1682. tree_rows: list[dict[str, object]] = []
  1683. file_hashes: dict[str, str] = {}
  1684. file_rels: list[str] = []
  1685. if ls_files is not None:
  1686. for raw in ls_files.split(b"\0"):
  1687. if not raw:
  1688. continue
  1689. rel = raw.decode("utf-8", errors="surrogateescape")
  1690. file_rels.append(rel)
  1691. path = root / Path(*rel.split("/"))
  1692. if not path.is_file():
  1693. continue
  1694. digest = sha256_file(path)
  1695. file_hashes[rel] = digest
  1696. tree_rows.append({"path": rel, "sha256": digest, "size": path.stat().st_size})
  1697. tree_rows.sort(key=lambda row: str(row["path"]))
  1698. artifacts[f"{meta_prefix}/HEAD.txt"] = f"{head or ''}\n".encode("utf-8")
  1699. if branch:
  1700. artifacts[f"{meta_prefix}/branch.txt"] = f"{branch}\n".encode("utf-8")
  1701. if status_payload is not None:
  1702. artifacts[f"{meta_prefix}/status.txt"] = status_payload
  1703. if log_payload is not None:
  1704. artifacts[f"{meta_prefix}/log-20.txt"] = log_payload
  1705. artifacts[f"{meta_prefix}/tree-manifest.json"] = json_bytes(
  1706. {
  1707. "schema": "cpld-review-git-tree-manifest-v1",
  1708. "head": head,
  1709. "file_count": len(tree_rows),
  1710. "files": tree_rows,
  1711. }
  1712. )
  1713. file_sha_payload = json_bytes(
  1714. {
  1715. "schema": "cpld-review-git-file-sha256-v1",
  1716. "head": head,
  1717. "files": file_hashes,
  1718. }
  1719. )
  1720. # Canonical name per finalize layout; keep legacy alias for older consumers.
  1721. artifacts[f"{meta_prefix}/source-file-sha256.json"] = file_sha_payload
  1722. artifacts[f"{meta_prefix}/file-sha256.json"] = file_sha_payload
  1723. if include_sanitized_git_snapshot:
  1724. snap_temp = temp_root if temp_root is not None else Path(
  1725. tempfile.mkdtemp(prefix="prod2u-sanitized-git-", dir=os.environ.get("TMPDIR", "/tmp"))
  1726. )
  1727. snap_temp.mkdir(parents=True, exist_ok=True)
  1728. snapshot_status, snap_artifacts = create_sanitized_git_snapshot(
  1729. root,
  1730. git=git,
  1731. original_head=head,
  1732. temp_root=snap_temp,
  1733. meta_prefix=meta_prefix,
  1734. file_rels=file_rels,
  1735. )
  1736. artifacts.update(snap_artifacts)
  1737. else:
  1738. snapshot_status = {
  1739. "requested": False,
  1740. "status": "not_requested",
  1741. "impersonates_original_tip": False,
  1742. "note": (
  1743. "Optional sanitized synthetic single-commit snapshot via "
  1744. "--include-sanitized-git-snapshot. When present it records "
  1745. "synthetic→original mapping and must not impersonate the original tip."
  1746. ),
  1747. }
  1748. artifacts[f"{meta_prefix}/sanitized-snapshot-status.json"] = json_bytes(
  1749. snapshot_status
  1750. )
  1751. capture_status = "pass"
  1752. if status_payload is None or log_payload is None or ls_files is None:
  1753. capture_status = "partial"
  1754. return {
  1755. "status": capture_status,
  1756. "branch": branch,
  1757. "head": head,
  1758. "tool": "git",
  1759. "full_bundle": False,
  1760. "status_captured": status_payload is not None,
  1761. "log20_captured": log_payload is not None,
  1762. "tree_manifest_files": len(tree_rows),
  1763. "sanitized_git_snapshot": snapshot_status,
  1764. }, artifacts
  1765. def build_size_budget(
  1766. inventory: list[dict[str, object]],
  1767. *,
  1768. zip_total_bytes: int | None = None,
  1769. ) -> dict[str, object]:
  1770. """Members ≥256KiB or >1% of ZIP (when known) enter the size-budget table."""
  1771. total = int(zip_total_bytes) if zip_total_bytes is not None else sum(
  1772. int(item.get("size", 0)) for item in inventory
  1773. )
  1774. rows: list[dict[str, object]] = []
  1775. for item in inventory:
  1776. size = int(item.get("size", 0))
  1777. share = (size / total) if total > 0 else 0.0
  1778. if size >= SIZE_BUDGET_MIN_BYTES or share > SIZE_BUDGET_MIN_SHARE:
  1779. rows.append(
  1780. {
  1781. "path": str(item.get("path", "")),
  1782. "size": size,
  1783. "share_of_total": round(share, 6),
  1784. "reason": (
  1785. "gte_256kiB"
  1786. if size >= SIZE_BUDGET_MIN_BYTES
  1787. else "gt_1pct_of_package"
  1788. ),
  1789. }
  1790. )
  1791. rows.sort(key=lambda row: (-int(row["size"]), str(row["path"]).casefold()))
  1792. return {
  1793. "schema": "cpld-review-size-budget-v1",
  1794. "total_bytes_basis": total,
  1795. "threshold_bytes": SIZE_BUDGET_MIN_BYTES,
  1796. "threshold_share": SIZE_BUDGET_MIN_SHARE,
  1797. "members": rows,
  1798. }
  1799. def package_purpose_text(profile: str, *, package_name: str) -> str:
  1800. lines = [
  1801. f"PACKAGE-PURPOSE: {package_name}",
  1802. f"profile: {profile}",
  1803. f"delivery_policy: {delivery_policy_for_profile(profile)}",
  1804. "",
  1805. ]
  1806. if profile == "review-compact":
  1807. lines.extend(
  1808. [
  1809. "Default remote-agent upload package.",
  1810. "Layout: source/ (active code+tests) + evidence/ (canonical final receipts, derived board-viewer) + meta/.",
  1811. "Does NOT include a full Git bundle, PDF/BRD/DSN originals, vendor installer zips, or license material.",
  1812. "Git provenance is commit/status/log-20/tree manifest/per-file SHA-256 plus TD source-closure binding.",
  1813. "meta/td-source-closure-binding.json binds real bitstream SHA-256 + full commit + source-manifest + TD reports when supplied; otherwise hook_ready until the integrator provides the tip bit.",
  1814. "Evidence is physically deduplicated; process lane receipts / matrix reruns require review-debug or --include-process-evidence.",
  1815. "Result-sensitive logs: PASS/not_run keep summaries; FAIL/BLOCKED/TIMEOUT/CRASH keep full evidence.",
  1816. "Hardware validation remains not_run unless a future task authorizes it.",
  1817. ]
  1818. )
  1819. elif profile == "review-debug":
  1820. lines.extend(
  1821. [
  1822. "Debug-oriented review package (unified layout).",
  1823. "Same heavy-original exclusions as review-compact; includes process evidence by default.",
  1824. "Still omits full Git history bundles by default.",
  1825. ]
  1826. )
  1827. elif profile == "archive-local":
  1828. lines.extend(
  1829. [
  1830. "Local archival package (not the default upload).",
  1831. "May include a full Git bundle / --include-full-history for offline restore.",
  1832. "Still uses unified source/evidence/meta layout.",
  1833. ]
  1834. )
  1835. else:
  1836. lines.append("Legacy inclusion-first or code-only analysis handoff.")
  1837. lines.append("")
  1838. return "\n".join(lines)
  1839. def build_metadata(
  1840. *,
  1841. package_name: str,
  1842. profile: str,
  1843. inventory: list[dict[str, object]],
  1844. excluded: list[dict[str, str]],
  1845. context: ScanContext,
  1846. provenance: dict[str, object],
  1847. ) -> dict[str, bytes]:
  1848. rule_counts = Counter(item["rule"] for item in excluded)
  1849. derived_evidence = []
  1850. for item in inventory:
  1851. path = str(item["path"])
  1852. name = path.casefold().rsplit("/", 1)[-1]
  1853. if name not in CODE_ONLY_GENERATED_VISUAL_ASSETS and name not in {
  1854. "board-data.json",
  1855. "build-info.json",
  1856. "import-report.json",
  1857. }:
  1858. continue
  1859. if "tools/board-viewer/generated/" not in path.casefold():
  1860. continue
  1861. role = (
  1862. "derived_from_brd_visual"
  1863. if name in CODE_ONLY_GENERATED_VISUAL_ASSETS
  1864. else "derived_from_brd_parsed"
  1865. )
  1866. derived_evidence.append(
  1867. {
  1868. "path": path,
  1869. "asset": name,
  1870. "role": role,
  1871. "authority": "analysis_evidence_not_source_closure",
  1872. "note": "Derived from the original Allegro BRD for remote analysis; not RTL/TD source closure.",
  1873. }
  1874. )
  1875. authority_boundary = (
  1876. "Inclusion-first analysis handoff of source, requirements, tests, original references, "
  1877. "board-viewer derived evidence (JSON/SVG labeled not source closure), and retained evidence. "
  1878. "It excludes credentials, license archives, vendor installers, caches, node_modules, venvs, "
  1879. "raw Git objects, and declared reconstructable runtime outputs."
  1880. )
  1881. if profile == "code-only":
  1882. authority_boundary = (
  1883. "This archive is a code-and-tests-only analysis handoff. It excludes reference materials, "
  1884. "generated board-viewer visual assets, credentials, private archives, raw Git objects, "
  1885. "and declared reconstructable runtime outputs."
  1886. )
  1887. derived_evidence = []
  1888. elif is_review_profile(profile):
  1889. authority_boundary = (
  1890. "Unified review package (source/evidence/meta). Keeps board-viewer derived assets and "
  1891. "small test fixtures; excludes PDF/BRD/DSN originals, vendor installers, license material, "
  1892. "caches, venvs, node_modules, and full Git bundles unless archive-local/--include-full-history."
  1893. )
  1894. manifest = {
  1895. "schema": "cpld-agent-handoff-v1",
  1896. "status": "pass",
  1897. "created_at": utc_now(),
  1898. "package_name": package_name,
  1899. "profile": profile,
  1900. "delivery_policy": delivery_policy_for_profile(profile),
  1901. "archive_root": ARCHIVE_ROOT,
  1902. "source_name": ARCHIVE_ROOT,
  1903. "included_file_count": len(inventory),
  1904. "included_bytes": sum(int(item["size"]) for item in inventory),
  1905. "excluded_entry_count": len(excluded),
  1906. "exclusion_rule_counts": dict(sorted(rule_counts.items())),
  1907. "derived_evidence": derived_evidence,
  1908. "changxin_temp_uart_version": context.changxin_version,
  1909. "git_provenance": provenance,
  1910. "archive_scan_limits": {
  1911. "max_depth": MAX_ARCHIVE_DEPTH,
  1912. "max_members": MAX_ARCHIVE_MEMBERS,
  1913. "max_uncompressed_bytes": MAX_ARCHIVE_UNCOMPRESSED_BYTES,
  1914. "source_file_size_limit": None,
  1915. },
  1916. "privacy": {
  1917. "manifest_contains_absolute_source_path": False,
  1918. "note": "Repository files are preserved byte-for-byte; review document and receipt contents before crossing a trust boundary.",
  1919. },
  1920. "authority_boundary": authority_boundary,
  1921. }
  1922. exclusions_payload = {
  1923. "schema": "cpld-agent-handoff-exclusions-v1",
  1924. "excluded": excluded,
  1925. "rule_counts": dict(sorted(rule_counts.items())),
  1926. }
  1927. inventory_payload = {
  1928. "schema": "cpld-agent-handoff-sha256-inventory-v1",
  1929. "inventory": inventory,
  1930. }
  1931. return {
  1932. f"{METADATA_ROOT}/manifest.json": json_bytes(manifest),
  1933. f"{METADATA_ROOT}/exclusions.json": json_bytes(exclusions_payload),
  1934. f"{METADATA_ROOT}/sha256-inventory.json": json_bytes(inventory_payload),
  1935. }
  1936. def validate_zip_entry(name: str) -> str:
  1937. if not name.startswith(ARCHIVE_ROOT + "/") or "\\" in name or name.startswith("/"):
  1938. raise PackagingError(f"unsafe ZIP entry: {name}")
  1939. relative = name[len(ARCHIVE_ROOT) + 1 :]
  1940. normalize_relative(relative.split("/"))
  1941. return windows_collision_key(name)
  1942. def verify_archive(
  1943. path: Path | BinaryIO,
  1944. *,
  1945. expected_names: set[str],
  1946. inventory: list[dict[str, object]],
  1947. expected_payloads: dict[str, bytes] | None = None,
  1948. ) -> None:
  1949. try:
  1950. with zipfile.ZipFile(path, "r", allowZip64=True) as archive:
  1951. names = archive.namelist()
  1952. if len(names) != len(set(names)):
  1953. raise PackagingError("ZIP contains duplicate entry names")
  1954. file_names = [name for name in names if not name.endswith("/")]
  1955. collision_keys: dict[str, str] = {}
  1956. for name in names:
  1957. if name.endswith("/"):
  1958. if name == ARCHIVE_ROOT + "/":
  1959. continue
  1960. if not name.startswith(ARCHIVE_ROOT + "/"):
  1961. raise PackagingError(f"unsafe ZIP directory entry: {name}")
  1962. relative_directory = name[len(ARCHIVE_ROOT) + 1 :].removesuffix("/")
  1963. normalize_relative(relative_directory.split("/"))
  1964. continue
  1965. key = validate_zip_entry(name)
  1966. previous = collision_keys.get(key)
  1967. if previous is not None and previous != name:
  1968. raise PackagingError(f"ZIP contains a Windows path collision: {previous} and {name}")
  1969. collision_keys[key] = name
  1970. if set(file_names) != expected_names:
  1971. missing = sorted(expected_names - set(file_names))
  1972. unexpected = sorted(set(file_names) - expected_names)
  1973. raise PackagingError(f"ZIP entry verification failed; missing={missing}, unexpected={unexpected}")
  1974. bad = archive.testzip()
  1975. if bad is not None:
  1976. raise PackagingError(f"ZIP CRC verification failed for {bad}")
  1977. for item in inventory:
  1978. entry_name = f"{ARCHIVE_ROOT}/{item['path']}"
  1979. digest = hashlib.sha256()
  1980. total = 0
  1981. with archive.open(entry_name, "r") as handle:
  1982. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  1983. digest.update(chunk)
  1984. total += len(chunk)
  1985. if total != item["size"] or digest.hexdigest() != item["sha256"]:
  1986. raise PackagingError(f"ZIP SHA256 verification failed for {item['path']}")
  1987. for name, expected_payload in (expected_payloads or {}).items():
  1988. if archive.read(name) != expected_payload:
  1989. raise PackagingError(f"ZIP generated metadata verification failed for {name}")
  1990. except (OSError, zipfile.BadZipFile) as exc:
  1991. raise PackagingError(f"unable to verify ZIP archive: {exc}") from exc
  1992. def publish_target_identity(file_stat: os.stat_result) -> tuple[int, int, int, int, int]:
  1993. return (
  1994. int(file_stat.st_dev),
  1995. int(file_stat.st_ino),
  1996. int(file_stat.st_mode),
  1997. int(file_stat.st_size),
  1998. int(file_stat.st_mtime_ns),
  1999. )
  2000. def stat_is_windows_read_only(file_stat: os.stat_result) -> bool:
  2001. attributes = int(getattr(file_stat, "st_file_attributes", 0))
  2002. read_only_flag = int(getattr(stat, "FILE_ATTRIBUTE_READONLY", 0))
  2003. return bool(read_only_flag and attributes & read_only_flag)
  2004. def stat_is_read_only(file_stat: os.stat_result) -> bool:
  2005. return stat_is_windows_read_only(file_stat) or (int(file_stat.st_mode) & 0o222) == 0
  2006. def validate_publish_targets(paths: Iterable[Path], *, force: bool) -> dict[Path, tuple[int, int, int, int, int]]:
  2007. existing: dict[Path, tuple[int, int, int, int, int]] = {}
  2008. for path in paths:
  2009. if not os.path.lexists(path):
  2010. continue
  2011. if not force:
  2012. raise PackagingError(f"package artifact already exists: {path.name}")
  2013. try:
  2014. file_stat = os.lstat(path)
  2015. except OSError as exc:
  2016. raise PackagingError(f"unable to inspect existing package artifact {path.name}: {exc}") from exc
  2017. if not stat.S_ISREG(file_stat.st_mode) or stat_is_reparse_point(file_stat):
  2018. raise PackagingError(f"existing package artifact is not a regular file: {path.name}")
  2019. if stat_is_read_only(file_stat):
  2020. raise PackagingError(f"existing package artifact is read-only: {path.name}")
  2021. existing[path] = publish_target_identity(file_stat)
  2022. return existing
  2023. def publish_artifacts_atomically(
  2024. artifacts: list[tuple[Path, Path]],
  2025. *,
  2026. force: bool,
  2027. verify_published: Callable[[], None] | None = None,
  2028. ) -> list[str]:
  2029. backups: dict[Path, Path] = {}
  2030. published: list[Path] = []
  2031. final_paths = [final_path for _, final_path in artifacts]
  2032. existing = validate_publish_targets(final_paths, force=force)
  2033. try:
  2034. for _, final_path in artifacts:
  2035. expected_identity = existing.get(final_path)
  2036. if expected_identity is not None:
  2037. try:
  2038. current = os.lstat(final_path)
  2039. except OSError as exc:
  2040. raise PackagingError(f"existing package artifact changed before publication: {final_path.name}") from exc
  2041. if (
  2042. not stat.S_ISREG(current.st_mode)
  2043. or stat_is_reparse_point(current)
  2044. or stat_is_read_only(current)
  2045. or publish_target_identity(current) != expected_identity
  2046. ):
  2047. raise PackagingError(f"existing package artifact changed before publication: {final_path.name}")
  2048. backup = final_path.with_name(f".{final_path.name}.{uuid.uuid4().hex}.backup")
  2049. os.replace(final_path, backup)
  2050. backups[final_path] = backup
  2051. elif os.path.lexists(final_path):
  2052. raise PackagingError(f"package artifact appeared during publication: {final_path.name}")
  2053. for temp_path, final_path in artifacts:
  2054. os.link(temp_path, final_path)
  2055. published.append(final_path)
  2056. if verify_published is not None:
  2057. verify_published()
  2058. except BaseException as exc:
  2059. rollback_errors: list[str] = []
  2060. for final_path in reversed(published):
  2061. if final_path in backups:
  2062. continue
  2063. try:
  2064. final_path.unlink(missing_ok=True)
  2065. except OSError as rollback_exc:
  2066. rollback_errors.append(
  2067. f"remove {final_path.name} ({type(rollback_exc).__name__})"
  2068. )
  2069. for final_path, backup in backups.items():
  2070. if os.path.lexists(backup):
  2071. try:
  2072. os.replace(backup, final_path)
  2073. except OSError as rollback_exc:
  2074. rollback_errors.append(
  2075. f"restore {final_path.name} from {backup.name} ({type(rollback_exc).__name__})"
  2076. )
  2077. if rollback_errors:
  2078. recovery_paths = sorted(
  2079. str(path)
  2080. for path in (*backups.values(), *published)
  2081. if os.path.lexists(path)
  2082. )
  2083. recovery = ", ".join(recovery_paths) if recovery_paths else "none"
  2084. details = "; ".join(rollback_errors)
  2085. raise PackagingError(
  2086. f"package publication failed and rollback was incomplete: {details}; "
  2087. f"manual recovery paths: {recovery}"
  2088. ) from exc
  2089. if isinstance(exc, PackagingError):
  2090. raise
  2091. if isinstance(exc, OSError):
  2092. raise PackagingError(f"unable to publish package artifacts atomically: {exc}") from exc
  2093. raise
  2094. cleanup_warnings: list[str] = []
  2095. for temp_path, _ in artifacts:
  2096. try:
  2097. temp_path.unlink(missing_ok=True)
  2098. except OSError as exc:
  2099. cleanup_warnings.append(
  2100. f"published temporary artifact could not be removed: {temp_path.name} ({type(exc).__name__})"
  2101. )
  2102. for backup in backups.values():
  2103. try:
  2104. backup.unlink(missing_ok=True)
  2105. except OSError as exc:
  2106. cleanup_warnings.append(
  2107. f"published artifact backup could not be removed: {backup.name} ({type(exc).__name__})"
  2108. )
  2109. return cleanup_warnings
  2110. def remove_partial_artifacts(paths: Iterable[Path]) -> None:
  2111. failures: list[str] = []
  2112. for path in paths:
  2113. try:
  2114. path.unlink(missing_ok=True)
  2115. except OSError:
  2116. failures.append(path.name)
  2117. if failures:
  2118. names = ", ".join(sorted(failures))
  2119. raise PackagingError(f"unable to remove partial package artifacts: {names}")
  2120. @contextmanager
  2121. def open_stable_regular_file(path: Path, label: str) -> Iterator[BinaryIO]:
  2122. try:
  2123. before = os.lstat(path)
  2124. except OSError as exc:
  2125. raise PackagingError(f"unable to inspect {label}: {exc}") from exc
  2126. if not stat.S_ISREG(before.st_mode) or stat_is_reparse_point(before):
  2127. raise PackagingError(f"published artifact is not a regular file: {label}")
  2128. flags = os.O_RDONLY
  2129. flags |= int(getattr(os, "O_BINARY", 0))
  2130. flags |= int(getattr(os, "O_NOINHERIT", 0))
  2131. flags |= int(getattr(os, "O_NOFOLLOW", 0))
  2132. try:
  2133. descriptor = os.open(path, flags)
  2134. except OSError as exc:
  2135. raise PackagingError(f"unable to open {label} without following links: {exc}") from exc
  2136. handle: BinaryIO | None = None
  2137. try:
  2138. opened = os.fstat(descriptor)
  2139. if publish_target_identity(opened) != publish_target_identity(before):
  2140. raise PackagingError(f"published artifact changed while opening: {label}")
  2141. handle = os.fdopen(descriptor, "rb", closefd=True)
  2142. descriptor = -1
  2143. yield handle
  2144. opened_after = os.fstat(handle.fileno())
  2145. if publish_target_identity(opened_after) != publish_target_identity(opened):
  2146. raise PackagingError(f"published artifact changed while reading: {label}")
  2147. finally:
  2148. if handle is not None:
  2149. handle.close()
  2150. if descriptor >= 0:
  2151. os.close(descriptor)
  2152. try:
  2153. after = os.lstat(path)
  2154. except OSError as exc:
  2155. raise PackagingError(f"unable to re-inspect {label}: {exc}") from exc
  2156. if publish_target_identity(after) != publish_target_identity(before):
  2157. raise PackagingError(f"published artifact changed during verification: {label}")
  2158. def read_stable_regular_bytes(path: Path, label: str, *, max_bytes: int) -> bytes:
  2159. with open_stable_regular_file(path, label) as handle:
  2160. payload = handle.read(max_bytes + 1)
  2161. if len(payload) > max_bytes:
  2162. raise PackagingError(f"regular file exceeds safe metadata read limit: {label}")
  2163. return payload
  2164. def verify_published_artifacts(
  2165. final_zip: Path,
  2166. final_sidecar: Path,
  2167. *,
  2168. expected_zip_sha256: str,
  2169. expected_sidecar: bytes,
  2170. expected_names: set[str],
  2171. inventory: list[dict[str, object]],
  2172. expected_payloads: dict[str, bytes],
  2173. ) -> None:
  2174. digest = hashlib.sha256()
  2175. with open_stable_regular_file(final_zip, final_zip.name) as handle:
  2176. verify_archive(
  2177. handle,
  2178. expected_names=expected_names,
  2179. inventory=inventory,
  2180. expected_payloads=expected_payloads,
  2181. )
  2182. handle.seek(0)
  2183. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  2184. digest.update(chunk)
  2185. if digest.hexdigest() != expected_zip_sha256:
  2186. raise PackagingError("published ZIP SHA256 does not match the verified package")
  2187. with open_stable_regular_file(final_sidecar, final_sidecar.name) as handle:
  2188. actual_sidecar = handle.read()
  2189. if actual_sidecar != expected_sidecar:
  2190. raise PackagingError("published SHA256 sidecar does not match the verified package")
  2191. def scan_snapshot(
  2192. candidates: Iterable[Candidate],
  2193. excluded: Iterable[dict[str, str]],
  2194. context: ScanContext,
  2195. ) -> tuple[tuple[tuple[object, ...], ...], tuple[tuple[str, str], ...], ScanContext]:
  2196. candidate_state = tuple(
  2197. (
  2198. item.relative,
  2199. item.size,
  2200. item.mtime_ns,
  2201. item.device,
  2202. item.inode,
  2203. item.mode,
  2204. )
  2205. for item in candidates
  2206. )
  2207. excluded_state = tuple((item["path"], item["rule"]) for item in excluded)
  2208. return candidate_state, excluded_state, context
  2209. def assert_source_tree_unchanged(
  2210. root: Path,
  2211. candidates: list[Candidate],
  2212. excluded: list[dict[str, str]],
  2213. context: ScanContext,
  2214. inventory: list[dict[str, object]],
  2215. *,
  2216. exclusion_resolver: Callable[..., str | None] | None = None,
  2217. ) -> None:
  2218. current_candidates, current_excluded, current_context = scan_tree(
  2219. root,
  2220. exclusion_resolver=exclusion_resolver,
  2221. profile=context.profile,
  2222. )
  2223. if scan_snapshot(candidates, excluded, context) != scan_snapshot(
  2224. current_candidates,
  2225. current_excluded,
  2226. current_context,
  2227. ):
  2228. raise PackagingError("source tree changed during packaging; retry from a stable workspace snapshot")
  2229. expected_by_path = {str(item["path"]): item for item in inventory}
  2230. if len(expected_by_path) != len(current_candidates):
  2231. raise PackagingError("source tree changed during packaging; retry from a stable workspace snapshot")
  2232. for candidate in current_candidates:
  2233. current = hash_candidate(candidate)
  2234. expected = expected_by_path.get(candidate.relative)
  2235. if (
  2236. expected is None
  2237. or current["size"] != expected["size"]
  2238. or current["sha256"] != expected["sha256"]
  2239. ):
  2240. raise PackagingError("source tree changed during packaging; retry from a stable workspace snapshot")
  2241. def _build_package_with_zipfile(
  2242. temp_zip: Path,
  2243. *,
  2244. root: Path,
  2245. package_name: str,
  2246. profile: str,
  2247. candidates: list[Candidate],
  2248. excluded: list[dict[str, str]],
  2249. context: ScanContext,
  2250. provenance: dict[str, object],
  2251. provenance_artifacts: dict[str, bytes],
  2252. ) -> tuple[list[dict[str, object]], dict[str, bytes], dict[str, bytes]]:
  2253. """Fallback ZIP writer when 7-Zip is not available."""
  2254. inventory: list[dict[str, object]] = []
  2255. with zipfile.ZipFile(
  2256. temp_zip,
  2257. "w",
  2258. compression=zipfile.ZIP_DEFLATED,
  2259. compresslevel=9,
  2260. allowZip64=True,
  2261. ) as archive:
  2262. for candidate in candidates:
  2263. inventory.append(write_candidate(archive, candidate))
  2264. metadata_artifacts = build_metadata(
  2265. package_name=package_name,
  2266. profile=profile,
  2267. inventory=inventory,
  2268. excluded=excluded,
  2269. context=context,
  2270. provenance=provenance,
  2271. )
  2272. for name, payload in sorted({**metadata_artifacts, **provenance_artifacts}.items()):
  2273. write_bytes_entry(archive, name, payload)
  2274. return inventory, metadata_artifacts, provenance_artifacts
  2275. def _build_package_with_7z(
  2276. seven_zip: Path,
  2277. temp_zip: Path,
  2278. *,
  2279. root: Path,
  2280. package_name: str,
  2281. profile: str,
  2282. token: str,
  2283. output_dir: Path,
  2284. candidates: list[Candidate],
  2285. excluded: list[dict[str, str]],
  2286. context: ScanContext,
  2287. provenance: dict[str, object],
  2288. provenance_artifacts: dict[str, bytes],
  2289. ) -> tuple[list[dict[str, object]], dict[str, bytes], dict[str, bytes], Path]:
  2290. inventory: list[dict[str, object]] = []
  2291. archive_renames: list[tuple[str, str]] = []
  2292. staging_root = Path(tempfile.mkdtemp(prefix=f".{package_name}.{token}.stage.", dir=output_dir))
  2293. try:
  2294. for number, candidate in enumerate(candidates):
  2295. staging_name = f"candidate-{number:08d}"
  2296. inventory.append(stage_candidate(staging_root, candidate, staging_name))
  2297. archive_renames.append(
  2298. (
  2299. f"{ARCHIVE_ROOT}/{staging_name}",
  2300. f"{ARCHIVE_ROOT}/{candidate.relative}",
  2301. )
  2302. )
  2303. metadata_artifacts = build_metadata(
  2304. package_name=package_name,
  2305. profile=profile,
  2306. inventory=inventory,
  2307. excluded=excluded,
  2308. context=context,
  2309. provenance=provenance,
  2310. )
  2311. for name, payload in sorted({**metadata_artifacts, **provenance_artifacts}.items()):
  2312. target = staging_root / Path(*name.split("/"))
  2313. target.parent.mkdir(parents=True, exist_ok=True)
  2314. scan_secret_markers(payload, b"", name)
  2315. target.write_bytes(payload)
  2316. run_7zip(
  2317. seven_zip,
  2318. build_7zip_create_command(temp_zip, staging_root),
  2319. cwd=staging_root,
  2320. )
  2321. rename_archive_entries(seven_zip, temp_zip, archive_renames)
  2322. except BaseException:
  2323. shutil.rmtree(staging_root, ignore_errors=True)
  2324. raise
  2325. return inventory, metadata_artifacts, provenance_artifacts, staging_root
  2326. def create_package(
  2327. *,
  2328. root: Path,
  2329. output_dir: Path,
  2330. package_name: str,
  2331. force: bool,
  2332. candidates: list[Candidate],
  2333. excluded: list[dict[str, str]],
  2334. context: ScanContext,
  2335. profile: str = "full",
  2336. exclusion_resolver: Callable[..., str | None] | None = None,
  2337. ) -> dict[str, object]:
  2338. # Prefer Python zipfile so UTF-8 arcnames stay consistent on Linux/Windows.
  2339. # 7-Zip remains available as an optional verifier, not the primary writer.
  2340. seven_zip = None
  2341. output_dir.mkdir(parents=True, exist_ok=True)
  2342. final_zip = output_dir / f"{package_name}.zip"
  2343. final_sidecar = output_dir / f"{package_name}.zip.sha256.txt"
  2344. validate_publish_targets((final_zip, final_sidecar), force=force)
  2345. token = f"{os.getpid()}.{uuid.uuid4().hex}"
  2346. temp_zip = output_dir / f".{package_name}.{token}.partial"
  2347. temp_sidecar = output_dir / f".{package_name}.{token}.sha256.partial"
  2348. inventory: list[dict[str, object]] = []
  2349. provenance, provenance_artifacts = collect_git_provenance(root)
  2350. metadata_artifacts: dict[str, bytes] = {}
  2351. staging_root: Path | None = None
  2352. try:
  2353. if seven_zip is None:
  2354. inventory, metadata_artifacts, provenance_artifacts = _build_package_with_zipfile(
  2355. temp_zip,
  2356. root=root,
  2357. package_name=package_name,
  2358. profile=profile,
  2359. candidates=candidates,
  2360. excluded=excluded,
  2361. context=context,
  2362. provenance=provenance,
  2363. provenance_artifacts=provenance_artifacts,
  2364. )
  2365. else:
  2366. inventory, metadata_artifacts, provenance_artifacts, staging_root = _build_package_with_7z(
  2367. seven_zip,
  2368. temp_zip,
  2369. root=root,
  2370. package_name=package_name,
  2371. profile=profile,
  2372. token=token,
  2373. output_dir=output_dir,
  2374. candidates=candidates,
  2375. excluded=excluded,
  2376. context=context,
  2377. provenance=provenance,
  2378. provenance_artifacts=provenance_artifacts,
  2379. )
  2380. expected_names = {f"{ARCHIVE_ROOT}/{item['path']}" for item in inventory}
  2381. expected_names.update(metadata_artifacts)
  2382. expected_names.update(provenance_artifacts)
  2383. expected_payloads = {**metadata_artifacts, **provenance_artifacts}
  2384. try:
  2385. with open_stable_regular_file(temp_zip, temp_zip.name) as verified_zip:
  2386. verify_archive(
  2387. verified_zip,
  2388. expected_names=expected_names,
  2389. inventory=inventory,
  2390. expected_payloads=expected_payloads,
  2391. )
  2392. verified_zip.seek(0)
  2393. zip_digest = hashlib.sha256()
  2394. for chunk in iter(lambda: verified_zip.read(1024 * 1024), b""):
  2395. zip_digest.update(chunk)
  2396. zip_sha256 = zip_digest.hexdigest()
  2397. except OSError as exc:
  2398. raise PackagingError("temporary ZIP changed during stable verification") from exc
  2399. assert_source_tree_unchanged(
  2400. root,
  2401. candidates,
  2402. excluded,
  2403. context,
  2404. inventory,
  2405. exclusion_resolver=exclusion_resolver,
  2406. )
  2407. sidecar_payload = f"{zip_sha256} {final_zip.name}\n".encode("ascii")
  2408. temp_sidecar.write_bytes(sidecar_payload)
  2409. def verify_publication() -> None:
  2410. verify_published_artifacts(
  2411. final_zip,
  2412. final_sidecar,
  2413. expected_zip_sha256=zip_sha256,
  2414. expected_sidecar=sidecar_payload,
  2415. expected_names=expected_names,
  2416. inventory=inventory,
  2417. expected_payloads=expected_payloads,
  2418. )
  2419. assert_source_tree_unchanged(
  2420. root,
  2421. candidates,
  2422. excluded,
  2423. context,
  2424. inventory,
  2425. exclusion_resolver=exclusion_resolver,
  2426. )
  2427. cleanup_warnings = publish_artifacts_atomically(
  2428. [(temp_zip, final_zip), (temp_sidecar, final_sidecar)],
  2429. force=force,
  2430. verify_published=verify_publication,
  2431. )
  2432. except BaseException as exc:
  2433. try:
  2434. remove_partial_artifacts((temp_zip, temp_sidecar))
  2435. except PackagingError as cleanup_exc:
  2436. raise PackagingError(f"{exc}; additionally, {cleanup_exc}") from exc
  2437. raise
  2438. finally:
  2439. if staging_root is not None:
  2440. shutil.rmtree(staging_root, ignore_errors=True)
  2441. return {
  2442. "status": "pass",
  2443. "mode": "package",
  2444. "profile": profile,
  2445. "package_name": package_name,
  2446. "package_zip": str(final_zip),
  2447. "package_zip_sha256": zip_sha256,
  2448. "sha256_sidecar": str(final_sidecar),
  2449. "included_file_count": len(inventory),
  2450. "included_bytes": sum(int(item["size"]) for item in inventory),
  2451. "excluded_entry_count": len(excluded),
  2452. "warnings": cleanup_warnings,
  2453. }
  2454. def validate_paths(source_root: Path, output_dir: Path) -> tuple[Path, Path]:
  2455. try:
  2456. source = source_root.expanduser().resolve(strict=True)
  2457. except OSError as exc:
  2458. raise PackagingError(f"SourceRoot is unavailable: {source_root}") from exc
  2459. if not source.is_dir():
  2460. raise PackagingError(f"SourceRoot is not a directory: {source_root}")
  2461. output = output_dir.expanduser().resolve(strict=False)
  2462. try:
  2463. output.relative_to(source)
  2464. except ValueError:
  2465. pass
  2466. else:
  2467. raise PackagingError("OutputDir must be outside SourceRoot to prevent recursive packaging")
  2468. return source, output
  2469. def build_parser() -> argparse.ArgumentParser:
  2470. parser = argparse.ArgumentParser(description=__doc__)
  2471. parser.add_argument("--source-root", type=Path, default=ROOT)
  2472. parser.add_argument(
  2473. "--output-dir",
  2474. type=Path,
  2475. default=Path(os.environ.get("TMPDIR", "/tmp")) / "prod2u-handoff",
  2476. )
  2477. parser.add_argument("--package-name")
  2478. parser.add_argument("--force-overwrite", action="store_true")
  2479. parser.add_argument("--audit-only", action="store_true")
  2480. parser.add_argument(
  2481. "--profile",
  2482. choices=sorted(HANDOFF_PROFILES),
  2483. default=DEFAULT_HANDOFF_PROFILE,
  2484. help=(
  2485. "review-compact (default upload, unified source/evidence/meta, no full git bundle); "
  2486. "review-debug; archive-local; legacy full/code-only"
  2487. ),
  2488. )
  2489. parser.add_argument(
  2490. "--reference-archive",
  2491. action="append",
  2492. default=[],
  2493. type=Path,
  2494. help="Additional reference ZIP/tar to ingest (repeatable)",
  2495. )
  2496. parser.add_argument(
  2497. "--reference-root",
  2498. action="append",
  2499. default=[],
  2500. type=Path,
  2501. help="Additional reference directory to ingest (repeatable)",
  2502. )
  2503. return parser
  2504. def main(argv: list[str] | None = None) -> int:
  2505. args = build_parser().parse_args(argv)
  2506. package_name = args.package_name or datetime.now(timezone.utc).strftime("cpld-agent-handoff-%Y%m%dT%H%M%SZ")
  2507. try:
  2508. portable_package_name = windows_collision_key(package_name)
  2509. except PackagingError:
  2510. portable_package_name = ""
  2511. if (
  2512. not SAFE_PACKAGE_NAME.fullmatch(package_name)
  2513. or package_name in {".", ".."}
  2514. or not portable_package_name
  2515. ):
  2516. print(
  2517. "error: PackageName must be a portable ASCII file name without path separators or Windows-reserved forms",
  2518. file=sys.stderr,
  2519. )
  2520. return 1
  2521. try:
  2522. source, output = validate_paths(args.source_root, args.output_dir)
  2523. exclusion_resolver = make_exclusion_resolver(args.profile)
  2524. candidates, excluded, context = scan_tree(
  2525. source,
  2526. exclusion_resolver=exclusion_resolver,
  2527. profile=args.profile,
  2528. )
  2529. if args.audit_only:
  2530. audit_inventory = audit_candidates(candidates)
  2531. assert_source_tree_unchanged(
  2532. source,
  2533. candidates,
  2534. excluded,
  2535. context,
  2536. audit_inventory,
  2537. exclusion_resolver=exclusion_resolver,
  2538. )
  2539. rule_counts = Counter(item["rule"] for item in excluded)
  2540. payload = {
  2541. "status": "pass",
  2542. "mode": "audit_only",
  2543. "profile": args.profile,
  2544. "package_name": package_name,
  2545. "included_file_count": len(candidates),
  2546. "included_bytes": sum(item.size for item in candidates),
  2547. "excluded_entry_count": len(excluded),
  2548. "exclusion_rule_counts": dict(sorted(rule_counts.items())),
  2549. "changxin_temp_uart_version": context.changxin_version,
  2550. }
  2551. else:
  2552. payload = create_package(
  2553. root=source,
  2554. output_dir=output,
  2555. package_name=package_name,
  2556. profile=args.profile,
  2557. force=args.force_overwrite,
  2558. candidates=candidates,
  2559. excluded=excluded,
  2560. context=context,
  2561. exclusion_resolver=exclusion_resolver,
  2562. )
  2563. except (PackagingError, OSError) as exc:
  2564. print(f"error: {exc}", file=sys.stderr)
  2565. return 1
  2566. print(json.dumps(payload, ensure_ascii=False, indent=2))
  2567. return 0
  2568. if __name__ == "__main__":
  2569. raise SystemExit(main())