package_agent_handoff.py 104 KB

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