package_for_agent_analysis.py 113 KB

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