package_agent_handoff.py 114 KB

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