package_agent_handoff.py 86 KB

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