package_for_agent_analysis.py 113 KB

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