package_agent_handoff.py 86 KB

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