package_for_agent_analysis.py 137 KB

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