package_for_agent_analysis.py 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568
  1. #!/usr/bin/env python3
  2. """Create a complete CPLD analysis handoff from configured source roots."""
  3. from __future__ import annotations
  4. import json
  5. import hashlib
  6. import argparse
  7. import concurrent.futures
  8. import os
  9. import re
  10. import shutil
  11. import stat
  12. import subprocess
  13. import sys
  14. import tempfile
  15. import uuid
  16. import zipfile
  17. from datetime import datetime, timezone
  18. from pathlib import Path
  19. from typing import NamedTuple
  20. ROOT = Path(__file__).resolve().parent
  21. TOOLS = ROOT / "tools"
  22. if str(TOOLS) not in sys.path:
  23. sys.path.insert(0, str(TOOLS))
  24. import package_agent_handoff as handoff # noqa: E402
  25. PackagingError = handoff.PackagingError
  26. CONFIG_SCHEMA = "cpld-agent-analysis-sources-v1"
  27. DEFAULT_CONFIG = ROOT / "config" / "agent_analysis_handoff_sources.json"
  28. DEFAULT_OUTPUT_DIR = Path(
  29. os.environ.get(
  30. "PRODU2_HANDOFF_DIR",
  31. str(Path(os.environ.get("TMPDIR", "/tmp")) / "prod2u-handoff"),
  32. )
  33. )
  34. CONTENT_DEDUP_MIN_BYTES = 4096
  35. DERIVED_BOARD_VIEWER_ASSETS = frozenset(
  36. {
  37. "board-copper.svg",
  38. "board-silkscreen.svg",
  39. "board-mask-edge.svg",
  40. "board-data.json",
  41. "build-info.json",
  42. "import-report.json",
  43. }
  44. )
  45. CATEGORY_ORDER = {
  46. "core": 0,
  47. "hardware": 1,
  48. "td-docs": 2,
  49. "evidence": 3,
  50. }
  51. GENERATED_BINARY_SUFFIXES = {
  52. ".bit",
  53. ".bid",
  54. ".data",
  55. ".db",
  56. ".timing",
  57. ".rpt",
  58. ".area",
  59. ".qor",
  60. ".vvp",
  61. }
  62. TRANSIENT_SUFFIXES = {".pyc", ".pyo", ".tmp", ".partial", ".part", ".swp", ".swo"}
  63. ARCHIVE_SUFFIXES = {".zip", ".rar", ".7z"}
  64. RUNTIME_EVIDENCE_SUFFIXES = {".log", ".logw", ".vcd", ".fst", ".lxt", ".gtkw", ".raw", ".bin"}
  65. BOARD_VIEWER_GENERATED_ASSETS = {
  66. "board-copper.svg",
  67. "board-silkscreen.svg",
  68. "board-mask-edge.svg",
  69. }
  70. BOARD_DESIGN_SUFFIXES = {".brd", ".sch", ".kicad_pcb", ".kicad_sch", ".kicad_pro", ".kicad_prl", ".dsn"}
  71. IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".webp", ".svg"}
  72. STRAY_FILENAMES = {"-", "a.out"}
  73. REASSEMBLER_SCRIPT = '''#!/usr/bin/env python3
  74. """Reassemble files that were split across analysis ZIP volumes."""
  75. from __future__ import annotations
  76. import argparse
  77. import hashlib
  78. import json
  79. import shutil
  80. import sys
  81. import zipfile
  82. from pathlib import Path, PurePosixPath
  83. def safe_output_path(root: Path, relative: str) -> Path:
  84. portable = PurePosixPath(relative)
  85. if portable.is_absolute() or not portable.parts or any(part in {"", ".", ".."} for part in portable.parts):
  86. raise RuntimeError(f"unsafe output path: {relative}")
  87. target = (root / Path(*portable.parts)).resolve(strict=False)
  88. try:
  89. target.relative_to(root.resolve(strict=False))
  90. except ValueError as exc:
  91. raise RuntimeError(f"output path escapes target directory: {relative}") from exc
  92. return target
  93. def sha256_path(path: Path) -> str:
  94. digest = hashlib.sha256()
  95. with path.open("rb") as handle:
  96. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  97. digest.update(chunk)
  98. return digest.hexdigest()
  99. def main() -> int:
  100. parser = argparse.ArgumentParser(description=__doc__)
  101. parser.add_argument("--package-dir", type=Path, default=Path(__file__).resolve().parent)
  102. parser.add_argument("--output-dir", type=Path, default=Path("reassembled"))
  103. args = parser.parse_args()
  104. package_dir = args.package_dir.resolve(strict=True)
  105. output_dir = args.output_dir.resolve(strict=False)
  106. index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
  107. output_dir.mkdir(parents=True, exist_ok=True)
  108. for item in index.get("large_files", []):
  109. target = safe_output_path(output_dir, item["path"])
  110. target.parent.mkdir(parents=True, exist_ok=True)
  111. temporary = target.with_name(target.name + ".partial")
  112. temporary.unlink(missing_ok=True)
  113. total = 0
  114. with temporary.open("xb") as destination:
  115. for chunk in sorted(item["chunks"], key=lambda value: value["number"]):
  116. volume = package_dir / chunk["volume"]
  117. with zipfile.ZipFile(volume, "r") as archive:
  118. with archive.open(chunk["archive_path"], "r") as source:
  119. digest = hashlib.sha256()
  120. chunk_bytes = 0
  121. while True:
  122. payload = source.read(1024 * 1024)
  123. if not payload:
  124. break
  125. destination.write(payload)
  126. digest.update(payload)
  127. chunk_bytes += len(payload)
  128. if chunk_bytes != chunk["size"] or digest.hexdigest() != chunk["sha256"]:
  129. raise RuntimeError(f"chunk verification failed: {chunk['archive_path']}")
  130. total += chunk_bytes
  131. if total != item["size"] or sha256_path(temporary) != item["sha256"]:
  132. temporary.unlink(missing_ok=True)
  133. raise RuntimeError(f"reassembled file verification failed: {item['path']}")
  134. temporary.replace(target)
  135. print(f"reassembled: {target}")
  136. return 0
  137. if __name__ == "__main__":
  138. try:
  139. raise SystemExit(main())
  140. except (OSError, RuntimeError, KeyError, ValueError, json.JSONDecodeError, zipfile.BadZipFile) as exc:
  141. print(f"error: {exc}", file=sys.stderr)
  142. raise SystemExit(1)
  143. '''
  144. class ExternalSource(NamedTuple):
  145. id: str
  146. category: str
  147. kind: str
  148. path_candidates: tuple[Path, ...]
  149. archive_policy: str
  150. class HandoffConfig(NamedTuple):
  151. max_zip_bytes: int
  152. target_zip_bytes: int
  153. external_sources: tuple[ExternalSource, ...]
  154. extra_exclusions: tuple[dict[str, str], ...]
  155. class ResolvedSource(NamedTuple):
  156. id: str
  157. category: str
  158. kind: str
  159. path: Path
  160. archive_policy: str
  161. class PackageItem(NamedTuple):
  162. candidate: handoff.Candidate
  163. category: str
  164. source_id: str
  165. original_path: str
  166. scan_archive: bool
  167. class SourceSnapshot(NamedTuple):
  168. source_id: str
  169. root: Path
  170. extra_exclusions: tuple[dict[str, str], ...]
  171. candidates: tuple[tuple[object, ...], ...]
  172. excluded: tuple[tuple[str, str], ...]
  173. class AnalysisCollection(NamedTuple):
  174. status: str
  175. items: tuple[PackageItem, ...]
  176. excluded: tuple[dict[str, str], ...]
  177. warnings: tuple[dict[str, str], ...]
  178. sources: tuple[dict[str, object], ...]
  179. git: tuple[dict[str, object], ...]
  180. source_snapshots: tuple[SourceSnapshot, ...] = ()
  181. def _is_reference_path(item: PackageItem) -> bool:
  182. parts = item.candidate.relative.casefold().split("/")
  183. for index, part in enumerate(parts):
  184. if part == "reference":
  185. next_part = parts[index + 1] if index + 1 < len(parts) else ""
  186. if next_part == "historical":
  187. return False
  188. return True
  189. return False
  190. def _is_reference_item(item: PackageItem) -> bool:
  191. return item.category == "td-docs" or _is_reference_path(item)
  192. def _split_collection_by_reference(
  193. collection: AnalysisCollection,
  194. ) -> tuple[AnalysisCollection, AnalysisCollection]:
  195. core_items: list[PackageItem] = []
  196. reference_items: list[PackageItem] = []
  197. for item in collection.items:
  198. if _is_reference_item(item):
  199. if item.category == "core" and _is_reference_path(item):
  200. item = item._replace(category="reference")
  201. reference_items.append(item)
  202. else:
  203. core_items.append(item)
  204. reference_items_tuple = tuple(reference_items)
  205. core_items_tuple = tuple(core_items)
  206. reference_source_ids = {item.source_id for item in reference_items_tuple}
  207. core_source_ids = {item.source_id for item in core_items_tuple}
  208. def _filter_sources(
  209. sources: tuple[dict[str, object], ...], source_ids: set[str]
  210. ) -> tuple[dict[str, object], ...]:
  211. return tuple(s for s in sources if s.get("id") in source_ids)
  212. def _filter_git(
  213. git: tuple[dict[str, object], ...], source_ids: set[str]
  214. ) -> tuple[dict[str, object], ...]:
  215. return tuple(g for g in git if g.get("source_id") in source_ids)
  216. def _filter_snapshots(
  217. snapshots: tuple[SourceSnapshot, ...], source_ids: set[str]
  218. ) -> tuple[SourceSnapshot, ...]:
  219. return tuple(ss for ss in snapshots if ss.source_id in source_ids)
  220. core_collection = AnalysisCollection(
  221. status=collection.status,
  222. items=core_items_tuple,
  223. excluded=collection.excluded,
  224. warnings=collection.warnings,
  225. sources=_filter_sources(collection.sources, core_source_ids),
  226. git=_filter_git(collection.git, core_source_ids),
  227. source_snapshots=_filter_snapshots(collection.source_snapshots, core_source_ids),
  228. )
  229. reference_collection = AnalysisCollection(
  230. status=collection.status,
  231. items=reference_items_tuple,
  232. excluded=collection.excluded,
  233. warnings=collection.warnings,
  234. sources=_filter_sources(collection.sources, reference_source_ids),
  235. git=_filter_git(collection.git, reference_source_ids),
  236. source_snapshots=_filter_snapshots(collection.source_snapshots, reference_source_ids),
  237. )
  238. return core_collection, reference_collection
  239. class ArchivePreparation(NamedTuple):
  240. items: tuple[PackageItem, ...]
  241. excluded: tuple[dict[str, str], ...]
  242. warnings: tuple[dict[str, str], ...]
  243. def _source_snapshot(
  244. root: Path,
  245. *,
  246. source_id: str,
  247. extra_exclusions: tuple[dict[str, str], ...],
  248. profile: str = "full",
  249. ) -> SourceSnapshot:
  250. candidates, excluded, _ = scan_analysis_root(
  251. root,
  252. extra_exclusions=extra_exclusions,
  253. profile=profile,
  254. )
  255. return SourceSnapshot(
  256. source_id=source_id,
  257. root=root.resolve(strict=True),
  258. extra_exclusions=extra_exclusions,
  259. candidates=tuple(
  260. (
  261. candidate.relative,
  262. candidate.size,
  263. candidate.mtime_ns,
  264. candidate.device,
  265. candidate.inode,
  266. candidate.mode,
  267. )
  268. for candidate in candidates
  269. ),
  270. excluded=tuple((item["path"], item["rule"]) for item in excluded),
  271. )
  272. def _require_keys(payload: dict[str, object], allowed: set[str], label: str) -> None:
  273. unknown = sorted(set(payload) - allowed)
  274. if unknown:
  275. if any("include" in item.casefold() for item in unknown):
  276. raise PackagingError(f"positive include rules are forbidden in {label}: {unknown}")
  277. raise PackagingError(f"unsupported fields in {label}: {unknown}")
  278. def _expand_path(value: str, *, repo_root: Path, user_profile: Path) -> Path:
  279. tokens = {
  280. "repo_root": str(repo_root),
  281. "user_profile": str(user_profile),
  282. "codex_temp": str(user_profile / "CodexTemp"),
  283. }
  284. try:
  285. expanded = value.format_map(tokens)
  286. except (KeyError, ValueError) as exc:
  287. raise PackagingError(f"unsupported path token in external source: {value}") from exc
  288. return Path(expanded).expanduser()
  289. def load_config(
  290. path: Path,
  291. *,
  292. repo_root: Path = ROOT,
  293. user_profile: Path | None = None,
  294. ) -> HandoffConfig:
  295. try:
  296. payload = json.loads(path.read_text(encoding="utf-8-sig"))
  297. except (OSError, UnicodeError, json.JSONDecodeError) as exc:
  298. raise PackagingError(f"unable to read analysis source config: {path}") from exc
  299. if not isinstance(payload, dict):
  300. raise PackagingError("analysis source config must be a JSON object")
  301. _require_keys(
  302. payload,
  303. {
  304. "schema",
  305. "max_zip_bytes",
  306. "target_zip_bytes",
  307. "external_sources",
  308. "extra_exclusions",
  309. },
  310. "config",
  311. )
  312. if payload.get("schema") != CONFIG_SCHEMA:
  313. raise PackagingError(f"unsupported analysis source config schema: {payload.get('schema')}")
  314. max_zip_bytes = payload.get("max_zip_bytes")
  315. target_zip_bytes = payload.get("target_zip_bytes")
  316. if not isinstance(max_zip_bytes, int) or max_zip_bytes <= 0:
  317. raise PackagingError("max_zip_bytes must be a positive integer")
  318. if not isinstance(target_zip_bytes, int) or not 0 < target_zip_bytes < max_zip_bytes:
  319. raise PackagingError("target_zip_bytes must be positive and smaller than max_zip_bytes")
  320. raw_sources = payload.get("external_sources")
  321. if not isinstance(raw_sources, list):
  322. raise PackagingError("external_sources must be an array")
  323. profile = user_profile or Path.home()
  324. sources: list[ExternalSource] = []
  325. seen_ids: set[str] = set()
  326. for index, raw_source in enumerate(raw_sources):
  327. if not isinstance(raw_source, dict):
  328. raise PackagingError(f"external_sources[{index}] must be an object")
  329. _require_keys(
  330. raw_source,
  331. {"id", "category", "kind", "path_candidates", "archive_policy"},
  332. f"external_sources[{index}]",
  333. )
  334. source_id = raw_source.get("id")
  335. category = raw_source.get("category")
  336. kind = raw_source.get("kind")
  337. archive_policy = raw_source.get("archive_policy")
  338. raw_paths = raw_source.get("path_candidates")
  339. if not isinstance(source_id, str) or not source_id or source_id in seen_ids:
  340. raise PackagingError(f"external source id is missing or duplicated: {source_id}")
  341. if not isinstance(category, str) or not category:
  342. raise PackagingError(f"external source category is invalid: {source_id}")
  343. if kind not in {"directory", "file", "git_worktree"}:
  344. raise PackagingError(f"external source kind is invalid: {source_id}")
  345. if archive_policy not in {"inspect", "copy"}:
  346. raise PackagingError(f"external archive policy is invalid: {source_id}")
  347. if not isinstance(raw_paths, list) or not raw_paths or not all(isinstance(item, str) for item in raw_paths):
  348. raise PackagingError(f"external source path_candidates are invalid: {source_id}")
  349. seen_ids.add(source_id)
  350. sources.append(
  351. ExternalSource(
  352. id=source_id,
  353. category=category,
  354. kind=kind,
  355. path_candidates=tuple(
  356. _expand_path(item, repo_root=repo_root, user_profile=profile)
  357. for item in raw_paths
  358. ),
  359. archive_policy=archive_policy,
  360. )
  361. )
  362. raw_exclusions = payload.get("extra_exclusions")
  363. if not isinstance(raw_exclusions, list) or not all(isinstance(item, dict) for item in raw_exclusions):
  364. raise PackagingError("extra_exclusions must be an array of objects")
  365. exclusions: list[dict[str, str]] = []
  366. for index, raw_exclusion in enumerate(raw_exclusions):
  367. _require_keys(raw_exclusion, {"path", "reason"}, f"extra_exclusions[{index}]")
  368. exclusion_path = raw_exclusion.get("path")
  369. reason = raw_exclusion.get("reason")
  370. if not isinstance(exclusion_path, str) or not exclusion_path or "\\" in exclusion_path:
  371. raise PackagingError(f"extra exclusion path is invalid: {index}")
  372. if not isinstance(reason, str) or not reason.strip():
  373. raise PackagingError(f"extra exclusion reason is invalid: {index}")
  374. normalized_path = handoff.normalize_relative(exclusion_path.strip("/").split("/"))
  375. exclusions.append({"path": normalized_path, "reason": reason.strip()})
  376. return HandoffConfig(
  377. max_zip_bytes=max_zip_bytes,
  378. target_zip_bytes=target_zip_bytes,
  379. external_sources=tuple(sources),
  380. extra_exclusions=tuple(exclusions),
  381. )
  382. def analysis_exclusion_reason(
  383. relative: str,
  384. *,
  385. is_dir: bool,
  386. context: handoff.ScanContext,
  387. extra_exclusions: tuple[dict[str, str], ...] = (),
  388. profile: str = "full",
  389. ) -> str | None:
  390. del context
  391. lower = relative.casefold()
  392. parts = lower.split("/")
  393. raw_parts = relative.split("/")
  394. name = parts[-1]
  395. secret_reason = handoff.secret_path_reason(relative, is_dir=is_dir)
  396. if secret_reason:
  397. return secret_reason
  398. if profile == "code-only":
  399. for prefix, reason in handoff.CODE_ONLY_ROOT_EXCLUSIONS.items():
  400. if handoff.is_under(lower, prefix):
  401. return reason
  402. if not is_dir and handoff.is_under(lower, "tools/board-viewer/generated"):
  403. if name in handoff.CODE_ONLY_GENERATED_VISUAL_ASSETS:
  404. return "generated_board_viewer_visual_asset"
  405. for item in extra_exclusions:
  406. prefix = str(item.get("path", "")).casefold().strip("/")
  407. if prefix and handoff.is_under(lower, prefix):
  408. return str(item.get("reason") or "configured_analysis_exclusion")
  409. explicit_roots = {
  410. ".git": "raw_git_metadata",
  411. ".codegraph": "declared_external_reparse_alias",
  412. ".codex": "codex_session_runtime",
  413. ".hypothesis": "hypothesis_cache",
  414. ".ruff_cache": "ruff_cache",
  415. ".pytest_cache": "pytest_cache",
  416. "dist": "generated_delivery_output",
  417. "log": "runtime_log_directory",
  418. "runs": "run_state_directory",
  419. "td/build": "td_build_output",
  420. "reference/historical": "reference_historical_material",
  421. "reference/original/legacy_rtl": "reference_legacy_rtl",
  422. "receipts/local": "local_runtime_receipt",
  423. # Packaged once via external source board-viewer-generated (derived evidence).
  424. "tools/board-viewer/generated": "board_viewer_generated_packaged_via_external_source",
  425. "anlogic_cd": "vendor_installer_payload",
  426. "node_modules": "node_modules_runtime",
  427. }
  428. for prefix, reason in explicit_roots.items():
  429. if handoff.is_under(lower, prefix):
  430. return reason
  431. if handoff.is_under(lower, "tmp/edge-headless-profile"):
  432. return "browser_runtime_profile"
  433. if handoff.is_under(lower, "tmp/rtl_sim"):
  434. return "compiled_rtl_simulation"
  435. if handoff.is_under(lower, "tmp/toolchain_probe"):
  436. return "toolchain_probe_runtime"
  437. if handoff.is_under(lower, "tmp/td"):
  438. return "td_runtime_snapshot"
  439. if handoff.is_under(lower, "tmp/refactor"):
  440. return "compiled_refactor_probe"
  441. if any(component.endswith("_Runs") for component in raw_parts):
  442. return "generated_run_directory"
  443. if re.match(r"^tmp/pytest-[^/]+$", lower):
  444. return "temporary_tool_runtime"
  445. if handoff.is_under(lower, "tmp"):
  446. return "temporary_workspace_directory"
  447. if handoff.is_under(lower, "td/project/log"):
  448. return "td_gui_runtime_log"
  449. if handoff.is_under(lower, "td/project") and len(parts) >= 3 and parts[2].endswith("_runs"):
  450. return "td_gui_runtime_run"
  451. if lower in {
  452. "td/project/.lock.f",
  453. "td/project/.recent_user_depot.ini",
  454. }:
  455. return "td_gui_runtime_state"
  456. if handoff.is_under(lower, ".git"):
  457. return "raw_git_metadata"
  458. if handoff.is_under(lower, ".omo"):
  459. return "agent_session_runtime"
  460. cache_components = {
  461. ".git": "raw_git_metadata",
  462. ".codegraph": "declared_external_reparse_alias",
  463. ".codex": "codex_session_runtime",
  464. "__pycache__": "python_bytecode_cache",
  465. ".pytest_cache": "pytest_cache",
  466. ".hypothesis": "hypothesis_cache",
  467. ".mypy_cache": "mypy_cache",
  468. ".ruff_cache": "ruff_cache",
  469. ".tox": "tox_environment",
  470. ".nox": "nox_environment",
  471. ".venv": "virtual_environment",
  472. "venv": "virtual_environment",
  473. "htmlcov": "coverage_report",
  474. "build": "build_output",
  475. "runs": "run_state_directory",
  476. "node_modules": "node_modules_runtime",
  477. ".playwright-browsers": "browser_runtime_cache",
  478. }
  479. for component in parts:
  480. if component in cache_components:
  481. return cache_components[component]
  482. if component == "dist":
  483. return "generated_delivery_output"
  484. if component.endswith(".egg-info"):
  485. return "python_package_metadata"
  486. if not is_dir:
  487. suffix = Path(name).suffix.casefold()
  488. if suffix in GENERATED_BINARY_SUFFIXES:
  489. return "generated_binary_artifact"
  490. if suffix in ARCHIVE_SUFFIXES:
  491. return "archive_file_not_source"
  492. if suffix in RUNTIME_EVIDENCE_SUFFIXES:
  493. return "runtime_evidence_or_waveform"
  494. if suffix in BOARD_DESIGN_SUFFIXES:
  495. if "reference" in parts:
  496. return None
  497. return "board_design_file"
  498. if suffix in IMAGE_SUFFIXES:
  499. if "reference" in parts:
  500. return None
  501. if name in BOARD_VIEWER_GENERATED_ASSETS:
  502. return None
  503. return "image_file"
  504. if name in STRAY_FILENAMES:
  505. return "stray_or_temporary_file"
  506. if suffix in TRANSIENT_SUFFIXES or name.endswith("~"):
  507. return "temporary_file"
  508. if suffix == ".dmp" or name.startswith("minidump-"):
  509. return "crash_dump"
  510. if name in {".ds_store", "thumbs.db", "desktop.ini"}:
  511. return "os_metadata_cache"
  512. return None
  513. def scan_analysis_root(
  514. root: Path,
  515. *,
  516. extra_exclusions: tuple[dict[str, str], ...] = (),
  517. profile: str = "full",
  518. ) -> tuple[list[handoff.Candidate], list[dict[str, str]], handoff.ScanContext]:
  519. def resolve(relative: str, *, is_dir: bool, context: handoff.ScanContext) -> str | None:
  520. return analysis_exclusion_reason(
  521. relative,
  522. is_dir=is_dir,
  523. context=context,
  524. extra_exclusions=extra_exclusions,
  525. profile=profile,
  526. )
  527. return handoff.scan_tree(root, exclusion_resolver=resolve, profile=profile)
  528. def resolve_external_sources(
  529. sources: tuple[ExternalSource, ...],
  530. ) -> tuple[list[ResolvedSource], list[dict[str, str]]]:
  531. resolved: list[ResolvedSource] = []
  532. warnings: list[dict[str, str]] = []
  533. for source in sources:
  534. selected: Path | None = None
  535. for candidate in source.path_candidates:
  536. if source.kind == "file" and candidate.is_file():
  537. selected = candidate.resolve(strict=True)
  538. break
  539. if source.kind in {"directory", "git_worktree"} and candidate.is_dir():
  540. selected = candidate.resolve(strict=True)
  541. break
  542. if selected is None:
  543. warnings.append(
  544. {
  545. "code": "missing_external_source",
  546. "source_id": source.id,
  547. "message": "no configured path candidate is available",
  548. }
  549. )
  550. continue
  551. resolved.append(
  552. ResolvedSource(
  553. id=source.id,
  554. category=source.category,
  555. kind=source.kind,
  556. path=selected,
  557. archive_policy=source.archive_policy,
  558. )
  559. )
  560. return resolved, warnings
  561. def _candidate_from_path(path: Path, relative: str) -> handoff.Candidate:
  562. try:
  563. file_stat = os.lstat(path)
  564. except OSError as exc:
  565. raise PackagingError(f"unable to inspect generated analysis input: {relative}") from exc
  566. if not stat.S_ISREG(file_stat.st_mode) or handoff.stat_is_reparse_point(file_stat):
  567. raise PackagingError(f"analysis input is not a regular file: {relative}")
  568. return handoff.Candidate(
  569. absolute=path,
  570. relative=handoff.normalize_relative(relative.split("/")),
  571. size=file_stat.st_size,
  572. mtime_ns=file_stat.st_mtime_ns,
  573. device=int(file_stat.st_dev),
  574. inode=int(file_stat.st_ino),
  575. mode=int(file_stat.st_mode),
  576. )
  577. def make_package_item(
  578. path: Path,
  579. *,
  580. relative: str,
  581. category: str,
  582. source_id: str,
  583. scan_archive: bool = True,
  584. ) -> PackageItem:
  585. return PackageItem(
  586. candidate=_candidate_from_path(path, relative),
  587. category=category,
  588. source_id=source_id,
  589. original_path=path.name,
  590. scan_archive=scan_archive,
  591. )
  592. def _rebase_candidate(candidate: handoff.Candidate, prefix: str) -> handoff.Candidate:
  593. return handoff.Candidate(
  594. absolute=candidate.absolute,
  595. relative=handoff.normalize_relative([*prefix.split("/"), *candidate.relative.split("/")]),
  596. size=candidate.size,
  597. mtime_ns=candidate.mtime_ns,
  598. device=candidate.device,
  599. inode=candidate.inode,
  600. mode=candidate.mode,
  601. )
  602. def _rebase_exclusions(excluded: list[dict[str, str]], prefix: str) -> list[dict[str, str]]:
  603. return [
  604. {
  605. "path": handoff.normalize_relative([*prefix.split("/"), *item["path"].split("/")]),
  606. "rule": item["rule"],
  607. }
  608. for item in excluded
  609. ]
  610. def _collect_directory_items(
  611. *,
  612. root: Path,
  613. source_id: str,
  614. category: str,
  615. prefix: str,
  616. extra_exclusions: tuple[dict[str, str], ...],
  617. profile: str = "full",
  618. ) -> tuple[list[PackageItem], list[dict[str, str]]]:
  619. candidates, excluded, _ = scan_analysis_root(
  620. root,
  621. extra_exclusions=extra_exclusions,
  622. profile=profile,
  623. )
  624. items = [
  625. PackageItem(
  626. candidate=_rebase_candidate(candidate, prefix),
  627. category=category,
  628. source_id=source_id,
  629. original_path=candidate.relative,
  630. scan_archive=True,
  631. )
  632. for candidate in candidates
  633. ]
  634. return items, _rebase_exclusions(excluded, prefix)
  635. def _run_git(command: list[str], *, cwd: Path, timeout: int = 300) -> str:
  636. try:
  637. completed = subprocess.run(
  638. command,
  639. cwd=cwd,
  640. stdout=subprocess.PIPE,
  641. stderr=subprocess.STDOUT,
  642. text=True,
  643. encoding="utf-8",
  644. errors="replace",
  645. timeout=timeout,
  646. check=False,
  647. )
  648. except (OSError, subprocess.TimeoutExpired) as exc:
  649. raise PackagingError(f"unable to run Git for {cwd.name}") from exc
  650. if completed.returncode != 0:
  651. detail = completed.stdout.strip().splitlines()
  652. suffix = f": {detail[-1]}" if detail else ""
  653. raise PackagingError(f"Git command failed for {cwd.name}{suffix}")
  654. return completed.stdout
  655. def _create_git_bundle(
  656. *,
  657. root: Path,
  658. source_id: str,
  659. temp_root: Path,
  660. ) -> tuple[PackageItem, dict[str, object]]:
  661. git = shutil.which("git")
  662. if not git:
  663. raise PackagingError("Git is required to create complete analysis history bundles")
  664. bundle_dir = temp_root / "git-bundles"
  665. bundle_dir.mkdir(parents=True, exist_ok=True)
  666. bundle_path = bundle_dir / f"{source_id}.bundle"
  667. _run_git([git, "bundle", "create", str(bundle_path), "--all"], cwd=root)
  668. verify_output = _run_git([git, "bundle", "verify", str(bundle_path)], cwd=root)
  669. head = _run_git([git, "rev-parse", "HEAD"], cwd=root).strip()
  670. branch = _run_git([git, "branch", "--show-current"], cwd=root).strip() or None
  671. status = _run_git(
  672. [
  673. git,
  674. "--no-optional-locks",
  675. "-c",
  676. "core.fsmonitor=false",
  677. "-c",
  678. "core.untrackedCache=false",
  679. "status",
  680. "--short",
  681. "--branch",
  682. "--untracked-files=all",
  683. ],
  684. cwd=root,
  685. )
  686. ref_lines = [line for line in verify_output.splitlines() if " refs/" in line or line.rstrip().endswith(" HEAD")]
  687. candidate = _candidate_from_path(bundle_path, f"git-history/{source_id}.bundle")
  688. item = PackageItem(
  689. candidate=candidate,
  690. category="core",
  691. source_id=source_id,
  692. original_path=".git",
  693. scan_archive=False,
  694. )
  695. metadata = {
  696. "source_id": source_id,
  697. "branch": branch,
  698. "head": head,
  699. "working_tree_clean": not any(
  700. line and not line.startswith("##") for line in status.splitlines()
  701. ),
  702. "status": "pass",
  703. "bundle_path": candidate.relative,
  704. "bundle_ref_count": len(ref_lines),
  705. "bundle_verify": "pass",
  706. }
  707. return item, metadata
  708. def collect_analysis_inputs(
  709. *,
  710. repo_root: Path,
  711. config: HandoffConfig,
  712. temp_root: Path,
  713. include_git_bundle: bool = True,
  714. profile: str = "full",
  715. ) -> AnalysisCollection:
  716. root = repo_root.resolve(strict=True)
  717. temp_root.mkdir(parents=True, exist_ok=True)
  718. if profile == "full" and not include_git_bundle:
  719. raise PackagingError(
  720. "full inclusion-first packages require a git bundle so replay can restore "
  721. "commit-to-commit source closure comparison"
  722. )
  723. items: list[PackageItem] = []
  724. excluded: list[dict[str, str]] = []
  725. warnings: list[dict[str, str]] = []
  726. sources: list[dict[str, object]] = []
  727. git_metadata: list[dict[str, object]] = []
  728. source_snapshots: list[SourceSnapshot] = []
  729. root_items, root_excluded = _collect_directory_items(
  730. root=root,
  731. source_id="workspace-current",
  732. category="core",
  733. prefix="workspace-current",
  734. extra_exclusions=config.extra_exclusions,
  735. profile=profile,
  736. )
  737. items.extend(root_items)
  738. excluded.extend(root_excluded)
  739. source_snapshots.append(
  740. _source_snapshot(
  741. root,
  742. source_id="workspace-current",
  743. extra_exclusions=config.extra_exclusions,
  744. profile=profile,
  745. )
  746. )
  747. sources.append(
  748. {
  749. "id": "workspace-current",
  750. "category": "core",
  751. "kind": "git_worktree",
  752. "path": str(root),
  753. "status": "pass",
  754. }
  755. )
  756. if include_git_bundle:
  757. bundle_item, bundle_metadata = _create_git_bundle(
  758. root=root,
  759. source_id="workspace-current",
  760. temp_root=temp_root,
  761. )
  762. items.append(bundle_item)
  763. git_metadata.append(bundle_metadata)
  764. resolved_sources, source_warnings = resolve_external_sources(config.external_sources)
  765. if profile == "code-only":
  766. resolved_sources = [
  767. source for source in resolved_sources if source.id != "board-viewer-generated"
  768. ]
  769. warnings.extend(source_warnings)
  770. for source in resolved_sources:
  771. prefix = f"external/{source.id}"
  772. if source.kind == "file":
  773. candidate = _candidate_from_path(source.path, f"{prefix}/{source.path.name}")
  774. items.append(
  775. PackageItem(
  776. candidate=candidate,
  777. category=source.category,
  778. source_id=source.id,
  779. original_path=source.path.name,
  780. scan_archive=source.archive_policy == "inspect",
  781. )
  782. )
  783. else:
  784. source_items, source_excluded = _collect_directory_items(
  785. root=source.path,
  786. source_id=source.id,
  787. category=source.category,
  788. prefix=prefix,
  789. extra_exclusions=config.extra_exclusions,
  790. profile=profile,
  791. )
  792. items.extend(source_items)
  793. excluded.extend(source_excluded)
  794. source_snapshots.append(
  795. _source_snapshot(
  796. source.path,
  797. source_id=source.id,
  798. extra_exclusions=config.extra_exclusions,
  799. profile=profile,
  800. )
  801. )
  802. sources.append(
  803. {
  804. "id": source.id,
  805. "category": source.category,
  806. "kind": source.kind,
  807. "path": str(source.path),
  808. "status": "pass",
  809. }
  810. )
  811. if source.kind == "git_worktree":
  812. external_bundle, external_git = _create_git_bundle(
  813. root=source.path,
  814. source_id=source.id,
  815. temp_root=temp_root,
  816. )
  817. items.append(external_bundle)
  818. git_metadata.append(external_git)
  819. items.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
  820. excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
  821. return AnalysisCollection(
  822. status="pass_with_warnings" if warnings else "pass",
  823. items=tuple(items),
  824. excluded=tuple(excluded),
  825. warnings=tuple(warnings),
  826. sources=tuple(sources),
  827. git=tuple(git_metadata),
  828. source_snapshots=tuple(source_snapshots),
  829. )
  830. def find_7z() -> Path | None:
  831. discovered = shutil.which("7z") or shutil.which("7zz")
  832. candidates = [
  833. Path(discovered) if discovered else None,
  834. Path(r"C:\Program Files\7-Zip\7z.exe"),
  835. Path(r"C:\Program Files (x86)\7-Zip\7z.exe"),
  836. ]
  837. for candidate in candidates:
  838. if candidate is not None and candidate.is_file():
  839. return candidate.resolve(strict=True)
  840. return None
  841. def build_7zip_create_command(archive_path: Path, staging_root: Path) -> list[str]:
  842. del staging_root
  843. return [
  844. "a",
  845. "-tzip",
  846. "-mm=Deflate",
  847. "-mx=9",
  848. "-mmt",
  849. "-y",
  850. "-r",
  851. str(archive_path),
  852. "CPLD\\*",
  853. ]
  854. def _run_7z(seven_zip: Path, arguments: list[str], *, cwd: Path) -> str:
  855. try:
  856. completed = subprocess.run(
  857. [str(seven_zip), *arguments],
  858. cwd=cwd,
  859. stdout=subprocess.PIPE,
  860. stderr=subprocess.STDOUT,
  861. text=True,
  862. encoding="utf-8",
  863. errors="replace",
  864. timeout=300,
  865. check=False,
  866. )
  867. except (OSError, subprocess.TimeoutExpired) as exc:
  868. raise PackagingError("unable to run 7-Zip for archive inspection") from exc
  869. if completed.returncode != 0:
  870. detail = completed.stdout.strip().splitlines()
  871. suffix = f": {detail[-1]}" if detail else ""
  872. raise PackagingError(f"7-Zip archive inspection failed{suffix}")
  873. return completed.stdout
  874. def _rename_archive_entries(
  875. seven_zip: Path,
  876. archive_path: Path,
  877. renames: list[tuple[str, str]],
  878. ) -> None:
  879. for offset in range(0, len(renames), 64):
  880. batch = renames[offset : offset + 64]
  881. arguments = ["rn", "-y", str(archive_path)]
  882. for old_name, new_name in batch:
  883. arguments.extend((old_name, new_name))
  884. _run_7z(seven_zip, arguments, cwd=archive_path.parent)
  885. def _parse_7z_members(payload: str, archive_label: str) -> list[dict[str, str]]:
  886. in_members = False
  887. current: dict[str, str] = {}
  888. members: list[dict[str, str]] = []
  889. for raw_line in payload.splitlines():
  890. line = raw_line.rstrip("\r\n")
  891. if line.strip() == "----------":
  892. in_members = True
  893. current = {}
  894. continue
  895. if not in_members:
  896. continue
  897. if not line.strip():
  898. if current:
  899. members.append(current)
  900. current = {}
  901. continue
  902. key, separator, value = line.partition(" = ")
  903. if separator:
  904. current[key.strip()] = value.strip()
  905. if current:
  906. members.append(current)
  907. for member in members:
  908. raw_path = member.get("Path", "")
  909. normalized = raw_path.replace("\\", "/")
  910. if not normalized or normalized.startswith("/") or re.match(r"^[A-Za-z]:", normalized):
  911. raise PackagingError(f"unsafe archive member path in {archive_label}")
  912. handoff.normalize_relative(normalized.split("/"))
  913. if member.get("Encrypted") not in {None, "", "-"}:
  914. raise PackagingError(f"encrypted archive member is unsupported in {archive_label}")
  915. if member.get("Symbolic Link") or member.get("Hard Link"):
  916. raise PackagingError(f"archive link member is unsupported in {archive_label}")
  917. if member.get("Alternate Stream") not in {None, "", "-"}:
  918. raise PackagingError(f"archive alternate stream is unsupported in {archive_label}")
  919. if member.get("Split Before") not in {None, "", "-"} or member.get("Split After") not in {
  920. None,
  921. "",
  922. "-",
  923. }:
  924. raise PackagingError(f"split archive member is unsupported in {archive_label}")
  925. return members
  926. def _inspect_and_extract_unsupported_archive(
  927. item: PackageItem,
  928. *,
  929. temp_root: Path,
  930. seven_zip: Path,
  931. extra_exclusions: tuple[dict[str, str], ...],
  932. ) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
  933. listing = _run_7z(
  934. seven_zip,
  935. ["l", "-slt", "-sccUTF-8", str(item.candidate.absolute)],
  936. cwd=item.candidate.absolute.parent,
  937. )
  938. members = _parse_7z_members(listing, item.candidate.relative)
  939. file_members = [
  940. member
  941. for member in members
  942. if member.get("Folder") != "+" and "D" not in member.get("Attributes", "")
  943. ]
  944. expected_bytes = sum(int(member.get("Size") or "0") for member in file_members)
  945. token = hashlib.sha256(item.candidate.relative.encode("utf-8")).hexdigest()[:16]
  946. extract_root = temp_root / "expanded-archives" / token
  947. extract_root.mkdir(parents=True, exist_ok=False)
  948. _run_7z(
  949. seven_zip,
  950. ["x", "-y", "-aoa", "-sccUTF-8", f"-o{extract_root}", str(item.candidate.absolute)],
  951. cwd=item.candidate.absolute.parent,
  952. )
  953. actual_files = [path for path in extract_root.rglob("*") if path.is_file()]
  954. actual_bytes = sum(path.stat().st_size for path in actual_files)
  955. if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
  956. raise PackagingError(
  957. f"archive extraction inventory mismatch: {item.candidate.relative} "
  958. f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
  959. )
  960. expanded_candidates, expanded_excluded, _ = scan_analysis_root(
  961. extract_root,
  962. extra_exclusions=extra_exclusions,
  963. )
  964. handoff.audit_candidates(expanded_candidates)
  965. expanded_prefix = f"{item.candidate.relative}.expanded"
  966. expanded_items = [
  967. PackageItem(
  968. candidate=_rebase_candidate(candidate, expanded_prefix),
  969. category=item.category,
  970. source_id=item.source_id,
  971. original_path=f"{item.original_path}!/{candidate.relative}",
  972. scan_archive=True,
  973. )
  974. for candidate in expanded_candidates
  975. ]
  976. rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
  977. sensitive_rules = {
  978. "credential_or_license_file",
  979. "credential_configuration_file",
  980. "private_key_file",
  981. "secret_environment_file",
  982. "cloud_credential_file",
  983. "container_registry_credential_file",
  984. }
  985. contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
  986. return expanded_items, rebased_excluded, contains_sensitive
  987. def _inspect_and_extract_zip_archive(
  988. item: PackageItem,
  989. *,
  990. temp_root: Path,
  991. extra_exclusions: tuple[dict[str, str], ...],
  992. ) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
  993. archive_label = item.candidate.relative
  994. try:
  995. with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
  996. file_members: list[zipfile.ZipInfo] = []
  997. expected_bytes = 0
  998. for info in archive.infolist():
  999. normalized = info.filename.replace("\\", "/")
  1000. if (
  1001. not normalized
  1002. or normalized.startswith("/")
  1003. or re.match(r"^[A-Za-z]:", normalized)
  1004. ):
  1005. raise PackagingError(
  1006. f"unsafe archive member path in {archive_label}"
  1007. )
  1008. handoff.normalize_relative(normalized.split("/"))
  1009. if info.flag_bits & 0x1:
  1010. raise PackagingError(
  1011. f"encrypted archive member is unsupported in {archive_label}"
  1012. )
  1013. member_mode = (info.external_attr >> 16) & 0xFFFF
  1014. member_type = stat.S_IFMT(member_mode)
  1015. if info.is_dir():
  1016. if (
  1017. info.file_size != 0
  1018. or info.compress_size != 0
  1019. or member_type not in {0, stat.S_IFDIR}
  1020. ):
  1021. raise PackagingError(
  1022. f"unsafe archive member type in {archive_label}"
  1023. )
  1024. continue
  1025. if member_type not in {0, stat.S_IFREG}:
  1026. raise PackagingError(
  1027. f"unsafe archive member type in {archive_label}"
  1028. )
  1029. file_members.append(info)
  1030. expected_bytes += info.file_size
  1031. except (OSError, zipfile.BadZipFile) as exc:
  1032. raise PackagingError(
  1033. f"unable to inspect source archive: {archive_label}"
  1034. ) from exc
  1035. token = hashlib.sha256(archive_label.encode("utf-8")).hexdigest()[:16]
  1036. extract_root = temp_root / "expanded-archives" / token
  1037. extract_root.mkdir(parents=True, exist_ok=False)
  1038. actual_files: list[Path] = []
  1039. actual_bytes = 0
  1040. try:
  1041. with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
  1042. for info in file_members:
  1043. parts = info.filename.replace("\\", "/").split("/")
  1044. target_path = extract_root / Path(*parts)
  1045. target_path.parent.mkdir(parents=True, exist_ok=True)
  1046. with archive.open(info, "r") as source, target_path.open("wb") as destination:
  1047. shutil.copyfileobj(source, destination, length=1024 * 1024)
  1048. actual_files.append(target_path)
  1049. actual_bytes += target_path.stat().st_size
  1050. except (OSError, zipfile.BadZipFile) as exc:
  1051. raise PackagingError(
  1052. f"unable to extract source archive: {archive_label}"
  1053. ) from exc
  1054. if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
  1055. raise PackagingError(
  1056. f"archive extraction inventory mismatch: {archive_label} "
  1057. f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
  1058. )
  1059. expanded_candidates, expanded_excluded, _ = scan_analysis_root(
  1060. extract_root,
  1061. extra_exclusions=extra_exclusions,
  1062. )
  1063. handoff.audit_candidates(expanded_candidates)
  1064. expanded_prefix = f"{archive_label}.expanded"
  1065. expanded_items = [
  1066. PackageItem(
  1067. candidate=_rebase_candidate(candidate, expanded_prefix),
  1068. category=item.category,
  1069. source_id=item.source_id,
  1070. original_path=f"{item.original_path}!/{candidate.relative}",
  1071. scan_archive=True,
  1072. )
  1073. for candidate in expanded_candidates
  1074. ]
  1075. rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
  1076. sensitive_rules = {
  1077. "credential_or_license_file",
  1078. "credential_configuration_file",
  1079. "private_key_file",
  1080. "secret_environment_file",
  1081. "cloud_credential_file",
  1082. "container_registry_credential_file",
  1083. }
  1084. contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
  1085. return expanded_items, rebased_excluded, contains_sensitive
  1086. def prepare_unsupported_archives(
  1087. items: tuple[PackageItem, ...],
  1088. *,
  1089. temp_root: Path,
  1090. seven_zip: Path | None,
  1091. extra_exclusions: tuple[dict[str, str], ...],
  1092. ) -> ArchivePreparation:
  1093. prepared: list[PackageItem] = []
  1094. excluded: list[dict[str, str]] = []
  1095. warnings: list[dict[str, str]] = []
  1096. temp_root.mkdir(parents=True, exist_ok=True)
  1097. for item in items:
  1098. archive_kind = handoff.archive_kind(item.candidate.relative)
  1099. if archive_kind is None:
  1100. prepared.append(item)
  1101. continue
  1102. if archive_kind == "zip":
  1103. expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_zip_archive(
  1104. item,
  1105. temp_root=temp_root,
  1106. extra_exclusions=extra_exclusions,
  1107. )
  1108. elif seven_zip is None:
  1109. if _is_reference_item(item):
  1110. warnings.append(
  1111. {
  1112. "code": "unsupported_archive_without_7zip",
  1113. "source_id": item.source_id,
  1114. "path": item.candidate.relative,
  1115. "message": "7-Zip is unavailable; unsupported archive kept unexpanded",
  1116. }
  1117. )
  1118. prepared.append(item._replace(scan_archive=False))
  1119. continue
  1120. if item.candidate.absolute.is_file():
  1121. raise PackagingError(
  1122. "7-Zip is required to inspect unsupported source archives"
  1123. )
  1124. prepared.append(item._replace(scan_archive=False))
  1125. continue
  1126. else:
  1127. expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_unsupported_archive(
  1128. item,
  1129. temp_root=temp_root,
  1130. seven_zip=seven_zip,
  1131. extra_exclusions=extra_exclusions,
  1132. )
  1133. has_filtered_members = bool(expanded_excluded)
  1134. if has_filtered_members:
  1135. prepared.extend(expanded_items)
  1136. excluded.extend(expanded_excluded)
  1137. if contains_sensitive:
  1138. excluded.append(
  1139. {
  1140. "path": item.candidate.relative,
  1141. "rule": "unsupported_archive_contains_sensitive_content",
  1142. }
  1143. )
  1144. elif has_filtered_members:
  1145. excluded.append(
  1146. {
  1147. "path": item.candidate.relative,
  1148. "rule": "archive_contains_excluded_members",
  1149. }
  1150. )
  1151. else:
  1152. prepared.append(item._replace(scan_archive=archive_kind != "unsupported"))
  1153. prepared.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
  1154. excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
  1155. return ArchivePreparation(
  1156. items=tuple(prepared),
  1157. excluded=tuple(excluded),
  1158. warnings=tuple(warnings),
  1159. )
  1160. def _utc_now() -> str:
  1161. return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
  1162. def _validate_package_name(package_name: str) -> None:
  1163. try:
  1164. collision_key = handoff.windows_collision_key(package_name)
  1165. except PackagingError as exc:
  1166. raise PackagingError("package name is not a portable Windows file name") from exc
  1167. if (
  1168. not handoff.SAFE_PACKAGE_NAME.fullmatch(package_name)
  1169. or package_name in {".", ".."}
  1170. or not collision_key
  1171. ):
  1172. raise PackagingError("package name is not a portable Windows file name")
  1173. def _item_sort_key(item: PackageItem) -> tuple[int, str, str]:
  1174. return (
  1175. CATEGORY_ORDER.get(item.category, len(CATEGORY_ORDER)),
  1176. item.category.casefold(),
  1177. handoff.windows_collision_key(item.candidate.relative),
  1178. )
  1179. def _path_basename(relative: str) -> str:
  1180. return relative.casefold().rsplit("/", 1)[-1]
  1181. def _is_board_viewer_generated_path(relative: str) -> bool:
  1182. lower = relative.casefold()
  1183. return (
  1184. "board-viewer-generated" in lower
  1185. or "/tools/board-viewer/generated/" in f"/{lower}/"
  1186. or lower.startswith("tools/board-viewer/generated/")
  1187. )
  1188. def _is_reference_original_path(relative: str) -> bool:
  1189. lower = f"/{relative.casefold()}/"
  1190. return "/reference/original/" in lower or lower.startswith("/reference/original/")
  1191. def _dedup_canonical_path(paths: list[str]) -> str:
  1192. def rank(path: str) -> tuple[int, int, str]:
  1193. name = _path_basename(path)
  1194. in_reference = _is_reference_original_path(path)
  1195. in_generated = _is_board_viewer_generated_path(path)
  1196. if name in BOARD_VIEWER_GENERATED_ASSETS or name in DERIVED_BOARD_VIEWER_ASSETS:
  1197. return (0 if in_generated else 1, 0 if in_reference else 1, path.casefold())
  1198. if name.endswith((".brd", ".pdf", ".dsn", ".sch")):
  1199. return (0 if in_reference else 1, 0 if in_generated else 1, path.casefold())
  1200. return (0 if in_reference else 1, 0 if in_generated else 1, path.casefold())
  1201. return sorted(paths, key=rank)[0]
  1202. def _should_content_dedup(size: int, relative: str) -> bool:
  1203. name = _path_basename(relative)
  1204. if name in DERIVED_BOARD_VIEWER_ASSETS or name.endswith((".brd", ".pdf")):
  1205. return True
  1206. return size >= CONTENT_DEDUP_MIN_BYTES
  1207. def apply_content_dedup(
  1208. items: tuple[PackageItem, ...],
  1209. inventory: list[dict[str, object]],
  1210. ) -> tuple[tuple[PackageItem, ...], list[dict[str, object]], list[dict[str, str]]]:
  1211. """Keep one physical copy per identical content hash; record logical aliases."""
  1212. by_path = {str(row["path"]): row for row in inventory}
  1213. groups: dict[str, list[PackageItem]] = {}
  1214. for item in items:
  1215. row = by_path[item.candidate.relative]
  1216. sha = str(row["sha256"])
  1217. size = int(row["size"])
  1218. if not _should_content_dedup(size, item.candidate.relative):
  1219. continue
  1220. groups.setdefault(sha, []).append(item)
  1221. drop_paths: set[str] = set()
  1222. dedup_records: list[dict[str, object]] = []
  1223. excluded: list[dict[str, str]] = []
  1224. for sha, group in sorted(groups.items(), key=lambda pair: pair[0]):
  1225. if len(group) < 2:
  1226. continue
  1227. paths = [item.candidate.relative for item in group]
  1228. canonical = _dedup_canonical_path(paths)
  1229. aliases = sorted(path for path in paths if path != canonical)
  1230. if not aliases:
  1231. continue
  1232. size = int(by_path[canonical]["size"])
  1233. dedup_records.append(
  1234. {
  1235. "sha256": sha,
  1236. "size": size,
  1237. "physical_path": canonical,
  1238. "logical_paths": aliases,
  1239. "reason": "identical_content_single_physical_copy",
  1240. }
  1241. )
  1242. for alias in aliases:
  1243. drop_paths.add(alias)
  1244. excluded.append(
  1245. {
  1246. "path": alias,
  1247. "rule": "duplicate_content_logical_alias",
  1248. }
  1249. )
  1250. physical_items = tuple(
  1251. item for item in items if item.candidate.relative not in drop_paths
  1252. )
  1253. dedup_records.sort(key=lambda row: str(row["physical_path"]).casefold())
  1254. excluded.sort(key=lambda row: handoff.windows_collision_key(row["path"]))
  1255. return physical_items, dedup_records, excluded
  1256. def classify_derived_evidence(items: tuple[PackageItem, ...]) -> list[dict[str, object]]:
  1257. derived: list[dict[str, object]] = []
  1258. for item in items:
  1259. name = _path_basename(item.candidate.relative)
  1260. if name not in DERIVED_BOARD_VIEWER_ASSETS:
  1261. continue
  1262. if not _is_board_viewer_generated_path(item.candidate.relative):
  1263. continue
  1264. role = "derived_from_brd_visual" if name in BOARD_VIEWER_GENERATED_ASSETS else "derived_from_brd_parsed"
  1265. derived.append(
  1266. {
  1267. "path": item.candidate.relative,
  1268. "asset": name,
  1269. "role": role,
  1270. "authority": "analysis_evidence_not_source_closure",
  1271. "note": "Derived from the original Allegro BRD for remote analysis; not RTL/TD source closure.",
  1272. }
  1273. )
  1274. derived.sort(key=lambda row: str(row["path"]).casefold())
  1275. return derived
  1276. def replay_analysis_package(package_dir: Path, *, extract_root: Path) -> dict[str, object]:
  1277. """Extract a published package and verify SHA256SUMS plus inventory hashes."""
  1278. package_dir = package_dir.expanduser().resolve(strict=True)
  1279. extract_root = extract_root.expanduser().resolve(strict=False)
  1280. if extract_root.exists():
  1281. raise PackagingError(f"replay extract root already exists: {extract_root}")
  1282. index_path = package_dir / "HANDOFF-INDEX.json"
  1283. sums_path = package_dir / "SHA256SUMS.txt"
  1284. exclusions_path = package_dir / "EXCLUSIONS.txt"
  1285. if not index_path.is_file() or not sums_path.is_file():
  1286. raise PackagingError("package directory is missing HANDOFF-INDEX.json or SHA256SUMS.txt")
  1287. index = json.loads(index_path.read_text(encoding="utf-8"))
  1288. extract_root.mkdir(parents=True, exist_ok=False)
  1289. zip_extract_root = extract_root / "from-zip"
  1290. tar_extract_root = extract_root / "from-tar-zst"
  1291. zip_extract_root.mkdir(parents=True, exist_ok=True)
  1292. verified_volumes: list[dict[str, object]] = []
  1293. verified_sidecars: list[dict[str, object]] = []
  1294. tar_zst_name: str | None = None
  1295. for line in sums_path.read_text(encoding="ascii").splitlines():
  1296. line = line.strip()
  1297. if not line or line.startswith("#"):
  1298. continue
  1299. digest, _, name = line.partition(" ")
  1300. if not digest or not name:
  1301. raise PackagingError(f"invalid SHA256SUMS line: {line}")
  1302. member_path = package_dir / name
  1303. actual = handoff.sha256_file(member_path)
  1304. if actual != digest:
  1305. raise PackagingError(f"SHA256SUMS mismatch for {name}")
  1306. lower = name.casefold()
  1307. if lower.endswith(".zip"):
  1308. with zipfile.ZipFile(member_path, "r", allowZip64=True) as archive:
  1309. archive.extractall(zip_extract_root)
  1310. verified_volumes.append({"file": name, "sha256": actual})
  1311. elif lower.endswith(".tar.zst"):
  1312. tar_zst_name = name
  1313. tar_extract_root.mkdir(parents=True, exist_ok=True)
  1314. completed = subprocess.run(
  1315. ["tar", "--zstd", "-xf", str(member_path), "-C", str(tar_extract_root)],
  1316. stdout=subprocess.PIPE,
  1317. stderr=subprocess.PIPE,
  1318. check=False,
  1319. )
  1320. if completed.returncode != 0:
  1321. raise PackagingError(
  1322. f"unable to extract tar.zst during replay: {name}: "
  1323. f"{completed.stderr.decode('utf-8', errors='replace').strip()}"
  1324. )
  1325. verified_sidecars.append({"file": name, "sha256": actual, "kind": "tar_zst"})
  1326. else:
  1327. verified_sidecars.append({"file": name, "sha256": actual, "kind": "sidecar"})
  1328. checked_files = 0
  1329. for item in index.get("files", []):
  1330. relative = str(item["path"])
  1331. target = zip_extract_root / "CPLD" / Path(*relative.split("/"))
  1332. if not target.is_file():
  1333. raise PackagingError(f"replay missing extracted file: {relative}")
  1334. digest = handoff.sha256_file(target)
  1335. if digest != item["sha256"] or target.stat().st_size != int(item["size"]):
  1336. raise PackagingError(f"replay hash mismatch for {relative}")
  1337. if tar_zst_name is not None:
  1338. # tar.zst is created from ZIP extract roots, so the same CPLD tree must round-trip.
  1339. tar_target = tar_extract_root / "CPLD" / Path(*relative.split("/"))
  1340. if not tar_target.is_file():
  1341. raise PackagingError(f"tar.zst replay missing extracted file: {relative}")
  1342. if handoff.sha256_file(tar_target) != digest:
  1343. raise PackagingError(f"tar.zst replay hash mismatch for {relative}")
  1344. checked_files += 1
  1345. for record in index.get("content_dedup", []):
  1346. physical = zip_extract_root / "CPLD" / Path(*str(record["physical_path"]).split("/"))
  1347. if not physical.is_file():
  1348. raise PackagingError(f"replay missing dedup physical file: {record['physical_path']}")
  1349. for alias in record.get("logical_paths", []):
  1350. alias_path = zip_extract_root / "CPLD" / Path(*str(alias).split("/"))
  1351. if alias_path.exists():
  1352. raise PackagingError(f"replay found duplicated physical alias path: {alias}")
  1353. return {
  1354. "status": "pass",
  1355. "mode": "package_replay",
  1356. "package_dir": str(package_dir),
  1357. "extract_root": str(extract_root),
  1358. "volumes": verified_volumes,
  1359. "sidecars": verified_sidecars,
  1360. "exclusions_present": exclusions_path.is_file(),
  1361. "tar_zst": tar_zst_name,
  1362. "checked_files": checked_files,
  1363. "content_dedup_groups": len(index.get("content_dedup", [])),
  1364. "derived_evidence_count": len(index.get("derived_evidence", [])),
  1365. }
  1366. def _audit_one_item(item: PackageItem) -> dict[str, object]:
  1367. if item.scan_archive:
  1368. file_inventory = handoff.stream_candidate(item.candidate)
  1369. else:
  1370. file_inventory = handoff.hash_candidate(item.candidate)
  1371. return {
  1372. **file_inventory,
  1373. "archive_path": f"CPLD/{item.candidate.relative}",
  1374. "category": item.category,
  1375. "source_id": item.source_id,
  1376. "original_path": item.original_path,
  1377. }
  1378. def _audit_package_items(items: tuple[PackageItem, ...]) -> list[dict[str, object]]:
  1379. sorted_items = sorted(items, key=_item_sort_key)
  1380. collision_paths: dict[str, str] = {}
  1381. for item in sorted_items:
  1382. key = handoff.windows_collision_key(item.candidate.relative)
  1383. previous = collision_paths.get(key)
  1384. if previous is not None:
  1385. raise PackagingError(
  1386. f"analysis inputs contain a Windows path collision: {previous} and {item.candidate.relative}"
  1387. )
  1388. collision_paths[key] = item.candidate.relative
  1389. max_workers = os.cpu_count() or 1
  1390. with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
  1391. return list(executor.map(_audit_one_item, sorted_items))
  1392. def _write_unscanned_candidate(
  1393. archive: zipfile.ZipFile,
  1394. item: PackageItem,
  1395. ) -> dict[str, object]:
  1396. candidate = item.candidate
  1397. digest = hashlib.sha256()
  1398. total = 0
  1399. secret_tail = b""
  1400. entry_name = f"CPLD/{candidate.relative}"
  1401. try:
  1402. with archive.open(handoff.zip_info(entry_name, candidate.mode), "w", force_zip64=True) as target:
  1403. with handoff.open_candidate(candidate) as source:
  1404. for chunk in iter(lambda: source.read(1024 * 1024), b""):
  1405. secret_tail = handoff.scan_secret_markers(
  1406. chunk,
  1407. secret_tail,
  1408. candidate.relative,
  1409. )
  1410. target.write(chunk)
  1411. digest.update(chunk)
  1412. total += len(chunk)
  1413. except OSError as exc:
  1414. raise PackagingError(f"unable to package {candidate.relative}: {exc}") from exc
  1415. if total != candidate.size:
  1416. raise PackagingError(f"source size changed during packaging: {candidate.relative}")
  1417. return {"path": candidate.relative, "size": total, "sha256": digest.hexdigest()}
  1418. def _write_package_item(
  1419. archive: zipfile.ZipFile,
  1420. item: PackageItem,
  1421. ) -> dict[str, object]:
  1422. if item.scan_archive:
  1423. return handoff.write_candidate(archive, item.candidate)
  1424. return _write_unscanned_candidate(archive, item)
  1425. def _stage_package_item(
  1426. staging_root: Path,
  1427. item: PackageItem,
  1428. staging_name: str,
  1429. ) -> dict[str, object]:
  1430. target = staging_root / "CPLD" / staging_name
  1431. target.parent.mkdir(parents=True, exist_ok=True)
  1432. if item.scan_archive:
  1433. try:
  1434. with target.open("wb") as destination:
  1435. return handoff.stream_candidate(item.candidate, target=destination)
  1436. except OSError as exc:
  1437. raise PackagingError(f"unable to stage {item.candidate.relative}: {exc}") from exc
  1438. digest = hashlib.sha256()
  1439. total = 0
  1440. secret_tail = b""
  1441. try:
  1442. with handoff.open_candidate(item.candidate) as source, target.open("wb") as destination:
  1443. for chunk in iter(lambda: source.read(1024 * 1024), b""):
  1444. secret_tail = handoff.scan_secret_markers(
  1445. chunk,
  1446. secret_tail,
  1447. item.candidate.relative,
  1448. )
  1449. destination.write(chunk)
  1450. digest.update(chunk)
  1451. total += len(chunk)
  1452. except OSError as exc:
  1453. raise PackagingError(f"unable to stage {item.candidate.relative}: {exc}") from exc
  1454. if total != item.candidate.size:
  1455. raise PackagingError(f"source size changed during staging: {item.candidate.relative}")
  1456. return {"path": item.candidate.relative, "size": total, "sha256": digest.hexdigest()}
  1457. def _volume_manifest(
  1458. *,
  1459. run_id: str,
  1460. package_name: str,
  1461. number: int,
  1462. count: int,
  1463. items: list[PackageItem],
  1464. inventory_by_path: dict[str, dict[str, object]],
  1465. ) -> dict[str, object]:
  1466. categories = sorted({item.category for item in items})
  1467. entries = [inventory_by_path[item.candidate.relative] for item in items]
  1468. return {
  1469. "schema": "cpld-agent-analysis-volume-v1",
  1470. "run_id": run_id,
  1471. "package_name": package_name,
  1472. "volume_number": number,
  1473. "volume_count": count,
  1474. "categories": categories,
  1475. "file_count": len(entries),
  1476. "uncompressed_bytes": sum(int(entry["size"]) for entry in entries),
  1477. "files": entries,
  1478. }
  1479. def _write_volume(
  1480. path: Path,
  1481. *,
  1482. run_id: str,
  1483. package_name: str,
  1484. number: int,
  1485. count: int,
  1486. items: list[PackageItem],
  1487. inventory_by_path: dict[str, dict[str, object]],
  1488. ) -> dict[str, object]:
  1489. manifest = _volume_manifest(
  1490. run_id=run_id,
  1491. package_name=package_name,
  1492. number=number,
  1493. count=count,
  1494. items=items,
  1495. inventory_by_path=inventory_by_path,
  1496. )
  1497. manifest_name = "CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json"
  1498. manifest_payload = handoff.json_bytes(manifest)
  1499. written_inventory: list[dict[str, object]] = []
  1500. try:
  1501. with zipfile.ZipFile(
  1502. path,
  1503. "w",
  1504. compression=zipfile.ZIP_DEFLATED,
  1505. compresslevel=9,
  1506. allowZip64=True,
  1507. ) as archive:
  1508. for item in sorted(items, key=_item_sort_key):
  1509. expected = inventory_by_path[item.candidate.relative]
  1510. if item.scan_archive:
  1511. actual = handoff.write_candidate(archive, item.candidate)
  1512. else:
  1513. actual = _write_unscanned_candidate(archive, item)
  1514. if (
  1515. actual["size"] != expected["size"]
  1516. or actual["sha256"] != expected["sha256"]
  1517. ):
  1518. raise PackagingError(
  1519. f"source changed while writing ZIP: {item.candidate.relative}"
  1520. )
  1521. written_inventory.append(actual)
  1522. with archive.open(
  1523. handoff.zip_info(manifest_name), "w", force_zip64=True
  1524. ) as target:
  1525. target.write(manifest_payload)
  1526. except (OSError, zipfile.BadZipFile) as exc:
  1527. raise PackagingError(f"unable to create ZIP volume: {exc}") from exc
  1528. expected_names = {f"CPLD/{item.candidate.relative}" for item in items}
  1529. expected_names.add(manifest_name)
  1530. handoff.verify_archive(
  1531. path,
  1532. expected_names=expected_names,
  1533. inventory=written_inventory,
  1534. expected_payloads={manifest_name: manifest_payload},
  1535. )
  1536. return {
  1537. "file": path.name,
  1538. "volume_number": number,
  1539. "volume_count": count,
  1540. "categories": manifest["categories"],
  1541. "file_count": len(items),
  1542. "uncompressed_bytes": manifest["uncompressed_bytes"],
  1543. "compressed_bytes": path.stat().st_size,
  1544. "sha256": handoff.sha256_file(path),
  1545. }
  1546. def _estimated_item_bytes(item: PackageItem) -> int:
  1547. return item.candidate.size + 512 + (len(item.candidate.relative.encode("utf-8")) * 2)
  1548. def _partition_items(
  1549. items: tuple[PackageItem, ...],
  1550. *,
  1551. target_zip_bytes: int,
  1552. ) -> list[list[PackageItem]]:
  1553. base_overhead = min(64_000, max(1_024, target_zip_bytes // 20))
  1554. groups: list[list[PackageItem]] = []
  1555. current: list[PackageItem] = []
  1556. current_category: str | None = None
  1557. estimated_bytes = base_overhead
  1558. for item in sorted(items, key=_item_sort_key):
  1559. item_estimate = _estimated_item_bytes(item)
  1560. if current and (
  1561. item.category != current_category
  1562. or estimated_bytes + item_estimate > target_zip_bytes
  1563. ):
  1564. groups.append(current)
  1565. current = []
  1566. estimated_bytes = base_overhead
  1567. if not current:
  1568. current_category = item.category
  1569. current.append(item)
  1570. estimated_bytes += item_estimate
  1571. if current:
  1572. groups.append(current)
  1573. return groups
  1574. def _split_oversized_groups(
  1575. staging: Path,
  1576. *,
  1577. run_id: str,
  1578. package_name: str,
  1579. groups: list[list[PackageItem]],
  1580. inventory_by_path: dict[str, dict[str, object]],
  1581. target_zip_bytes: int,
  1582. max_zip_bytes: int,
  1583. ) -> list[list[PackageItem]]:
  1584. pending = list(groups)
  1585. accepted: list[list[PackageItem]] = []
  1586. probe_number = 0
  1587. while pending:
  1588. group = pending.pop(0)
  1589. probe_number += 1
  1590. probe = staging / f".volume-probe-{probe_number:04d}.zip"
  1591. try:
  1592. _write_volume(
  1593. probe,
  1594. run_id=run_id,
  1595. package_name=package_name,
  1596. number=1,
  1597. count=1,
  1598. items=group,
  1599. inventory_by_path=inventory_by_path,
  1600. )
  1601. size = probe.stat().st_size
  1602. finally:
  1603. probe.unlink(missing_ok=True)
  1604. if size < max_zip_bytes and (size <= target_zip_bytes or len(group) == 1):
  1605. accepted.append(group)
  1606. continue
  1607. if len(group) == 1:
  1608. raise PackagingError(
  1609. f"single analysis file requires chunking before ZIP creation: {group[0].candidate.relative}"
  1610. )
  1611. middle = len(group) // 2
  1612. pending[0:0] = [group[:middle], group[middle:]]
  1613. return accepted
  1614. def _prepare_large_file_chunks(
  1615. staging: Path,
  1616. *,
  1617. run_id: str,
  1618. package_name: str,
  1619. items: tuple[PackageItem, ...],
  1620. inventory_by_path: dict[str, dict[str, object]],
  1621. target_zip_bytes: int,
  1622. max_zip_bytes: int,
  1623. ) -> tuple[tuple[PackageItem, ...], list[dict[str, object]], Path | None]:
  1624. packaged_items: list[PackageItem] = []
  1625. large_files: list[dict[str, object]] = []
  1626. chunk_root: Path | None = None
  1627. probe_number = 0
  1628. chunk_payload_bytes = max(1, (target_zip_bytes * 3) // 4)
  1629. for item in sorted(items, key=_item_sort_key):
  1630. must_probe = _estimated_item_bytes(item) > target_zip_bytes
  1631. if must_probe:
  1632. probe_number += 1
  1633. probe = staging / f".large-file-probe-{probe_number:04d}.zip"
  1634. try:
  1635. _write_volume(
  1636. probe,
  1637. run_id=run_id,
  1638. package_name=package_name,
  1639. number=1,
  1640. count=1,
  1641. items=[item],
  1642. inventory_by_path=inventory_by_path,
  1643. )
  1644. probe_size = probe.stat().st_size
  1645. finally:
  1646. probe.unlink(missing_ok=True)
  1647. if probe_size <= target_zip_bytes and probe_size < max_zip_bytes:
  1648. packaged_items.append(item)
  1649. continue
  1650. else:
  1651. packaged_items.append(item)
  1652. continue
  1653. if chunk_root is None:
  1654. chunk_root = staging / ".large-file-chunks"
  1655. chunk_root.mkdir()
  1656. original = inventory_by_path[item.candidate.relative]
  1657. file_id = hashlib.sha256(item.candidate.relative.encode("utf-8")).hexdigest()[:16]
  1658. file_chunk_root = chunk_root / file_id
  1659. file_chunk_root.mkdir()
  1660. file_name = Path(item.candidate.relative).name
  1661. chunks: list[dict[str, object]] = []
  1662. original_digest = hashlib.sha256()
  1663. original_bytes = 0
  1664. secret_tail = b""
  1665. with handoff.open_candidate(item.candidate) as source:
  1666. number = 0
  1667. while True:
  1668. payload = source.read(chunk_payload_bytes)
  1669. if not payload:
  1670. break
  1671. number += 1
  1672. secret_tail = handoff.scan_secret_markers(
  1673. payload,
  1674. secret_tail,
  1675. item.candidate.relative,
  1676. )
  1677. original_digest.update(payload)
  1678. original_bytes += len(payload)
  1679. chunk_name = f"{file_name}.part{number:04d}"
  1680. chunk_path = file_chunk_root / chunk_name
  1681. with chunk_path.open("xb") as handle:
  1682. handle.write(payload)
  1683. chunk_relative = f"HANDOFF-LARGE-FILES/{file_id}/{chunk_name}"
  1684. chunk_item = make_package_item(
  1685. chunk_path,
  1686. relative=chunk_relative,
  1687. category=item.category,
  1688. source_id=item.source_id,
  1689. scan_archive=False,
  1690. )
  1691. packaged_items.append(chunk_item)
  1692. chunks.append(
  1693. {
  1694. "number": number,
  1695. "path": chunk_relative,
  1696. "archive_path": f"CPLD/{chunk_relative}",
  1697. "size": len(payload),
  1698. "sha256": hashlib.sha256(payload).hexdigest(),
  1699. }
  1700. )
  1701. if original_bytes != original["size"] or original_digest.hexdigest() != original["sha256"]:
  1702. raise PackagingError(f"source changed while splitting large file: {item.candidate.relative}")
  1703. if len(chunks) < 2:
  1704. raise PackagingError(f"large file split did not produce multiple chunks: {item.candidate.relative}")
  1705. large_files.append(
  1706. {
  1707. "path": item.candidate.relative,
  1708. "category": item.category,
  1709. "source_id": item.source_id,
  1710. "original_path": item.original_path,
  1711. "size": original["size"],
  1712. "sha256": original["sha256"],
  1713. "chunks": chunks,
  1714. }
  1715. )
  1716. return tuple(packaged_items), large_files, chunk_root
  1717. def _assert_items_unchanged(
  1718. items: tuple[PackageItem, ...],
  1719. inventory_by_path: dict[str, dict[str, object]],
  1720. ) -> None:
  1721. for item in items:
  1722. current = handoff.hash_candidate(item.candidate)
  1723. expected = inventory_by_path[item.candidate.relative]
  1724. if current["size"] != expected["size"] or current["sha256"] != expected["sha256"]:
  1725. raise PackagingError(f"source changed during analysis packaging: {item.candidate.relative}")
  1726. def _assert_source_trees_unchanged(collection: AnalysisCollection, *, profile: str = "full") -> None:
  1727. for snapshot in collection.source_snapshots:
  1728. current = _source_snapshot(
  1729. snapshot.root,
  1730. source_id=snapshot.source_id,
  1731. extra_exclusions=snapshot.extra_exclusions,
  1732. profile=profile,
  1733. )
  1734. if (
  1735. current.candidates != snapshot.candidates
  1736. or current.excluded != snapshot.excluded
  1737. ):
  1738. raise PackagingError("source tree changed during analysis packaging: retry from a stable workspace snapshot")
  1739. def _start_here_text(package_name: str, volume_count: int) -> str:
  1740. return (
  1741. f"# {package_name} 分析交付包\n\n"
  1742. f"本目录包含 {volume_count} 个互相独立的普通 ZIP,以及可选的 `.tar.zst` 同源归档。"
  1743. "请先核对 `SHA256SUMS.txt`,再把所有 ZIP 解压到同一个目录;"
  1744. "也可用 `tar --zstd -xf <package>.tar.zst` 还原。\n\n"
  1745. "`HANDOFF-INDEX.json` 记录每个原始文件的来源、目标卷、大小和 SHA-256,"
  1746. "`EXCLUSIONS.txt` 列出排除路径与规则,"
  1747. "以及 `excluded`(排除原因)、`derived_evidence`(由原始 BRD 派生的 board-viewer JSON/SVG,"
  1748. "不是 RTL/TD source closure)和 `content_dedup`(相同大文件只保留一份物理副本时的逻辑归属)。\n"
  1749. "完整 full 包必须包含 `git-history/*.bundle`,以便在干净提取后用 commit-to-commit "
  1750. "恢复 source closure 比对。\n"
  1751. )
  1752. def write_exclusions_text(excluded: list[dict[str, object]]) -> str:
  1753. """Render a portable EXCLUSIONS.txt for the package sidecar layout."""
  1754. lines = [
  1755. "# path<TAB>rule",
  1756. "# Inclusion-first package: only versioned recursive exclusions are listed.",
  1757. ]
  1758. for item in sorted(excluded, key=lambda row: handoff.windows_collision_key(str(row.get("path", "")))):
  1759. path = str(item.get("path", ""))
  1760. rule = str(item.get("rule", item.get("reason", "excluded")))
  1761. lines.append(f"{path}\t{rule}")
  1762. return "\n".join(lines) + "\n"
  1763. def create_tar_zst_archive(source_dir: Path, archive_path: Path) -> str:
  1764. """Create a deterministic-enough tar.zst of source_dir contents; return SHA-256."""
  1765. source_dir = source_dir.resolve(strict=True)
  1766. archive_path = archive_path.resolve(strict=False)
  1767. if archive_path.exists():
  1768. archive_path.unlink()
  1769. zstd = shutil.which("zstd")
  1770. if zstd is None:
  1771. raise PackagingError("zstd is required to create .tar.zst package archives")
  1772. # Prefer GNU tar --zstd when available; fall back to compress-program.
  1773. command = [
  1774. "tar",
  1775. "--zstd",
  1776. "-cf",
  1777. str(archive_path),
  1778. "--sort=name",
  1779. "--mtime=UTC 1980-01-01",
  1780. "--owner=0",
  1781. "--group=0",
  1782. "--numeric-owner",
  1783. "-C",
  1784. str(source_dir),
  1785. ".",
  1786. ]
  1787. completed = subprocess.run(
  1788. command,
  1789. stdout=subprocess.PIPE,
  1790. stderr=subprocess.PIPE,
  1791. check=False,
  1792. )
  1793. if completed.returncode != 0:
  1794. # Older tar without --zstd / --sort: use compress-program path.
  1795. fallback = [
  1796. "tar",
  1797. "-cf",
  1798. str(archive_path),
  1799. "-I",
  1800. zstd,
  1801. "-C",
  1802. str(source_dir),
  1803. ".",
  1804. ]
  1805. completed = subprocess.run(
  1806. fallback,
  1807. stdout=subprocess.PIPE,
  1808. stderr=subprocess.PIPE,
  1809. check=False,
  1810. )
  1811. if completed.returncode != 0:
  1812. detail = completed.stderr.decode("utf-8", errors="replace").strip()
  1813. raise PackagingError(f"unable to create tar.zst archive: {detail or 'tar failed'}")
  1814. return handoff.sha256_file(archive_path)
  1815. def write_package_layout_sidecars(
  1816. staging: Path,
  1817. *,
  1818. index: dict[str, object],
  1819. excluded: list[dict[str, object]],
  1820. package_name: str,
  1821. include_tar_zst: bool = True,
  1822. ) -> list[dict[str, object]]:
  1823. """Write index/checksums/exclusions and optional tar.zst; return checksum rows."""
  1824. staging.mkdir(parents=True, exist_ok=True)
  1825. (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
  1826. (staging / "EXCLUSIONS.txt").write_text(
  1827. write_exclusions_text(excluded),
  1828. encoding="utf-8",
  1829. newline="\n",
  1830. )
  1831. (staging / "START-HERE.zh-CN.md").write_text(
  1832. _start_here_text(package_name, len(index.get("volumes", []))),
  1833. encoding="utf-8",
  1834. newline="\n",
  1835. )
  1836. checksum_rows: list[dict[str, object]] = []
  1837. for info in index.get("volumes", []):
  1838. name = str(info["file"])
  1839. checksum_rows.append({"file": name, "sha256": str(info["sha256"])})
  1840. if include_tar_zst:
  1841. # Stage CPLD tree from ZIP volumes into a temporary extract for tar.zst.
  1842. extract_root = staging / ".tar-zst-staging"
  1843. if extract_root.exists():
  1844. shutil.rmtree(extract_root)
  1845. extract_root.mkdir(parents=True, exist_ok=True)
  1846. for info in index.get("volumes", []):
  1847. volume_path = staging / str(info["file"])
  1848. with zipfile.ZipFile(volume_path, "r", allowZip64=True) as archive:
  1849. archive.extractall(extract_root)
  1850. tar_name = f"{package_name}.tar.zst"
  1851. tar_path = staging / tar_name
  1852. tar_sha = create_tar_zst_archive(extract_root, tar_path)
  1853. shutil.rmtree(extract_root)
  1854. checksum_rows.append({"file": tar_name, "sha256": tar_sha})
  1855. index["formats"] = {
  1856. "zip_volumes": [str(info["file"]) for info in index.get("volumes", [])],
  1857. "tar_zst": tar_name,
  1858. "tar_zst_sha256": tar_sha,
  1859. }
  1860. (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
  1861. for sidecar in ("HANDOFF-INDEX.json", "EXCLUSIONS.txt", "START-HERE.zh-CN.md"):
  1862. checksum_rows.append(
  1863. {"file": sidecar, "sha256": handoff.sha256_file(staging / sidecar)}
  1864. )
  1865. checksum_lines = [f"{row['sha256']} {row['file']}" for row in checksum_rows]
  1866. (staging / "SHA256SUMS.txt").write_text(
  1867. "\n".join(checksum_lines) + "\n",
  1868. encoding="ascii",
  1869. newline="\n",
  1870. )
  1871. return checksum_rows
  1872. def _publish_directory_atomically(staging: Path, final: Path, *, force: bool) -> None:
  1873. backup: Path | None = None
  1874. backup_created = False
  1875. new_directory_published = False
  1876. if os.path.lexists(final):
  1877. if not force:
  1878. raise PackagingError(f"package output already exists: {final}")
  1879. file_stat = os.lstat(final)
  1880. if not stat.S_ISDIR(file_stat.st_mode) or handoff.stat_is_reparse_point(file_stat):
  1881. raise PackagingError(f"existing package output is not a regular directory: {final}")
  1882. backup = final.with_name(f".{final.name}.{uuid.uuid4().hex}.backup")
  1883. try:
  1884. if backup is not None:
  1885. os.replace(final, backup)
  1886. backup_created = True
  1887. os.replace(staging, final)
  1888. new_directory_published = True
  1889. except BaseException as exc:
  1890. if new_directory_published and os.path.lexists(final):
  1891. try:
  1892. shutil.rmtree(final)
  1893. except OSError:
  1894. pass
  1895. if backup_created and backup is not None and os.path.lexists(backup):
  1896. try:
  1897. os.replace(backup, final)
  1898. except OSError as rollback_exc:
  1899. raise PackagingError(
  1900. f"package publication failed and rollback was incomplete: {rollback_exc}"
  1901. ) from exc
  1902. if isinstance(exc, PackagingError):
  1903. raise
  1904. raise PackagingError(f"unable to publish package directory atomically: {exc}") from exc
  1905. if backup is not None:
  1906. shutil.rmtree(backup)
  1907. def create_analysis_package(
  1908. *,
  1909. collection: AnalysisCollection,
  1910. output_root: Path,
  1911. package_name: str,
  1912. max_zip_bytes: int,
  1913. target_zip_bytes: int,
  1914. force: bool,
  1915. profile: str = "full",
  1916. ) -> dict[str, object]:
  1917. _validate_package_name(package_name)
  1918. if max_zip_bytes <= 0 or not 0 < target_zip_bytes < max_zip_bytes:
  1919. raise PackagingError("ZIP size limits are invalid")
  1920. if not collection.items:
  1921. raise PackagingError("analysis package has no included files")
  1922. output_root = output_root.expanduser().resolve(strict=False)
  1923. output_root.mkdir(parents=True, exist_ok=True)
  1924. final_dir = output_root / package_name
  1925. if os.path.lexists(final_dir) and not force:
  1926. raise PackagingError(f"package output already exists: {final_dir}")
  1927. run_id = uuid.uuid4().hex
  1928. staging = Path(tempfile.mkdtemp(prefix=f".{package_name}.{run_id}.", dir=output_root))
  1929. try:
  1930. full_inventory = _audit_package_items(collection.items)
  1931. physical_items, content_dedup, dedup_excluded = apply_content_dedup(
  1932. collection.items,
  1933. full_inventory,
  1934. )
  1935. inventory = [
  1936. row
  1937. for row in full_inventory
  1938. if str(row["path"]) in {item.candidate.relative for item in physical_items}
  1939. ]
  1940. inventory_by_path = {str(item["path"]): item for item in inventory}
  1941. package_excluded = list(collection.excluded) + dedup_excluded
  1942. package_excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
  1943. derived_evidence = classify_derived_evidence(physical_items)
  1944. package_items = physical_items
  1945. package_inventory = inventory
  1946. package_inventory_by_path = inventory_by_path
  1947. large_files: list[dict[str, object]] = []
  1948. chunk_root: Path | None = None
  1949. single_path = staging / f"{package_name}.zip"
  1950. single_info = _write_volume(
  1951. single_path,
  1952. run_id=run_id,
  1953. package_name=package_name,
  1954. number=1,
  1955. count=1,
  1956. items=list(sorted(physical_items, key=_item_sort_key)),
  1957. inventory_by_path=inventory_by_path,
  1958. )
  1959. if single_path.stat().st_size < max_zip_bytes:
  1960. volume_infos = [single_info]
  1961. groups = [list(sorted(physical_items, key=_item_sort_key))]
  1962. else:
  1963. single_path.unlink()
  1964. package_items, large_files, chunk_root = _prepare_large_file_chunks(
  1965. staging,
  1966. run_id=run_id,
  1967. package_name=package_name,
  1968. items=physical_items,
  1969. inventory_by_path=inventory_by_path,
  1970. target_zip_bytes=target_zip_bytes,
  1971. max_zip_bytes=max_zip_bytes,
  1972. )
  1973. package_inventory = _audit_package_items(package_items)
  1974. package_inventory_by_path = {
  1975. str(item["path"]): item for item in package_inventory
  1976. }
  1977. initial_groups = _partition_items(
  1978. package_items,
  1979. target_zip_bytes=target_zip_bytes,
  1980. )
  1981. groups = _split_oversized_groups(
  1982. staging,
  1983. run_id=run_id,
  1984. package_name=package_name,
  1985. groups=initial_groups,
  1986. inventory_by_path=package_inventory_by_path,
  1987. target_zip_bytes=target_zip_bytes,
  1988. max_zip_bytes=max_zip_bytes,
  1989. )
  1990. volume_infos = []
  1991. count = len(groups)
  1992. for number, group in enumerate(groups, start=1):
  1993. category = group[0].category if len({item.category for item in group}) == 1 else "mixed"
  1994. safe_category = re.sub(r"[^a-z0-9]+", "-", category.casefold()).strip("-") or "data"
  1995. volume_path = staging / f"{package_name}.part{number:03d}-{safe_category}.zip"
  1996. volume_info = _write_volume(
  1997. volume_path,
  1998. run_id=run_id,
  1999. package_name=package_name,
  2000. number=number,
  2001. count=count,
  2002. items=group,
  2003. inventory_by_path=package_inventory_by_path,
  2004. )
  2005. if volume_path.stat().st_size >= max_zip_bytes:
  2006. raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
  2007. volume_infos.append(volume_info)
  2008. volume_by_path: dict[str, str] = {}
  2009. for volume_info, group in zip(volume_infos, groups, strict=True):
  2010. for item in group:
  2011. volume_by_path[item.candidate.relative] = str(volume_info["file"])
  2012. large_paths = {str(item["path"]) for item in large_files}
  2013. indexed_files = [
  2014. {**item, "volume": volume_by_path[str(item["path"])]}
  2015. for item in inventory
  2016. if str(item["path"]) not in large_paths
  2017. ]
  2018. for large_file in large_files:
  2019. for chunk in large_file["chunks"]:
  2020. chunk["volume"] = volume_by_path[str(chunk["path"])]
  2021. index = {
  2022. "schema": "cpld-agent-analysis-index-v1",
  2023. "run_id": run_id,
  2024. "created_at_utc": _utc_now(),
  2025. "package_name": package_name,
  2026. "status": collection.status,
  2027. "profile": profile,
  2028. "delivery_policy": "code-only" if profile == "code-only" else "inclusion-first",
  2029. "max_zip_bytes": max_zip_bytes,
  2030. "target_zip_bytes": target_zip_bytes,
  2031. "sources": list(collection.sources),
  2032. "git": list(collection.git),
  2033. "warnings": list(collection.warnings),
  2034. "excluded": package_excluded,
  2035. "content_dedup": content_dedup,
  2036. "derived_evidence": derived_evidence,
  2037. "volumes": volume_infos,
  2038. "files": indexed_files,
  2039. "large_files": large_files,
  2040. }
  2041. if large_files:
  2042. (staging / "reassemble_large_files.py").write_text(
  2043. REASSEMBLER_SCRIPT,
  2044. encoding="utf-8",
  2045. newline="\n",
  2046. )
  2047. for info in volume_infos:
  2048. volume_path = staging / str(info["file"])
  2049. if volume_path.stat().st_size >= max_zip_bytes:
  2050. raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
  2051. if handoff.sha256_file(volume_path) != info["sha256"]:
  2052. raise PackagingError(f"ZIP volume hash changed after verification: {volume_path.name}")
  2053. checksum_rows = write_package_layout_sidecars(
  2054. staging,
  2055. index=index,
  2056. excluded=package_excluded,
  2057. package_name=package_name,
  2058. include_tar_zst=True,
  2059. )
  2060. full_inventory_by_path = {str(item["path"]): item for item in full_inventory}
  2061. _assert_items_unchanged(collection.items, full_inventory_by_path)
  2062. _assert_source_trees_unchanged(collection, profile=profile)
  2063. if chunk_root is not None:
  2064. shutil.rmtree(chunk_root)
  2065. _publish_directory_atomically(staging, final_dir, force=force)
  2066. except BaseException:
  2067. if os.path.lexists(staging):
  2068. shutil.rmtree(staging, ignore_errors=True)
  2069. raise
  2070. formats = {}
  2071. index_path = final_dir / "HANDOFF-INDEX.json"
  2072. if index_path.is_file():
  2073. formats = json.loads(index_path.read_text(encoding="utf-8")).get("formats", {})
  2074. return {
  2075. "status": collection.status,
  2076. "mode": "package",
  2077. "profile": profile,
  2078. "delivery_policy": "code-only" if profile == "code-only" else "inclusion-first",
  2079. "run_id": run_id,
  2080. "output_dir": str(final_dir),
  2081. "volumes": volume_infos,
  2082. "formats": formats,
  2083. "checksum_entries": len(checksum_rows),
  2084. "included_file_count": len(inventory),
  2085. "included_bytes": sum(int(item["size"]) for item in inventory),
  2086. "excluded_entry_count": len(package_excluded),
  2087. "content_dedup_groups": len(content_dedup),
  2088. "derived_evidence_count": len(derived_evidence),
  2089. "warning_count": len(collection.warnings),
  2090. }
  2091. def _reference_fingerprint(inventory: list[dict[str, object]]) -> str:
  2092. digest = hashlib.sha256()
  2093. for item in sorted(inventory, key=lambda row: str(row["path"])):
  2094. path = str(item["path"])
  2095. size = str(item["size"])
  2096. sha = str(item["sha256"])
  2097. digest.update(f"{path}|{size}|{sha}\n".encode("utf-8"))
  2098. return digest.hexdigest()
  2099. def _create_reference_package_with_cache(
  2100. *,
  2101. collection: AnalysisCollection,
  2102. output_root: Path,
  2103. package_name: str,
  2104. max_zip_bytes: int,
  2105. target_zip_bytes: int,
  2106. force: bool,
  2107. ) -> dict[str, object]:
  2108. reference_package_name = f"{package_name}-reference"
  2109. reference_dir = output_root / reference_package_name
  2110. fingerprint_path = reference_dir / "REFERENCE-FINGERPRINT"
  2111. inventory = _audit_package_items(collection.items)
  2112. fingerprint = _reference_fingerprint(inventory)
  2113. if not force and fingerprint_path.exists():
  2114. previous = fingerprint_path.read_text(encoding="ascii").strip()
  2115. if previous == fingerprint:
  2116. index_path = reference_dir / "HANDOFF-INDEX.json"
  2117. if index_path.exists():
  2118. index = json.loads(index_path.read_text(encoding="utf-8"))
  2119. return {
  2120. "status": collection.status,
  2121. "mode": "reference_cached",
  2122. "package_name": reference_package_name,
  2123. "output_dir": str(reference_dir),
  2124. "volumes": index.get("volumes", []),
  2125. "included_file_count": len(inventory),
  2126. "included_bytes": sum(int(item["size"]) for item in inventory),
  2127. "fingerprint": fingerprint,
  2128. "skipped": True,
  2129. }
  2130. payload = create_analysis_package(
  2131. collection=collection,
  2132. output_root=output_root,
  2133. package_name=reference_package_name,
  2134. max_zip_bytes=max_zip_bytes,
  2135. target_zip_bytes=target_zip_bytes,
  2136. force=force,
  2137. )
  2138. reference_dir = Path(payload["output_dir"])
  2139. fingerprint_path = reference_dir / "REFERENCE-FINGERPRINT"
  2140. fingerprint_path.write_text(fingerprint + "\n", encoding="ascii")
  2141. payload["fingerprint"] = fingerprint
  2142. payload["skipped"] = False
  2143. return payload
  2144. def merge_archive_preparation(
  2145. collection: AnalysisCollection,
  2146. preparation: ArchivePreparation,
  2147. ) -> AnalysisCollection:
  2148. warnings = (*collection.warnings, *preparation.warnings)
  2149. excluded = sorted(
  2150. (*collection.excluded, *preparation.excluded),
  2151. key=lambda item: handoff.windows_collision_key(item["path"]),
  2152. )
  2153. return AnalysisCollection(
  2154. status="pass_with_warnings" if warnings else "pass",
  2155. items=preparation.items,
  2156. excluded=tuple(excluded),
  2157. warnings=tuple(warnings),
  2158. sources=collection.sources,
  2159. git=collection.git,
  2160. source_snapshots=collection.source_snapshots,
  2161. )
  2162. def explain_analysis_path(
  2163. path: Path,
  2164. *,
  2165. repo_root: Path,
  2166. config: HandoffConfig,
  2167. profile: str = "full",
  2168. ) -> dict[str, object]:
  2169. root = repo_root.resolve(strict=True)
  2170. requested = path if path.is_absolute() else root / path
  2171. target = requested.expanduser().resolve(strict=False)
  2172. resolved_sources, warnings = resolve_external_sources(config.external_sources)
  2173. source_roots: list[tuple[str, str, Path, Path | None]] = [
  2174. ("workspace-current", "core", root, None)
  2175. ]
  2176. for source in resolved_sources:
  2177. if source.kind == "file":
  2178. source_roots.append((source.id, source.category, source.path.parent, source.path))
  2179. else:
  2180. source_roots.append((source.id, source.category, source.path, None))
  2181. matches: list[tuple[int, str, str, Path, Path | None]] = []
  2182. for source_id, category, source_root, exact_file in source_roots:
  2183. if exact_file is not None and target != exact_file:
  2184. continue
  2185. try:
  2186. target.relative_to(source_root)
  2187. except ValueError:
  2188. continue
  2189. matches.append((len(source_root.parts), source_id, category, source_root, exact_file))
  2190. if not matches:
  2191. raise PackagingError("path is outside the current repository and configured external sources")
  2192. _, source_id, category, source_root, exact_file = max(matches, key=lambda item: item[0])
  2193. relative = exact_file.name if exact_file is not None else target.relative_to(source_root).as_posix()
  2194. if not relative:
  2195. relative = "."
  2196. is_dir = target.is_dir()
  2197. context = handoff.load_scan_context(source_root)
  2198. reason = analysis_exclusion_reason(
  2199. relative,
  2200. is_dir=is_dir,
  2201. context=context,
  2202. extra_exclusions=config.extra_exclusions,
  2203. profile=profile,
  2204. )
  2205. archive_relative = (
  2206. f"workspace-current/{relative}"
  2207. if source_id == "workspace-current"
  2208. else f"external/{source_id}/{relative}"
  2209. )
  2210. return {
  2211. "status": "pass_with_warnings" if warnings else "pass",
  2212. "mode": "explain",
  2213. "path": str(target),
  2214. "exists": target.exists(),
  2215. "source_id": source_id,
  2216. "category": category,
  2217. "source_relative_path": relative,
  2218. "archive_path": f"CPLD/{archive_relative}",
  2219. "decision": "exclude" if reason else "include",
  2220. "reason": reason,
  2221. "content_scan": "not_run",
  2222. "warnings": warnings,
  2223. }
  2224. def audit_analysis_collection(collection: AnalysisCollection) -> dict[str, object]:
  2225. inventory = _audit_package_items(collection.items)
  2226. inventory_by_path = {str(item["path"]): item for item in inventory}
  2227. _assert_items_unchanged(collection.items, inventory_by_path)
  2228. return {
  2229. "status": collection.status,
  2230. "mode": "audit_only",
  2231. "included_file_count": len(inventory),
  2232. "included_bytes": sum(int(item["size"]) for item in inventory),
  2233. "excluded_entry_count": len(collection.excluded),
  2234. "warning_count": len(collection.warnings),
  2235. "warnings": list(collection.warnings),
  2236. "sources": list(collection.sources),
  2237. "git": list(collection.git),
  2238. }
  2239. def _validate_output_root(
  2240. output_root: Path,
  2241. *,
  2242. repo_root: Path,
  2243. config: HandoffConfig,
  2244. ) -> Path:
  2245. output = output_root.expanduser().resolve(strict=False)
  2246. source_paths = [repo_root.resolve(strict=True)]
  2247. resolved_sources, _ = resolve_external_sources(config.external_sources)
  2248. source_paths.extend(source.path if source.kind != "file" else source.path.parent for source in resolved_sources)
  2249. for source_path in source_paths:
  2250. try:
  2251. output.relative_to(source_path)
  2252. except ValueError:
  2253. continue
  2254. raise PackagingError(f"output directory must be outside every packaged source root: {source_path}")
  2255. return output
  2256. def build_parser() -> argparse.ArgumentParser:
  2257. parser = argparse.ArgumentParser(description=__doc__)
  2258. parser.add_argument("--audit-only", action="store_true", help="scan and verify inputs without creating ZIP files")
  2259. parser.add_argument("--explain", type=Path, metavar="PATH", help="explain whether one path is included or excluded")
  2260. parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG, help="source and exclusion configuration JSON")
  2261. parser.add_argument("--source-root", type=Path, default=ROOT, help="root directory to package as the primary source")
  2262. parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR, help="parent directory for the package directory")
  2263. parser.add_argument("--package-name", help="portable package directory and ZIP base name")
  2264. parser.add_argument("--force-overwrite", action="store_true", help="atomically replace an existing package directory")
  2265. parser.add_argument("--no-git-bundle", action="store_true", help="omit the git history bundle from the package")
  2266. parser.add_argument(
  2267. "--profile",
  2268. choices=sorted(handoff.HANDOFF_PROFILES),
  2269. default="full",
  2270. help=(
  2271. "inclusion-first full profile packages source+reference+derived board-viewer evidence "
  2272. "(core/reference split); code-only excludes reference/ and heavy SVG assets"
  2273. ),
  2274. )
  2275. parser.add_argument(
  2276. "--replay-package",
  2277. type=Path,
  2278. metavar="DIR",
  2279. help="verify SHA256SUMS and replay-extract an existing package directory (selftest)",
  2280. )
  2281. parser.add_argument(
  2282. "--replay-extract-dir",
  2283. type=Path,
  2284. help="extract target for --replay-package (must not already exist)",
  2285. )
  2286. return parser
  2287. def main(argv: list[str] | None = None) -> int:
  2288. args = build_parser().parse_args(argv)
  2289. package_name = args.package_name or datetime.now(timezone.utc).strftime(
  2290. "cpld-agent-analysis-%Y%m%dT%H%M%SZ"
  2291. )
  2292. try:
  2293. if args.replay_package is not None:
  2294. extract_root = args.replay_extract_dir or Path(
  2295. tempfile.mkdtemp(prefix="prod2u-package-replay-", dir=os.environ.get("TMPDIR", "/tmp"))
  2296. )
  2297. payload = replay_analysis_package(args.replay_package, extract_root=extract_root)
  2298. print(json.dumps(payload, ensure_ascii=False, indent=2))
  2299. return 0
  2300. source_root = args.source_root.expanduser().resolve(strict=True)
  2301. if args.profile not in handoff.HANDOFF_PROFILES:
  2302. raise PackagingError(f"unsupported handoff profile: {args.profile}")
  2303. config = load_config(args.config, repo_root=source_root)
  2304. if args.explain is not None:
  2305. payload = explain_analysis_path(
  2306. args.explain,
  2307. repo_root=source_root,
  2308. config=config,
  2309. profile=args.profile,
  2310. )
  2311. else:
  2312. seven_zip = find_7z()
  2313. _validate_package_name(package_name)
  2314. output_root = _validate_output_root(args.output_dir, repo_root=source_root, config=config)
  2315. with tempfile.TemporaryDirectory(prefix="ca-") as temporary:
  2316. temp_root = Path(temporary)
  2317. collection = collect_analysis_inputs(
  2318. repo_root=source_root,
  2319. config=config,
  2320. temp_root=temp_root / "inputs",
  2321. include_git_bundle=not args.no_git_bundle,
  2322. profile=args.profile,
  2323. )
  2324. preparation = prepare_unsupported_archives(
  2325. collection.items,
  2326. temp_root=temp_root / "archives",
  2327. seven_zip=seven_zip,
  2328. extra_exclusions=config.extra_exclusions,
  2329. )
  2330. prepared_collection = merge_archive_preparation(collection, preparation)
  2331. if args.audit_only:
  2332. payload = audit_analysis_collection(prepared_collection)
  2333. payload["profile"] = args.profile
  2334. elif args.profile == "code-only":
  2335. if not prepared_collection.items:
  2336. raise PackagingError("analysis package has no included files")
  2337. payload = create_analysis_package(
  2338. collection=prepared_collection,
  2339. output_root=output_root,
  2340. package_name=package_name,
  2341. max_zip_bytes=config.max_zip_bytes,
  2342. target_zip_bytes=config.target_zip_bytes,
  2343. force=args.force_overwrite,
  2344. profile=args.profile,
  2345. )
  2346. else:
  2347. core_collection, reference_collection = _split_collection_by_reference(
  2348. prepared_collection
  2349. )
  2350. if not core_collection.items and not reference_collection.items:
  2351. raise PackagingError("analysis package has no included files")
  2352. payload: dict[str, object] = {}
  2353. if core_collection.items:
  2354. payload["core"] = create_analysis_package(
  2355. collection=core_collection,
  2356. output_root=output_root,
  2357. package_name=package_name,
  2358. max_zip_bytes=config.max_zip_bytes,
  2359. target_zip_bytes=config.target_zip_bytes,
  2360. force=args.force_overwrite,
  2361. profile=args.profile,
  2362. )
  2363. if reference_collection.items:
  2364. payload["reference"] = _create_reference_package_with_cache(
  2365. collection=reference_collection,
  2366. output_root=output_root,
  2367. package_name=package_name,
  2368. max_zip_bytes=config.max_zip_bytes,
  2369. target_zip_bytes=config.target_zip_bytes,
  2370. force=args.force_overwrite,
  2371. )
  2372. except (PackagingError, OSError, ValueError) as exc:
  2373. print(f"error: {exc}", file=sys.stderr)
  2374. return 1
  2375. print(json.dumps(payload, ensure_ascii=False, indent=2))
  2376. return 0
  2377. if __name__ == "__main__":
  2378. raise SystemExit(main())