package_agent_handoff.py 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985
  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. HANDOFF_PROFILES = frozenset({"full", "code-only"})
  86. CODE_ONLY_ROOT_EXCLUSIONS = {
  87. "reference": "reference_material",
  88. }
  89. CODE_ONLY_GENERATED_VISUAL_ASSETS = frozenset(
  90. {
  91. "board-copper.svg",
  92. "board-silkscreen.svg",
  93. "board-mask-edge.svg",
  94. }
  95. )
  96. WINDOWS_RESERVED_NAMES = {
  97. "con",
  98. "prn",
  99. "aux",
  100. "nul",
  101. *(f"com{index}" for index in range(1, 10)),
  102. *(f"lpt{index}" for index in range(1, 10)),
  103. }
  104. WINDOWS_INVALID_FILENAME_CHARS = frozenset('<>:"/\\|?*')
  105. class PackagingError(RuntimeError):
  106. """Raised when a handoff archive cannot be produced safely."""
  107. @dataclass(frozen=True)
  108. class Candidate:
  109. absolute: Path
  110. relative: str
  111. size: int
  112. mtime_ns: int
  113. device: int
  114. inode: int
  115. mode: int
  116. @dataclass
  117. class CandidateSnapshot:
  118. stream: BinaryIO
  119. inventory: dict[str, object]
  120. @dataclass
  121. class ArchiveScanBudget:
  122. member_count: int = 0
  123. uncompressed_bytes: int = 0
  124. @dataclass(frozen=True)
  125. class ScanContext:
  126. changxin_version: str | None
  127. profile: str = "full"
  128. def utc_now() -> str:
  129. return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
  130. def find_7z() -> Path | None:
  131. discovered = shutil.which("7z") or shutil.which("7zz")
  132. candidates = [
  133. Path(discovered) if discovered else None,
  134. Path(r"C:\Program Files\7-Zip\7z.exe"),
  135. Path(r"C:\Program Files (x86)\7-Zip\7z.exe"),
  136. ]
  137. for candidate in candidates:
  138. if candidate is not None and candidate.is_file():
  139. return candidate.resolve(strict=True)
  140. return None
  141. def build_7zip_create_command(archive_path: Path, staging_root: Path) -> list[str]:
  142. del staging_root
  143. return [
  144. "a",
  145. "-tzip",
  146. "-mm=Deflate",
  147. "-mx=9",
  148. "-mmt",
  149. "-y",
  150. "-r",
  151. str(archive_path),
  152. "CPLD\\*",
  153. ]
  154. def run_7zip(seven_zip: Path, arguments: list[str], *, cwd: Path) -> str:
  155. try:
  156. completed = subprocess.run(
  157. [str(seven_zip), *arguments],
  158. cwd=cwd,
  159. stdout=subprocess.PIPE,
  160. stderr=subprocess.STDOUT,
  161. text=True,
  162. encoding="utf-8",
  163. errors="replace",
  164. timeout=300,
  165. check=False,
  166. )
  167. except (OSError, subprocess.TimeoutExpired) as exc:
  168. raise PackagingError("unable to run 7-Zip") from exc
  169. if completed.returncode != 0:
  170. detail = completed.stdout.strip().splitlines()
  171. suffix = f": {detail[-1]}" if detail else ""
  172. raise PackagingError(f"7-Zip failed{suffix}")
  173. return completed.stdout
  174. def rename_archive_entries(
  175. seven_zip: Path,
  176. archive_path: Path,
  177. renames: list[tuple[str, str]],
  178. ) -> None:
  179. for offset in range(0, len(renames), 64):
  180. batch = renames[offset : offset + 64]
  181. arguments = ["rn", "-y", str(archive_path)]
  182. for old_name, new_name in batch:
  183. arguments.extend((old_name, new_name))
  184. run_7zip(seven_zip, arguments, cwd=archive_path.parent)
  185. def validate_windows_component(component: str, relative: str) -> str:
  186. if component.endswith((" ", ".")):
  187. raise PackagingError(f"path component has a Windows-unsafe trailing character: {relative}")
  188. if any(ord(character) < 32 or character in WINDOWS_INVALID_FILENAME_CHARS for character in component):
  189. raise PackagingError(f"path component contains a Windows-invalid character: {relative}")
  190. normalized = component.casefold()
  191. if normalized.split(".", 1)[0] in WINDOWS_RESERVED_NAMES:
  192. raise PackagingError(f"Windows reserved device name is not portable: {relative}")
  193. return normalized
  194. def normalize_relative(parts: Iterable[str]) -> str:
  195. try:
  196. relative = unicodedata.normalize("NFC", "/".join(parts))
  197. relative.encode("utf-8", errors="strict")
  198. except UnicodeError as exc:
  199. raise PackagingError("path is not valid UTF-8") from exc
  200. components = relative.split("/")
  201. if not relative or relative.startswith("/") or any(part in {"", ".", ".."} for part in components):
  202. raise PackagingError(f"unsafe relative path: {relative!r}")
  203. for component in components:
  204. validate_windows_component(component, relative)
  205. return relative
  206. def windows_collision_key(relative: str) -> str:
  207. components = []
  208. for component in unicodedata.normalize("NFC", relative).split("/"):
  209. if not component:
  210. raise PackagingError(f"path component is empty after Windows normalization: {relative}")
  211. normalized = validate_windows_component(component, relative)
  212. components.append(normalized)
  213. return "/".join(components)
  214. def is_under(relative: str, prefix: str) -> bool:
  215. return relative == prefix or relative.startswith(prefix + "/")
  216. def load_scan_context(root: Path, *, profile: str = "full") -> ScanContext:
  217. pyproject = root / "tools" / "changxin-temp-uart" / "pyproject.toml"
  218. version: str | None = None
  219. try:
  220. raw_payload = read_stable_regular_bytes(
  221. pyproject,
  222. "Changxin pyproject",
  223. max_bytes=1024 * 1024,
  224. )
  225. payload = tomllib.loads(raw_payload.decode("utf-8-sig", errors="strict"))
  226. value = payload.get("project", {}).get("version")
  227. if isinstance(value, str) and value.strip():
  228. version = value.strip()
  229. except (PackagingError, UnicodeError, tomllib.TOMLDecodeError):
  230. version = None
  231. return ScanContext(version, profile=profile)
  232. def secret_path_reason(relative: str, *, is_dir: bool) -> str | None:
  233. if is_dir:
  234. return None
  235. name = relative.rsplit("/", 1)[-1].casefold()
  236. parts = relative.casefold().split("/")
  237. suffix = Path(name).suffix.casefold()
  238. if name == ".env" or (
  239. name.startswith(".env.")
  240. and not name.endswith((".example", ".sample", ".template", ".dist"))
  241. ):
  242. return "secret_environment_file"
  243. if name in {"id_rsa", "id_dsa", "id_ecdsa", "id_ed25519"} or name.startswith("id_rsa."):
  244. return "private_key_file"
  245. if name in {".netrc", "_netrc", ".pypirc", ".npmrc", ".git-credentials"}:
  246. return "credential_configuration_file"
  247. if len(parts) >= 2 and parts[-2:] == [".aws", "credentials"]:
  248. return "cloud_credential_file"
  249. if len(parts) >= 2 and parts[-2:] == [".docker", "config.json"]:
  250. return "container_registry_credential_file"
  251. if len(parts) >= 2 and parts[-2:] == ["gcloud", "application_default_credentials.json"]:
  252. return "cloud_credential_file"
  253. if suffix in {".key", ".pfx", ".p12", ".lic"}:
  254. return "credential_or_license_file"
  255. return None
  256. def common_file_exclusion_reason(relative: str) -> str | None:
  257. lower = relative.casefold()
  258. name = lower.rsplit("/", 1)[-1]
  259. suffix = Path(name).suffix.casefold()
  260. if suffix in {".pyc", ".pyo"}:
  261. return "python_bytecode"
  262. if suffix in {".tmp", ".partial", ".part", ".swp", ".swo"} or name.endswith("~"):
  263. return "atomic_or_editor_temporary_file"
  264. if suffix == ".dmp" or name.startswith("minidump-"):
  265. return "crash_dump"
  266. if name == "a.out" or (name.startswith("tmp_last_pkg") and name.endswith(".txt")):
  267. return "temporary_build_artifact"
  268. if name in {".ds_store", "thumbs.db", "desktop.ini"}:
  269. return "os_metadata_cache"
  270. if name in {".coverage", "coverage.xml"}:
  271. return "coverage_cache"
  272. if name.startswith(".coverage."):
  273. return "coverage_cache"
  274. if lower.startswith("td/td_") and suffix in {".log", ".logw"}:
  275. return "td_root_runtime_log"
  276. if "/" not in lower and lower.startswith("td_") and suffix in {".log", ".logw"}:
  277. return "td_root_runtime_log"
  278. generated_binary_suffixes = {
  279. ".bit",
  280. ".bid",
  281. ".data",
  282. ".db",
  283. ".timing",
  284. ".rpt",
  285. ".area",
  286. ".qor",
  287. ".vvp",
  288. }
  289. if suffix in generated_binary_suffixes:
  290. return "generated_binary_artifact"
  291. if suffix == ".exe":
  292. return "vendor_executable"
  293. # Vendor tool installers / release archives must never enter analysis packages.
  294. if name.startswith(("bw_release_", "td_release_", "oss-cad-suite")) and suffix in {
  295. ".zip",
  296. ".tgz",
  297. ".tar",
  298. ".gz",
  299. ".7z",
  300. ".rar",
  301. }:
  302. return "vendor_toolchain_archive"
  303. if "license" in name and suffix in {".zip", ".tgz", ".7z", ".rar"}:
  304. return "license_archive"
  305. if name.endswith((".lic",)) or name in {"anlogic.lic"}:
  306. return "credential_or_license_file"
  307. return None
  308. def exclusion_reason(relative: str, *, is_dir: bool, context: ScanContext) -> str | None:
  309. lower = relative.casefold()
  310. parts = lower.split("/")
  311. raw_parts = relative.split("/")
  312. name = parts[-1]
  313. if parts[0] == "handoff-metadata":
  314. raise PackagingError(f"source uses reserved package path: {relative}")
  315. secret_reason = secret_path_reason(relative, is_dir=is_dir)
  316. if secret_reason:
  317. return secret_reason
  318. explicit_roots = {
  319. ".git": "raw_git_metadata",
  320. ".codegraph": "external_codegraph_cache",
  321. ".omo": "agent_session_runtime",
  322. ".hypothesis": "hypothesis_cache",
  323. ".pytest_cache": "pytest_cache",
  324. "workspace": "deprecated_workspace",
  325. "_archive": "deprecated_archive",
  326. "unused": "unused_workspace_area",
  327. "log": "runtime_log_directory",
  328. "dist": "generated_handoff_output",
  329. "anlogic_cd": "vendor_installer_payload",
  330. "receipts/local": "local_runtime_receipt",
  331. "j6-binary921-deliverables": "generated_delivery_package",
  332. "j6tmp-v2-tailfix-package": "generated_delivery_package",
  333. "cpld-deliverables": "generated_delivery_package",
  334. "runs": "run_state_directory",
  335. }
  336. for prefix, reason in explicit_roots.items():
  337. if is_under(lower, prefix):
  338. return reason
  339. if lower in {"td/project/.lock.f", "td/project/.recent_user_depot.ini"}:
  340. return "td_gui_runtime_state"
  341. if is_under(lower, "td/project/log"):
  342. return "td_gui_runtime_log"
  343. if is_under(lower, "td/project") and len(parts) >= 3 and parts[2].endswith("_runs"):
  344. return "td_gui_runtime_run"
  345. if any(component.endswith("_Runs") for component in raw_parts):
  346. return "generated_run_directory"
  347. if lower == "tests/cocotb/results.xml":
  348. return "cocotb_transient_result"
  349. if not is_dir:
  350. common_reason = common_file_exclusion_reason(relative)
  351. if common_reason:
  352. return common_reason
  353. cache_components = {
  354. ".git": "raw_git_metadata",
  355. ".codegraph": "external_codegraph_cache",
  356. ".codex": "codex_local_runtime",
  357. "__pycache__": "python_bytecode_cache",
  358. ".pytest_cache": "pytest_cache",
  359. ".hypothesis": "hypothesis_cache",
  360. ".mypy_cache": "mypy_cache",
  361. ".ruff_cache": "ruff_cache",
  362. ".tox": "tox_environment",
  363. ".nox": "nox_environment",
  364. ".venv": "virtual_environment",
  365. "venv": "virtual_environment",
  366. "htmlcov": "coverage_report",
  367. "sim_build": "simulation_build",
  368. "obj_dir": "verilator_build",
  369. "node_modules": "node_modules_runtime",
  370. ".playwright-browsers": "browser_runtime_cache",
  371. "build": "build_output",
  372. "runs": "run_state_directory",
  373. }
  374. for component in parts:
  375. if component in cache_components:
  376. return cache_components[component]
  377. if component.endswith(".egg-info"):
  378. return "python_package_metadata"
  379. if component == "dist":
  380. return "generated_delivery_output"
  381. if component == ".logs":
  382. return "td_generated_run_directory"
  383. if is_under(lower, ".codex"):
  384. return "codex_local_runtime"
  385. if is_under(lower, "tools/changxin-temp-uart/build"):
  386. return "python_package_build_copy"
  387. if is_under(lower, "tools/changxin-temp-uart/pyinstaller-build"):
  388. return "pyinstaller_build_cache"
  389. if is_under(lower, "tools/changxin-temp-uart/pyinstaller-spec"):
  390. return "pyinstaller_spec_cache"
  391. if lower in {
  392. "tools/changxin-temp-uart/pyinstaller-entry.py",
  393. "tools/changxin-temp-uart/linux-onefile-build.json",
  394. "tools/changxin-temp-uart/changxin-temp-uart-static",
  395. }:
  396. return "pyinstaller_generated_output"
  397. if lower == "tools/changxin-temp-uart/dist":
  398. return None
  399. if is_under(lower, "tools/changxin-temp-uart/dist"):
  400. return None
  401. if is_under(lower, "td/build"):
  402. return "td_build_output"
  403. if lower == "tmp":
  404. return None
  405. if is_under(lower, "tmp"):
  406. transient_tmp_roots = {
  407. "tmp/rtl_sim": "compiled_rtl_simulation",
  408. "tmp/cocotb": "cocotb_runtime",
  409. "tmp/detector_selftest": "detector_selftest_runtime",
  410. "tmp/toolchain_probe": "toolchain_probe_runtime",
  411. "tmp/edge-headless-profile": "browser_runtime_profile",
  412. "tmp/td": "td_runtime_snapshot",
  413. "tmp/refactor": "compiled_refactor_probe",
  414. }
  415. for prefix, reason in transient_tmp_roots.items():
  416. if is_under(lower, prefix):
  417. return reason
  418. for evidence_prefix in (
  419. "tmp/resource_audit",
  420. "tmp/pwm_executor_probe",
  421. ):
  422. if is_under(lower, evidence_prefix):
  423. evidence_parts = parts[len(evidence_prefix.split("/")) :]
  424. if "td_user_env" in evidence_parts:
  425. return "td_staged_source_or_runtime_copy"
  426. return None
  427. if len(parts) == 2 and parts[1].startswith("pytest-"):
  428. return "temporary_test_runtime"
  429. return None
  430. return None
  431. def code_only_exclusion_reason(relative: str, *, is_dir: bool) -> str | None:
  432. lower = relative.casefold()
  433. name = lower.rsplit("/", 1)[-1]
  434. for prefix, reason in CODE_ONLY_ROOT_EXCLUSIONS.items():
  435. if is_under(lower, prefix):
  436. return reason
  437. if not is_dir and is_under(lower, "tools/board-viewer/generated"):
  438. if name in CODE_ONLY_GENERATED_VISUAL_ASSETS:
  439. return "generated_board_viewer_visual_asset"
  440. return None
  441. def make_exclusion_resolver(profile: str) -> Callable[..., str | None]:
  442. if profile not in HANDOFF_PROFILES:
  443. raise PackagingError(f"unsupported handoff profile: {profile}")
  444. def resolve(relative: str, *, is_dir: bool, context: ScanContext) -> str | None:
  445. if profile == "code-only":
  446. code_only_reason = code_only_exclusion_reason(relative, is_dir=is_dir)
  447. if code_only_reason:
  448. return code_only_reason
  449. return exclusion_reason(relative, is_dir=is_dir, context=context)
  450. return resolve
  451. def stat_is_reparse_point(file_stat: os.stat_result) -> bool:
  452. attributes = int(getattr(file_stat, "st_file_attributes", 0))
  453. reparse_flag = int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0))
  454. return stat.S_ISLNK(file_stat.st_mode) or bool(reparse_flag and attributes & reparse_flag)
  455. def is_reparse_point(entry: os.DirEntry[str], file_stat: os.stat_result) -> bool:
  456. return entry.is_symlink() or stat_is_reparse_point(file_stat)
  457. def invalid_receipt_reason(path: Path, relative: str, size: int) -> str | None:
  458. if not relative.casefold().startswith("receipts/") or not relative.casefold().endswith(".json"):
  459. return None
  460. if size == 0:
  461. return "empty_receipt"
  462. if size <= 32:
  463. try:
  464. if path.read_bytes().strip().lower() == b"null":
  465. return "null_receipt"
  466. except OSError as exc:
  467. raise PackagingError(f"unable to inspect receipt {relative}: {exc}") from exc
  468. return None
  469. def scan_tree(
  470. root: Path,
  471. *,
  472. exclusion_resolver: Callable[..., str | None] | None = None,
  473. profile: str = "full",
  474. ) -> tuple[list[Candidate], list[dict[str, str]], ScanContext]:
  475. context = load_scan_context(root, profile=profile)
  476. resolve_exclusion = exclusion_resolver or exclusion_reason
  477. included: list[Candidate] = []
  478. excluded: list[dict[str, str]] = []
  479. collision_paths: dict[str, str] = {}
  480. def record_exclusion(relative: str, reason: str) -> None:
  481. excluded.append({"path": relative, "rule": reason})
  482. def walk(directory: Path, relative_parts: tuple[str, ...]) -> None:
  483. try:
  484. with os.scandir(directory) as iterator:
  485. entries = sorted(
  486. list(iterator),
  487. key=lambda item: unicodedata.normalize("NFC", item.name).casefold(),
  488. )
  489. except OSError as exc:
  490. relative = "/".join(relative_parts) or "."
  491. raise PackagingError(f"unable to enumerate {relative}: {exc}") from exc
  492. for entry in entries:
  493. relative = normalize_relative((*relative_parts, entry.name))
  494. scan_secret_markers(relative.encode("utf-8"), b"", "[source path]")
  495. try:
  496. file_stat = os.lstat(entry.path)
  497. except OSError as exc:
  498. raise PackagingError(f"unable to inspect {relative}: {exc}") from exc
  499. is_directory = stat.S_ISDIR(file_stat.st_mode)
  500. reason = resolve_exclusion(relative, is_dir=is_directory, context=context)
  501. if is_reparse_point(entry, file_stat):
  502. if reason:
  503. record_exclusion(relative, reason)
  504. continue
  505. raise PackagingError(f"undeclared reparse point refuses packaging: {relative}")
  506. if reason:
  507. record_exclusion(relative, reason)
  508. continue
  509. if is_directory:
  510. walk(Path(entry.path), (*relative_parts, entry.name))
  511. continue
  512. if not stat.S_ISREG(file_stat.st_mode):
  513. raise PackagingError(f"unsupported non-regular file: {relative}")
  514. receipt_reason = invalid_receipt_reason(Path(entry.path), relative, file_stat.st_size)
  515. if receipt_reason:
  516. record_exclusion(relative, receipt_reason)
  517. continue
  518. key = windows_collision_key(relative)
  519. previous = collision_paths.get(key)
  520. if previous is not None:
  521. raise PackagingError(f"Windows ZIP path collision: {previous} and {relative}")
  522. collision_paths[key] = relative
  523. if int(file_stat.st_dev) == 0 or int(file_stat.st_ino) == 0:
  524. raise PackagingError(f"filesystem does not expose a stable file identity: {relative}")
  525. included.append(
  526. Candidate(
  527. Path(entry.path),
  528. relative,
  529. file_stat.st_size,
  530. file_stat.st_mtime_ns,
  531. int(file_stat.st_dev),
  532. int(file_stat.st_ino),
  533. int(file_stat.st_mode),
  534. )
  535. )
  536. walk(root, ())
  537. included.sort(key=lambda item: windows_collision_key(item.relative))
  538. excluded.sort(key=lambda item: (windows_collision_key(item["path"]), item["rule"]))
  539. return included, excluded, context
  540. def sha256_file(path: Path) -> str:
  541. digest = hashlib.sha256()
  542. with path.open("rb") as handle:
  543. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  544. digest.update(chunk)
  545. return digest.hexdigest()
  546. def scan_secret_markers(chunk: bytes, tail: bytes, relative: str) -> bytes:
  547. combined = tail + chunk
  548. for label, pattern in SECRET_PATTERNS:
  549. if pattern.search(combined):
  550. raise PackagingError(f"high-confidence {label} secret found in {relative}")
  551. return combined[-SECRET_SCAN_OVERLAP:]
  552. def candidate_stat_matches(file_stat: os.stat_result, candidate: Candidate) -> bool:
  553. return (
  554. stat.S_ISREG(file_stat.st_mode)
  555. and not stat_is_reparse_point(file_stat)
  556. and int(file_stat.st_dev) == candidate.device
  557. and int(file_stat.st_ino) == candidate.inode
  558. and (os.name == "nt" or int(file_stat.st_mode) == candidate.mode)
  559. and file_stat.st_size == candidate.size
  560. and file_stat.st_mtime_ns == candidate.mtime_ns
  561. )
  562. @contextmanager
  563. def open_candidate(candidate: Candidate) -> Iterator[BinaryIO]:
  564. try:
  565. before = os.lstat(candidate.absolute)
  566. except OSError as exc:
  567. raise PackagingError(f"unable to inspect {candidate.relative} before packaging: {exc}") from exc
  568. if not candidate_stat_matches(before, candidate):
  569. raise PackagingError(f"source changed after enumeration: {candidate.relative}")
  570. flags = os.O_RDONLY
  571. flags |= int(getattr(os, "O_BINARY", 0))
  572. flags |= int(getattr(os, "O_NOINHERIT", 0))
  573. flags |= int(getattr(os, "O_NOFOLLOW", 0))
  574. try:
  575. file_descriptor = os.open(candidate.absolute, flags)
  576. except OSError as exc:
  577. raise PackagingError(f"unable to open {candidate.relative} without following links: {exc}") from exc
  578. source: BinaryIO | None = None
  579. try:
  580. try:
  581. opened = os.fstat(file_descriptor)
  582. except OSError as exc:
  583. raise PackagingError(f"unable to inspect opened source {candidate.relative}: {exc}") from exc
  584. if not candidate_stat_matches(opened, candidate):
  585. raise PackagingError(f"source identity changed while opening: {candidate.relative}")
  586. source = os.fdopen(file_descriptor, "rb", closefd=True)
  587. file_descriptor = -1
  588. try:
  589. yield source
  590. try:
  591. opened_after = os.fstat(source.fileno())
  592. except OSError as exc:
  593. raise PackagingError(f"unable to inspect opened source {candidate.relative} after reading: {exc}") from exc
  594. finally:
  595. source.close()
  596. if not candidate_stat_matches(opened_after, candidate):
  597. raise PackagingError(f"source changed while reading: {candidate.relative}")
  598. finally:
  599. if file_descriptor >= 0:
  600. os.close(file_descriptor)
  601. try:
  602. after = os.lstat(candidate.absolute)
  603. except OSError as exc:
  604. raise PackagingError(f"unable to inspect {candidate.relative} after packaging: {exc}") from exc
  605. if not candidate_stat_matches(after, candidate):
  606. raise PackagingError(f"source changed during packaging: {candidate.relative}")
  607. @contextmanager
  608. def snapshot_candidate(
  609. candidate: Candidate,
  610. *,
  611. allow_disk: bool,
  612. ) -> Iterator[CandidateSnapshot]:
  613. snapshot = cast(BinaryIO, tempfile.TemporaryFile()) if allow_disk else cast(BinaryIO, io.BytesIO())
  614. try:
  615. digest = hashlib.sha256()
  616. total = 0
  617. secret_tail = b""
  618. with open_candidate(candidate) as source:
  619. while True:
  620. chunk = source.read(1024 * 1024)
  621. if not chunk:
  622. break
  623. secret_tail = scan_secret_markers(chunk, secret_tail, candidate.relative)
  624. snapshot.write(chunk)
  625. digest.update(chunk)
  626. total += len(chunk)
  627. if total != candidate.size:
  628. raise PackagingError(f"source size changed during packaging: {candidate.relative}")
  629. snapshot.seek(0)
  630. yield CandidateSnapshot(
  631. stream=snapshot,
  632. inventory={"path": candidate.relative, "size": total, "sha256": digest.hexdigest()},
  633. )
  634. except MemoryError as exc:
  635. raise PackagingError(f"insufficient memory to audit source file: {candidate.relative}") from exc
  636. finally:
  637. snapshot.close()
  638. def archive_kind(name: str) -> str | None:
  639. lower = name.casefold()
  640. if lower.endswith((".zip", ".whl", ".jar", ".apk", ".nupkg")):
  641. return "zip"
  642. if lower.endswith((".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz", ".tar")):
  643. return "tar"
  644. if lower.endswith(".gz"):
  645. return "gzip"
  646. if lower.endswith((".rar", ".7z")):
  647. return "unsupported"
  648. return None
  649. def detect_archive_kind(source: BinaryIO, name: str) -> str | None:
  650. position = source.tell()
  651. try:
  652. source.seek(0)
  653. prefix = source.read(512)
  654. source.seek(0)
  655. if zipfile.is_zipfile(source):
  656. return "zip"
  657. hint = archive_kind(name)
  658. if prefix.startswith((b"7z\xbc\xaf'\x1c", b"Rar!\x1a\x07", b"(\xb5/\xfd", b"\x04\x22\x4d\x18")):
  659. return "unsupported"
  660. if prefix.startswith((b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08")):
  661. return "zip"
  662. if prefix.startswith(b"\x1f\x8b"):
  663. return "tar" if hint == "tar" else "gzip"
  664. if prefix.startswith((b"BZh", b"\xfd7zXZ\x00")):
  665. return "tar"
  666. if len(prefix) >= 262 and prefix[257:262] == b"ustar":
  667. return "tar"
  668. if prefix.startswith((b"!<arch>\n", b"MSCF", b"xar!")):
  669. return "unsupported"
  670. return hint
  671. finally:
  672. source.seek(position)
  673. def archive_member_label(archive_label: str, member_name: str) -> str:
  674. normalized = unicodedata.normalize("NFC", member_name)
  675. if (
  676. "\\" in normalized
  677. or "\x00" in normalized
  678. or normalized.startswith("/")
  679. or re.match(r"^[A-Za-z]:", normalized)
  680. ):
  681. raise PackagingError(f"unsafe archive member path in {archive_label}")
  682. normalized = normalized.removesuffix("/")
  683. if not normalized:
  684. raise PackagingError(f"unsafe archive member path in {archive_label}")
  685. parts = normalized.split("/")
  686. if any(part in {"", ".", ".."} for part in parts):
  687. raise PackagingError(f"unsafe archive member path in {archive_label}")
  688. scan_secret_markers(normalized.encode("utf-8"), b"", f"{archive_label} member path")
  689. return f"{archive_label}!/{normalized}"
  690. def scan_archive_metadata(value: str | bytes, label: str) -> None:
  691. try:
  692. payload = value if isinstance(value, bytes) else value.encode("utf-8", errors="strict")
  693. except UnicodeError as exc:
  694. raise PackagingError(f"archive metadata is not valid UTF-8 in {label}") from exc
  695. scan_secret_markers(payload, b"", label)
  696. def account_archive_member(budget: ArchiveScanBudget, label: str) -> None:
  697. budget.member_count += 1
  698. if budget.member_count > MAX_ARCHIVE_MEMBERS:
  699. raise PackagingError(f"archive scan resource limit exceeded in {label}")
  700. def ensure_archive_bytes_available(budget: ArchiveScanBudget, size: int, label: str) -> None:
  701. if size < 0 or budget.uncompressed_bytes + size > MAX_ARCHIVE_UNCOMPRESSED_BYTES:
  702. raise PackagingError(f"archive scan resource limit exceeded in {label}")
  703. def scan_archive_member_stream(
  704. source: BinaryIO,
  705. *,
  706. member_name: str,
  707. label: str,
  708. depth: int,
  709. budget: ArchiveScanBudget,
  710. allow_disk: bool,
  711. ) -> None:
  712. sensitive_reason = secret_path_reason(member_name.removesuffix("/"), is_dir=False)
  713. if sensitive_reason is not None:
  714. raise PackagingError(
  715. f"credential or license path found in archive member: {label} ({sensitive_reason})"
  716. )
  717. nested = cast(BinaryIO, tempfile.TemporaryFile()) if allow_disk else cast(BinaryIO, io.BytesIO())
  718. try:
  719. secret_tail = b""
  720. while True:
  721. chunk = source.read(1024 * 1024)
  722. if not chunk:
  723. break
  724. ensure_archive_bytes_available(budget, len(chunk), label)
  725. budget.uncompressed_bytes += len(chunk)
  726. secret_tail = scan_secret_markers(chunk, secret_tail, label)
  727. nested.write(chunk)
  728. nested.seek(0)
  729. if detect_archive_kind(nested, member_name) is not None:
  730. scan_archive_stream(
  731. nested,
  732. name=member_name,
  733. label=label,
  734. depth=depth + 1,
  735. budget=budget,
  736. allow_disk=allow_disk,
  737. )
  738. except MemoryError as exc:
  739. raise PackagingError(f"insufficient memory to audit archive member: {label}") from exc
  740. finally:
  741. nested.close()
  742. def scan_archive_stream(
  743. source: BinaryIO,
  744. *,
  745. name: str,
  746. label: str,
  747. depth: int,
  748. budget: ArchiveScanBudget,
  749. allow_disk: bool,
  750. ) -> None:
  751. kind = detect_archive_kind(source, name)
  752. if kind is None:
  753. return
  754. if kind == "unsupported":
  755. raise PackagingError(f"unsupported archive format cannot be secret-scanned: {label}")
  756. if depth > MAX_ARCHIVE_DEPTH:
  757. raise PackagingError(f"archive scan resource limit exceeded in {label}")
  758. try:
  759. if kind == "zip":
  760. with zipfile.ZipFile(source) as archive:
  761. scan_archive_metadata(archive.comment, f"{label} archive comment")
  762. for zip_member in archive.infolist():
  763. account_archive_member(budget, label)
  764. member_label = archive_member_label(label, zip_member.filename)
  765. member_mode = (zip_member.external_attr >> 16) & 0xFFFF
  766. member_type = stat.S_IFMT(member_mode)
  767. scan_archive_metadata(zip_member.comment, f"{member_label} comment")
  768. scan_archive_metadata(zip_member.extra, f"{member_label} extra metadata")
  769. if zip_member.flag_bits & 0x1:
  770. raise PackagingError(f"unsafe archive member type in {member_label}")
  771. if zip_member.is_dir():
  772. if (
  773. zip_member.file_size != 0
  774. or zip_member.compress_size != 0
  775. or member_type not in {0, stat.S_IFDIR}
  776. ):
  777. raise PackagingError(f"unsafe archive member type in {member_label}")
  778. continue
  779. if member_type not in {0, stat.S_IFREG}:
  780. raise PackagingError(f"unsafe archive member type in {member_label}")
  781. ensure_archive_bytes_available(budget, zip_member.file_size, member_label)
  782. with archive.open(zip_member, "r") as zip_member_source:
  783. scan_archive_member_stream(
  784. cast(BinaryIO, zip_member_source),
  785. member_name=zip_member.filename,
  786. label=member_label,
  787. depth=depth,
  788. budget=budget,
  789. allow_disk=allow_disk,
  790. )
  791. return
  792. if kind == "tar":
  793. with tarfile.open(fileobj=source, mode="r:*") as archive:
  794. for key, value in archive.pax_headers.items():
  795. scan_archive_metadata(key, f"{label} global pax key")
  796. scan_archive_metadata(value, f"{label} global pax value")
  797. for tar_member in archive:
  798. account_archive_member(budget, label)
  799. member_label = archive_member_label(label, tar_member.name)
  800. for field_name, value in (
  801. ("linkname", tar_member.linkname),
  802. ("uname", tar_member.uname),
  803. ("gname", tar_member.gname),
  804. ):
  805. scan_archive_metadata(value, f"{member_label} {field_name}")
  806. for key, value in tar_member.pax_headers.items():
  807. scan_archive_metadata(key, f"{member_label} pax key")
  808. scan_archive_metadata(value, f"{member_label} pax value")
  809. if tar_member.isdir():
  810. if tar_member.size != 0:
  811. raise PackagingError(f"unsafe archive member type in {member_label}")
  812. continue
  813. if not tar_member.isfile():
  814. raise PackagingError(f"unsafe archive member type in {member_label}")
  815. ensure_archive_bytes_available(budget, tar_member.size, member_label)
  816. tar_member_source = archive.extractfile(tar_member)
  817. if tar_member_source is None:
  818. raise PackagingError(f"unable to inspect archive member in {member_label}")
  819. with tar_member_source:
  820. scan_archive_member_stream(
  821. cast(BinaryIO, tar_member_source),
  822. member_name=tar_member.name,
  823. label=member_label,
  824. depth=depth,
  825. budget=budget,
  826. allow_disk=allow_disk,
  827. )
  828. return
  829. with gzip.GzipFile(fileobj=source, mode="rb") as gzip_member_source:
  830. scan_archive_member_stream(
  831. cast(BinaryIO, gzip_member_source),
  832. member_name=name.removesuffix(".gz"),
  833. label=f"{label}!/<gzip>",
  834. depth=depth,
  835. budget=budget,
  836. allow_disk=allow_disk,
  837. )
  838. except PackagingError:
  839. raise
  840. except (OSError, EOFError, RuntimeError, tarfile.TarError, zipfile.BadZipFile) as exc:
  841. raise PackagingError(f"unable to inspect archive safely: {label} ({type(exc).__name__})") from exc
  842. def scan_candidate_archive(candidate: Candidate) -> None:
  843. with snapshot_candidate(candidate, allow_disk=True) as snapshot:
  844. scan_archive_stream(
  845. snapshot.stream,
  846. name=candidate.relative,
  847. label=candidate.relative,
  848. depth=0,
  849. budget=ArchiveScanBudget(),
  850. allow_disk=True,
  851. )
  852. def audit_candidates(candidates: Iterable[Candidate]) -> list[dict[str, object]]:
  853. inventory = []
  854. for candidate in candidates:
  855. inventory.append(stream_candidate(candidate))
  856. return inventory
  857. def zip_info(name: str, mode: int = stat.S_IFREG | 0o644) -> zipfile.ZipInfo:
  858. info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0))
  859. info.compress_type = zipfile.ZIP_DEFLATED
  860. info.create_system = 3
  861. info.flag_bits |= 0x800 # UTF-8 filenames
  862. info.external_attr = ((stat.S_IFREG | (mode & 0o777)) & 0xFFFF) << 16
  863. return info
  864. def stream_candidate(
  865. candidate: Candidate,
  866. target: BinaryIO | None = None,
  867. *,
  868. allow_disk: bool = True,
  869. ) -> dict[str, object]:
  870. with snapshot_candidate(candidate, allow_disk=allow_disk) as snapshot:
  871. scan_archive_stream(
  872. snapshot.stream,
  873. name=candidate.relative,
  874. label=candidate.relative,
  875. depth=0,
  876. budget=ArchiveScanBudget(),
  877. allow_disk=allow_disk,
  878. )
  879. if target is not None:
  880. snapshot.stream.seek(0)
  881. shutil.copyfileobj(snapshot.stream, target, length=1024 * 1024)
  882. return snapshot.inventory
  883. def hash_candidate(candidate: Candidate) -> dict[str, object]:
  884. digest = hashlib.sha256()
  885. total = 0
  886. secret_tail = b""
  887. with open_candidate(candidate) as source:
  888. for chunk in iter(lambda: source.read(1024 * 1024), b""):
  889. secret_tail = scan_secret_markers(chunk, secret_tail, candidate.relative)
  890. digest.update(chunk)
  891. total += len(chunk)
  892. if total != candidate.size:
  893. raise PackagingError(f"source size changed during packaging: {candidate.relative}")
  894. return {"path": candidate.relative, "size": total, "sha256": digest.hexdigest()}
  895. def write_candidate(archive: zipfile.ZipFile, candidate: Candidate) -> dict[str, object]:
  896. entry_name = f"{ARCHIVE_ROOT}/{candidate.relative}"
  897. try:
  898. with archive.open(zip_info(entry_name, candidate.mode), "w", force_zip64=True) as target:
  899. return stream_candidate(candidate, target)
  900. except OSError as exc:
  901. raise PackagingError(f"unable to package {candidate.relative}: {exc}") from exc
  902. def stage_candidate(
  903. staging_root: Path,
  904. candidate: Candidate,
  905. staging_name: str | None = None,
  906. ) -> dict[str, object]:
  907. target = staging_root / ARCHIVE_ROOT / (
  908. staging_name if staging_name is not None else Path(*candidate.relative.split("/"))
  909. )
  910. target.parent.mkdir(parents=True, exist_ok=True)
  911. try:
  912. with target.open("wb") as destination:
  913. return stream_candidate(candidate, target=destination)
  914. except OSError as exc:
  915. raise PackagingError(f"unable to stage {candidate.relative}: {exc}") from exc
  916. def write_bytes_entry(archive: zipfile.ZipFile, name: str, payload: bytes) -> None:
  917. scan_secret_markers(payload, b"", name)
  918. with archive.open(zip_info(name), "w", force_zip64=True) as handle:
  919. handle.write(payload)
  920. def json_bytes(payload: object) -> bytes:
  921. return (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
  922. def path_contains_reparse_point(root: Path, candidate: Path) -> bool:
  923. root_absolute = Path(os.path.abspath(root))
  924. candidate_absolute = Path(os.path.abspath(candidate))
  925. try:
  926. relative = candidate_absolute.relative_to(root_absolute)
  927. except ValueError:
  928. return True
  929. current = root_absolute
  930. for component in relative.parts:
  931. current /= component
  932. try:
  933. file_stat = os.lstat(current)
  934. except OSError:
  935. return True
  936. if stat_is_reparse_point(file_stat):
  937. return True
  938. return False
  939. def resolve_git_dir(root: Path) -> Path | None:
  940. marker = root / ".git"
  941. try:
  942. marker_stat = os.lstat(marker)
  943. except OSError:
  944. return None
  945. if stat_is_reparse_point(marker_stat):
  946. return None
  947. root_resolved = root.resolve(strict=True)
  948. if stat.S_ISDIR(marker_stat.st_mode):
  949. try:
  950. candidate = marker.resolve(strict=True)
  951. candidate.relative_to(root_resolved)
  952. except (OSError, RuntimeError, ValueError):
  953. return None
  954. return candidate
  955. if stat.S_ISREG(marker_stat.st_mode):
  956. try:
  957. text = read_stable_regular_bytes(marker, ".git marker", max_bytes=4096).decode(
  958. "utf-8",
  959. errors="strict",
  960. ).strip()
  961. except (PackagingError, UnicodeError):
  962. return None
  963. if text.startswith("gitdir:"):
  964. raw_candidate = root / text.split(":", 1)[1].strip()
  965. try:
  966. candidate = raw_candidate.resolve(strict=True)
  967. candidate.relative_to(root_resolved)
  968. except (OSError, RuntimeError, ValueError):
  969. return None
  970. if path_contains_reparse_point(root_resolved, raw_candidate):
  971. return None
  972. try:
  973. candidate_stat = os.lstat(candidate)
  974. except OSError:
  975. return None
  976. return candidate if stat.S_ISDIR(candidate_stat.st_mode) and not stat_is_reparse_point(candidate_stat) else None
  977. return None
  978. def read_head_metadata(git_dir: Path) -> tuple[str | None, str | None]:
  979. try:
  980. head = read_stable_regular_bytes(git_dir / "HEAD", "Git HEAD", max_bytes=4096).decode(
  981. "ascii",
  982. errors="strict",
  983. ).strip()
  984. except (PackagingError, UnicodeError):
  985. return None, None
  986. if not head.startswith("ref: "):
  987. return None, head if re.fullmatch(r"[0-9a-fA-F]{40}", head) else None
  988. ref = head[5:].strip()
  989. ref_parts = ref.split("/")
  990. if (
  991. not ref.startswith("refs/")
  992. or "\\" in ref
  993. or any(part in {"", ".", ".."} for part in ref_parts)
  994. or ".." in ref
  995. or "@{" in ref
  996. or ref.endswith((".", "/", ".lock"))
  997. or re.fullmatch(r"[A-Za-z0-9._/-]+", ref) is None
  998. ):
  999. return None, None
  1000. branch = ref.removeprefix("refs/heads/") if ref.startswith("refs/heads/") else ref
  1001. ref_file = git_dir.joinpath(*ref_parts)
  1002. commit: str | None = None
  1003. if os.path.lexists(ref_file):
  1004. if path_contains_reparse_point(git_dir, ref_file):
  1005. return branch, None
  1006. try:
  1007. commit = read_stable_regular_bytes(ref_file, f"Git ref {ref}", max_bytes=4096).decode(
  1008. "ascii",
  1009. errors="strict",
  1010. ).strip()
  1011. except (PackagingError, UnicodeError):
  1012. return branch, None
  1013. if commit is None:
  1014. commit = None
  1015. packed_refs = git_dir / "packed-refs"
  1016. if os.path.lexists(packed_refs) and not path_contains_reparse_point(git_dir, packed_refs):
  1017. try:
  1018. packed_text = read_stable_regular_bytes(
  1019. packed_refs,
  1020. "Git packed-refs",
  1021. max_bytes=16 * 1024 * 1024,
  1022. ).decode("ascii", errors="strict")
  1023. except (PackagingError, UnicodeError):
  1024. packed_text = ""
  1025. for line in packed_text.splitlines():
  1026. if not line or line.startswith(("#", "^")):
  1027. continue
  1028. sha, _, packed_ref = line.partition(" ")
  1029. if packed_ref == ref:
  1030. commit = sha
  1031. break
  1032. if commit and not re.fullmatch(r"[0-9a-fA-F]{40}", commit):
  1033. commit = None
  1034. return branch, commit
  1035. def run_capture(command: list[str], *, cwd: Path, timeout: int = 60) -> tuple[int, bytes]:
  1036. try:
  1037. completed = subprocess.run(
  1038. command,
  1039. cwd=cwd,
  1040. stdout=subprocess.PIPE,
  1041. stderr=subprocess.STDOUT,
  1042. timeout=timeout,
  1043. check=False,
  1044. )
  1045. except (OSError, subprocess.TimeoutExpired):
  1046. return 1, b""
  1047. return completed.returncode, completed.stdout
  1048. def collect_git_provenance(root: Path) -> tuple[dict[str, object], dict[str, bytes]]:
  1049. git_dir = resolve_git_dir(root)
  1050. if git_dir is None:
  1051. return {"status": "not_a_git_worktree", "branch": None, "head": None, "tool": None}, {}
  1052. branch, head = read_head_metadata(git_dir)
  1053. tool: str | None = None
  1054. status_command: list[str] | None = None
  1055. git = shutil.which("git")
  1056. if git:
  1057. tool = "git"
  1058. status_command = [
  1059. git,
  1060. "--no-optional-locks",
  1061. "-c",
  1062. "core.fsmonitor=false",
  1063. "-c",
  1064. "core.untrackedCache=false",
  1065. "status",
  1066. "--short",
  1067. "--branch",
  1068. "--untracked-files=all",
  1069. ]
  1070. elif importlib.util.find_spec("dulwich") is not None:
  1071. tool = "dulwich"
  1072. status_command = [sys.executable, "-I", "-m", "dulwich", "status"]
  1073. if status_command is None:
  1074. return {"status": "blocked_missing_git_tool", "branch": branch, "head": head, "tool": None}, {}
  1075. status_code, status_payload = run_capture(status_command, cwd=root)
  1076. artifacts: dict[str, bytes] = {}
  1077. if status_code == 0:
  1078. artifacts[f"{METADATA_ROOT}/git-status.txt"] = status_payload
  1079. capture_status = "pass" if status_code == 0 else "partial"
  1080. return {
  1081. "status": capture_status,
  1082. "branch": branch,
  1083. "head": head,
  1084. "tool": tool,
  1085. "status_captured": status_code == 0,
  1086. }, artifacts
  1087. def build_metadata(
  1088. *,
  1089. package_name: str,
  1090. profile: str,
  1091. inventory: list[dict[str, object]],
  1092. excluded: list[dict[str, str]],
  1093. context: ScanContext,
  1094. provenance: dict[str, object],
  1095. ) -> dict[str, bytes]:
  1096. rule_counts = Counter(item["rule"] for item in excluded)
  1097. derived_evidence = []
  1098. for item in inventory:
  1099. path = str(item["path"])
  1100. name = path.casefold().rsplit("/", 1)[-1]
  1101. if name not in CODE_ONLY_GENERATED_VISUAL_ASSETS and name not in {
  1102. "board-data.json",
  1103. "build-info.json",
  1104. "import-report.json",
  1105. }:
  1106. continue
  1107. if "tools/board-viewer/generated/" not in path.casefold():
  1108. continue
  1109. role = (
  1110. "derived_from_brd_visual"
  1111. if name in CODE_ONLY_GENERATED_VISUAL_ASSETS
  1112. else "derived_from_brd_parsed"
  1113. )
  1114. derived_evidence.append(
  1115. {
  1116. "path": path,
  1117. "asset": name,
  1118. "role": role,
  1119. "authority": "analysis_evidence_not_source_closure",
  1120. "note": "Derived from the original Allegro BRD for remote analysis; not RTL/TD source closure.",
  1121. }
  1122. )
  1123. authority_boundary = (
  1124. "Inclusion-first analysis handoff of source, requirements, tests, original references, "
  1125. "board-viewer derived evidence (JSON/SVG labeled not source closure), and retained evidence. "
  1126. "It excludes credentials, license archives, vendor installers, caches, node_modules, venvs, "
  1127. "raw Git objects, and declared reconstructable runtime outputs."
  1128. )
  1129. if profile == "code-only":
  1130. authority_boundary = (
  1131. "This archive is a code-and-tests-only analysis handoff. It excludes reference materials, "
  1132. "generated board-viewer visual assets, credentials, private archives, raw Git objects, "
  1133. "and declared reconstructable runtime outputs."
  1134. )
  1135. derived_evidence = []
  1136. manifest = {
  1137. "schema": "cpld-agent-handoff-v1",
  1138. "status": "pass",
  1139. "created_at": utc_now(),
  1140. "package_name": package_name,
  1141. "profile": profile,
  1142. "delivery_policy": "code-only" if profile == "code-only" else "inclusion-first",
  1143. "archive_root": ARCHIVE_ROOT,
  1144. "source_name": ARCHIVE_ROOT,
  1145. "included_file_count": len(inventory),
  1146. "included_bytes": sum(int(item["size"]) for item in inventory),
  1147. "excluded_entry_count": len(excluded),
  1148. "exclusion_rule_counts": dict(sorted(rule_counts.items())),
  1149. "derived_evidence": derived_evidence,
  1150. "changxin_temp_uart_version": context.changxin_version,
  1151. "git_provenance": provenance,
  1152. "archive_scan_limits": {
  1153. "max_depth": MAX_ARCHIVE_DEPTH,
  1154. "max_members": MAX_ARCHIVE_MEMBERS,
  1155. "max_uncompressed_bytes": MAX_ARCHIVE_UNCOMPRESSED_BYTES,
  1156. "source_file_size_limit": None,
  1157. },
  1158. "privacy": {
  1159. "manifest_contains_absolute_source_path": False,
  1160. "note": "Repository files are preserved byte-for-byte; review document and receipt contents before crossing a trust boundary.",
  1161. },
  1162. "authority_boundary": authority_boundary,
  1163. }
  1164. exclusions_payload = {
  1165. "schema": "cpld-agent-handoff-exclusions-v1",
  1166. "excluded": excluded,
  1167. "rule_counts": dict(sorted(rule_counts.items())),
  1168. }
  1169. inventory_payload = {
  1170. "schema": "cpld-agent-handoff-sha256-inventory-v1",
  1171. "inventory": inventory,
  1172. }
  1173. return {
  1174. f"{METADATA_ROOT}/manifest.json": json_bytes(manifest),
  1175. f"{METADATA_ROOT}/exclusions.json": json_bytes(exclusions_payload),
  1176. f"{METADATA_ROOT}/sha256-inventory.json": json_bytes(inventory_payload),
  1177. }
  1178. def validate_zip_entry(name: str) -> str:
  1179. if not name.startswith(ARCHIVE_ROOT + "/") or "\\" in name or name.startswith("/"):
  1180. raise PackagingError(f"unsafe ZIP entry: {name}")
  1181. relative = name[len(ARCHIVE_ROOT) + 1 :]
  1182. normalize_relative(relative.split("/"))
  1183. return windows_collision_key(name)
  1184. def verify_archive(
  1185. path: Path | BinaryIO,
  1186. *,
  1187. expected_names: set[str],
  1188. inventory: list[dict[str, object]],
  1189. expected_payloads: dict[str, bytes] | None = None,
  1190. ) -> None:
  1191. try:
  1192. with zipfile.ZipFile(path, "r", allowZip64=True) as archive:
  1193. names = archive.namelist()
  1194. if len(names) != len(set(names)):
  1195. raise PackagingError("ZIP contains duplicate entry names")
  1196. file_names = [name for name in names if not name.endswith("/")]
  1197. collision_keys: dict[str, str] = {}
  1198. for name in names:
  1199. if name.endswith("/"):
  1200. if name == ARCHIVE_ROOT + "/":
  1201. continue
  1202. if not name.startswith(ARCHIVE_ROOT + "/"):
  1203. raise PackagingError(f"unsafe ZIP directory entry: {name}")
  1204. relative_directory = name[len(ARCHIVE_ROOT) + 1 :].removesuffix("/")
  1205. normalize_relative(relative_directory.split("/"))
  1206. continue
  1207. key = validate_zip_entry(name)
  1208. previous = collision_keys.get(key)
  1209. if previous is not None and previous != name:
  1210. raise PackagingError(f"ZIP contains a Windows path collision: {previous} and {name}")
  1211. collision_keys[key] = name
  1212. if set(file_names) != expected_names:
  1213. missing = sorted(expected_names - set(file_names))
  1214. unexpected = sorted(set(file_names) - expected_names)
  1215. raise PackagingError(f"ZIP entry verification failed; missing={missing}, unexpected={unexpected}")
  1216. bad = archive.testzip()
  1217. if bad is not None:
  1218. raise PackagingError(f"ZIP CRC verification failed for {bad}")
  1219. for item in inventory:
  1220. entry_name = f"{ARCHIVE_ROOT}/{item['path']}"
  1221. digest = hashlib.sha256()
  1222. total = 0
  1223. with archive.open(entry_name, "r") as handle:
  1224. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  1225. digest.update(chunk)
  1226. total += len(chunk)
  1227. if total != item["size"] or digest.hexdigest() != item["sha256"]:
  1228. raise PackagingError(f"ZIP SHA256 verification failed for {item['path']}")
  1229. for name, expected_payload in (expected_payloads or {}).items():
  1230. if archive.read(name) != expected_payload:
  1231. raise PackagingError(f"ZIP generated metadata verification failed for {name}")
  1232. except (OSError, zipfile.BadZipFile) as exc:
  1233. raise PackagingError(f"unable to verify ZIP archive: {exc}") from exc
  1234. def publish_target_identity(file_stat: os.stat_result) -> tuple[int, int, int, int, int]:
  1235. return (
  1236. int(file_stat.st_dev),
  1237. int(file_stat.st_ino),
  1238. int(file_stat.st_mode),
  1239. int(file_stat.st_size),
  1240. int(file_stat.st_mtime_ns),
  1241. )
  1242. def stat_is_windows_read_only(file_stat: os.stat_result) -> bool:
  1243. attributes = int(getattr(file_stat, "st_file_attributes", 0))
  1244. read_only_flag = int(getattr(stat, "FILE_ATTRIBUTE_READONLY", 0))
  1245. return bool(read_only_flag and attributes & read_only_flag)
  1246. def stat_is_read_only(file_stat: os.stat_result) -> bool:
  1247. return stat_is_windows_read_only(file_stat) or (int(file_stat.st_mode) & 0o222) == 0
  1248. def validate_publish_targets(paths: Iterable[Path], *, force: bool) -> dict[Path, tuple[int, int, int, int, int]]:
  1249. existing: dict[Path, tuple[int, int, int, int, int]] = {}
  1250. for path in paths:
  1251. if not os.path.lexists(path):
  1252. continue
  1253. if not force:
  1254. raise PackagingError(f"package artifact already exists: {path.name}")
  1255. try:
  1256. file_stat = os.lstat(path)
  1257. except OSError as exc:
  1258. raise PackagingError(f"unable to inspect existing package artifact {path.name}: {exc}") from exc
  1259. if not stat.S_ISREG(file_stat.st_mode) or stat_is_reparse_point(file_stat):
  1260. raise PackagingError(f"existing package artifact is not a regular file: {path.name}")
  1261. if stat_is_read_only(file_stat):
  1262. raise PackagingError(f"existing package artifact is read-only: {path.name}")
  1263. existing[path] = publish_target_identity(file_stat)
  1264. return existing
  1265. def publish_artifacts_atomically(
  1266. artifacts: list[tuple[Path, Path]],
  1267. *,
  1268. force: bool,
  1269. verify_published: Callable[[], None] | None = None,
  1270. ) -> list[str]:
  1271. backups: dict[Path, Path] = {}
  1272. published: list[Path] = []
  1273. final_paths = [final_path for _, final_path in artifacts]
  1274. existing = validate_publish_targets(final_paths, force=force)
  1275. try:
  1276. for _, final_path in artifacts:
  1277. expected_identity = existing.get(final_path)
  1278. if expected_identity is not None:
  1279. try:
  1280. current = os.lstat(final_path)
  1281. except OSError as exc:
  1282. raise PackagingError(f"existing package artifact changed before publication: {final_path.name}") from exc
  1283. if (
  1284. not stat.S_ISREG(current.st_mode)
  1285. or stat_is_reparse_point(current)
  1286. or stat_is_read_only(current)
  1287. or publish_target_identity(current) != expected_identity
  1288. ):
  1289. raise PackagingError(f"existing package artifact changed before publication: {final_path.name}")
  1290. backup = final_path.with_name(f".{final_path.name}.{uuid.uuid4().hex}.backup")
  1291. os.replace(final_path, backup)
  1292. backups[final_path] = backup
  1293. elif os.path.lexists(final_path):
  1294. raise PackagingError(f"package artifact appeared during publication: {final_path.name}")
  1295. for temp_path, final_path in artifacts:
  1296. os.link(temp_path, final_path)
  1297. published.append(final_path)
  1298. if verify_published is not None:
  1299. verify_published()
  1300. except BaseException as exc:
  1301. rollback_errors: list[str] = []
  1302. for final_path in reversed(published):
  1303. if final_path in backups:
  1304. continue
  1305. try:
  1306. final_path.unlink(missing_ok=True)
  1307. except OSError as rollback_exc:
  1308. rollback_errors.append(
  1309. f"remove {final_path.name} ({type(rollback_exc).__name__})"
  1310. )
  1311. for final_path, backup in backups.items():
  1312. if os.path.lexists(backup):
  1313. try:
  1314. os.replace(backup, final_path)
  1315. except OSError as rollback_exc:
  1316. rollback_errors.append(
  1317. f"restore {final_path.name} from {backup.name} ({type(rollback_exc).__name__})"
  1318. )
  1319. if rollback_errors:
  1320. recovery_paths = sorted(
  1321. str(path)
  1322. for path in (*backups.values(), *published)
  1323. if os.path.lexists(path)
  1324. )
  1325. recovery = ", ".join(recovery_paths) if recovery_paths else "none"
  1326. details = "; ".join(rollback_errors)
  1327. raise PackagingError(
  1328. f"package publication failed and rollback was incomplete: {details}; "
  1329. f"manual recovery paths: {recovery}"
  1330. ) from exc
  1331. if isinstance(exc, PackagingError):
  1332. raise
  1333. if isinstance(exc, OSError):
  1334. raise PackagingError(f"unable to publish package artifacts atomically: {exc}") from exc
  1335. raise
  1336. cleanup_warnings: list[str] = []
  1337. for temp_path, _ in artifacts:
  1338. try:
  1339. temp_path.unlink(missing_ok=True)
  1340. except OSError as exc:
  1341. cleanup_warnings.append(
  1342. f"published temporary artifact could not be removed: {temp_path.name} ({type(exc).__name__})"
  1343. )
  1344. for backup in backups.values():
  1345. try:
  1346. backup.unlink(missing_ok=True)
  1347. except OSError as exc:
  1348. cleanup_warnings.append(
  1349. f"published artifact backup could not be removed: {backup.name} ({type(exc).__name__})"
  1350. )
  1351. return cleanup_warnings
  1352. def remove_partial_artifacts(paths: Iterable[Path]) -> None:
  1353. failures: list[str] = []
  1354. for path in paths:
  1355. try:
  1356. path.unlink(missing_ok=True)
  1357. except OSError:
  1358. failures.append(path.name)
  1359. if failures:
  1360. names = ", ".join(sorted(failures))
  1361. raise PackagingError(f"unable to remove partial package artifacts: {names}")
  1362. @contextmanager
  1363. def open_stable_regular_file(path: Path, label: str) -> Iterator[BinaryIO]:
  1364. try:
  1365. before = os.lstat(path)
  1366. except OSError as exc:
  1367. raise PackagingError(f"unable to inspect {label}: {exc}") from exc
  1368. if not stat.S_ISREG(before.st_mode) or stat_is_reparse_point(before):
  1369. raise PackagingError(f"published artifact is not a regular file: {label}")
  1370. flags = os.O_RDONLY
  1371. flags |= int(getattr(os, "O_BINARY", 0))
  1372. flags |= int(getattr(os, "O_NOINHERIT", 0))
  1373. flags |= int(getattr(os, "O_NOFOLLOW", 0))
  1374. try:
  1375. descriptor = os.open(path, flags)
  1376. except OSError as exc:
  1377. raise PackagingError(f"unable to open {label} without following links: {exc}") from exc
  1378. handle: BinaryIO | None = None
  1379. try:
  1380. opened = os.fstat(descriptor)
  1381. if publish_target_identity(opened) != publish_target_identity(before):
  1382. raise PackagingError(f"published artifact changed while opening: {label}")
  1383. handle = os.fdopen(descriptor, "rb", closefd=True)
  1384. descriptor = -1
  1385. yield handle
  1386. opened_after = os.fstat(handle.fileno())
  1387. if publish_target_identity(opened_after) != publish_target_identity(opened):
  1388. raise PackagingError(f"published artifact changed while reading: {label}")
  1389. finally:
  1390. if handle is not None:
  1391. handle.close()
  1392. if descriptor >= 0:
  1393. os.close(descriptor)
  1394. try:
  1395. after = os.lstat(path)
  1396. except OSError as exc:
  1397. raise PackagingError(f"unable to re-inspect {label}: {exc}") from exc
  1398. if publish_target_identity(after) != publish_target_identity(before):
  1399. raise PackagingError(f"published artifact changed during verification: {label}")
  1400. def read_stable_regular_bytes(path: Path, label: str, *, max_bytes: int) -> bytes:
  1401. with open_stable_regular_file(path, label) as handle:
  1402. payload = handle.read(max_bytes + 1)
  1403. if len(payload) > max_bytes:
  1404. raise PackagingError(f"regular file exceeds safe metadata read limit: {label}")
  1405. return payload
  1406. def verify_published_artifacts(
  1407. final_zip: Path,
  1408. final_sidecar: Path,
  1409. *,
  1410. expected_zip_sha256: str,
  1411. expected_sidecar: bytes,
  1412. expected_names: set[str],
  1413. inventory: list[dict[str, object]],
  1414. expected_payloads: dict[str, bytes],
  1415. ) -> None:
  1416. digest = hashlib.sha256()
  1417. with open_stable_regular_file(final_zip, final_zip.name) as handle:
  1418. verify_archive(
  1419. handle,
  1420. expected_names=expected_names,
  1421. inventory=inventory,
  1422. expected_payloads=expected_payloads,
  1423. )
  1424. handle.seek(0)
  1425. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  1426. digest.update(chunk)
  1427. if digest.hexdigest() != expected_zip_sha256:
  1428. raise PackagingError("published ZIP SHA256 does not match the verified package")
  1429. with open_stable_regular_file(final_sidecar, final_sidecar.name) as handle:
  1430. actual_sidecar = handle.read()
  1431. if actual_sidecar != expected_sidecar:
  1432. raise PackagingError("published SHA256 sidecar does not match the verified package")
  1433. def scan_snapshot(
  1434. candidates: Iterable[Candidate],
  1435. excluded: Iterable[dict[str, str]],
  1436. context: ScanContext,
  1437. ) -> tuple[tuple[tuple[object, ...], ...], tuple[tuple[str, str], ...], ScanContext]:
  1438. candidate_state = tuple(
  1439. (
  1440. item.relative,
  1441. item.size,
  1442. item.mtime_ns,
  1443. item.device,
  1444. item.inode,
  1445. item.mode,
  1446. )
  1447. for item in candidates
  1448. )
  1449. excluded_state = tuple((item["path"], item["rule"]) for item in excluded)
  1450. return candidate_state, excluded_state, context
  1451. def assert_source_tree_unchanged(
  1452. root: Path,
  1453. candidates: list[Candidate],
  1454. excluded: list[dict[str, str]],
  1455. context: ScanContext,
  1456. inventory: list[dict[str, object]],
  1457. *,
  1458. exclusion_resolver: Callable[..., str | None] | None = None,
  1459. ) -> None:
  1460. current_candidates, current_excluded, current_context = scan_tree(
  1461. root,
  1462. exclusion_resolver=exclusion_resolver,
  1463. profile=context.profile,
  1464. )
  1465. if scan_snapshot(candidates, excluded, context) != scan_snapshot(
  1466. current_candidates,
  1467. current_excluded,
  1468. current_context,
  1469. ):
  1470. raise PackagingError("source tree changed during packaging; retry from a stable workspace snapshot")
  1471. expected_by_path = {str(item["path"]): item for item in inventory}
  1472. if len(expected_by_path) != len(current_candidates):
  1473. raise PackagingError("source tree changed during packaging; retry from a stable workspace snapshot")
  1474. for candidate in current_candidates:
  1475. current = hash_candidate(candidate)
  1476. expected = expected_by_path.get(candidate.relative)
  1477. if (
  1478. expected is None
  1479. or current["size"] != expected["size"]
  1480. or current["sha256"] != expected["sha256"]
  1481. ):
  1482. raise PackagingError("source tree changed during packaging; retry from a stable workspace snapshot")
  1483. def _build_package_with_zipfile(
  1484. temp_zip: Path,
  1485. *,
  1486. root: Path,
  1487. package_name: str,
  1488. profile: str,
  1489. candidates: list[Candidate],
  1490. excluded: list[dict[str, str]],
  1491. context: ScanContext,
  1492. provenance: dict[str, object],
  1493. provenance_artifacts: dict[str, bytes],
  1494. ) -> tuple[list[dict[str, object]], dict[str, bytes], dict[str, bytes]]:
  1495. """Fallback ZIP writer when 7-Zip is not available."""
  1496. inventory: list[dict[str, object]] = []
  1497. with zipfile.ZipFile(
  1498. temp_zip,
  1499. "w",
  1500. compression=zipfile.ZIP_DEFLATED,
  1501. compresslevel=9,
  1502. allowZip64=True,
  1503. ) as archive:
  1504. for candidate in candidates:
  1505. inventory.append(write_candidate(archive, candidate))
  1506. metadata_artifacts = build_metadata(
  1507. package_name=package_name,
  1508. profile=profile,
  1509. inventory=inventory,
  1510. excluded=excluded,
  1511. context=context,
  1512. provenance=provenance,
  1513. )
  1514. for name, payload in sorted({**metadata_artifacts, **provenance_artifacts}.items()):
  1515. write_bytes_entry(archive, name, payload)
  1516. return inventory, metadata_artifacts, provenance_artifacts
  1517. def _build_package_with_7z(
  1518. seven_zip: Path,
  1519. temp_zip: Path,
  1520. *,
  1521. root: Path,
  1522. package_name: str,
  1523. profile: str,
  1524. token: str,
  1525. output_dir: Path,
  1526. candidates: list[Candidate],
  1527. excluded: list[dict[str, str]],
  1528. context: ScanContext,
  1529. provenance: dict[str, object],
  1530. provenance_artifacts: dict[str, bytes],
  1531. ) -> tuple[list[dict[str, object]], dict[str, bytes], dict[str, bytes], Path]:
  1532. inventory: list[dict[str, object]] = []
  1533. archive_renames: list[tuple[str, str]] = []
  1534. staging_root = Path(tempfile.mkdtemp(prefix=f".{package_name}.{token}.stage.", dir=output_dir))
  1535. try:
  1536. for number, candidate in enumerate(candidates):
  1537. staging_name = f"candidate-{number:08d}"
  1538. inventory.append(stage_candidate(staging_root, candidate, staging_name))
  1539. archive_renames.append(
  1540. (
  1541. f"{ARCHIVE_ROOT}/{staging_name}",
  1542. f"{ARCHIVE_ROOT}/{candidate.relative}",
  1543. )
  1544. )
  1545. metadata_artifacts = build_metadata(
  1546. package_name=package_name,
  1547. profile=profile,
  1548. inventory=inventory,
  1549. excluded=excluded,
  1550. context=context,
  1551. provenance=provenance,
  1552. )
  1553. for name, payload in sorted({**metadata_artifacts, **provenance_artifacts}.items()):
  1554. target = staging_root / Path(*name.split("/"))
  1555. target.parent.mkdir(parents=True, exist_ok=True)
  1556. scan_secret_markers(payload, b"", name)
  1557. target.write_bytes(payload)
  1558. run_7zip(
  1559. seven_zip,
  1560. build_7zip_create_command(temp_zip, staging_root),
  1561. cwd=staging_root,
  1562. )
  1563. rename_archive_entries(seven_zip, temp_zip, archive_renames)
  1564. except BaseException:
  1565. shutil.rmtree(staging_root, ignore_errors=True)
  1566. raise
  1567. return inventory, metadata_artifacts, provenance_artifacts, staging_root
  1568. def create_package(
  1569. *,
  1570. root: Path,
  1571. output_dir: Path,
  1572. package_name: str,
  1573. force: bool,
  1574. candidates: list[Candidate],
  1575. excluded: list[dict[str, str]],
  1576. context: ScanContext,
  1577. profile: str = "full",
  1578. exclusion_resolver: Callable[..., str | None] | None = None,
  1579. ) -> dict[str, object]:
  1580. # Prefer Python zipfile so UTF-8 arcnames stay consistent on Linux/Windows.
  1581. # 7-Zip remains available as an optional verifier, not the primary writer.
  1582. seven_zip = None
  1583. output_dir.mkdir(parents=True, exist_ok=True)
  1584. final_zip = output_dir / f"{package_name}.zip"
  1585. final_sidecar = output_dir / f"{package_name}.zip.sha256.txt"
  1586. validate_publish_targets((final_zip, final_sidecar), force=force)
  1587. token = f"{os.getpid()}.{uuid.uuid4().hex}"
  1588. temp_zip = output_dir / f".{package_name}.{token}.partial"
  1589. temp_sidecar = output_dir / f".{package_name}.{token}.sha256.partial"
  1590. inventory: list[dict[str, object]] = []
  1591. provenance, provenance_artifacts = collect_git_provenance(root)
  1592. metadata_artifacts: dict[str, bytes] = {}
  1593. staging_root: Path | None = None
  1594. try:
  1595. if seven_zip is None:
  1596. inventory, metadata_artifacts, provenance_artifacts = _build_package_with_zipfile(
  1597. temp_zip,
  1598. root=root,
  1599. package_name=package_name,
  1600. profile=profile,
  1601. candidates=candidates,
  1602. excluded=excluded,
  1603. context=context,
  1604. provenance=provenance,
  1605. provenance_artifacts=provenance_artifacts,
  1606. )
  1607. else:
  1608. inventory, metadata_artifacts, provenance_artifacts, staging_root = _build_package_with_7z(
  1609. seven_zip,
  1610. temp_zip,
  1611. root=root,
  1612. package_name=package_name,
  1613. profile=profile,
  1614. token=token,
  1615. output_dir=output_dir,
  1616. candidates=candidates,
  1617. excluded=excluded,
  1618. context=context,
  1619. provenance=provenance,
  1620. provenance_artifacts=provenance_artifacts,
  1621. )
  1622. expected_names = {f"{ARCHIVE_ROOT}/{item['path']}" for item in inventory}
  1623. expected_names.update(metadata_artifacts)
  1624. expected_names.update(provenance_artifacts)
  1625. expected_payloads = {**metadata_artifacts, **provenance_artifacts}
  1626. try:
  1627. with open_stable_regular_file(temp_zip, temp_zip.name) as verified_zip:
  1628. verify_archive(
  1629. verified_zip,
  1630. expected_names=expected_names,
  1631. inventory=inventory,
  1632. expected_payloads=expected_payloads,
  1633. )
  1634. verified_zip.seek(0)
  1635. zip_digest = hashlib.sha256()
  1636. for chunk in iter(lambda: verified_zip.read(1024 * 1024), b""):
  1637. zip_digest.update(chunk)
  1638. zip_sha256 = zip_digest.hexdigest()
  1639. except OSError as exc:
  1640. raise PackagingError("temporary ZIP changed during stable verification") from exc
  1641. assert_source_tree_unchanged(
  1642. root,
  1643. candidates,
  1644. excluded,
  1645. context,
  1646. inventory,
  1647. exclusion_resolver=exclusion_resolver,
  1648. )
  1649. sidecar_payload = f"{zip_sha256} {final_zip.name}\n".encode("ascii")
  1650. temp_sidecar.write_bytes(sidecar_payload)
  1651. def verify_publication() -> None:
  1652. verify_published_artifacts(
  1653. final_zip,
  1654. final_sidecar,
  1655. expected_zip_sha256=zip_sha256,
  1656. expected_sidecar=sidecar_payload,
  1657. expected_names=expected_names,
  1658. inventory=inventory,
  1659. expected_payloads=expected_payloads,
  1660. )
  1661. assert_source_tree_unchanged(
  1662. root,
  1663. candidates,
  1664. excluded,
  1665. context,
  1666. inventory,
  1667. exclusion_resolver=exclusion_resolver,
  1668. )
  1669. cleanup_warnings = publish_artifacts_atomically(
  1670. [(temp_zip, final_zip), (temp_sidecar, final_sidecar)],
  1671. force=force,
  1672. verify_published=verify_publication,
  1673. )
  1674. except BaseException as exc:
  1675. try:
  1676. remove_partial_artifacts((temp_zip, temp_sidecar))
  1677. except PackagingError as cleanup_exc:
  1678. raise PackagingError(f"{exc}; additionally, {cleanup_exc}") from exc
  1679. raise
  1680. finally:
  1681. if staging_root is not None:
  1682. shutil.rmtree(staging_root, ignore_errors=True)
  1683. return {
  1684. "status": "pass",
  1685. "mode": "package",
  1686. "profile": profile,
  1687. "package_name": package_name,
  1688. "package_zip": str(final_zip),
  1689. "package_zip_sha256": zip_sha256,
  1690. "sha256_sidecar": str(final_sidecar),
  1691. "included_file_count": len(inventory),
  1692. "included_bytes": sum(int(item["size"]) for item in inventory),
  1693. "excluded_entry_count": len(excluded),
  1694. "warnings": cleanup_warnings,
  1695. }
  1696. def validate_paths(source_root: Path, output_dir: Path) -> tuple[Path, Path]:
  1697. try:
  1698. source = source_root.expanduser().resolve(strict=True)
  1699. except OSError as exc:
  1700. raise PackagingError(f"SourceRoot is unavailable: {source_root}") from exc
  1701. if not source.is_dir():
  1702. raise PackagingError(f"SourceRoot is not a directory: {source_root}")
  1703. output = output_dir.expanduser().resolve(strict=False)
  1704. try:
  1705. output.relative_to(source)
  1706. except ValueError:
  1707. pass
  1708. else:
  1709. raise PackagingError("OutputDir must be outside SourceRoot to prevent recursive packaging")
  1710. return source, output
  1711. def build_parser() -> argparse.ArgumentParser:
  1712. parser = argparse.ArgumentParser(description=__doc__)
  1713. parser.add_argument("--source-root", type=Path, default=ROOT)
  1714. parser.add_argument(
  1715. "--output-dir",
  1716. type=Path,
  1717. default=Path(os.environ.get("TMPDIR", "/tmp")) / "prod2u-handoff",
  1718. )
  1719. parser.add_argument("--package-name")
  1720. parser.add_argument("--force-overwrite", action="store_true")
  1721. parser.add_argument("--audit-only", action="store_true")
  1722. parser.add_argument(
  1723. "--profile",
  1724. choices=sorted(HANDOFF_PROFILES),
  1725. default="full",
  1726. help=(
  1727. "inclusion-first full profile includes reference + derived board-viewer JSON/SVG; "
  1728. "code-only excludes reference/ and heavy board-viewer SVG assets"
  1729. ),
  1730. )
  1731. parser.add_argument(
  1732. "--reference-archive",
  1733. action="append",
  1734. default=[],
  1735. type=Path,
  1736. help="Additional reference ZIP/tar to ingest (repeatable)",
  1737. )
  1738. parser.add_argument(
  1739. "--reference-root",
  1740. action="append",
  1741. default=[],
  1742. type=Path,
  1743. help="Additional reference directory to ingest (repeatable)",
  1744. )
  1745. return parser
  1746. def main(argv: list[str] | None = None) -> int:
  1747. args = build_parser().parse_args(argv)
  1748. package_name = args.package_name or datetime.now(timezone.utc).strftime("cpld-agent-handoff-%Y%m%dT%H%M%SZ")
  1749. try:
  1750. portable_package_name = windows_collision_key(package_name)
  1751. except PackagingError:
  1752. portable_package_name = ""
  1753. if (
  1754. not SAFE_PACKAGE_NAME.fullmatch(package_name)
  1755. or package_name in {".", ".."}
  1756. or not portable_package_name
  1757. ):
  1758. print(
  1759. "error: PackageName must be a portable ASCII file name without path separators or Windows-reserved forms",
  1760. file=sys.stderr,
  1761. )
  1762. return 1
  1763. try:
  1764. source, output = validate_paths(args.source_root, args.output_dir)
  1765. exclusion_resolver = make_exclusion_resolver(args.profile)
  1766. candidates, excluded, context = scan_tree(
  1767. source,
  1768. exclusion_resolver=exclusion_resolver,
  1769. profile=args.profile,
  1770. )
  1771. if args.audit_only:
  1772. audit_inventory = audit_candidates(candidates)
  1773. assert_source_tree_unchanged(
  1774. source,
  1775. candidates,
  1776. excluded,
  1777. context,
  1778. audit_inventory,
  1779. exclusion_resolver=exclusion_resolver,
  1780. )
  1781. rule_counts = Counter(item["rule"] for item in excluded)
  1782. payload = {
  1783. "status": "pass",
  1784. "mode": "audit_only",
  1785. "profile": args.profile,
  1786. "package_name": package_name,
  1787. "included_file_count": len(candidates),
  1788. "included_bytes": sum(item.size for item in candidates),
  1789. "excluded_entry_count": len(excluded),
  1790. "exclusion_rule_counts": dict(sorted(rule_counts.items())),
  1791. "changxin_temp_uart_version": context.changxin_version,
  1792. }
  1793. else:
  1794. payload = create_package(
  1795. root=source,
  1796. output_dir=output,
  1797. package_name=package_name,
  1798. profile=args.profile,
  1799. force=args.force_overwrite,
  1800. candidates=candidates,
  1801. excluded=excluded,
  1802. context=context,
  1803. exclusion_resolver=exclusion_resolver,
  1804. )
  1805. except (PackagingError, OSError) as exc:
  1806. print(f"error: {exc}", file=sys.stderr)
  1807. return 1
  1808. print(json.dumps(payload, ensure_ascii=False, indent=2))
  1809. return 0
  1810. if __name__ == "__main__":
  1811. raise SystemExit(main())