package_for_agent_analysis.py 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394
  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. items: list[PackageItem] = []
  719. excluded: list[dict[str, str]] = []
  720. warnings: list[dict[str, str]] = []
  721. sources: list[dict[str, object]] = []
  722. git_metadata: list[dict[str, object]] = []
  723. source_snapshots: list[SourceSnapshot] = []
  724. root_items, root_excluded = _collect_directory_items(
  725. root=root,
  726. source_id="workspace-current",
  727. category="core",
  728. prefix="workspace-current",
  729. extra_exclusions=config.extra_exclusions,
  730. profile=profile,
  731. )
  732. items.extend(root_items)
  733. excluded.extend(root_excluded)
  734. source_snapshots.append(
  735. _source_snapshot(
  736. root,
  737. source_id="workspace-current",
  738. extra_exclusions=config.extra_exclusions,
  739. profile=profile,
  740. )
  741. )
  742. sources.append(
  743. {
  744. "id": "workspace-current",
  745. "category": "core",
  746. "kind": "git_worktree",
  747. "path": str(root),
  748. "status": "pass",
  749. }
  750. )
  751. if include_git_bundle:
  752. bundle_item, bundle_metadata = _create_git_bundle(
  753. root=root,
  754. source_id="workspace-current",
  755. temp_root=temp_root,
  756. )
  757. items.append(bundle_item)
  758. git_metadata.append(bundle_metadata)
  759. resolved_sources, source_warnings = resolve_external_sources(config.external_sources)
  760. if profile == "code-only":
  761. resolved_sources = [
  762. source for source in resolved_sources if source.id != "board-viewer-generated"
  763. ]
  764. warnings.extend(source_warnings)
  765. for source in resolved_sources:
  766. prefix = f"external/{source.id}"
  767. if source.kind == "file":
  768. candidate = _candidate_from_path(source.path, f"{prefix}/{source.path.name}")
  769. items.append(
  770. PackageItem(
  771. candidate=candidate,
  772. category=source.category,
  773. source_id=source.id,
  774. original_path=source.path.name,
  775. scan_archive=source.archive_policy == "inspect",
  776. )
  777. )
  778. else:
  779. source_items, source_excluded = _collect_directory_items(
  780. root=source.path,
  781. source_id=source.id,
  782. category=source.category,
  783. prefix=prefix,
  784. extra_exclusions=config.extra_exclusions,
  785. profile=profile,
  786. )
  787. items.extend(source_items)
  788. excluded.extend(source_excluded)
  789. source_snapshots.append(
  790. _source_snapshot(
  791. source.path,
  792. source_id=source.id,
  793. extra_exclusions=config.extra_exclusions,
  794. profile=profile,
  795. )
  796. )
  797. sources.append(
  798. {
  799. "id": source.id,
  800. "category": source.category,
  801. "kind": source.kind,
  802. "path": str(source.path),
  803. "status": "pass",
  804. }
  805. )
  806. if source.kind == "git_worktree":
  807. external_bundle, external_git = _create_git_bundle(
  808. root=source.path,
  809. source_id=source.id,
  810. temp_root=temp_root,
  811. )
  812. items.append(external_bundle)
  813. git_metadata.append(external_git)
  814. items.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
  815. excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
  816. return AnalysisCollection(
  817. status="pass_with_warnings" if warnings else "pass",
  818. items=tuple(items),
  819. excluded=tuple(excluded),
  820. warnings=tuple(warnings),
  821. sources=tuple(sources),
  822. git=tuple(git_metadata),
  823. source_snapshots=tuple(source_snapshots),
  824. )
  825. def find_7z() -> Path | None:
  826. discovered = shutil.which("7z") or shutil.which("7zz")
  827. candidates = [
  828. Path(discovered) if discovered else None,
  829. Path(r"C:\Program Files\7-Zip\7z.exe"),
  830. Path(r"C:\Program Files (x86)\7-Zip\7z.exe"),
  831. ]
  832. for candidate in candidates:
  833. if candidate is not None and candidate.is_file():
  834. return candidate.resolve(strict=True)
  835. return None
  836. def build_7zip_create_command(archive_path: Path, staging_root: Path) -> list[str]:
  837. del staging_root
  838. return [
  839. "a",
  840. "-tzip",
  841. "-mm=Deflate",
  842. "-mx=9",
  843. "-mmt",
  844. "-y",
  845. "-r",
  846. str(archive_path),
  847. "CPLD\\*",
  848. ]
  849. def _run_7z(seven_zip: Path, arguments: list[str], *, cwd: Path) -> str:
  850. try:
  851. completed = subprocess.run(
  852. [str(seven_zip), *arguments],
  853. cwd=cwd,
  854. stdout=subprocess.PIPE,
  855. stderr=subprocess.STDOUT,
  856. text=True,
  857. encoding="utf-8",
  858. errors="replace",
  859. timeout=300,
  860. check=False,
  861. )
  862. except (OSError, subprocess.TimeoutExpired) as exc:
  863. raise PackagingError("unable to run 7-Zip for archive inspection") from exc
  864. if completed.returncode != 0:
  865. detail = completed.stdout.strip().splitlines()
  866. suffix = f": {detail[-1]}" if detail else ""
  867. raise PackagingError(f"7-Zip archive inspection failed{suffix}")
  868. return completed.stdout
  869. def _rename_archive_entries(
  870. seven_zip: Path,
  871. archive_path: Path,
  872. renames: list[tuple[str, str]],
  873. ) -> None:
  874. for offset in range(0, len(renames), 64):
  875. batch = renames[offset : offset + 64]
  876. arguments = ["rn", "-y", str(archive_path)]
  877. for old_name, new_name in batch:
  878. arguments.extend((old_name, new_name))
  879. _run_7z(seven_zip, arguments, cwd=archive_path.parent)
  880. def _parse_7z_members(payload: str, archive_label: str) -> list[dict[str, str]]:
  881. in_members = False
  882. current: dict[str, str] = {}
  883. members: list[dict[str, str]] = []
  884. for raw_line in payload.splitlines():
  885. line = raw_line.rstrip("\r\n")
  886. if line.strip() == "----------":
  887. in_members = True
  888. current = {}
  889. continue
  890. if not in_members:
  891. continue
  892. if not line.strip():
  893. if current:
  894. members.append(current)
  895. current = {}
  896. continue
  897. key, separator, value = line.partition(" = ")
  898. if separator:
  899. current[key.strip()] = value.strip()
  900. if current:
  901. members.append(current)
  902. for member in members:
  903. raw_path = member.get("Path", "")
  904. normalized = raw_path.replace("\\", "/")
  905. if not normalized or normalized.startswith("/") or re.match(r"^[A-Za-z]:", normalized):
  906. raise PackagingError(f"unsafe archive member path in {archive_label}")
  907. handoff.normalize_relative(normalized.split("/"))
  908. if member.get("Encrypted") not in {None, "", "-"}:
  909. raise PackagingError(f"encrypted archive member is unsupported in {archive_label}")
  910. if member.get("Symbolic Link") or member.get("Hard Link"):
  911. raise PackagingError(f"archive link member is unsupported in {archive_label}")
  912. if member.get("Alternate Stream") not in {None, "", "-"}:
  913. raise PackagingError(f"archive alternate stream is unsupported in {archive_label}")
  914. if member.get("Split Before") not in {None, "", "-"} or member.get("Split After") not in {
  915. None,
  916. "",
  917. "-",
  918. }:
  919. raise PackagingError(f"split archive member is unsupported in {archive_label}")
  920. return members
  921. def _inspect_and_extract_unsupported_archive(
  922. item: PackageItem,
  923. *,
  924. temp_root: Path,
  925. seven_zip: Path,
  926. extra_exclusions: tuple[dict[str, str], ...],
  927. ) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
  928. listing = _run_7z(
  929. seven_zip,
  930. ["l", "-slt", "-sccUTF-8", str(item.candidate.absolute)],
  931. cwd=item.candidate.absolute.parent,
  932. )
  933. members = _parse_7z_members(listing, item.candidate.relative)
  934. file_members = [
  935. member
  936. for member in members
  937. if member.get("Folder") != "+" and "D" not in member.get("Attributes", "")
  938. ]
  939. expected_bytes = sum(int(member.get("Size") or "0") for member in file_members)
  940. token = hashlib.sha256(item.candidate.relative.encode("utf-8")).hexdigest()[:16]
  941. extract_root = temp_root / "expanded-archives" / token
  942. extract_root.mkdir(parents=True, exist_ok=False)
  943. _run_7z(
  944. seven_zip,
  945. ["x", "-y", "-aoa", "-sccUTF-8", f"-o{extract_root}", str(item.candidate.absolute)],
  946. cwd=item.candidate.absolute.parent,
  947. )
  948. actual_files = [path for path in extract_root.rglob("*") if path.is_file()]
  949. actual_bytes = sum(path.stat().st_size for path in actual_files)
  950. if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
  951. raise PackagingError(
  952. f"archive extraction inventory mismatch: {item.candidate.relative} "
  953. f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
  954. )
  955. expanded_candidates, expanded_excluded, _ = scan_analysis_root(
  956. extract_root,
  957. extra_exclusions=extra_exclusions,
  958. )
  959. handoff.audit_candidates(expanded_candidates)
  960. expanded_prefix = f"{item.candidate.relative}.expanded"
  961. expanded_items = [
  962. PackageItem(
  963. candidate=_rebase_candidate(candidate, expanded_prefix),
  964. category=item.category,
  965. source_id=item.source_id,
  966. original_path=f"{item.original_path}!/{candidate.relative}",
  967. scan_archive=True,
  968. )
  969. for candidate in expanded_candidates
  970. ]
  971. rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
  972. sensitive_rules = {
  973. "credential_or_license_file",
  974. "credential_configuration_file",
  975. "private_key_file",
  976. "secret_environment_file",
  977. "cloud_credential_file",
  978. "container_registry_credential_file",
  979. }
  980. contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
  981. return expanded_items, rebased_excluded, contains_sensitive
  982. def _inspect_and_extract_zip_archive(
  983. item: PackageItem,
  984. *,
  985. temp_root: Path,
  986. extra_exclusions: tuple[dict[str, str], ...],
  987. ) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
  988. archive_label = item.candidate.relative
  989. try:
  990. with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
  991. file_members: list[zipfile.ZipInfo] = []
  992. expected_bytes = 0
  993. for info in archive.infolist():
  994. normalized = info.filename.replace("\\", "/")
  995. if (
  996. not normalized
  997. or normalized.startswith("/")
  998. or re.match(r"^[A-Za-z]:", normalized)
  999. ):
  1000. raise PackagingError(
  1001. f"unsafe archive member path in {archive_label}"
  1002. )
  1003. handoff.normalize_relative(normalized.split("/"))
  1004. if info.flag_bits & 0x1:
  1005. raise PackagingError(
  1006. f"encrypted archive member is unsupported in {archive_label}"
  1007. )
  1008. member_mode = (info.external_attr >> 16) & 0xFFFF
  1009. member_type = stat.S_IFMT(member_mode)
  1010. if info.is_dir():
  1011. if (
  1012. info.file_size != 0
  1013. or info.compress_size != 0
  1014. or member_type not in {0, stat.S_IFDIR}
  1015. ):
  1016. raise PackagingError(
  1017. f"unsafe archive member type in {archive_label}"
  1018. )
  1019. continue
  1020. if member_type not in {0, stat.S_IFREG}:
  1021. raise PackagingError(
  1022. f"unsafe archive member type in {archive_label}"
  1023. )
  1024. file_members.append(info)
  1025. expected_bytes += info.file_size
  1026. except (OSError, zipfile.BadZipFile) as exc:
  1027. raise PackagingError(
  1028. f"unable to inspect source archive: {archive_label}"
  1029. ) from exc
  1030. token = hashlib.sha256(archive_label.encode("utf-8")).hexdigest()[:16]
  1031. extract_root = temp_root / "expanded-archives" / token
  1032. extract_root.mkdir(parents=True, exist_ok=False)
  1033. actual_files: list[Path] = []
  1034. actual_bytes = 0
  1035. try:
  1036. with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
  1037. for info in file_members:
  1038. parts = info.filename.replace("\\", "/").split("/")
  1039. target_path = extract_root / Path(*parts)
  1040. target_path.parent.mkdir(parents=True, exist_ok=True)
  1041. with archive.open(info, "r") as source, target_path.open("wb") as destination:
  1042. shutil.copyfileobj(source, destination, length=1024 * 1024)
  1043. actual_files.append(target_path)
  1044. actual_bytes += target_path.stat().st_size
  1045. except (OSError, zipfile.BadZipFile) as exc:
  1046. raise PackagingError(
  1047. f"unable to extract source archive: {archive_label}"
  1048. ) from exc
  1049. if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
  1050. raise PackagingError(
  1051. f"archive extraction inventory mismatch: {archive_label} "
  1052. f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
  1053. )
  1054. expanded_candidates, expanded_excluded, _ = scan_analysis_root(
  1055. extract_root,
  1056. extra_exclusions=extra_exclusions,
  1057. )
  1058. handoff.audit_candidates(expanded_candidates)
  1059. expanded_prefix = f"{archive_label}.expanded"
  1060. expanded_items = [
  1061. PackageItem(
  1062. candidate=_rebase_candidate(candidate, expanded_prefix),
  1063. category=item.category,
  1064. source_id=item.source_id,
  1065. original_path=f"{item.original_path}!/{candidate.relative}",
  1066. scan_archive=True,
  1067. )
  1068. for candidate in expanded_candidates
  1069. ]
  1070. rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
  1071. sensitive_rules = {
  1072. "credential_or_license_file",
  1073. "credential_configuration_file",
  1074. "private_key_file",
  1075. "secret_environment_file",
  1076. "cloud_credential_file",
  1077. "container_registry_credential_file",
  1078. }
  1079. contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
  1080. return expanded_items, rebased_excluded, contains_sensitive
  1081. def prepare_unsupported_archives(
  1082. items: tuple[PackageItem, ...],
  1083. *,
  1084. temp_root: Path,
  1085. seven_zip: Path | None,
  1086. extra_exclusions: tuple[dict[str, str], ...],
  1087. ) -> ArchivePreparation:
  1088. prepared: list[PackageItem] = []
  1089. excluded: list[dict[str, str]] = []
  1090. warnings: list[dict[str, str]] = []
  1091. temp_root.mkdir(parents=True, exist_ok=True)
  1092. for item in items:
  1093. archive_kind = handoff.archive_kind(item.candidate.relative)
  1094. if archive_kind is None:
  1095. prepared.append(item)
  1096. continue
  1097. if archive_kind == "zip":
  1098. expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_zip_archive(
  1099. item,
  1100. temp_root=temp_root,
  1101. extra_exclusions=extra_exclusions,
  1102. )
  1103. elif seven_zip is None:
  1104. if _is_reference_item(item):
  1105. warnings.append(
  1106. {
  1107. "code": "unsupported_archive_without_7zip",
  1108. "source_id": item.source_id,
  1109. "path": item.candidate.relative,
  1110. "message": "7-Zip is unavailable; unsupported archive kept unexpanded",
  1111. }
  1112. )
  1113. prepared.append(item._replace(scan_archive=False))
  1114. continue
  1115. if item.candidate.absolute.is_file():
  1116. raise PackagingError(
  1117. "7-Zip is required to inspect unsupported source archives"
  1118. )
  1119. prepared.append(item._replace(scan_archive=False))
  1120. continue
  1121. else:
  1122. expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_unsupported_archive(
  1123. item,
  1124. temp_root=temp_root,
  1125. seven_zip=seven_zip,
  1126. extra_exclusions=extra_exclusions,
  1127. )
  1128. has_filtered_members = bool(expanded_excluded)
  1129. if has_filtered_members:
  1130. prepared.extend(expanded_items)
  1131. excluded.extend(expanded_excluded)
  1132. if contains_sensitive:
  1133. excluded.append(
  1134. {
  1135. "path": item.candidate.relative,
  1136. "rule": "unsupported_archive_contains_sensitive_content",
  1137. }
  1138. )
  1139. elif has_filtered_members:
  1140. excluded.append(
  1141. {
  1142. "path": item.candidate.relative,
  1143. "rule": "archive_contains_excluded_members",
  1144. }
  1145. )
  1146. else:
  1147. prepared.append(item._replace(scan_archive=archive_kind != "unsupported"))
  1148. prepared.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
  1149. excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
  1150. return ArchivePreparation(
  1151. items=tuple(prepared),
  1152. excluded=tuple(excluded),
  1153. warnings=tuple(warnings),
  1154. )
  1155. def _utc_now() -> str:
  1156. return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
  1157. def _validate_package_name(package_name: str) -> None:
  1158. try:
  1159. collision_key = handoff.windows_collision_key(package_name)
  1160. except PackagingError as exc:
  1161. raise PackagingError("package name is not a portable Windows file name") from exc
  1162. if (
  1163. not handoff.SAFE_PACKAGE_NAME.fullmatch(package_name)
  1164. or package_name in {".", ".."}
  1165. or not collision_key
  1166. ):
  1167. raise PackagingError("package name is not a portable Windows file name")
  1168. def _item_sort_key(item: PackageItem) -> tuple[int, str, str]:
  1169. return (
  1170. CATEGORY_ORDER.get(item.category, len(CATEGORY_ORDER)),
  1171. item.category.casefold(),
  1172. handoff.windows_collision_key(item.candidate.relative),
  1173. )
  1174. def _path_basename(relative: str) -> str:
  1175. return relative.casefold().rsplit("/", 1)[-1]
  1176. def _is_board_viewer_generated_path(relative: str) -> bool:
  1177. lower = relative.casefold()
  1178. return (
  1179. "board-viewer-generated" in lower
  1180. or "/tools/board-viewer/generated/" in f"/{lower}/"
  1181. or lower.startswith("tools/board-viewer/generated/")
  1182. )
  1183. def _is_reference_original_path(relative: str) -> bool:
  1184. lower = f"/{relative.casefold()}/"
  1185. return "/reference/original/" in lower or lower.startswith("/reference/original/")
  1186. def _dedup_canonical_path(paths: list[str]) -> str:
  1187. def rank(path: str) -> tuple[int, int, str]:
  1188. name = _path_basename(path)
  1189. in_reference = _is_reference_original_path(path)
  1190. in_generated = _is_board_viewer_generated_path(path)
  1191. if name in BOARD_VIEWER_GENERATED_ASSETS or name in DERIVED_BOARD_VIEWER_ASSETS:
  1192. return (0 if in_generated else 1, 0 if in_reference else 1, path.casefold())
  1193. if name.endswith((".brd", ".pdf", ".dsn", ".sch")):
  1194. return (0 if in_reference else 1, 0 if in_generated else 1, path.casefold())
  1195. return (0 if in_reference else 1, 0 if in_generated else 1, path.casefold())
  1196. return sorted(paths, key=rank)[0]
  1197. def _should_content_dedup(size: int, relative: str) -> bool:
  1198. name = _path_basename(relative)
  1199. if name in DERIVED_BOARD_VIEWER_ASSETS or name.endswith((".brd", ".pdf")):
  1200. return True
  1201. return size >= CONTENT_DEDUP_MIN_BYTES
  1202. def apply_content_dedup(
  1203. items: tuple[PackageItem, ...],
  1204. inventory: list[dict[str, object]],
  1205. ) -> tuple[tuple[PackageItem, ...], list[dict[str, object]], list[dict[str, str]]]:
  1206. """Keep one physical copy per identical content hash; record logical aliases."""
  1207. by_path = {str(row["path"]): row for row in inventory}
  1208. groups: dict[str, list[PackageItem]] = {}
  1209. for item in items:
  1210. row = by_path[item.candidate.relative]
  1211. sha = str(row["sha256"])
  1212. size = int(row["size"])
  1213. if not _should_content_dedup(size, item.candidate.relative):
  1214. continue
  1215. groups.setdefault(sha, []).append(item)
  1216. drop_paths: set[str] = set()
  1217. dedup_records: list[dict[str, object]] = []
  1218. excluded: list[dict[str, str]] = []
  1219. for sha, group in sorted(groups.items(), key=lambda pair: pair[0]):
  1220. if len(group) < 2:
  1221. continue
  1222. paths = [item.candidate.relative for item in group]
  1223. canonical = _dedup_canonical_path(paths)
  1224. aliases = sorted(path for path in paths if path != canonical)
  1225. if not aliases:
  1226. continue
  1227. size = int(by_path[canonical]["size"])
  1228. dedup_records.append(
  1229. {
  1230. "sha256": sha,
  1231. "size": size,
  1232. "physical_path": canonical,
  1233. "logical_paths": aliases,
  1234. "reason": "identical_content_single_physical_copy",
  1235. }
  1236. )
  1237. for alias in aliases:
  1238. drop_paths.add(alias)
  1239. excluded.append(
  1240. {
  1241. "path": alias,
  1242. "rule": "duplicate_content_logical_alias",
  1243. }
  1244. )
  1245. physical_items = tuple(
  1246. item for item in items if item.candidate.relative not in drop_paths
  1247. )
  1248. dedup_records.sort(key=lambda row: str(row["physical_path"]).casefold())
  1249. excluded.sort(key=lambda row: handoff.windows_collision_key(row["path"]))
  1250. return physical_items, dedup_records, excluded
  1251. def classify_derived_evidence(items: tuple[PackageItem, ...]) -> list[dict[str, object]]:
  1252. derived: list[dict[str, object]] = []
  1253. for item in items:
  1254. name = _path_basename(item.candidate.relative)
  1255. if name not in DERIVED_BOARD_VIEWER_ASSETS:
  1256. continue
  1257. if not _is_board_viewer_generated_path(item.candidate.relative):
  1258. continue
  1259. role = "derived_from_brd_visual" if name in BOARD_VIEWER_GENERATED_ASSETS else "derived_from_brd_parsed"
  1260. derived.append(
  1261. {
  1262. "path": item.candidate.relative,
  1263. "asset": name,
  1264. "role": role,
  1265. "authority": "analysis_evidence_not_source_closure",
  1266. "note": "Derived from the original Allegro BRD for remote analysis; not RTL/TD source closure.",
  1267. }
  1268. )
  1269. derived.sort(key=lambda row: str(row["path"]).casefold())
  1270. return derived
  1271. def replay_analysis_package(package_dir: Path, *, extract_root: Path) -> dict[str, object]:
  1272. """Extract a published package and verify SHA256SUMS plus inventory hashes."""
  1273. package_dir = package_dir.expanduser().resolve(strict=True)
  1274. extract_root = extract_root.expanduser().resolve(strict=False)
  1275. if extract_root.exists():
  1276. raise PackagingError(f"replay extract root already exists: {extract_root}")
  1277. index_path = package_dir / "HANDOFF-INDEX.json"
  1278. sums_path = package_dir / "SHA256SUMS.txt"
  1279. if not index_path.is_file() or not sums_path.is_file():
  1280. raise PackagingError("package directory is missing HANDOFF-INDEX.json or SHA256SUMS.txt")
  1281. index = json.loads(index_path.read_text(encoding="utf-8"))
  1282. extract_root.mkdir(parents=True, exist_ok=False)
  1283. verified_volumes: list[dict[str, object]] = []
  1284. for line in sums_path.read_text(encoding="ascii").splitlines():
  1285. line = line.strip()
  1286. if not line:
  1287. continue
  1288. digest, _, name = line.partition(" ")
  1289. if not digest or not name:
  1290. raise PackagingError(f"invalid SHA256SUMS line: {line}")
  1291. volume_path = package_dir / name
  1292. actual = handoff.sha256_file(volume_path)
  1293. if actual != digest:
  1294. raise PackagingError(f"SHA256SUMS mismatch for {name}")
  1295. with zipfile.ZipFile(volume_path, "r", allowZip64=True) as archive:
  1296. archive.extractall(extract_root)
  1297. verified_volumes.append({"file": name, "sha256": actual})
  1298. checked_files = 0
  1299. for item in index.get("files", []):
  1300. relative = str(item["path"])
  1301. target = extract_root / "CPLD" / Path(*relative.split("/"))
  1302. if not target.is_file():
  1303. raise PackagingError(f"replay missing extracted file: {relative}")
  1304. digest = handoff.sha256_file(target)
  1305. if digest != item["sha256"] or target.stat().st_size != int(item["size"]):
  1306. raise PackagingError(f"replay hash mismatch for {relative}")
  1307. checked_files += 1
  1308. for record in index.get("content_dedup", []):
  1309. physical = extract_root / "CPLD" / Path(*str(record["physical_path"]).split("/"))
  1310. if not physical.is_file():
  1311. raise PackagingError(f"replay missing dedup physical file: {record['physical_path']}")
  1312. for alias in record.get("logical_paths", []):
  1313. alias_path = extract_root / "CPLD" / Path(*str(alias).split("/"))
  1314. if alias_path.exists():
  1315. raise PackagingError(f"replay found duplicated physical alias path: {alias}")
  1316. return {
  1317. "status": "pass",
  1318. "mode": "package_replay",
  1319. "package_dir": str(package_dir),
  1320. "extract_root": str(extract_root),
  1321. "volumes": verified_volumes,
  1322. "checked_files": checked_files,
  1323. "content_dedup_groups": len(index.get("content_dedup", [])),
  1324. "derived_evidence_count": len(index.get("derived_evidence", [])),
  1325. }
  1326. def _audit_one_item(item: PackageItem) -> dict[str, object]:
  1327. if item.scan_archive:
  1328. file_inventory = handoff.stream_candidate(item.candidate)
  1329. else:
  1330. file_inventory = handoff.hash_candidate(item.candidate)
  1331. return {
  1332. **file_inventory,
  1333. "archive_path": f"CPLD/{item.candidate.relative}",
  1334. "category": item.category,
  1335. "source_id": item.source_id,
  1336. "original_path": item.original_path,
  1337. }
  1338. def _audit_package_items(items: tuple[PackageItem, ...]) -> list[dict[str, object]]:
  1339. sorted_items = sorted(items, key=_item_sort_key)
  1340. collision_paths: dict[str, str] = {}
  1341. for item in sorted_items:
  1342. key = handoff.windows_collision_key(item.candidate.relative)
  1343. previous = collision_paths.get(key)
  1344. if previous is not None:
  1345. raise PackagingError(
  1346. f"analysis inputs contain a Windows path collision: {previous} and {item.candidate.relative}"
  1347. )
  1348. collision_paths[key] = item.candidate.relative
  1349. max_workers = os.cpu_count() or 1
  1350. with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
  1351. return list(executor.map(_audit_one_item, sorted_items))
  1352. def _write_unscanned_candidate(
  1353. archive: zipfile.ZipFile,
  1354. item: PackageItem,
  1355. ) -> dict[str, object]:
  1356. candidate = item.candidate
  1357. digest = hashlib.sha256()
  1358. total = 0
  1359. secret_tail = b""
  1360. entry_name = f"CPLD/{candidate.relative}"
  1361. try:
  1362. with archive.open(handoff.zip_info(entry_name, candidate.mode), "w", force_zip64=True) as target:
  1363. with handoff.open_candidate(candidate) as source:
  1364. for chunk in iter(lambda: source.read(1024 * 1024), b""):
  1365. secret_tail = handoff.scan_secret_markers(
  1366. chunk,
  1367. secret_tail,
  1368. candidate.relative,
  1369. )
  1370. target.write(chunk)
  1371. digest.update(chunk)
  1372. total += len(chunk)
  1373. except OSError as exc:
  1374. raise PackagingError(f"unable to package {candidate.relative}: {exc}") from exc
  1375. if total != candidate.size:
  1376. raise PackagingError(f"source size changed during packaging: {candidate.relative}")
  1377. return {"path": candidate.relative, "size": total, "sha256": digest.hexdigest()}
  1378. def _write_package_item(
  1379. archive: zipfile.ZipFile,
  1380. item: PackageItem,
  1381. ) -> dict[str, object]:
  1382. if item.scan_archive:
  1383. return handoff.write_candidate(archive, item.candidate)
  1384. return _write_unscanned_candidate(archive, item)
  1385. def _stage_package_item(
  1386. staging_root: Path,
  1387. item: PackageItem,
  1388. staging_name: str,
  1389. ) -> dict[str, object]:
  1390. target = staging_root / "CPLD" / staging_name
  1391. target.parent.mkdir(parents=True, exist_ok=True)
  1392. if item.scan_archive:
  1393. try:
  1394. with target.open("wb") as destination:
  1395. return handoff.stream_candidate(item.candidate, target=destination)
  1396. except OSError as exc:
  1397. raise PackagingError(f"unable to stage {item.candidate.relative}: {exc}") from exc
  1398. digest = hashlib.sha256()
  1399. total = 0
  1400. secret_tail = b""
  1401. try:
  1402. with handoff.open_candidate(item.candidate) as source, target.open("wb") as destination:
  1403. for chunk in iter(lambda: source.read(1024 * 1024), b""):
  1404. secret_tail = handoff.scan_secret_markers(
  1405. chunk,
  1406. secret_tail,
  1407. item.candidate.relative,
  1408. )
  1409. destination.write(chunk)
  1410. digest.update(chunk)
  1411. total += len(chunk)
  1412. except OSError as exc:
  1413. raise PackagingError(f"unable to stage {item.candidate.relative}: {exc}") from exc
  1414. if total != item.candidate.size:
  1415. raise PackagingError(f"source size changed during staging: {item.candidate.relative}")
  1416. return {"path": item.candidate.relative, "size": total, "sha256": digest.hexdigest()}
  1417. def _volume_manifest(
  1418. *,
  1419. run_id: str,
  1420. package_name: str,
  1421. number: int,
  1422. count: int,
  1423. items: list[PackageItem],
  1424. inventory_by_path: dict[str, dict[str, object]],
  1425. ) -> dict[str, object]:
  1426. categories = sorted({item.category for item in items})
  1427. entries = [inventory_by_path[item.candidate.relative] for item in items]
  1428. return {
  1429. "schema": "cpld-agent-analysis-volume-v1",
  1430. "run_id": run_id,
  1431. "package_name": package_name,
  1432. "volume_number": number,
  1433. "volume_count": count,
  1434. "categories": categories,
  1435. "file_count": len(entries),
  1436. "uncompressed_bytes": sum(int(entry["size"]) for entry in entries),
  1437. "files": entries,
  1438. }
  1439. def _write_volume(
  1440. path: Path,
  1441. *,
  1442. run_id: str,
  1443. package_name: str,
  1444. number: int,
  1445. count: int,
  1446. items: list[PackageItem],
  1447. inventory_by_path: dict[str, dict[str, object]],
  1448. ) -> dict[str, object]:
  1449. manifest = _volume_manifest(
  1450. run_id=run_id,
  1451. package_name=package_name,
  1452. number=number,
  1453. count=count,
  1454. items=items,
  1455. inventory_by_path=inventory_by_path,
  1456. )
  1457. manifest_name = "CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json"
  1458. manifest_payload = handoff.json_bytes(manifest)
  1459. written_inventory: list[dict[str, object]] = []
  1460. try:
  1461. with zipfile.ZipFile(
  1462. path,
  1463. "w",
  1464. compression=zipfile.ZIP_DEFLATED,
  1465. compresslevel=9,
  1466. allowZip64=True,
  1467. ) as archive:
  1468. for item in sorted(items, key=_item_sort_key):
  1469. expected = inventory_by_path[item.candidate.relative]
  1470. if item.scan_archive:
  1471. actual = handoff.write_candidate(archive, item.candidate)
  1472. else:
  1473. actual = _write_unscanned_candidate(archive, item)
  1474. if (
  1475. actual["size"] != expected["size"]
  1476. or actual["sha256"] != expected["sha256"]
  1477. ):
  1478. raise PackagingError(
  1479. f"source changed while writing ZIP: {item.candidate.relative}"
  1480. )
  1481. written_inventory.append(actual)
  1482. with archive.open(
  1483. handoff.zip_info(manifest_name), "w", force_zip64=True
  1484. ) as target:
  1485. target.write(manifest_payload)
  1486. except (OSError, zipfile.BadZipFile) as exc:
  1487. raise PackagingError(f"unable to create ZIP volume: {exc}") from exc
  1488. expected_names = {f"CPLD/{item.candidate.relative}" for item in items}
  1489. expected_names.add(manifest_name)
  1490. handoff.verify_archive(
  1491. path,
  1492. expected_names=expected_names,
  1493. inventory=written_inventory,
  1494. expected_payloads={manifest_name: manifest_payload},
  1495. )
  1496. return {
  1497. "file": path.name,
  1498. "volume_number": number,
  1499. "volume_count": count,
  1500. "categories": manifest["categories"],
  1501. "file_count": len(items),
  1502. "uncompressed_bytes": manifest["uncompressed_bytes"],
  1503. "compressed_bytes": path.stat().st_size,
  1504. "sha256": handoff.sha256_file(path),
  1505. }
  1506. def _estimated_item_bytes(item: PackageItem) -> int:
  1507. return item.candidate.size + 512 + (len(item.candidate.relative.encode("utf-8")) * 2)
  1508. def _partition_items(
  1509. items: tuple[PackageItem, ...],
  1510. *,
  1511. target_zip_bytes: int,
  1512. ) -> list[list[PackageItem]]:
  1513. base_overhead = min(64_000, max(1_024, target_zip_bytes // 20))
  1514. groups: list[list[PackageItem]] = []
  1515. current: list[PackageItem] = []
  1516. current_category: str | None = None
  1517. estimated_bytes = base_overhead
  1518. for item in sorted(items, key=_item_sort_key):
  1519. item_estimate = _estimated_item_bytes(item)
  1520. if current and (
  1521. item.category != current_category
  1522. or estimated_bytes + item_estimate > target_zip_bytes
  1523. ):
  1524. groups.append(current)
  1525. current = []
  1526. estimated_bytes = base_overhead
  1527. if not current:
  1528. current_category = item.category
  1529. current.append(item)
  1530. estimated_bytes += item_estimate
  1531. if current:
  1532. groups.append(current)
  1533. return groups
  1534. def _split_oversized_groups(
  1535. staging: Path,
  1536. *,
  1537. run_id: str,
  1538. package_name: str,
  1539. groups: list[list[PackageItem]],
  1540. inventory_by_path: dict[str, dict[str, object]],
  1541. target_zip_bytes: int,
  1542. max_zip_bytes: int,
  1543. ) -> list[list[PackageItem]]:
  1544. pending = list(groups)
  1545. accepted: list[list[PackageItem]] = []
  1546. probe_number = 0
  1547. while pending:
  1548. group = pending.pop(0)
  1549. probe_number += 1
  1550. probe = staging / f".volume-probe-{probe_number:04d}.zip"
  1551. try:
  1552. _write_volume(
  1553. probe,
  1554. run_id=run_id,
  1555. package_name=package_name,
  1556. number=1,
  1557. count=1,
  1558. items=group,
  1559. inventory_by_path=inventory_by_path,
  1560. )
  1561. size = probe.stat().st_size
  1562. finally:
  1563. probe.unlink(missing_ok=True)
  1564. if size < max_zip_bytes and (size <= target_zip_bytes or len(group) == 1):
  1565. accepted.append(group)
  1566. continue
  1567. if len(group) == 1:
  1568. raise PackagingError(
  1569. f"single analysis file requires chunking before ZIP creation: {group[0].candidate.relative}"
  1570. )
  1571. middle = len(group) // 2
  1572. pending[0:0] = [group[:middle], group[middle:]]
  1573. return accepted
  1574. def _prepare_large_file_chunks(
  1575. staging: Path,
  1576. *,
  1577. run_id: str,
  1578. package_name: str,
  1579. items: tuple[PackageItem, ...],
  1580. inventory_by_path: dict[str, dict[str, object]],
  1581. target_zip_bytes: int,
  1582. max_zip_bytes: int,
  1583. ) -> tuple[tuple[PackageItem, ...], list[dict[str, object]], Path | None]:
  1584. packaged_items: list[PackageItem] = []
  1585. large_files: list[dict[str, object]] = []
  1586. chunk_root: Path | None = None
  1587. probe_number = 0
  1588. chunk_payload_bytes = max(1, (target_zip_bytes * 3) // 4)
  1589. for item in sorted(items, key=_item_sort_key):
  1590. must_probe = _estimated_item_bytes(item) > target_zip_bytes
  1591. if must_probe:
  1592. probe_number += 1
  1593. probe = staging / f".large-file-probe-{probe_number:04d}.zip"
  1594. try:
  1595. _write_volume(
  1596. probe,
  1597. run_id=run_id,
  1598. package_name=package_name,
  1599. number=1,
  1600. count=1,
  1601. items=[item],
  1602. inventory_by_path=inventory_by_path,
  1603. )
  1604. probe_size = probe.stat().st_size
  1605. finally:
  1606. probe.unlink(missing_ok=True)
  1607. if probe_size <= target_zip_bytes and probe_size < max_zip_bytes:
  1608. packaged_items.append(item)
  1609. continue
  1610. else:
  1611. packaged_items.append(item)
  1612. continue
  1613. if chunk_root is None:
  1614. chunk_root = staging / ".large-file-chunks"
  1615. chunk_root.mkdir()
  1616. original = inventory_by_path[item.candidate.relative]
  1617. file_id = hashlib.sha256(item.candidate.relative.encode("utf-8")).hexdigest()[:16]
  1618. file_chunk_root = chunk_root / file_id
  1619. file_chunk_root.mkdir()
  1620. file_name = Path(item.candidate.relative).name
  1621. chunks: list[dict[str, object]] = []
  1622. original_digest = hashlib.sha256()
  1623. original_bytes = 0
  1624. secret_tail = b""
  1625. with handoff.open_candidate(item.candidate) as source:
  1626. number = 0
  1627. while True:
  1628. payload = source.read(chunk_payload_bytes)
  1629. if not payload:
  1630. break
  1631. number += 1
  1632. secret_tail = handoff.scan_secret_markers(
  1633. payload,
  1634. secret_tail,
  1635. item.candidate.relative,
  1636. )
  1637. original_digest.update(payload)
  1638. original_bytes += len(payload)
  1639. chunk_name = f"{file_name}.part{number:04d}"
  1640. chunk_path = file_chunk_root / chunk_name
  1641. with chunk_path.open("xb") as handle:
  1642. handle.write(payload)
  1643. chunk_relative = f"HANDOFF-LARGE-FILES/{file_id}/{chunk_name}"
  1644. chunk_item = make_package_item(
  1645. chunk_path,
  1646. relative=chunk_relative,
  1647. category=item.category,
  1648. source_id=item.source_id,
  1649. scan_archive=False,
  1650. )
  1651. packaged_items.append(chunk_item)
  1652. chunks.append(
  1653. {
  1654. "number": number,
  1655. "path": chunk_relative,
  1656. "archive_path": f"CPLD/{chunk_relative}",
  1657. "size": len(payload),
  1658. "sha256": hashlib.sha256(payload).hexdigest(),
  1659. }
  1660. )
  1661. if original_bytes != original["size"] or original_digest.hexdigest() != original["sha256"]:
  1662. raise PackagingError(f"source changed while splitting large file: {item.candidate.relative}")
  1663. if len(chunks) < 2:
  1664. raise PackagingError(f"large file split did not produce multiple chunks: {item.candidate.relative}")
  1665. large_files.append(
  1666. {
  1667. "path": item.candidate.relative,
  1668. "category": item.category,
  1669. "source_id": item.source_id,
  1670. "original_path": item.original_path,
  1671. "size": original["size"],
  1672. "sha256": original["sha256"],
  1673. "chunks": chunks,
  1674. }
  1675. )
  1676. return tuple(packaged_items), large_files, chunk_root
  1677. def _assert_items_unchanged(
  1678. items: tuple[PackageItem, ...],
  1679. inventory_by_path: dict[str, dict[str, object]],
  1680. ) -> None:
  1681. for item in items:
  1682. current = handoff.hash_candidate(item.candidate)
  1683. expected = inventory_by_path[item.candidate.relative]
  1684. if current["size"] != expected["size"] or current["sha256"] != expected["sha256"]:
  1685. raise PackagingError(f"source changed during analysis packaging: {item.candidate.relative}")
  1686. def _assert_source_trees_unchanged(collection: AnalysisCollection, *, profile: str = "full") -> None:
  1687. for snapshot in collection.source_snapshots:
  1688. current = _source_snapshot(
  1689. snapshot.root,
  1690. source_id=snapshot.source_id,
  1691. extra_exclusions=snapshot.extra_exclusions,
  1692. profile=profile,
  1693. )
  1694. if (
  1695. current.candidates != snapshot.candidates
  1696. or current.excluded != snapshot.excluded
  1697. ):
  1698. raise PackagingError("source tree changed during analysis packaging: retry from a stable workspace snapshot")
  1699. def _start_here_text(package_name: str, volume_count: int) -> str:
  1700. return (
  1701. f"# {package_name} 分析交付包\n\n"
  1702. f"本目录包含 {volume_count} 个互相独立的普通 ZIP。请先核对 `SHA256SUMS.txt`,"
  1703. "再把所有 ZIP 解压到同一个目录。\n\n"
  1704. "`HANDOFF-INDEX.json` 记录每个原始文件的来源、目标卷、大小和 SHA-256,"
  1705. "以及 `excluded`(排除原因)、`derived_evidence`(由原始 BRD 派生的 board-viewer JSON/SVG,"
  1706. "不是 RTL/TD source closure)和 `content_dedup`(相同大文件只保留一份物理副本时的逻辑归属)。\n"
  1707. )
  1708. def _publish_directory_atomically(staging: Path, final: Path, *, force: bool) -> None:
  1709. backup: Path | None = None
  1710. backup_created = False
  1711. new_directory_published = False
  1712. if os.path.lexists(final):
  1713. if not force:
  1714. raise PackagingError(f"package output already exists: {final}")
  1715. file_stat = os.lstat(final)
  1716. if not stat.S_ISDIR(file_stat.st_mode) or handoff.stat_is_reparse_point(file_stat):
  1717. raise PackagingError(f"existing package output is not a regular directory: {final}")
  1718. backup = final.with_name(f".{final.name}.{uuid.uuid4().hex}.backup")
  1719. try:
  1720. if backup is not None:
  1721. os.replace(final, backup)
  1722. backup_created = True
  1723. os.replace(staging, final)
  1724. new_directory_published = True
  1725. except BaseException as exc:
  1726. if new_directory_published and os.path.lexists(final):
  1727. try:
  1728. shutil.rmtree(final)
  1729. except OSError:
  1730. pass
  1731. if backup_created and backup is not None and os.path.lexists(backup):
  1732. try:
  1733. os.replace(backup, final)
  1734. except OSError as rollback_exc:
  1735. raise PackagingError(
  1736. f"package publication failed and rollback was incomplete: {rollback_exc}"
  1737. ) from exc
  1738. if isinstance(exc, PackagingError):
  1739. raise
  1740. raise PackagingError(f"unable to publish package directory atomically: {exc}") from exc
  1741. if backup is not None:
  1742. shutil.rmtree(backup)
  1743. def create_analysis_package(
  1744. *,
  1745. collection: AnalysisCollection,
  1746. output_root: Path,
  1747. package_name: str,
  1748. max_zip_bytes: int,
  1749. target_zip_bytes: int,
  1750. force: bool,
  1751. profile: str = "full",
  1752. ) -> dict[str, object]:
  1753. _validate_package_name(package_name)
  1754. if max_zip_bytes <= 0 or not 0 < target_zip_bytes < max_zip_bytes:
  1755. raise PackagingError("ZIP size limits are invalid")
  1756. if not collection.items:
  1757. raise PackagingError("analysis package has no included files")
  1758. output_root = output_root.expanduser().resolve(strict=False)
  1759. output_root.mkdir(parents=True, exist_ok=True)
  1760. final_dir = output_root / package_name
  1761. if os.path.lexists(final_dir) and not force:
  1762. raise PackagingError(f"package output already exists: {final_dir}")
  1763. run_id = uuid.uuid4().hex
  1764. staging = Path(tempfile.mkdtemp(prefix=f".{package_name}.{run_id}.", dir=output_root))
  1765. try:
  1766. full_inventory = _audit_package_items(collection.items)
  1767. physical_items, content_dedup, dedup_excluded = apply_content_dedup(
  1768. collection.items,
  1769. full_inventory,
  1770. )
  1771. inventory = [
  1772. row
  1773. for row in full_inventory
  1774. if str(row["path"]) in {item.candidate.relative for item in physical_items}
  1775. ]
  1776. inventory_by_path = {str(item["path"]): item for item in inventory}
  1777. package_excluded = list(collection.excluded) + dedup_excluded
  1778. package_excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
  1779. derived_evidence = classify_derived_evidence(physical_items)
  1780. package_items = physical_items
  1781. package_inventory = inventory
  1782. package_inventory_by_path = inventory_by_path
  1783. large_files: list[dict[str, object]] = []
  1784. chunk_root: Path | None = None
  1785. single_path = staging / f"{package_name}.zip"
  1786. single_info = _write_volume(
  1787. single_path,
  1788. run_id=run_id,
  1789. package_name=package_name,
  1790. number=1,
  1791. count=1,
  1792. items=list(sorted(physical_items, key=_item_sort_key)),
  1793. inventory_by_path=inventory_by_path,
  1794. )
  1795. if single_path.stat().st_size < max_zip_bytes:
  1796. volume_infos = [single_info]
  1797. groups = [list(sorted(physical_items, key=_item_sort_key))]
  1798. else:
  1799. single_path.unlink()
  1800. package_items, large_files, chunk_root = _prepare_large_file_chunks(
  1801. staging,
  1802. run_id=run_id,
  1803. package_name=package_name,
  1804. items=physical_items,
  1805. inventory_by_path=inventory_by_path,
  1806. target_zip_bytes=target_zip_bytes,
  1807. max_zip_bytes=max_zip_bytes,
  1808. )
  1809. package_inventory = _audit_package_items(package_items)
  1810. package_inventory_by_path = {
  1811. str(item["path"]): item for item in package_inventory
  1812. }
  1813. initial_groups = _partition_items(
  1814. package_items,
  1815. target_zip_bytes=target_zip_bytes,
  1816. )
  1817. groups = _split_oversized_groups(
  1818. staging,
  1819. run_id=run_id,
  1820. package_name=package_name,
  1821. groups=initial_groups,
  1822. inventory_by_path=package_inventory_by_path,
  1823. target_zip_bytes=target_zip_bytes,
  1824. max_zip_bytes=max_zip_bytes,
  1825. )
  1826. volume_infos = []
  1827. count = len(groups)
  1828. for number, group in enumerate(groups, start=1):
  1829. category = group[0].category if len({item.category for item in group}) == 1 else "mixed"
  1830. safe_category = re.sub(r"[^a-z0-9]+", "-", category.casefold()).strip("-") or "data"
  1831. volume_path = staging / f"{package_name}.part{number:03d}-{safe_category}.zip"
  1832. volume_info = _write_volume(
  1833. volume_path,
  1834. run_id=run_id,
  1835. package_name=package_name,
  1836. number=number,
  1837. count=count,
  1838. items=group,
  1839. inventory_by_path=package_inventory_by_path,
  1840. )
  1841. if volume_path.stat().st_size >= max_zip_bytes:
  1842. raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
  1843. volume_infos.append(volume_info)
  1844. volume_by_path: dict[str, str] = {}
  1845. for volume_info, group in zip(volume_infos, groups, strict=True):
  1846. for item in group:
  1847. volume_by_path[item.candidate.relative] = str(volume_info["file"])
  1848. large_paths = {str(item["path"]) for item in large_files}
  1849. indexed_files = [
  1850. {**item, "volume": volume_by_path[str(item["path"])]}
  1851. for item in inventory
  1852. if str(item["path"]) not in large_paths
  1853. ]
  1854. for large_file in large_files:
  1855. for chunk in large_file["chunks"]:
  1856. chunk["volume"] = volume_by_path[str(chunk["path"])]
  1857. index = {
  1858. "schema": "cpld-agent-analysis-index-v1",
  1859. "run_id": run_id,
  1860. "created_at_utc": _utc_now(),
  1861. "package_name": package_name,
  1862. "status": collection.status,
  1863. "profile": profile,
  1864. "delivery_policy": "code-only" if profile == "code-only" else "inclusion-first",
  1865. "max_zip_bytes": max_zip_bytes,
  1866. "target_zip_bytes": target_zip_bytes,
  1867. "sources": list(collection.sources),
  1868. "git": list(collection.git),
  1869. "warnings": list(collection.warnings),
  1870. "excluded": package_excluded,
  1871. "content_dedup": content_dedup,
  1872. "derived_evidence": derived_evidence,
  1873. "volumes": volume_infos,
  1874. "files": indexed_files,
  1875. "large_files": large_files,
  1876. }
  1877. if large_files:
  1878. (staging / "reassemble_large_files.py").write_text(
  1879. REASSEMBLER_SCRIPT,
  1880. encoding="utf-8",
  1881. newline="\n",
  1882. )
  1883. (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
  1884. (staging / "START-HERE.zh-CN.md").write_text(
  1885. _start_here_text(package_name, len(volume_infos)),
  1886. encoding="utf-8",
  1887. newline="\n",
  1888. )
  1889. checksum_lines = [f"{info['sha256']} {info['file']}" for info in volume_infos]
  1890. (staging / "SHA256SUMS.txt").write_text(
  1891. "\n".join(checksum_lines) + "\n",
  1892. encoding="ascii",
  1893. newline="\n",
  1894. )
  1895. for info in volume_infos:
  1896. volume_path = staging / str(info["file"])
  1897. if volume_path.stat().st_size >= max_zip_bytes:
  1898. raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
  1899. if handoff.sha256_file(volume_path) != info["sha256"]:
  1900. raise PackagingError(f"ZIP volume hash changed after verification: {volume_path.name}")
  1901. full_inventory_by_path = {str(item["path"]): item for item in full_inventory}
  1902. _assert_items_unchanged(collection.items, full_inventory_by_path)
  1903. _assert_source_trees_unchanged(collection, profile=profile)
  1904. if chunk_root is not None:
  1905. shutil.rmtree(chunk_root)
  1906. _publish_directory_atomically(staging, final_dir, force=force)
  1907. except BaseException:
  1908. if os.path.lexists(staging):
  1909. shutil.rmtree(staging, ignore_errors=True)
  1910. raise
  1911. return {
  1912. "status": collection.status,
  1913. "mode": "package",
  1914. "profile": profile,
  1915. "delivery_policy": "code-only" if profile == "code-only" else "inclusion-first",
  1916. "run_id": run_id,
  1917. "output_dir": str(final_dir),
  1918. "volumes": volume_infos,
  1919. "included_file_count": len(inventory),
  1920. "included_bytes": sum(int(item["size"]) for item in inventory),
  1921. "excluded_entry_count": len(package_excluded),
  1922. "content_dedup_groups": len(content_dedup),
  1923. "derived_evidence_count": len(derived_evidence),
  1924. "warning_count": len(collection.warnings),
  1925. }
  1926. def _reference_fingerprint(inventory: list[dict[str, object]]) -> str:
  1927. digest = hashlib.sha256()
  1928. for item in sorted(inventory, key=lambda row: str(row["path"])):
  1929. path = str(item["path"])
  1930. size = str(item["size"])
  1931. sha = str(item["sha256"])
  1932. digest.update(f"{path}|{size}|{sha}\n".encode("utf-8"))
  1933. return digest.hexdigest()
  1934. def _create_reference_package_with_cache(
  1935. *,
  1936. collection: AnalysisCollection,
  1937. output_root: Path,
  1938. package_name: str,
  1939. max_zip_bytes: int,
  1940. target_zip_bytes: int,
  1941. force: bool,
  1942. ) -> dict[str, object]:
  1943. reference_package_name = f"{package_name}-reference"
  1944. reference_dir = output_root / reference_package_name
  1945. fingerprint_path = reference_dir / "REFERENCE-FINGERPRINT"
  1946. inventory = _audit_package_items(collection.items)
  1947. fingerprint = _reference_fingerprint(inventory)
  1948. if not force and fingerprint_path.exists():
  1949. previous = fingerprint_path.read_text(encoding="ascii").strip()
  1950. if previous == fingerprint:
  1951. index_path = reference_dir / "HANDOFF-INDEX.json"
  1952. if index_path.exists():
  1953. index = json.loads(index_path.read_text(encoding="utf-8"))
  1954. return {
  1955. "status": collection.status,
  1956. "mode": "reference_cached",
  1957. "package_name": reference_package_name,
  1958. "output_dir": str(reference_dir),
  1959. "volumes": index.get("volumes", []),
  1960. "included_file_count": len(inventory),
  1961. "included_bytes": sum(int(item["size"]) for item in inventory),
  1962. "fingerprint": fingerprint,
  1963. "skipped": True,
  1964. }
  1965. payload = create_analysis_package(
  1966. collection=collection,
  1967. output_root=output_root,
  1968. package_name=reference_package_name,
  1969. max_zip_bytes=max_zip_bytes,
  1970. target_zip_bytes=target_zip_bytes,
  1971. force=force,
  1972. )
  1973. reference_dir = Path(payload["output_dir"])
  1974. fingerprint_path = reference_dir / "REFERENCE-FINGERPRINT"
  1975. fingerprint_path.write_text(fingerprint + "\n", encoding="ascii")
  1976. payload["fingerprint"] = fingerprint
  1977. payload["skipped"] = False
  1978. return payload
  1979. def merge_archive_preparation(
  1980. collection: AnalysisCollection,
  1981. preparation: ArchivePreparation,
  1982. ) -> AnalysisCollection:
  1983. warnings = (*collection.warnings, *preparation.warnings)
  1984. excluded = sorted(
  1985. (*collection.excluded, *preparation.excluded),
  1986. key=lambda item: handoff.windows_collision_key(item["path"]),
  1987. )
  1988. return AnalysisCollection(
  1989. status="pass_with_warnings" if warnings else "pass",
  1990. items=preparation.items,
  1991. excluded=tuple(excluded),
  1992. warnings=tuple(warnings),
  1993. sources=collection.sources,
  1994. git=collection.git,
  1995. source_snapshots=collection.source_snapshots,
  1996. )
  1997. def explain_analysis_path(
  1998. path: Path,
  1999. *,
  2000. repo_root: Path,
  2001. config: HandoffConfig,
  2002. profile: str = "full",
  2003. ) -> dict[str, object]:
  2004. root = repo_root.resolve(strict=True)
  2005. requested = path if path.is_absolute() else root / path
  2006. target = requested.expanduser().resolve(strict=False)
  2007. resolved_sources, warnings = resolve_external_sources(config.external_sources)
  2008. source_roots: list[tuple[str, str, Path, Path | None]] = [
  2009. ("workspace-current", "core", root, None)
  2010. ]
  2011. for source in resolved_sources:
  2012. if source.kind == "file":
  2013. source_roots.append((source.id, source.category, source.path.parent, source.path))
  2014. else:
  2015. source_roots.append((source.id, source.category, source.path, None))
  2016. matches: list[tuple[int, str, str, Path, Path | None]] = []
  2017. for source_id, category, source_root, exact_file in source_roots:
  2018. if exact_file is not None and target != exact_file:
  2019. continue
  2020. try:
  2021. target.relative_to(source_root)
  2022. except ValueError:
  2023. continue
  2024. matches.append((len(source_root.parts), source_id, category, source_root, exact_file))
  2025. if not matches:
  2026. raise PackagingError("path is outside the current repository and configured external sources")
  2027. _, source_id, category, source_root, exact_file = max(matches, key=lambda item: item[0])
  2028. relative = exact_file.name if exact_file is not None else target.relative_to(source_root).as_posix()
  2029. if not relative:
  2030. relative = "."
  2031. is_dir = target.is_dir()
  2032. context = handoff.load_scan_context(source_root)
  2033. reason = analysis_exclusion_reason(
  2034. relative,
  2035. is_dir=is_dir,
  2036. context=context,
  2037. extra_exclusions=config.extra_exclusions,
  2038. profile=profile,
  2039. )
  2040. archive_relative = (
  2041. f"workspace-current/{relative}"
  2042. if source_id == "workspace-current"
  2043. else f"external/{source_id}/{relative}"
  2044. )
  2045. return {
  2046. "status": "pass_with_warnings" if warnings else "pass",
  2047. "mode": "explain",
  2048. "path": str(target),
  2049. "exists": target.exists(),
  2050. "source_id": source_id,
  2051. "category": category,
  2052. "source_relative_path": relative,
  2053. "archive_path": f"CPLD/{archive_relative}",
  2054. "decision": "exclude" if reason else "include",
  2055. "reason": reason,
  2056. "content_scan": "not_run",
  2057. "warnings": warnings,
  2058. }
  2059. def audit_analysis_collection(collection: AnalysisCollection) -> dict[str, object]:
  2060. inventory = _audit_package_items(collection.items)
  2061. inventory_by_path = {str(item["path"]): item for item in inventory}
  2062. _assert_items_unchanged(collection.items, inventory_by_path)
  2063. return {
  2064. "status": collection.status,
  2065. "mode": "audit_only",
  2066. "included_file_count": len(inventory),
  2067. "included_bytes": sum(int(item["size"]) for item in inventory),
  2068. "excluded_entry_count": len(collection.excluded),
  2069. "warning_count": len(collection.warnings),
  2070. "warnings": list(collection.warnings),
  2071. "sources": list(collection.sources),
  2072. "git": list(collection.git),
  2073. }
  2074. def _validate_output_root(
  2075. output_root: Path,
  2076. *,
  2077. repo_root: Path,
  2078. config: HandoffConfig,
  2079. ) -> Path:
  2080. output = output_root.expanduser().resolve(strict=False)
  2081. source_paths = [repo_root.resolve(strict=True)]
  2082. resolved_sources, _ = resolve_external_sources(config.external_sources)
  2083. source_paths.extend(source.path if source.kind != "file" else source.path.parent for source in resolved_sources)
  2084. for source_path in source_paths:
  2085. try:
  2086. output.relative_to(source_path)
  2087. except ValueError:
  2088. continue
  2089. raise PackagingError(f"output directory must be outside every packaged source root: {source_path}")
  2090. return output
  2091. def build_parser() -> argparse.ArgumentParser:
  2092. parser = argparse.ArgumentParser(description=__doc__)
  2093. parser.add_argument("--audit-only", action="store_true", help="scan and verify inputs without creating ZIP files")
  2094. parser.add_argument("--explain", type=Path, metavar="PATH", help="explain whether one path is included or excluded")
  2095. parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG, help="source and exclusion configuration JSON")
  2096. parser.add_argument("--source-root", type=Path, default=ROOT, help="root directory to package as the primary source")
  2097. parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR, help="parent directory for the package directory")
  2098. parser.add_argument("--package-name", help="portable package directory and ZIP base name")
  2099. parser.add_argument("--force-overwrite", action="store_true", help="atomically replace an existing package directory")
  2100. parser.add_argument("--no-git-bundle", action="store_true", help="omit the git history bundle from the package")
  2101. parser.add_argument(
  2102. "--profile",
  2103. choices=sorted(handoff.HANDOFF_PROFILES),
  2104. default="full",
  2105. help=(
  2106. "inclusion-first full profile packages source+reference+derived board-viewer evidence "
  2107. "(core/reference split); code-only excludes reference/ and heavy SVG assets"
  2108. ),
  2109. )
  2110. parser.add_argument(
  2111. "--replay-package",
  2112. type=Path,
  2113. metavar="DIR",
  2114. help="verify SHA256SUMS and replay-extract an existing package directory (selftest)",
  2115. )
  2116. parser.add_argument(
  2117. "--replay-extract-dir",
  2118. type=Path,
  2119. help="extract target for --replay-package (must not already exist)",
  2120. )
  2121. return parser
  2122. def main(argv: list[str] | None = None) -> int:
  2123. args = build_parser().parse_args(argv)
  2124. package_name = args.package_name or datetime.now(timezone.utc).strftime(
  2125. "cpld-agent-analysis-%Y%m%dT%H%M%SZ"
  2126. )
  2127. try:
  2128. if args.replay_package is not None:
  2129. extract_root = args.replay_extract_dir or Path(
  2130. tempfile.mkdtemp(prefix="prod2u-package-replay-", dir=os.environ.get("TMPDIR", "/tmp"))
  2131. )
  2132. payload = replay_analysis_package(args.replay_package, extract_root=extract_root)
  2133. print(json.dumps(payload, ensure_ascii=False, indent=2))
  2134. return 0
  2135. source_root = args.source_root.expanduser().resolve(strict=True)
  2136. if args.profile not in handoff.HANDOFF_PROFILES:
  2137. raise PackagingError(f"unsupported handoff profile: {args.profile}")
  2138. config = load_config(args.config, repo_root=source_root)
  2139. if args.explain is not None:
  2140. payload = explain_analysis_path(
  2141. args.explain,
  2142. repo_root=source_root,
  2143. config=config,
  2144. profile=args.profile,
  2145. )
  2146. else:
  2147. seven_zip = find_7z()
  2148. _validate_package_name(package_name)
  2149. output_root = _validate_output_root(args.output_dir, repo_root=source_root, config=config)
  2150. with tempfile.TemporaryDirectory(prefix="ca-") as temporary:
  2151. temp_root = Path(temporary)
  2152. collection = collect_analysis_inputs(
  2153. repo_root=source_root,
  2154. config=config,
  2155. temp_root=temp_root / "inputs",
  2156. include_git_bundle=not args.no_git_bundle,
  2157. profile=args.profile,
  2158. )
  2159. preparation = prepare_unsupported_archives(
  2160. collection.items,
  2161. temp_root=temp_root / "archives",
  2162. seven_zip=seven_zip,
  2163. extra_exclusions=config.extra_exclusions,
  2164. )
  2165. prepared_collection = merge_archive_preparation(collection, preparation)
  2166. if args.audit_only:
  2167. payload = audit_analysis_collection(prepared_collection)
  2168. payload["profile"] = args.profile
  2169. elif args.profile == "code-only":
  2170. if not prepared_collection.items:
  2171. raise PackagingError("analysis package has no included files")
  2172. payload = create_analysis_package(
  2173. collection=prepared_collection,
  2174. output_root=output_root,
  2175. package_name=package_name,
  2176. max_zip_bytes=config.max_zip_bytes,
  2177. target_zip_bytes=config.target_zip_bytes,
  2178. force=args.force_overwrite,
  2179. profile=args.profile,
  2180. )
  2181. else:
  2182. core_collection, reference_collection = _split_collection_by_reference(
  2183. prepared_collection
  2184. )
  2185. if not core_collection.items and not reference_collection.items:
  2186. raise PackagingError("analysis package has no included files")
  2187. payload: dict[str, object] = {}
  2188. if core_collection.items:
  2189. payload["core"] = create_analysis_package(
  2190. collection=core_collection,
  2191. output_root=output_root,
  2192. package_name=package_name,
  2193. max_zip_bytes=config.max_zip_bytes,
  2194. target_zip_bytes=config.target_zip_bytes,
  2195. force=args.force_overwrite,
  2196. profile=args.profile,
  2197. )
  2198. if reference_collection.items:
  2199. payload["reference"] = _create_reference_package_with_cache(
  2200. collection=reference_collection,
  2201. output_root=output_root,
  2202. package_name=package_name,
  2203. max_zip_bytes=config.max_zip_bytes,
  2204. target_zip_bytes=config.target_zip_bytes,
  2205. force=args.force_overwrite,
  2206. )
  2207. except (PackagingError, OSError, ValueError) as exc:
  2208. print(f"error: {exc}", file=sys.stderr)
  2209. return 1
  2210. print(json.dumps(payload, ensure_ascii=False, indent=2))
  2211. return 0
  2212. if __name__ == "__main__":
  2213. raise SystemExit(main())