package_agent_handoff.py 114 KB

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