package_agent_handoff.py 63 KB

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