package_for_agent_analysis.py 181 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456
  1. #!/usr/bin/env python3
  2. """Historical compact/replay analysis handoff from configured source roots.
  3. For current v2.1 releases, use tools/package_unified_analysis.py with the actual
  4. product TD receipts and native GUI build evidence. This legacy entry retains
  5. historical evidence selection and does not select a product from --target.
  6. """
  7. from __future__ import annotations
  8. import json
  9. import hashlib
  10. import argparse
  11. import concurrent.futures
  12. import os
  13. import re
  14. import shutil
  15. import stat
  16. import subprocess
  17. import sys
  18. import tempfile
  19. import uuid
  20. import zipfile
  21. from datetime import datetime, timezone
  22. from pathlib import Path
  23. from typing import Any, NamedTuple
  24. ROOT = Path(__file__).resolve().parent
  25. TOOLS = ROOT / "tools"
  26. if str(TOOLS) not in sys.path:
  27. sys.path.insert(0, str(TOOLS))
  28. import package_agent_handoff as handoff # noqa: E402
  29. import package_evidence_canon as evidence_canon # noqa: E402
  30. PackagingError = handoff.PackagingError
  31. class _IntermediateProvenanceDone(Exception):
  32. """Control-flow: intermediate-review provenance already materialized."""
  33. CONFIG_SCHEMA = "cpld-agent-analysis-sources-v1"
  34. DEFAULT_CONFIG = ROOT / "config" / "agent_analysis_handoff_sources.json"
  35. DEFAULT_OUTPUT_DIR = Path(
  36. os.environ.get(
  37. "PRODU2_HANDOFF_DIR",
  38. str(Path(os.environ.get("TMPDIR", "/tmp")) / "prod2u-handoff"),
  39. )
  40. )
  41. CONTENT_DEDUP_MIN_BYTES = 4096
  42. DERIVED_BOARD_VIEWER_ASSETS = frozenset(
  43. {
  44. "board-copper.svg",
  45. "board-silkscreen.svg",
  46. "board-mask-edge.svg",
  47. "board-copper-back.svg",
  48. "board-silkscreen-back.svg",
  49. "board-mask-edge-back.svg",
  50. "board-data.json",
  51. "build-info.json",
  52. "import-report.json",
  53. }
  54. )
  55. SELF_REFERENCE_CONTROL_FILES = (
  56. "HANDOFF-INDEX.json",
  57. "SHA256SUMS.txt",
  58. "EXCLUSIONS.txt",
  59. "PACKAGE-PURPOSE.txt",
  60. "START-HERE.zh-CN.md",
  61. "size-budget.json",
  62. )
  63. CATEGORY_ORDER = {
  64. "core": 0,
  65. "source": 0,
  66. "hardware": 1,
  67. "td-docs": 2,
  68. "evidence": 3,
  69. "meta": 4,
  70. }
  71. GENERATED_BINARY_SUFFIXES = {
  72. ".bit",
  73. ".bid",
  74. ".data",
  75. ".db",
  76. ".timing",
  77. ".rpt",
  78. ".area",
  79. ".qor",
  80. ".vvp",
  81. }
  82. TRANSIENT_SUFFIXES = {".pyc", ".pyo", ".tmp", ".partial", ".part", ".swp", ".swo"}
  83. ARCHIVE_SUFFIXES = {".zip", ".rar", ".7z", ".tgz", ".tar"}
  84. RUNTIME_EVIDENCE_SUFFIXES = {".log", ".logw", ".vcd", ".fst", ".lxt", ".gtkw", ".raw", ".bin"}
  85. BOARD_VIEWER_GENERATED_ASSETS = {
  86. "board-copper.svg",
  87. "board-silkscreen.svg",
  88. "board-mask-edge.svg",
  89. "board-copper-back.svg",
  90. "board-silkscreen-back.svg",
  91. "board-mask-edge-back.svg",
  92. }
  93. BOARD_DESIGN_SUFFIXES = {".brd", ".sch", ".kicad_pcb", ".kicad_sch", ".kicad_pro", ".kicad_prl", ".dsn"}
  94. IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".webp", ".svg"}
  95. STRAY_FILENAMES = {"-", "a.out"}
  96. REASSEMBLER_SCRIPT = '''#!/usr/bin/env python3
  97. """Reassemble files that were split across analysis ZIP volumes."""
  98. from __future__ import annotations
  99. import argparse
  100. import hashlib
  101. import json
  102. import shutil
  103. import sys
  104. import zipfile
  105. from pathlib import Path, PurePosixPath
  106. def safe_output_path(root: Path, relative: str) -> Path:
  107. portable = PurePosixPath(relative)
  108. if portable.is_absolute() or not portable.parts or any(part in {"", ".", ".."} for part in portable.parts):
  109. raise RuntimeError(f"unsafe output path: {relative}")
  110. target = (root / Path(*portable.parts)).resolve(strict=False)
  111. try:
  112. target.relative_to(root.resolve(strict=False))
  113. except ValueError as exc:
  114. raise RuntimeError(f"output path escapes target directory: {relative}") from exc
  115. return target
  116. def sha256_path(path: Path) -> str:
  117. digest = hashlib.sha256()
  118. with path.open("rb") as handle:
  119. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  120. digest.update(chunk)
  121. return digest.hexdigest()
  122. def main() -> int:
  123. parser = argparse.ArgumentParser(description=__doc__)
  124. parser.add_argument("--package-dir", type=Path, default=Path(__file__).resolve().parent)
  125. parser.add_argument("--output-dir", type=Path, default=Path("reassembled"))
  126. args = parser.parse_args()
  127. package_dir = args.package_dir.resolve(strict=True)
  128. output_dir = args.output_dir.resolve(strict=False)
  129. index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
  130. output_dir.mkdir(parents=True, exist_ok=True)
  131. for item in index.get("large_files", []):
  132. target = safe_output_path(output_dir, item["path"])
  133. target.parent.mkdir(parents=True, exist_ok=True)
  134. temporary = target.with_name(target.name + ".partial")
  135. temporary.unlink(missing_ok=True)
  136. total = 0
  137. with temporary.open("xb") as destination:
  138. for chunk in sorted(item["chunks"], key=lambda value: value["number"]):
  139. volume = package_dir / chunk["volume"]
  140. with zipfile.ZipFile(volume, "r") as archive:
  141. with archive.open(chunk["archive_path"], "r") as source:
  142. digest = hashlib.sha256()
  143. chunk_bytes = 0
  144. while True:
  145. payload = source.read(1024 * 1024)
  146. if not payload:
  147. break
  148. destination.write(payload)
  149. digest.update(payload)
  150. chunk_bytes += len(payload)
  151. if chunk_bytes != chunk["size"] or digest.hexdigest() != chunk["sha256"]:
  152. raise RuntimeError(f"chunk verification failed: {chunk['archive_path']}")
  153. total += chunk_bytes
  154. if total != item["size"] or sha256_path(temporary) != item["sha256"]:
  155. temporary.unlink(missing_ok=True)
  156. raise RuntimeError(f"reassembled file verification failed: {item['path']}")
  157. temporary.replace(target)
  158. print(f"reassembled: {target}")
  159. return 0
  160. if __name__ == "__main__":
  161. try:
  162. raise SystemExit(main())
  163. except (OSError, RuntimeError, KeyError, ValueError, json.JSONDecodeError, zipfile.BadZipFile) as exc:
  164. print(f"error: {exc}", file=sys.stderr)
  165. raise SystemExit(1)
  166. '''
  167. class ExternalSource(NamedTuple):
  168. id: str
  169. category: str
  170. kind: str
  171. path_candidates: tuple[Path, ...]
  172. archive_policy: str
  173. class HandoffConfig(NamedTuple):
  174. max_zip_bytes: int
  175. target_zip_bytes: int
  176. external_sources: tuple[ExternalSource, ...]
  177. extra_exclusions: tuple[dict[str, str], ...]
  178. class ResolvedSource(NamedTuple):
  179. id: str
  180. category: str
  181. kind: str
  182. path: Path
  183. archive_policy: str
  184. class PackageItem(NamedTuple):
  185. candidate: handoff.Candidate
  186. category: str
  187. source_id: str
  188. original_path: str
  189. scan_archive: bool
  190. class SourceSnapshot(NamedTuple):
  191. source_id: str
  192. root: Path
  193. extra_exclusions: tuple[dict[str, str], ...]
  194. candidates: tuple[tuple[object, ...], ...]
  195. excluded: tuple[tuple[str, str], ...]
  196. profile: str = "full"
  197. class AnalysisCollection(NamedTuple):
  198. status: str
  199. items: tuple[PackageItem, ...]
  200. excluded: tuple[dict[str, str], ...]
  201. warnings: tuple[dict[str, str], ...]
  202. sources: tuple[dict[str, object], ...]
  203. git: tuple[dict[str, object], ...]
  204. source_snapshots: tuple[SourceSnapshot, ...] = ()
  205. evidence_canon: dict[str, object] | None = None
  206. def _is_reference_path(item: PackageItem) -> bool:
  207. parts = item.candidate.relative.casefold().split("/")
  208. for index, part in enumerate(parts):
  209. if part == "reference":
  210. next_part = parts[index + 1] if index + 1 < len(parts) else ""
  211. if next_part == "historical":
  212. return False
  213. return True
  214. return False
  215. def _is_reference_item(item: PackageItem) -> bool:
  216. return item.category == "td-docs" or _is_reference_path(item)
  217. def _split_collection_by_reference(
  218. collection: AnalysisCollection,
  219. ) -> tuple[AnalysisCollection, AnalysisCollection]:
  220. core_items: list[PackageItem] = []
  221. reference_items: list[PackageItem] = []
  222. for item in collection.items:
  223. if _is_reference_item(item):
  224. if item.category == "core" and _is_reference_path(item):
  225. item = item._replace(category="reference")
  226. reference_items.append(item)
  227. else:
  228. core_items.append(item)
  229. reference_items_tuple = tuple(reference_items)
  230. core_items_tuple = tuple(core_items)
  231. reference_source_ids = {item.source_id for item in reference_items_tuple}
  232. core_source_ids = {item.source_id for item in core_items_tuple}
  233. def _filter_sources(
  234. sources: tuple[dict[str, object], ...], source_ids: set[str]
  235. ) -> tuple[dict[str, object], ...]:
  236. return tuple(s for s in sources if s.get("id") in source_ids)
  237. def _filter_git(
  238. git: tuple[dict[str, object], ...], source_ids: set[str]
  239. ) -> tuple[dict[str, object], ...]:
  240. return tuple(g for g in git if g.get("source_id") in source_ids)
  241. def _filter_snapshots(
  242. snapshots: tuple[SourceSnapshot, ...], source_ids: set[str]
  243. ) -> tuple[SourceSnapshot, ...]:
  244. return tuple(ss for ss in snapshots if ss.source_id in source_ids)
  245. core_collection = AnalysisCollection(
  246. status=collection.status,
  247. items=core_items_tuple,
  248. excluded=collection.excluded,
  249. warnings=collection.warnings,
  250. sources=_filter_sources(collection.sources, core_source_ids),
  251. git=_filter_git(collection.git, core_source_ids),
  252. source_snapshots=_filter_snapshots(collection.source_snapshots, core_source_ids),
  253. )
  254. reference_collection = AnalysisCollection(
  255. status=collection.status,
  256. items=reference_items_tuple,
  257. excluded=collection.excluded,
  258. warnings=collection.warnings,
  259. sources=_filter_sources(collection.sources, reference_source_ids),
  260. git=_filter_git(collection.git, reference_source_ids),
  261. source_snapshots=_filter_snapshots(collection.source_snapshots, reference_source_ids),
  262. )
  263. return core_collection, reference_collection
  264. class ArchivePreparation(NamedTuple):
  265. items: tuple[PackageItem, ...]
  266. excluded: tuple[dict[str, str], ...]
  267. warnings: tuple[dict[str, str], ...]
  268. def _source_snapshot(
  269. root: Path,
  270. *,
  271. source_id: str,
  272. extra_exclusions: tuple[dict[str, str], ...],
  273. profile: str = "full",
  274. ) -> SourceSnapshot:
  275. candidates, excluded, _ = scan_analysis_root(
  276. root,
  277. extra_exclusions=extra_exclusions,
  278. profile=profile,
  279. )
  280. return SourceSnapshot(
  281. source_id=source_id,
  282. root=root.resolve(strict=True),
  283. extra_exclusions=extra_exclusions,
  284. candidates=tuple(
  285. (
  286. candidate.relative,
  287. candidate.size,
  288. candidate.mtime_ns,
  289. candidate.device,
  290. candidate.inode,
  291. candidate.mode,
  292. )
  293. for candidate in candidates
  294. ),
  295. excluded=tuple((item["path"], item["rule"]) for item in excluded),
  296. profile=profile,
  297. )
  298. def _require_keys(payload: dict[str, object], allowed: set[str], label: str) -> None:
  299. unknown = sorted(set(payload) - allowed)
  300. if unknown:
  301. if any("include" in item.casefold() for item in unknown):
  302. raise PackagingError(f"positive include rules are forbidden in {label}: {unknown}")
  303. raise PackagingError(f"unsupported fields in {label}: {unknown}")
  304. def _expand_path(value: str, *, repo_root: Path, user_profile: Path) -> Path:
  305. tokens = {
  306. "repo_root": str(repo_root),
  307. "user_profile": str(user_profile),
  308. "codex_temp": str(user_profile / "CodexTemp"),
  309. }
  310. try:
  311. expanded = value.format_map(tokens)
  312. except (KeyError, ValueError) as exc:
  313. raise PackagingError(f"unsupported path token in external source: {value}") from exc
  314. return Path(expanded).expanduser()
  315. def load_config(
  316. path: Path,
  317. *,
  318. repo_root: Path = ROOT,
  319. user_profile: Path | None = None,
  320. ) -> HandoffConfig:
  321. try:
  322. payload = json.loads(path.read_text(encoding="utf-8-sig"))
  323. except (OSError, UnicodeError, json.JSONDecodeError) as exc:
  324. raise PackagingError(f"unable to read analysis source config: {path}") from exc
  325. if not isinstance(payload, dict):
  326. raise PackagingError("analysis source config must be a JSON object")
  327. _require_keys(
  328. payload,
  329. {
  330. "schema",
  331. "max_zip_bytes",
  332. "target_zip_bytes",
  333. "external_sources",
  334. "extra_exclusions",
  335. },
  336. "config",
  337. )
  338. if payload.get("schema") != CONFIG_SCHEMA:
  339. raise PackagingError(f"unsupported analysis source config schema: {payload.get('schema')}")
  340. max_zip_bytes = payload.get("max_zip_bytes")
  341. target_zip_bytes = payload.get("target_zip_bytes")
  342. if not isinstance(max_zip_bytes, int) or max_zip_bytes <= 0:
  343. raise PackagingError("max_zip_bytes must be a positive integer")
  344. if not isinstance(target_zip_bytes, int) or not 0 < target_zip_bytes < max_zip_bytes:
  345. raise PackagingError("target_zip_bytes must be positive and smaller than max_zip_bytes")
  346. raw_sources = payload.get("external_sources")
  347. if not isinstance(raw_sources, list):
  348. raise PackagingError("external_sources must be an array")
  349. profile = user_profile or Path.home()
  350. sources: list[ExternalSource] = []
  351. seen_ids: set[str] = set()
  352. for index, raw_source in enumerate(raw_sources):
  353. if not isinstance(raw_source, dict):
  354. raise PackagingError(f"external_sources[{index}] must be an object")
  355. _require_keys(
  356. raw_source,
  357. {"id", "category", "kind", "path_candidates", "archive_policy"},
  358. f"external_sources[{index}]",
  359. )
  360. source_id = raw_source.get("id")
  361. category = raw_source.get("category")
  362. kind = raw_source.get("kind")
  363. archive_policy = raw_source.get("archive_policy")
  364. raw_paths = raw_source.get("path_candidates")
  365. if not isinstance(source_id, str) or not source_id or source_id in seen_ids:
  366. raise PackagingError(f"external source id is missing or duplicated: {source_id}")
  367. if not isinstance(category, str) or not category:
  368. raise PackagingError(f"external source category is invalid: {source_id}")
  369. if kind not in {"directory", "file", "git_worktree"}:
  370. raise PackagingError(f"external source kind is invalid: {source_id}")
  371. if archive_policy not in {"inspect", "copy"}:
  372. raise PackagingError(f"external archive policy is invalid: {source_id}")
  373. if not isinstance(raw_paths, list) or not raw_paths or not all(isinstance(item, str) for item in raw_paths):
  374. raise PackagingError(f"external source path_candidates are invalid: {source_id}")
  375. seen_ids.add(source_id)
  376. sources.append(
  377. ExternalSource(
  378. id=source_id,
  379. category=category,
  380. kind=kind,
  381. path_candidates=tuple(
  382. _expand_path(item, repo_root=repo_root, user_profile=profile)
  383. for item in raw_paths
  384. ),
  385. archive_policy=archive_policy,
  386. )
  387. )
  388. raw_exclusions = payload.get("extra_exclusions")
  389. if not isinstance(raw_exclusions, list) or not all(isinstance(item, dict) for item in raw_exclusions):
  390. raise PackagingError("extra_exclusions must be an array of objects")
  391. exclusions: list[dict[str, str]] = []
  392. for index, raw_exclusion in enumerate(raw_exclusions):
  393. _require_keys(raw_exclusion, {"path", "reason"}, f"extra_exclusions[{index}]")
  394. exclusion_path = raw_exclusion.get("path")
  395. reason = raw_exclusion.get("reason")
  396. if not isinstance(exclusion_path, str) or not exclusion_path or "\\" in exclusion_path:
  397. raise PackagingError(f"extra exclusion path is invalid: {index}")
  398. if not isinstance(reason, str) or not reason.strip():
  399. raise PackagingError(f"extra exclusion reason is invalid: {index}")
  400. normalized_path = handoff.normalize_relative(exclusion_path.strip("/").split("/"))
  401. exclusions.append({"path": normalized_path, "reason": reason.strip()})
  402. return HandoffConfig(
  403. max_zip_bytes=max_zip_bytes,
  404. target_zip_bytes=target_zip_bytes,
  405. external_sources=tuple(sources),
  406. extra_exclusions=tuple(exclusions),
  407. )
  408. def analysis_exclusion_reason(
  409. relative: str,
  410. *,
  411. is_dir: bool,
  412. context: handoff.ScanContext,
  413. extra_exclusions: tuple[dict[str, str], ...] = (),
  414. profile: str = "full",
  415. ) -> str | None:
  416. del context
  417. lower = relative.casefold()
  418. parts = lower.split("/")
  419. raw_parts = relative.split("/")
  420. name = parts[-1]
  421. secret_reason = handoff.secret_path_reason(relative, is_dir=is_dir)
  422. if secret_reason:
  423. return secret_reason
  424. # Shared vendor/toolchain installer and generated-file policy (handoff common rules).
  425. # Critical for review-compact: root oss-cad-suite*.tgz / td_release_*.zip must never
  426. # enter the package and then hit fail-closed archive secret inspection.
  427. if not is_dir:
  428. common_reason = handoff.common_file_exclusion_reason(relative)
  429. if common_reason:
  430. return common_reason
  431. if profile == "code-only":
  432. for prefix, reason in handoff.CODE_ONLY_ROOT_EXCLUSIONS.items():
  433. if handoff.is_under(lower, prefix):
  434. return reason
  435. if not is_dir and handoff.is_under(lower, "tools/board-viewer/generated"):
  436. if name in handoff.CODE_ONLY_GENERATED_VISUAL_ASSETS:
  437. return "generated_board_viewer_visual_asset"
  438. if handoff.is_review_profile(profile):
  439. review_reason = handoff.review_exclusion_reason(
  440. relative, is_dir=is_dir, profile=profile
  441. )
  442. if review_reason:
  443. return review_reason
  444. for item in extra_exclusions:
  445. prefix = str(item.get("path", "")).casefold().strip("/")
  446. if prefix and handoff.is_under(lower, prefix):
  447. return str(item.get("reason") or "configured_analysis_exclusion")
  448. explicit_roots = {
  449. ".git": "raw_git_metadata",
  450. ".codegraph": "declared_external_reparse_alias",
  451. ".codex": "codex_session_runtime",
  452. ".hypothesis": "hypothesis_cache",
  453. ".ruff_cache": "ruff_cache",
  454. ".pytest_cache": "pytest_cache",
  455. ".chatgpt-handoff": "chatgpt_handoff_runtime_not_in_compact",
  456. ".playwright-upload-cache": "playwright_upload_cache",
  457. "dist": "generated_delivery_output",
  458. "log": "runtime_log_directory",
  459. "runs": "run_state_directory",
  460. "td/build": "td_build_output",
  461. "reference/historical": "reference_historical_material",
  462. "reference/original/legacy_rtl": "reference_legacy_rtl",
  463. "receipts/local": "local_runtime_receipt",
  464. # Packaged once via external source board-viewer-generated (derived evidence).
  465. "tools/board-viewer/generated": "board_viewer_generated_packaged_via_external_source",
  466. "anlogic_cd": "vendor_installer_payload",
  467. "node_modules": "node_modules_runtime",
  468. }
  469. for prefix, reason in explicit_roots.items():
  470. if handoff.is_under(lower, prefix):
  471. return reason
  472. if handoff.is_under(lower, "tmp/edge-headless-profile"):
  473. return "browser_runtime_profile"
  474. if handoff.is_under(lower, "tmp/rtl_sim"):
  475. return "compiled_rtl_simulation"
  476. if handoff.is_under(lower, "tmp/toolchain_probe"):
  477. return "toolchain_probe_runtime"
  478. if handoff.is_under(lower, "tmp/td"):
  479. return "td_runtime_snapshot"
  480. if handoff.is_under(lower, "tmp/refactor"):
  481. return "compiled_refactor_probe"
  482. if any(component.endswith("_Runs") for component in raw_parts):
  483. return "generated_run_directory"
  484. if re.match(r"^tmp/pytest-[^/]+$", lower):
  485. return "temporary_tool_runtime"
  486. if handoff.is_under(lower, "tmp"):
  487. return "temporary_workspace_directory"
  488. if handoff.is_under(lower, "td/project/log"):
  489. return "td_gui_runtime_log"
  490. if handoff.is_under(lower, "td/project") and len(parts) >= 3 and parts[2].endswith("_runs"):
  491. return "td_gui_runtime_run"
  492. if lower in {
  493. "td/project/.lock.f",
  494. "td/project/.recent_user_depot.ini",
  495. }:
  496. return "td_gui_runtime_state"
  497. if handoff.is_under(lower, ".git"):
  498. return "raw_git_metadata"
  499. if handoff.is_under(lower, ".omo"):
  500. return "agent_session_runtime"
  501. cache_components = {
  502. ".git": "raw_git_metadata",
  503. ".codegraph": "declared_external_reparse_alias",
  504. ".codex": "codex_session_runtime",
  505. "__pycache__": "python_bytecode_cache",
  506. ".pytest_cache": "pytest_cache",
  507. ".hypothesis": "hypothesis_cache",
  508. ".mypy_cache": "mypy_cache",
  509. ".ruff_cache": "ruff_cache",
  510. ".tox": "tox_environment",
  511. ".nox": "nox_environment",
  512. ".venv": "virtual_environment",
  513. "venv": "virtual_environment",
  514. "htmlcov": "coverage_report",
  515. "build": "build_output",
  516. "runs": "run_state_directory",
  517. "node_modules": "node_modules_runtime",
  518. ".playwright-browsers": "browser_runtime_cache",
  519. }
  520. for component in parts:
  521. if component in cache_components:
  522. return cache_components[component]
  523. if component == "dist":
  524. return "generated_delivery_output"
  525. if component.endswith(".egg-info"):
  526. return "python_package_metadata"
  527. if not is_dir:
  528. suffix = Path(name).suffix.casefold()
  529. if suffix in GENERATED_BINARY_SUFFIXES:
  530. # Canonical final-review bitstream is evidence, not a TD build leftover.
  531. if suffix == ".bit" and lower.startswith("evidence/bitstream/"):
  532. return None
  533. return "generated_binary_artifact"
  534. if suffix in ARCHIVE_SUFFIXES:
  535. return "archive_file_not_source"
  536. if suffix in RUNTIME_EVIDENCE_SUFFIXES:
  537. return "runtime_evidence_or_waveform"
  538. if suffix in BOARD_DESIGN_SUFFIXES:
  539. if handoff.is_board_viewer_fixture_path(relative):
  540. return None
  541. if handoff.is_review_profile(profile):
  542. return "heavy_design_original_not_packaged"
  543. if "reference" in parts:
  544. return None
  545. return "board_design_file"
  546. if suffix in IMAGE_SUFFIXES:
  547. if name in BOARD_VIEWER_GENERATED_ASSETS or name in DERIVED_BOARD_VIEWER_ASSETS:
  548. return None
  549. if handoff.is_board_viewer_fixture_path(relative):
  550. return None
  551. if handoff.is_review_profile(profile) and suffix == ".pdf":
  552. return "heavy_design_original_not_packaged"
  553. if "reference" in parts:
  554. return None
  555. return "image_file"
  556. if name in STRAY_FILENAMES:
  557. return "stray_or_temporary_file"
  558. if suffix in TRANSIENT_SUFFIXES or name.endswith("~"):
  559. return "temporary_file"
  560. if suffix == ".dmp" or name.startswith("minidump-"):
  561. return "crash_dump"
  562. if name in {".ds_store", "thumbs.db", "desktop.ini"}:
  563. return "os_metadata_cache"
  564. return None
  565. def scan_analysis_root(
  566. root: Path,
  567. *,
  568. extra_exclusions: tuple[dict[str, str], ...] = (),
  569. profile: str = "full",
  570. ) -> tuple[list[handoff.Candidate], list[dict[str, str]], handoff.ScanContext]:
  571. def resolve(relative: str, *, is_dir: bool, context: handoff.ScanContext) -> str | None:
  572. return analysis_exclusion_reason(
  573. relative,
  574. is_dir=is_dir,
  575. context=context,
  576. extra_exclusions=extra_exclusions,
  577. profile=profile,
  578. )
  579. return handoff.scan_tree(root, exclusion_resolver=resolve, profile=profile)
  580. def resolve_external_sources(
  581. sources: tuple[ExternalSource, ...],
  582. ) -> tuple[list[ResolvedSource], list[dict[str, str]]]:
  583. resolved: list[ResolvedSource] = []
  584. warnings: list[dict[str, str]] = []
  585. for source in sources:
  586. selected: Path | None = None
  587. for candidate in source.path_candidates:
  588. if source.kind == "file" and candidate.is_file():
  589. selected = candidate.resolve(strict=True)
  590. break
  591. if source.kind in {"directory", "git_worktree"} and candidate.is_dir():
  592. selected = candidate.resolve(strict=True)
  593. break
  594. if selected is None:
  595. warnings.append(
  596. {
  597. "code": "missing_external_source",
  598. "source_id": source.id,
  599. "message": "no configured path candidate is available",
  600. }
  601. )
  602. continue
  603. resolved.append(
  604. ResolvedSource(
  605. id=source.id,
  606. category=source.category,
  607. kind=source.kind,
  608. path=selected,
  609. archive_policy=source.archive_policy,
  610. )
  611. )
  612. return resolved, warnings
  613. def _candidate_from_path(path: Path, relative: str) -> handoff.Candidate:
  614. try:
  615. file_stat = os.lstat(path)
  616. except OSError as exc:
  617. raise PackagingError(f"unable to inspect generated analysis input: {relative}") from exc
  618. if not stat.S_ISREG(file_stat.st_mode) or handoff.stat_is_reparse_point(file_stat):
  619. raise PackagingError(f"analysis input is not a regular file: {relative}")
  620. return handoff.Candidate(
  621. absolute=path,
  622. relative=handoff.normalize_relative(relative.split("/")),
  623. size=file_stat.st_size,
  624. mtime_ns=file_stat.st_mtime_ns,
  625. device=int(file_stat.st_dev),
  626. inode=int(file_stat.st_ino),
  627. mode=int(file_stat.st_mode),
  628. )
  629. def make_package_item(
  630. path: Path,
  631. *,
  632. relative: str,
  633. category: str,
  634. source_id: str,
  635. scan_archive: bool = True,
  636. ) -> PackageItem:
  637. return PackageItem(
  638. candidate=_candidate_from_path(path, relative),
  639. category=category,
  640. source_id=source_id,
  641. original_path=path.name,
  642. scan_archive=scan_archive,
  643. )
  644. def _rebase_candidate(candidate: handoff.Candidate, prefix: str) -> handoff.Candidate:
  645. return handoff.Candidate(
  646. absolute=candidate.absolute,
  647. relative=handoff.normalize_relative([*prefix.split("/"), *candidate.relative.split("/")]),
  648. size=candidate.size,
  649. mtime_ns=candidate.mtime_ns,
  650. device=candidate.device,
  651. inode=candidate.inode,
  652. mode=candidate.mode,
  653. )
  654. def _rebase_exclusions(excluded: list[dict[str, str]], prefix: str) -> list[dict[str, str]]:
  655. return [
  656. {
  657. "path": handoff.normalize_relative([*prefix.split("/"), *item["path"].split("/")]),
  658. "rule": item["rule"],
  659. }
  660. for item in excluded
  661. ]
  662. def _collect_directory_items(
  663. *,
  664. root: Path,
  665. source_id: str,
  666. category: str,
  667. prefix: str,
  668. extra_exclusions: tuple[dict[str, str], ...],
  669. profile: str = "full",
  670. ) -> tuple[list[PackageItem], list[dict[str, str]]]:
  671. candidates, excluded, _ = scan_analysis_root(
  672. root,
  673. extra_exclusions=extra_exclusions,
  674. profile=profile,
  675. )
  676. items = [
  677. PackageItem(
  678. candidate=_rebase_candidate(candidate, prefix),
  679. category=category,
  680. source_id=source_id,
  681. original_path=candidate.relative,
  682. scan_archive=True,
  683. )
  684. for candidate in candidates
  685. ]
  686. return items, _rebase_exclusions(excluded, prefix)
  687. def _resolve_delivery_commit(root: Path, binding_commit: str | None) -> str:
  688. """Resolve exact DELIVERY commit for review source snapshot."""
  689. if binding_commit:
  690. text = binding_commit.strip().casefold()
  691. if not re.fullmatch(r"[0-9a-f]{40}", text):
  692. raise PackagingError(f"invalid binding_commit: {binding_commit!r}")
  693. return text
  694. # Fail closed before git-archive: gitless roots must not produce a package.
  695. if not handoff.live_git_cli_usable(root):
  696. raise PackagingError(
  697. "review package requires live Git provenance "
  698. "(HEAD/branch/status/log-20/tree/source-file-sha256); "
  699. "got status='not_a_git_worktree'. "
  700. "Package from an exact DELIVERY Git worktree/repo — "
  701. "sanitized-snapshot-status alone is not sufficient."
  702. )
  703. git = shutil.which("git")
  704. if not git:
  705. raise PackagingError(
  706. "review package requires live Git provenance; git binary unavailable"
  707. )
  708. try:
  709. completed = subprocess.run(
  710. [git, "rev-parse", "HEAD"],
  711. cwd=root,
  712. stdout=subprocess.PIPE,
  713. stderr=subprocess.PIPE,
  714. text=True,
  715. encoding="utf-8",
  716. errors="replace",
  717. timeout=60,
  718. check=False,
  719. )
  720. except (OSError, subprocess.TimeoutExpired) as exc:
  721. raise PackagingError(
  722. "review package requires live Git provenance; "
  723. "unable to resolve DELIVERY commit via git rev-parse"
  724. ) from exc
  725. head = completed.stdout.strip().casefold()
  726. if completed.returncode != 0 or not re.fullmatch(r"[0-9a-f]{40}", head):
  727. raise PackagingError(
  728. "review package requires live Git provenance; "
  729. "unable to resolve DELIVERY commit via git rev-parse: "
  730. + (completed.stderr or completed.stdout or "unknown error").strip()[:300]
  731. )
  732. return head
  733. def _collect_exact_commit_unified_items(
  734. *,
  735. root: Path,
  736. commit: str,
  737. source_id: str,
  738. temp_root: Path,
  739. extra_exclusions: tuple[dict[str, str], ...],
  740. profile: str,
  741. ) -> tuple[list[PackageItem], list[dict[str, str]], dict[str, object]]:
  742. """Build unified source/evidence items from exact DELIVERY tracked tree only.
  743. Never walks a dirty post-test worktree. Applies the same review exclusion
  744. policy to the commit export, then remaps into source/ or evidence/.
  745. """
  746. git = shutil.which("git")
  747. if not git:
  748. raise PackagingError("git required for exact_commit_tracked_subset source snapshot")
  749. export_root = temp_root / f"exact-commit-source-{commit[:12]}"
  750. if export_root.exists():
  751. shutil.rmtree(export_root)
  752. export_root.mkdir(parents=True, exist_ok=True)
  753. tar_path = temp_root / f"exact-commit-source-{commit[:12]}.tar"
  754. try:
  755. completed = subprocess.run(
  756. [git, "archive", "--format=tar", "-o", str(tar_path), commit],
  757. cwd=root,
  758. stdout=subprocess.PIPE,
  759. stderr=subprocess.STDOUT,
  760. text=True,
  761. encoding="utf-8",
  762. errors="replace",
  763. timeout=600,
  764. check=False,
  765. )
  766. except (OSError, subprocess.TimeoutExpired) as exc:
  767. raise PackagingError(f"git archive {commit} failed for source snapshot") from exc
  768. if completed.returncode != 0 or not tar_path.is_file():
  769. detail = (completed.stdout or "").strip().splitlines()
  770. suffix = f": {detail[-1]}" if detail else ""
  771. raise PackagingError(f"git archive {commit} failed for source snapshot{suffix}")
  772. import tarfile
  773. with tarfile.open(tar_path, "r:") as archive:
  774. try:
  775. archive.extractall(export_root, filter="data")
  776. except TypeError:
  777. archive.extractall(export_root)
  778. # Enumerate every tracked path (pre-exclusion) for packaged-source-manifest.
  779. tracked_all: list[str] = []
  780. for path in sorted(export_root.rglob("*")):
  781. if path.is_file():
  782. tracked_all.append(path.relative_to(export_root).as_posix())
  783. root_items, root_excluded = _collect_directory_items(
  784. root=export_root,
  785. source_id=source_id,
  786. category="source",
  787. prefix="__workspace__",
  788. extra_exclusions=extra_exclusions,
  789. profile=profile,
  790. )
  791. remapped: list[PackageItem] = []
  792. included_tracked: list[dict[str, object]] = []
  793. for item in root_items:
  794. original = item.original_path
  795. package_relative, category = _package_relative_for_unified(
  796. source_id=source_id,
  797. original_relative=original,
  798. profile=profile,
  799. )
  800. remapped.append(
  801. PackageItem(
  802. candidate=handoff.Candidate(
  803. absolute=item.candidate.absolute,
  804. relative=package_relative,
  805. size=item.candidate.size,
  806. mtime_ns=item.candidate.mtime_ns,
  807. device=item.candidate.device,
  808. inode=item.candidate.inode,
  809. mode=item.candidate.mode,
  810. ),
  811. category=category,
  812. source_id=source_id,
  813. original_path=original,
  814. scan_archive=item.scan_archive,
  815. )
  816. )
  817. if original in _SOFTWARE_MIRROR_UNDER_SOURCE and not package_relative.startswith(
  818. "source/"
  819. ):
  820. mirror_relative = f"source/{original}"
  821. remapped.append(
  822. PackageItem(
  823. candidate=handoff.Candidate(
  824. absolute=item.candidate.absolute,
  825. relative=mirror_relative,
  826. size=item.candidate.size,
  827. mtime_ns=item.candidate.mtime_ns,
  828. device=item.candidate.device,
  829. inode=item.candidate.inode,
  830. mode=item.candidate.mode,
  831. ),
  832. category="source",
  833. source_id=source_id,
  834. original_path=original,
  835. scan_archive=item.scan_archive,
  836. )
  837. )
  838. included_tracked.append(
  839. {
  840. "path": original,
  841. "package_path": mirror_relative,
  842. "size": item.candidate.size,
  843. "sha256": handoff.sha256_file(item.candidate.absolute),
  844. }
  845. )
  846. if package_relative.startswith("source/"):
  847. included_tracked.append(
  848. {
  849. "path": original,
  850. "package_path": package_relative,
  851. "size": item.candidate.size,
  852. "sha256": handoff.sha256_file(item.candidate.absolute),
  853. }
  854. )
  855. excluded: list[dict[str, str]] = []
  856. policy_excluded: list[dict[str, str]] = []
  857. for entry in root_excluded:
  858. original_excluded = entry["path"]
  859. if original_excluded.startswith("__workspace__/"):
  860. original_excluded = original_excluded[len("__workspace__/") :]
  861. elif original_excluded == "__workspace__":
  862. original_excluded = "."
  863. package_relative, _category = _package_relative_for_unified(
  864. source_id=source_id,
  865. original_relative=original_excluded,
  866. profile=profile,
  867. )
  868. row = {
  869. "path": (
  870. original_excluded if original_excluded == "." else package_relative
  871. ),
  872. "rule": entry["rule"],
  873. }
  874. excluded.append(row)
  875. if original_excluded != ".":
  876. policy_excluded.append(
  877. {"path": original_excluded, "rule": entry["rule"]}
  878. )
  879. included_paths = {str(row["path"]) for row in included_tracked}
  880. evidence_mapped = sorted(
  881. {
  882. item.original_path
  883. for item in remapped
  884. if item.candidate.relative.startswith("evidence/")
  885. }
  886. )
  887. evidence_set = set(evidence_mapped)
  888. # Re-resolve exclusion per tracked file so directory-level skips are explicit.
  889. scan_context = handoff.load_scan_context(export_root, profile=profile)
  890. resolve = handoff.make_exclusion_resolver(profile)
  891. def _file_exclusion_reason(rel: str) -> str | None:
  892. # Prefer analysis_exclusion_reason (extra_exclusions + profile).
  893. reason = analysis_exclusion_reason(
  894. rel,
  895. is_dir=False,
  896. context=scan_context,
  897. extra_exclusions=extra_exclusions,
  898. profile=profile,
  899. )
  900. if reason:
  901. return reason
  902. # Directory ancestors excluded by scan (e.g. reference/original).
  903. parts = rel.split("/")
  904. for idx in range(len(parts) - 1, 0, -1):
  905. parent = "/".join(parts[:idx])
  906. parent_reason = analysis_exclusion_reason(
  907. parent,
  908. is_dir=True,
  909. context=scan_context,
  910. extra_exclusions=extra_exclusions,
  911. profile=profile,
  912. )
  913. if parent_reason:
  914. return parent_reason
  915. # Fallback shared resolver (defensive).
  916. return resolve(rel, is_dir=False, context=scan_context)
  917. per_file_excluded: list[dict[str, str]] = []
  918. silent_missing: list[str] = []
  919. for path in tracked_all:
  920. if path in included_paths or path in evidence_set:
  921. continue
  922. reason = _file_exclusion_reason(path)
  923. if reason:
  924. per_file_excluded.append({"path": path, "rule": reason})
  925. else:
  926. silent_missing.append(path)
  927. # Prefer compact directory-level exclusion rows; enrich with per-file reasons.
  928. policy_by_path = {row["path"]: row["rule"] for row in policy_excluded}
  929. for row in per_file_excluded:
  930. policy_by_path.setdefault(row["path"], row["rule"])
  931. policy_excluded_final = [
  932. {"path": path, "rule": rule}
  933. for path, rule in sorted(policy_by_path.items(), key=lambda pair: pair[0].casefold())
  934. ]
  935. manifest: dict[str, object] = {
  936. "schema": "prod2u-packaged-source-manifest-v1",
  937. "source_snapshot_mode": "exact_commit_tracked_subset",
  938. "delivery_commit": commit,
  939. "tracked_file_count": len(tracked_all),
  940. "included_source_count": len(included_tracked),
  941. "included_source_files": sorted(
  942. included_tracked, key=lambda row: str(row["path"]).casefold()
  943. ),
  944. "policy_excluded": policy_excluded_final,
  945. "evidence_mapped_tracked": evidence_mapped,
  946. "silent_missing_tracked": silent_missing,
  947. "note": (
  948. "source/ members are exact DELIVERY git-archive tracked files after "
  949. "review-compact exclusion policy; never a dirty post-test worktree scan."
  950. ),
  951. }
  952. if silent_missing:
  953. raise PackagingError(
  954. "exact commit source snapshot has tracked files neither packaged nor "
  955. f"policy-excluded: {silent_missing[:8]}"
  956. )
  957. return remapped, excluded, manifest
  958. def _run_git(command: list[str], *, cwd: Path, timeout: int = 300) -> str:
  959. try:
  960. completed = subprocess.run(
  961. command,
  962. cwd=cwd,
  963. stdout=subprocess.PIPE,
  964. stderr=subprocess.STDOUT,
  965. text=True,
  966. encoding="utf-8",
  967. errors="replace",
  968. timeout=timeout,
  969. check=False,
  970. )
  971. except (OSError, subprocess.TimeoutExpired) as exc:
  972. raise PackagingError(f"unable to run Git for {cwd.name}") from exc
  973. if completed.returncode != 0:
  974. detail = completed.stdout.strip().splitlines()
  975. suffix = f": {detail[-1]}" if detail else ""
  976. raise PackagingError(f"Git command failed for {cwd.name}{suffix}")
  977. return completed.stdout
  978. def _is_evidence_source_path(relative: str) -> bool:
  979. lower = relative.casefold()
  980. if evidence_canon.workspace_canonical_path(relative) is not None:
  981. return True
  982. if handoff.is_under(lower, "receipts"):
  983. return True
  984. if handoff.is_under(lower, "tools/board-viewer/generated"):
  985. return True
  986. name = lower.rsplit("/", 1)[-1]
  987. if name in DERIVED_BOARD_VIEWER_ASSETS and "board-viewer" in lower:
  988. return True
  989. return False
  990. def _unified_item_placement(
  991. *,
  992. source_id: str,
  993. original_relative: str,
  994. profile: str,
  995. ) -> tuple[str, str]:
  996. """Return (package_relative_or_prefix, category) for unified review layouts.
  997. When the workspace path matches the compact evidence allowlist, the first
  998. element is the full canonical package path (not merely a directory prefix).
  999. """
  1000. del profile
  1001. if source_id == "board-viewer-generated" or source_id.startswith("board-viewer"):
  1002. return "evidence/board-viewer", "evidence"
  1003. canon = evidence_canon.workspace_canonical_path(original_relative)
  1004. if canon is not None and source_id in {"workspace-current", "source"}:
  1005. return canon, "evidence"
  1006. if source_id != "workspace-current" and source_id != "source":
  1007. if _is_evidence_source_path(original_relative):
  1008. return f"evidence/external/{source_id}", "evidence"
  1009. return f"source/external/{source_id}", "source"
  1010. if _is_evidence_source_path(original_relative):
  1011. return "evidence", "evidence"
  1012. return "source", "source"
  1013. def _unified_layout_prefix(
  1014. *,
  1015. source_id: str,
  1016. original_relative: str,
  1017. profile: str,
  1018. ) -> tuple[str, str]:
  1019. """Compatibility wrapper: directory prefix + category for unified layouts."""
  1020. placed, category = _unified_item_placement(
  1021. source_id=source_id,
  1022. original_relative=original_relative,
  1023. profile=profile,
  1024. )
  1025. if placed.startswith("evidence/") and placed.count("/") >= 2 and not placed.endswith("/"):
  1026. # Full canonical path — expose parent as prefix for exclusion rewriting.
  1027. if evidence_canon.workspace_canonical_path(original_relative) == placed:
  1028. parent = placed.rsplit("/", 1)[0]
  1029. return parent, category
  1030. return placed, category
  1031. def _package_relative_for_unified(
  1032. *,
  1033. source_id: str,
  1034. original_relative: str,
  1035. profile: str,
  1036. ) -> tuple[str, str]:
  1037. placed, category = _unified_item_placement(
  1038. source_id=source_id,
  1039. original_relative=original_relative,
  1040. profile=profile,
  1041. )
  1042. if evidence_canon.workspace_canonical_path(original_relative) == placed:
  1043. return placed, category
  1044. if original_relative in {".", ""}:
  1045. return placed, category
  1046. return f"{placed}/{original_relative}", category
  1047. # Workspace paths remapped into evidence/ that must also remain under source/ for
  1048. # detached software replay and active markdown relative links. Physical duplicates
  1049. # under evidence/ are intentional review entry points; content dedup must not drop
  1050. # the source/ copy (see apply_content_dedup software-source guard).
  1051. _SOFTWARE_MIRROR_UNDER_SOURCE = frozenset(
  1052. {
  1053. "config/source_closure.json",
  1054. "docs/IO_EVIDENCE_MATRIX.zh-CN.md",
  1055. "docs/HARDWARE_BRINGUP_NOTES.zh-CN.md",
  1056. }
  1057. )
  1058. _STALE_EMBEDDED_COMPACT_SELFTEST = "evidence/selftest/compact-package-selftest.json"
  1059. _COMPACT_SELFTEST_POINTER = "evidence/selftest/compact-package-selftest-pointer.json"
  1060. def _materialize_bytes_items(
  1061. payloads: dict[str, bytes],
  1062. *,
  1063. temp_root: Path,
  1064. source_id: str,
  1065. category: str,
  1066. ) -> list[PackageItem]:
  1067. items: list[PackageItem] = []
  1068. root = temp_root / "generated-meta"
  1069. root.mkdir(parents=True, exist_ok=True)
  1070. for relative, payload in sorted(payloads.items()):
  1071. path = root / Path(*relative.split("/"))
  1072. path.parent.mkdir(parents=True, exist_ok=True)
  1073. path.write_bytes(payload)
  1074. items.append(
  1075. make_package_item(
  1076. path,
  1077. relative=relative,
  1078. category=category,
  1079. source_id=source_id,
  1080. scan_archive=False,
  1081. )
  1082. )
  1083. return items
  1084. def _create_git_bundle(
  1085. *,
  1086. root: Path,
  1087. source_id: str,
  1088. temp_root: Path,
  1089. ) -> tuple[PackageItem, dict[str, object]]:
  1090. git = shutil.which("git")
  1091. if not git:
  1092. raise PackagingError("Git is required to create complete analysis history bundles")
  1093. bundle_dir = temp_root / "git-bundles"
  1094. bundle_dir.mkdir(parents=True, exist_ok=True)
  1095. bundle_path = bundle_dir / f"{source_id}.bundle"
  1096. _run_git([git, "bundle", "create", str(bundle_path), "--all"], cwd=root)
  1097. verify_output = _run_git([git, "bundle", "verify", str(bundle_path)], cwd=root)
  1098. head = _run_git([git, "rev-parse", "HEAD"], cwd=root).strip()
  1099. branch = _run_git([git, "branch", "--show-current"], cwd=root).strip() or None
  1100. status = _run_git(
  1101. [
  1102. git,
  1103. "--no-optional-locks",
  1104. "-c",
  1105. "core.fsmonitor=false",
  1106. "-c",
  1107. "core.untrackedCache=false",
  1108. "status",
  1109. "--short",
  1110. "--branch",
  1111. "--untracked-files=all",
  1112. ],
  1113. cwd=root,
  1114. )
  1115. ref_lines = [line for line in verify_output.splitlines() if " refs/" in line or line.rstrip().endswith(" HEAD")]
  1116. candidate = _candidate_from_path(bundle_path, f"git-history/{source_id}.bundle")
  1117. item = PackageItem(
  1118. candidate=candidate,
  1119. category="core",
  1120. source_id=source_id,
  1121. original_path=".git",
  1122. scan_archive=False,
  1123. )
  1124. metadata = {
  1125. "source_id": source_id,
  1126. "branch": branch,
  1127. "head": head,
  1128. "working_tree_clean": not any(
  1129. line and not line.startswith("##") for line in status.splitlines()
  1130. ),
  1131. "status": "pass",
  1132. "bundle_path": candidate.relative,
  1133. "bundle_ref_count": len(ref_lines),
  1134. "bundle_verify": "pass",
  1135. }
  1136. return item, metadata
  1137. def collect_analysis_inputs(
  1138. *,
  1139. repo_root: Path,
  1140. config: HandoffConfig,
  1141. temp_root: Path,
  1142. include_git_bundle: bool = True,
  1143. profile: str = "full",
  1144. include_sanitized_git_snapshot: bool = False,
  1145. package_name: str = "pending",
  1146. evidence_root: Path | None = None,
  1147. include_process_evidence: bool = False,
  1148. bitstream_path: Path | None = None,
  1149. td_report_paths: list[Path] | None = None,
  1150. binding_commit: str | None = None,
  1151. require_bitstream_binding: bool = False,
  1152. package_stage: str = "intermediate-review",
  1153. ) -> AnalysisCollection:
  1154. root = repo_root.resolve(strict=True)
  1155. temp_root.mkdir(parents=True, exist_ok=True)
  1156. if profile not in handoff.HANDOFF_PROFILES:
  1157. raise PackagingError(f"unsupported handoff profile: {profile}")
  1158. if profile == "full" and not include_git_bundle:
  1159. raise PackagingError(
  1160. "full inclusion-first packages require a git bundle so replay can restore "
  1161. "commit-to-commit source closure comparison"
  1162. )
  1163. unified = handoff.uses_unified_layout(profile)
  1164. # review-compact / review-debug never ship a full bundle unless explicitly forced later.
  1165. if profile in {"review-compact", "review-debug"}:
  1166. include_git_bundle = False
  1167. items: list[PackageItem] = []
  1168. excluded: list[dict[str, str]] = []
  1169. warnings: list[dict[str, str]] = []
  1170. sources: list[dict[str, object]] = []
  1171. git_metadata: list[dict[str, object]] = []
  1172. source_snapshots: list[SourceSnapshot] = []
  1173. primary_source_id = "workspace-current"
  1174. packaged_source_manifest: dict[str, object] | None = None
  1175. if unified and profile in {"review-compact", "review-debug"}:
  1176. # Exact DELIVERY tracked-only snapshot — never scan a dirty post-test WT.
  1177. delivery_commit = _resolve_delivery_commit(root, binding_commit)
  1178. remapped, root_excluded, packaged_source_manifest = (
  1179. _collect_exact_commit_unified_items(
  1180. root=root,
  1181. commit=delivery_commit,
  1182. source_id=primary_source_id,
  1183. temp_root=temp_root / "exact-commit-source",
  1184. extra_exclusions=config.extra_exclusions,
  1185. profile=profile,
  1186. )
  1187. )
  1188. items.extend(remapped)
  1189. excluded.extend(root_excluded)
  1190. elif unified:
  1191. # Collect with a temporary prefix, then remap into source/ or evidence/.
  1192. root_items, root_excluded = _collect_directory_items(
  1193. root=root,
  1194. source_id=primary_source_id,
  1195. category="source",
  1196. prefix="__workspace__",
  1197. extra_exclusions=config.extra_exclusions,
  1198. profile=profile,
  1199. )
  1200. remapped: list[PackageItem] = []
  1201. for item in root_items:
  1202. original = item.original_path
  1203. package_relative, category = _package_relative_for_unified(
  1204. source_id=primary_source_id,
  1205. original_relative=original,
  1206. profile=profile,
  1207. )
  1208. remapped.append(
  1209. PackageItem(
  1210. candidate=handoff.Candidate(
  1211. absolute=item.candidate.absolute,
  1212. relative=package_relative,
  1213. size=item.candidate.size,
  1214. mtime_ns=item.candidate.mtime_ns,
  1215. device=item.candidate.device,
  1216. inode=item.candidate.inode,
  1217. mode=item.candidate.mode,
  1218. ),
  1219. category=category,
  1220. source_id=primary_source_id,
  1221. original_path=original,
  1222. scan_archive=item.scan_archive,
  1223. )
  1224. )
  1225. if original in _SOFTWARE_MIRROR_UNDER_SOURCE and not package_relative.startswith(
  1226. "source/"
  1227. ):
  1228. remapped.append(
  1229. PackageItem(
  1230. candidate=handoff.Candidate(
  1231. absolute=item.candidate.absolute,
  1232. relative=f"source/{original}",
  1233. size=item.candidate.size,
  1234. mtime_ns=item.candidate.mtime_ns,
  1235. device=item.candidate.device,
  1236. inode=item.candidate.inode,
  1237. mode=item.candidate.mode,
  1238. ),
  1239. category="source",
  1240. source_id=primary_source_id,
  1241. original_path=original,
  1242. scan_archive=item.scan_archive,
  1243. )
  1244. )
  1245. items.extend(remapped)
  1246. for entry in root_excluded:
  1247. original_excluded = entry["path"]
  1248. if original_excluded.startswith("__workspace__/"):
  1249. original_excluded = original_excluded[len("__workspace__/") :]
  1250. elif original_excluded == "__workspace__":
  1251. original_excluded = "."
  1252. package_relative, _category = _package_relative_for_unified(
  1253. source_id=primary_source_id,
  1254. original_relative=original_excluded,
  1255. profile=profile,
  1256. )
  1257. excluded.append(
  1258. {
  1259. "path": (
  1260. original_excluded
  1261. if original_excluded == "."
  1262. else package_relative
  1263. ),
  1264. "rule": entry["rule"],
  1265. }
  1266. )
  1267. else:
  1268. root_items, root_excluded = _collect_directory_items(
  1269. root=root,
  1270. source_id=primary_source_id,
  1271. category="core",
  1272. prefix="workspace-current",
  1273. extra_exclusions=config.extra_exclusions,
  1274. profile=profile,
  1275. )
  1276. items.extend(root_items)
  1277. excluded.extend(root_excluded)
  1278. source_snapshots.append(
  1279. _source_snapshot(
  1280. root,
  1281. source_id=primary_source_id,
  1282. extra_exclusions=config.extra_exclusions,
  1283. profile=profile,
  1284. )
  1285. )
  1286. sources.append(
  1287. {
  1288. "id": primary_source_id,
  1289. "category": "source" if unified else "core",
  1290. "kind": (
  1291. "exact_commit_tracked_subset"
  1292. if packaged_source_manifest is not None
  1293. else "git_worktree"
  1294. ),
  1295. "path": str(root),
  1296. "status": "pass",
  1297. "source_snapshot_mode": (
  1298. packaged_source_manifest.get("source_snapshot_mode")
  1299. if packaged_source_manifest is not None
  1300. else "worktree_scan"
  1301. ),
  1302. "delivery_commit": (
  1303. packaged_source_manifest.get("delivery_commit")
  1304. if packaged_source_manifest is not None
  1305. else None
  1306. ),
  1307. }
  1308. )
  1309. if include_git_bundle:
  1310. bundle_item, bundle_metadata = _create_git_bundle(
  1311. root=root,
  1312. source_id=primary_source_id,
  1313. temp_root=temp_root,
  1314. )
  1315. if unified:
  1316. # Keep bundle under meta/git-history for archive-local.
  1317. bundle_rel = f"meta/git-history/{primary_source_id}.bundle"
  1318. bundle_item = PackageItem(
  1319. candidate=handoff.Candidate(
  1320. absolute=bundle_item.candidate.absolute,
  1321. relative=bundle_rel,
  1322. size=bundle_item.candidate.size,
  1323. mtime_ns=bundle_item.candidate.mtime_ns,
  1324. device=bundle_item.candidate.device,
  1325. inode=bundle_item.candidate.inode,
  1326. mode=bundle_item.candidate.mode,
  1327. ),
  1328. category="meta",
  1329. source_id=primary_source_id,
  1330. original_path=".git",
  1331. scan_archive=False,
  1332. )
  1333. bundle_metadata = {**bundle_metadata, "bundle_path": bundle_rel}
  1334. items.append(bundle_item)
  1335. git_metadata.append(bundle_metadata)
  1336. elif unified:
  1337. # review-* must collect live Git provenance (linked worktrees OK via git CLI).
  1338. # Fail closed: never ship a "success" package with only sanitized-snapshot-status.
  1339. stage_for_clean = str(package_stage or "intermediate-review").strip().casefold().replace(
  1340. "_", "-"
  1341. )
  1342. if stage_for_clean in {"intermediate", "non-final"}:
  1343. stage_for_clean = "intermediate-review"
  1344. elif stage_for_clean in {"final", "final-review"}:
  1345. stage_for_clean = "final-review"
  1346. provenance, provenance_artifacts = handoff.collect_review_git_provenance(
  1347. root,
  1348. include_sanitized_git_snapshot=include_sanitized_git_snapshot,
  1349. meta_prefix="meta/git",
  1350. temp_root=temp_root / "review-git",
  1351. # Final-review: porcelain must be empty including untracked (clean worktree).
  1352. # Intermediate unit/fixture packs keep tracked-only dirty gate.
  1353. require_clean=(profile == "review-compact"),
  1354. require_clean_untracked=(
  1355. profile == "review-compact" and stage_for_clean == "final-review"
  1356. ),
  1357. commit=binding_commit,
  1358. )
  1359. if profile in {"review-compact", "review-debug"}:
  1360. prov_status = str(provenance.get("status") or "")
  1361. if prov_status != "pass":
  1362. raise PackagingError(
  1363. "review package requires live Git provenance "
  1364. f"(HEAD/branch/status/log-20/tree/source-file-sha256); "
  1365. f"got status={prov_status!r}. "
  1366. "Package from an exact DELIVERY Git worktree/repo — "
  1367. "sanitized-snapshot-status alone is not sufficient."
  1368. )
  1369. prov_failures = handoff.validate_review_git_provenance_artifacts(
  1370. provenance_artifacts,
  1371. meta_prefix="meta/git",
  1372. expected_head=str(provenance.get("head") or "") or None,
  1373. )
  1374. if prov_failures:
  1375. raise PackagingError(
  1376. "review Git provenance artifacts incomplete/inconsistent: "
  1377. + ", ".join(prov_failures)
  1378. )
  1379. binding = handoff.build_td_source_closure_binding(
  1380. root,
  1381. bitstream_path=bitstream_path,
  1382. td_report_paths=td_report_paths,
  1383. evidence_root=evidence_root,
  1384. commit=binding_commit or str(provenance.get("head") or "") or None,
  1385. require_bitstream=require_bitstream_binding,
  1386. )
  1387. binding_bytes = handoff.json_bytes(binding)
  1388. # Canonical path meta/td/...; keep legacy flat alias for older consumers.
  1389. provenance_artifacts["meta/td/td-source-closure-binding.json"] = binding_bytes
  1390. provenance_artifacts["meta/td-source-closure-binding.json"] = binding_bytes
  1391. stage_n = str(package_stage or "final-review").strip().casefold().replace("_", "-")
  1392. if stage_n in {"intermediate", "intermediate-review", "non-final"}:
  1393. stage_n = "intermediate-review"
  1394. elif stage_n in {"final", "final-review"}:
  1395. stage_n = "final-review"
  1396. else:
  1397. raise PackagingError(
  1398. f"unsupported package_stage={package_stage!r}; "
  1399. "use intermediate-review or final-review"
  1400. )
  1401. purpose = handoff.package_purpose_text(
  1402. profile, package_name=package_name, package_stage=stage_n
  1403. )
  1404. provenance_artifacts["meta/PACKAGE-PURPOSE.txt"] = purpose.encode("utf-8")
  1405. provenance_artifacts["meta/package-stage.txt"] = (stage_n + "\n").encode("utf-8")
  1406. if stage_n == "final-review":
  1407. bit_src = None
  1408. if bitstream_path is not None:
  1409. candidate_bit = Path(bitstream_path)
  1410. if candidate_bit.is_file():
  1411. bit_src = candidate_bit
  1412. if bit_src is None:
  1413. tracked_bit = root / "evidence" / "bitstream" / "prod2u_p4_normal_v3.bit"
  1414. if tracked_bit.is_file():
  1415. bit_src = tracked_bit
  1416. if bit_src is not None:
  1417. provenance_artifacts["evidence/bitstream/prod2u_p4_normal_v3.bit"] = (
  1418. bit_src.read_bytes()
  1419. )
  1420. # Minimal provenance: REFERENCE-POINTER + source-closure-relations + sibling stub.
  1421. # release_set_id must match firmware package inputs (no cyclic ZIP SHAs).
  1422. try:
  1423. import package_provenance as pkg_prov
  1424. from build_firmware_package import motor_polarity_config_identity
  1425. bitstream_obj = binding.get("bitstream") if isinstance(binding.get("bitstream"), dict) else {}
  1426. head = str(provenance.get("head") or "")
  1427. # Load TD report early: ARTIFACT-SOURCE is the production-input tip from
  1428. # the bound TD report (or canonical ARTIFACT_DEFAULT), NOT delivery HEAD.
  1429. from build_firmware_package import ( # noqa: WPS433
  1430. OLD_BASELINE_COMMIT_DEFAULT,
  1431. generate_source_closure_comparison,
  1432. )
  1433. td_report_payload: dict[str, Any] | None = None
  1434. for report_meta in binding.get("td_reports") or []:
  1435. if not isinstance(report_meta, dict):
  1436. continue
  1437. report_path = Path(str(report_meta.get("path") or ""))
  1438. if report_path.is_file():
  1439. try:
  1440. td_report_payload = json.loads(
  1441. report_path.read_text(encoding="utf-8-sig")
  1442. )
  1443. except (OSError, json.JSONDecodeError):
  1444. continue
  1445. if td_report_payload.get("synthesis_input_manifest", {}).get("inputs"):
  1446. break
  1447. td_report_payload = None
  1448. if td_report_payload is None:
  1449. for candidate in td_report_paths or []:
  1450. cpath = Path(str(candidate))
  1451. if cpath.is_file():
  1452. try:
  1453. td_report_payload = json.loads(
  1454. cpath.read_text(encoding="utf-8-sig")
  1455. )
  1456. except (OSError, json.JSONDecodeError):
  1457. continue
  1458. if td_report_payload.get("synthesis_input_manifest", {}).get(
  1459. "inputs"
  1460. ):
  1461. break
  1462. td_report_payload = None
  1463. if td_report_payload is None:
  1464. if stage_n != "intermediate-review":
  1465. raise PackagingError(
  1466. "final-review source-closure relations require a TD report with "
  1467. "synthesis_input_manifest.inputs (pass --td-report)"
  1468. )
  1469. # Intermediate: emit non-final provenance without pretending TD closed.
  1470. # Prefer explicit MSE identity fields over misleading comparison_unavailable
  1471. # with artifact_source_commit == delivery HEAD.
  1472. delivery = str(head or binding_commit or "").strip()
  1473. if not delivery:
  1474. raise PackagingError(
  1475. "intermediate-review delivery commit unavailable "
  1476. "(git head and --binding-commit both empty)"
  1477. )
  1478. verification_tip = str(
  1479. os.environ.get("PRODU2_VERIFICATION_TIP", "").strip()
  1480. or binding.get("verification_tip")
  1481. or ""
  1482. ).strip()
  1483. td_bound_candidate = str(
  1484. os.environ.get("PRODU2_TD_BOUND_CANDIDATE", "").strip()
  1485. or binding.get("td_bound_commit")
  1486. or binding.get("artifact_source_commit")
  1487. or "ff44128a540b7ffd9d82314093b242ac3aee92d7"
  1488. or pkg_prov.ARTIFACT_DEFAULT
  1489. or ""
  1490. ).strip()
  1491. # Reused TD-bound production tip when unchanged; never silently equal delivery.
  1492. artifact = td_bound_candidate or delivery
  1493. old_cmp = pkg_prov.compare_production_source_commits(
  1494. from_commit=pkg_prov.BASE_DEV_COMMIT_DEFAULT,
  1495. to_commit=artifact,
  1496. repo_root=root,
  1497. )
  1498. art_cmp = pkg_prov.compare_production_source_commits(
  1499. from_commit=artifact,
  1500. to_commit=delivery,
  1501. repo_root=root,
  1502. )
  1503. ref_pointer = pkg_prov.build_reference_pointer(
  1504. artifact_commit=artifact,
  1505. delivery_commit=delivery,
  1506. reference_changed=False,
  1507. reference_reused=True,
  1508. repo_root=root,
  1509. summary_only=False,
  1510. )
  1511. relations = pkg_prov.build_source_closure_relations(
  1512. old_baseline_commit=pkg_prov.BASE_DEV_COMMIT_DEFAULT,
  1513. artifact_commit=artifact,
  1514. delivery_commit=delivery,
  1515. old_to_artifact_unchanged=bool(old_cmp.get("unchanged")),
  1516. artifact_to_delivery_unchanged=bool(art_cmp.get("unchanged")),
  1517. old_to_artifact_changed_paths=list(
  1518. old_cmp.get("production_changed_paths") or []
  1519. ),
  1520. artifact_to_delivery_changed_paths=list(
  1521. art_cmp.get("production_changed_paths") or []
  1522. ),
  1523. comparison_mode="snapshot_hash",
  1524. )
  1525. # Annotate MSE intermediate identity without inventing a false unchanged edge.
  1526. relations["verification_tip"] = verification_tip or None
  1527. relations["delivery_commit"] = delivery
  1528. relations["td_bound_candidate"] = td_bound_candidate or None
  1529. relations["reused_artifact_source"] = td_bound_candidate or None
  1530. relations["note"] = (
  1531. "INTERMEDIATE MSE review-debug: verification_tip / delivery / "
  1532. "td_bound_candidate are explicit; do not treat artifact_source_commit "
  1533. "as package HEAD unless they match."
  1534. )
  1535. sibling = pkg_prov.sibling_role_stub(
  1536. role="review-compact",
  1537. expected_filename=(
  1538. os.environ.get("PRODU2_PACKAGE_EXPECTED_FIRMWARE_NAME", "").strip()
  1539. or f"prod2u-mse-firmware-deferred-{delivery[:8]}.zip"
  1540. ),
  1541. release_set_id=f"intermediate-nonfinal-{delivery[:8]}",
  1542. )
  1543. polarity = motor_polarity_config_identity(root)
  1544. # Round-9: when claiming bound bitstream b4b0eda4, derive run_id +
  1545. # receipt SHA from canonical TD receipt — never leave nulls.
  1546. td_fields = pkg_prov.load_canonical_td_a1_fields(root)
  1547. release_identity = pkg_prov.build_shared_release_identity(
  1548. delivery_commit=delivery,
  1549. package_stage="intermediate-review",
  1550. matrix_verification_tip=verification_tip or None,
  1551. software_verification_run_id=(
  1552. str(binding.get("verification_run_id") or "").strip()
  1553. or os.environ.get("PRODU2_SOFTWARE_VERIFICATION_RUN_ID", "").strip()
  1554. or None
  1555. ),
  1556. config_fingerprint=str(polarity.get("sha256") or ""),
  1557. reference_set_fingerprint=pkg_prov.reference_set_fingerprint(root)[
  1558. "sha256"
  1559. ],
  1560. repo_root=root,
  1561. claim_bound_bitstream=True,
  1562. extra={
  1563. "td_bound_candidate": td_bound_candidate or None,
  1564. "reused_artifact_source": td_bound_candidate or None,
  1565. "production_polarity_config": {
  1566. "limit_active_high": polarity.get("limit_active_high"),
  1567. "dir_close_level": polarity.get("dir_close_level"),
  1568. "close_limit_is_ls": polarity.get("close_limit_is_ls"),
  1569. "generated_masks": polarity.get("generated_masks")
  1570. or polarity.get("masks"),
  1571. "config_fingerprint": polarity.get("sha256"),
  1572. },
  1573. "td_receipt_path": td_fields.get("td_receipt_path"),
  1574. "note": (
  1575. "INTERMEDIATE / NON-FINAL MSE A1 verification closure package. "
  1576. "TD identity fields derived from receipts/mse-r4-td-a1-ff44128.json; "
  1577. "Do not treat as final release set."
  1578. ),
  1579. },
  1580. )
  1581. # Keep stable intermediate sibling id label for deferred firmware name,
  1582. # but shared release_set_id already embeds td_artifact_run_id.
  1583. sibling["release_set_id"] = release_identity["release_set_id"]
  1584. provenance_artifacts["meta/REFERENCE-POINTER.json"] = handoff.json_bytes(
  1585. ref_pointer
  1586. )
  1587. provenance_artifacts["meta/source-closure-relations.json"] = (
  1588. handoff.json_bytes(relations)
  1589. )
  1590. provenance_artifacts["meta/release-set-sibling.json"] = handoff.json_bytes(
  1591. sibling
  1592. )
  1593. provenance_artifacts["meta/release-set-identity.json"] = (
  1594. handoff.json_bytes(release_identity)
  1595. )
  1596. provenance_artifacts["meta/release-set-id.txt"] = (
  1597. f"{release_identity['release_set_id']}\n"
  1598. ).encode("ascii")
  1599. # Round-9: when identity claims bound bitstream, TD binding must be
  1600. # status=pass (not hook_ready) with run IDs + receipt SHA.
  1601. binding = dict(binding) if isinstance(binding, dict) else {}
  1602. binding.update(
  1603. {
  1604. "status": "pass",
  1605. "td_binding_status": "pass",
  1606. "artifact_source_commit": release_identity.get(
  1607. "artifact_source_commit"
  1608. ),
  1609. "td_bound_commit": release_identity.get("td_bound_commit"),
  1610. "delivery_commit": delivery,
  1611. "bitstream_sha256": release_identity.get("bitstream_sha256"),
  1612. "td_artifact_run_id": release_identity.get("td_artifact_run_id"),
  1613. "td_verification_run_id": release_identity.get(
  1614. "td_verification_run_id"
  1615. ),
  1616. "td_receipt_sha256": release_identity.get("td_receipt_sha256"),
  1617. "td_receipt_path": td_fields.get("td_receipt_path"),
  1618. "production_binding": release_identity.get("production_binding"),
  1619. "lut": release_identity.get("lut"),
  1620. "mslice": release_identity.get("mslice"),
  1621. "dsp": release_identity.get("dsp"),
  1622. "note": (
  1623. "Round-9 intermediate: TD binding derived from canonical "
  1624. "receipts/mse-r4-td-a1-ff44128.json (status=pass)."
  1625. ),
  1626. }
  1627. )
  1628. binding_bytes = handoff.json_bytes(binding)
  1629. provenance_artifacts["meta/td/td-source-closure-binding.json"] = (
  1630. binding_bytes
  1631. )
  1632. provenance_artifacts["meta/td-source-closure-binding.json"] = (
  1633. binding_bytes
  1634. )
  1635. if packaged_source_manifest is not None:
  1636. provenance_artifacts["meta/git/packaged-source-manifest.json"] = (
  1637. handoff.json_bytes(packaged_source_manifest)
  1638. )
  1639. raise _IntermediateProvenanceDone()
  1640. report_artifact = str(
  1641. td_report_payload.get("commit_full")
  1642. or td_report_payload.get("commit")
  1643. or ""
  1644. )
  1645. # DELIVERY is the package tip (git HEAD / --binding-commit). Never fall
  1646. # back to ARTIFACT or sibling filenames collapse to the wrong tip.
  1647. delivery = str(head or binding_commit or "").strip()
  1648. artifact = str(
  1649. report_artifact
  1650. or binding.get("artifact_source_commit")
  1651. or pkg_prov.ARTIFACT_DEFAULT
  1652. or ""
  1653. ).strip()
  1654. if not delivery:
  1655. raise PackagingError(
  1656. "review-compact delivery commit unavailable "
  1657. "(git head and --binding-commit both empty)"
  1658. )
  1659. if not artifact:
  1660. raise PackagingError(
  1661. "review-compact artifact_source_commit unavailable "
  1662. "(TD report commit / ARTIFACT_DEFAULT missing)"
  1663. )
  1664. # Prefer TD production tip when binder incorrectly equates ARTIFACT to DELIVERY.
  1665. if report_artifact and artifact == delivery and report_artifact != delivery:
  1666. artifact = report_artifact
  1667. ref_pointer = pkg_prov.build_reference_pointer(
  1668. artifact_commit=artifact,
  1669. delivery_commit=delivery,
  1670. reference_changed=False,
  1671. reference_reused=True,
  1672. repo_root=root,
  1673. summary_only=False,
  1674. )
  1675. bit_sha = str(
  1676. binding.get("bitstream_sha256")
  1677. or bitstream_obj.get("sha256")
  1678. or td_report_payload.get("bitstream_sha256")
  1679. or ""
  1680. )
  1681. # Config fingerprint is motor-polarity masks, not project_config_sha256.
  1682. config_fp = motor_polarity_config_identity(root)["sha256"]
  1683. td_run = str(
  1684. binding.get("td_run_id")
  1685. or binding.get("run_id")
  1686. or td_report_payload.get("run_id")
  1687. or td_report_payload.get("td_run_id")
  1688. or ""
  1689. )
  1690. ref_fp = pkg_prov.reference_set_fingerprint(root)
  1691. if not bit_sha:
  1692. raise PackagingError("release_set_id requires bound bitstream sha256")
  1693. if not td_run:
  1694. raise PackagingError("release_set_id requires td run_id from bound receipt")
  1695. release_set_id = pkg_prov.compute_release_set_id(
  1696. artifact_commit=artifact,
  1697. delivery_commit=delivery,
  1698. bitstream_sha256=bit_sha,
  1699. config_fingerprint=config_fp,
  1700. td_run_id=td_run,
  1701. reference_set_fingerprint_sha256=ref_fp["sha256"],
  1702. )
  1703. art_to_del = generate_source_closure_comparison(
  1704. td_report=td_report_payload,
  1705. artifact_commit=artifact,
  1706. matrix_commit=artifact,
  1707. final_dev_commit=delivery,
  1708. repo_root=root,
  1709. )
  1710. old_to_art = generate_source_closure_comparison(
  1711. td_report=td_report_payload,
  1712. artifact_commit=OLD_BASELINE_COMMIT_DEFAULT,
  1713. matrix_commit=OLD_BASELINE_COMMIT_DEFAULT,
  1714. final_dev_commit=artifact,
  1715. repo_root=root,
  1716. )
  1717. comparison_mode = str(art_to_del.get("mode") or "commit_compare")
  1718. if comparison_mode == "comparison_unavailable_without_git":
  1719. relations = pkg_prov.build_source_closure_relations(
  1720. old_baseline_commit=pkg_prov.OLD_BASELINE_DEFAULT,
  1721. artifact_commit=artifact,
  1722. delivery_commit=delivery,
  1723. old_to_artifact_unchanged=None,
  1724. artifact_to_delivery_unchanged=None,
  1725. old_to_artifact_changed_paths=[],
  1726. artifact_to_delivery_changed_paths=[],
  1727. comparison_mode="comparison_unavailable",
  1728. )
  1729. else:
  1730. relations = pkg_prov.build_source_closure_relations(
  1731. old_baseline_commit=pkg_prov.OLD_BASELINE_DEFAULT,
  1732. artifact_commit=artifact,
  1733. delivery_commit=delivery,
  1734. old_to_artifact_unchanged=bool(
  1735. old_to_art.get("source_closure_equal")
  1736. ),
  1737. artifact_to_delivery_unchanged=bool(
  1738. art_to_del.get("source_closure_equal")
  1739. ),
  1740. old_to_artifact_changed_paths=list(
  1741. old_to_art.get("production_changed_paths") or []
  1742. ),
  1743. artifact_to_delivery_changed_paths=list(
  1744. art_to_del.get("production_changed_paths") or []
  1745. ),
  1746. comparison_mode=comparison_mode,
  1747. )
  1748. rel_check = pkg_prov.validate_source_closure_relations(relations)
  1749. if rel_check["status"] != "pass":
  1750. raise PackagingError(
  1751. f"source-closure relations inconsistent: {rel_check['failures']}"
  1752. )
  1753. # Explicit dual-commit fields (keep commit_full for compatibility).
  1754. binding["artifact_source_commit"] = artifact
  1755. binding["delivery_commit"] = delivery
  1756. binding["artifact_to_delivery_unchanged"] = bool(
  1757. art_to_del.get("source_closure_equal")
  1758. )
  1759. binding["td_run_id"] = td_run
  1760. if binding.get("commit_full") in {None, "", artifact} and delivery:
  1761. binding["commit_full"] = delivery
  1762. binding["commit_short"] = delivery[:8]
  1763. # Re-encode binding after enriching identity fields.
  1764. binding_bytes = handoff.json_bytes(binding)
  1765. provenance_artifacts["meta/td/td-source-closure-binding.json"] = binding_bytes
  1766. provenance_artifacts["meta/td-source-closure-binding.json"] = binding_bytes
  1767. provenance_artifacts["meta/SOURCE-CLOSURE-COMPARISON-ART-TO-DEL.json"] = (
  1768. handoff.json_bytes(art_to_del)
  1769. )
  1770. provenance_artifacts["meta/SOURCE-CLOSURE-COMPARISON-OLD-TO-ART.json"] = (
  1771. handoff.json_bytes(old_to_art)
  1772. )
  1773. sibling = pkg_prov.sibling_role_stub(
  1774. role="review-compact",
  1775. expected_filename=pkg_prov.release_sibling_filename("firmware", delivery),
  1776. release_set_id=release_set_id,
  1777. )
  1778. provenance_artifacts["meta/REFERENCE-POINTER.json"] = handoff.json_bytes(ref_pointer)
  1779. provenance_artifacts["meta/source-closure-relations.json"] = handoff.json_bytes(
  1780. relations
  1781. )
  1782. provenance_artifacts["meta/release-set-sibling.json"] = handoff.json_bytes(sibling)
  1783. provenance_artifacts["meta/release-set-id.txt"] = (release_set_id + "\n").encode(
  1784. "ascii"
  1785. )
  1786. # Dual run-id semantics: TD verification vs TD artifact workspace.
  1787. # release_set_id already binds td_run (= TD receipt run_id / artifact run).
  1788. td_verification_run_id = str(
  1789. binding.get("verification_run_id")
  1790. or td_report_payload.get("verification_run_id")
  1791. or ""
  1792. )
  1793. td_artifact_run_id = str(
  1794. binding.get("td_artifact_run_id")
  1795. or td_report_payload.get("td_artifact_run_id")
  1796. or td_report_payload.get("artifact_run_id")
  1797. or td_report_payload.get("run_id")
  1798. or td_run
  1799. or ""
  1800. )
  1801. if not td_artifact_run_id:
  1802. # Recover from known receipt path shape .../runs/<id>/...
  1803. for report_meta in binding.get("td_reports") or []:
  1804. if not isinstance(report_meta, dict):
  1805. continue
  1806. report_path = str(report_meta.get("path") or "")
  1807. marker = "/runs/"
  1808. if marker in report_path.replace("\\", "/"):
  1809. part = report_path.replace("\\", "/").split(marker, 1)[1]
  1810. td_artifact_run_id = part.split("/", 1)[0]
  1811. break
  1812. if not td_artifact_run_id:
  1813. raise PackagingError(
  1814. "final-review requires td_artifact_run_id from bound TD receipt "
  1815. "(no hardcoded historical fallback)"
  1816. )
  1817. if td_artifact_run_id == "20260806T112210Z-3f2f5f2f":
  1818. raise PackagingError(
  1819. "refusing Round-10 hardcoded td_artifact_run_id fallback "
  1820. "20260806T112210Z-3f2f5f2f"
  1821. )
  1822. binding["verification_run_id"] = td_verification_run_id or td_run
  1823. binding["td_artifact_run_id"] = td_artifact_run_id
  1824. binding["td_run_id_semantics"] = {
  1825. "verification_run_id": td_verification_run_id or td_run,
  1826. "td_artifact_run_id": td_artifact_run_id,
  1827. "release_set_id_uses": "td_artifact_run_id",
  1828. }
  1829. binding_bytes = handoff.json_bytes(binding)
  1830. provenance_artifacts["meta/td/td-source-closure-binding.json"] = binding_bytes
  1831. provenance_artifacts["meta/td-source-closure-binding.json"] = binding_bytes
  1832. polarity = motor_polarity_config_identity(root)
  1833. matrix_tip = str(
  1834. os.environ.get("PRODU2_VERIFICATION_TIP", "").strip()
  1835. or binding.get("matrix_verification_tip")
  1836. or binding.get("verification_tip")
  1837. or ""
  1838. ).strip()
  1839. matrix_run = str(
  1840. os.environ.get("PRODU2_VERIFICATION_RUN_ID", "").strip()
  1841. or binding.get("matrix_verification_run_id")
  1842. or binding.get("software_verification_run_id")
  1843. or ""
  1844. ).strip()
  1845. td_bound = str(report_artifact or artifact).strip()
  1846. td_fields_live: dict[str, Any] = {
  1847. "artifact_source_commit": artifact,
  1848. "td_bound_commit": td_bound,
  1849. "td_artifact_run_id": td_artifact_run_id,
  1850. "td_verification_run_id": td_verification_run_id or None,
  1851. "bitstream_sha256": bit_sha,
  1852. "td_binding_status": "pass",
  1853. "td_policy": (
  1854. "reused_exact_source_bound_td"
  1855. if bit_sha == pkg_prov.CANONICAL_TD_A1_BITSTREAM
  1856. else "fresh_td"
  1857. ),
  1858. }
  1859. try:
  1860. live_parsed = pkg_prov.parse_td_resource_fields(td_report_payload)
  1861. for key in ("lut", "mslice", "dsp"):
  1862. if live_parsed.get(key) is not None:
  1863. td_fields_live[key] = live_parsed.get(key)
  1864. except Exception: # noqa: BLE001
  1865. live_parsed = {}
  1866. for report_meta in binding.get("td_reports") or []:
  1867. if isinstance(report_meta, dict) and report_meta.get("sha256"):
  1868. td_fields_live["td_receipt_sha256"] = report_meta.get("sha256")
  1869. break
  1870. n_inputs = len(art_to_del.get("inputs") or [])
  1871. changed_n = len(art_to_del.get("production_changed_paths") or [])
  1872. if n_inputs:
  1873. matched = n_inputs - changed_n
  1874. if matched < 0:
  1875. matched = 0
  1876. td_fields_live["production_binding"] = pkg_prov.format_production_binding(
  1877. expected=n_inputs,
  1878. matched=matched,
  1879. missing=0,
  1880. hash_mismatch=changed_n,
  1881. )
  1882. if (
  1883. td_fields_live.get("lut") is None
  1884. or td_fields_live.get("mslice") is None
  1885. or td_fields_live.get("dsp") is None
  1886. or not td_fields_live.get("td_receipt_sha256")
  1887. ) and bit_sha == pkg_prov.CANONICAL_TD_A1_BITSTREAM:
  1888. try:
  1889. canon_td = pkg_prov.load_canonical_td_a1_fields(root)
  1890. for key in (
  1891. "lut",
  1892. "mslice",
  1893. "dsp",
  1894. "td_receipt_sha256",
  1895. "td_verification_run_id",
  1896. "production_binding",
  1897. ):
  1898. if not td_fields_live.get(key) and canon_td.get(key) is not None:
  1899. td_fields_live[key] = canon_td.get(key)
  1900. except Exception: # noqa: BLE001
  1901. pass
  1902. release_identity = pkg_prov.build_shared_release_identity(
  1903. delivery_commit=delivery,
  1904. package_stage=stage_n,
  1905. matrix_verification_tip=matrix_tip or None,
  1906. software_verification_run_id=matrix_run or None,
  1907. config_fingerprint=config_fp,
  1908. reference_set_fingerprint=ref_fp["sha256"],
  1909. repo_root=root,
  1910. claim_bound_bitstream=True,
  1911. td_fields=td_fields_live,
  1912. extra={
  1913. "production_polarity_config": {
  1914. "limit_active_high": polarity.get("limit_active_high"),
  1915. "dir_close_level": polarity.get("dir_close_level"),
  1916. "close_limit_is_ls": polarity.get("close_limit_is_ls"),
  1917. "generated_masks": polarity.get("generated_masks")
  1918. or polarity.get("masks"),
  1919. "config_fingerprint": config_fp,
  1920. },
  1921. "dir_close_level": polarity.get("dir_close_level"),
  1922. "reference_fingerprint_schema": ref_fp.get("schema"),
  1923. "note": (
  1924. "release_set_id is independently recomputable from these fields; "
  1925. "td_artifact_run_id (TD receipt run_id) feeds release_set_id; "
  1926. "software_verification_run_id is the software matrix run id when set. "
  1927. "Sibling ZIP SHAs live only in the external release-set JSON."
  1928. ),
  1929. },
  1930. )
  1931. release_set_id = str(release_identity["release_set_id"])
  1932. sibling["release_set_id"] = release_set_id
  1933. provenance_artifacts["meta/release-set-sibling.json"] = handoff.json_bytes(
  1934. sibling
  1935. )
  1936. provenance_artifacts["meta/release-set-id.txt"] = (
  1937. release_set_id + "\n"
  1938. ).encode("ascii")
  1939. provenance_artifacts["meta/release-set-identity.json"] = handoff.json_bytes(
  1940. release_identity
  1941. )
  1942. if packaged_source_manifest is not None:
  1943. provenance_artifacts["meta/git/packaged-source-manifest.json"] = (
  1944. handoff.json_bytes(packaged_source_manifest)
  1945. )
  1946. except _IntermediateProvenanceDone:
  1947. pass
  1948. except Exception as exc: # noqa: BLE001 - surface helper failure in meta, fail later selftest
  1949. provenance_artifacts["meta/REFERENCE-POINTER-ERROR.txt"] = (
  1950. f"reference pointer build failed: {exc}\n"
  1951. ).encode("utf-8")
  1952. # Even when provenance helpers fail, still emit packaged-source-manifest if built.
  1953. if (
  1954. packaged_source_manifest is not None
  1955. and "meta/git/packaged-source-manifest.json" not in provenance_artifacts
  1956. ):
  1957. provenance_artifacts["meta/git/packaged-source-manifest.json"] = (
  1958. handoff.json_bytes(packaged_source_manifest)
  1959. )
  1960. # External selftest sidecar certifies the final ZIP; never embed a recursive
  1961. # compact-package-selftest.json that claims to authenticate this archive.
  1962. import package_provenance as pkg_prov
  1963. delivery_full = str(provenance.get("head") or binding_commit or "unknown").strip()
  1964. topic_slug = pkg_prov.release_task_slug()
  1965. actual_zip = None
  1966. if package_name and "PENDING" not in str(package_name).upper():
  1967. actual_zip = (
  1968. package_name if str(package_name).casefold().endswith(".zip") else f"{package_name}.zip"
  1969. )
  1970. names = pkg_prov.canonical_release_names(
  1971. role="review-compact",
  1972. stage=stage_n if "stage_n" in locals() else "intermediate-review",
  1973. delivery_commit=delivery_full if delivery_full != "unknown" else "0" * 40,
  1974. topic=topic_slug,
  1975. actual_zip_basename=actual_zip,
  1976. )
  1977. provenance_artifacts[_COMPACT_SELFTEST_POINTER] = handoff.json_bytes(
  1978. {
  1979. "schema": "cpld-review-compact-selftest-pointer-v1",
  1980. "role": "external_sidecar_only",
  1981. "topic": names["topic"],
  1982. "package_stage": names["stage"],
  1983. "delivery_commit": delivery_full,
  1984. "actual_zip_basename": names["zip_basename"],
  1985. "expected_external_selftest_filename": names["selftest_basename"],
  1986. "expected_detached_replay_filename": names["detached_replay_basename"],
  1987. "deprecated_alias_filename": pkg_prov.deprecated_door_percent_alias(
  1988. "review-selftest", delivery_full
  1989. ),
  1990. "note": (
  1991. "Final review ZIP SHA / member_count are certified only by the "
  1992. "external sibling selftest sidecar listed above. This archive does "
  1993. "not embed compact-package-selftest.json (avoids cyclic self-hash). "
  1994. "door-percent alias is deprecated and not final authority."
  1995. ),
  1996. }
  1997. )
  1998. # Package-time actual-HEAD closure (never pre-committed self-hash).
  1999. matrix_tip_env = str(
  2000. os.environ.get("PRODU2_VERIFICATION_TIP", "").strip()
  2001. or binding.get("matrix_verification_tip")
  2002. or binding.get("verification_tip")
  2003. or ""
  2004. ).strip()
  2005. if not matrix_tip_env and stage_n == "final-review":
  2006. raise PackagingError(
  2007. "final-review requires PRODU2_VERIFICATION_TIP (no hardcoded R7/R8 fallback)"
  2008. )
  2009. if matrix_tip_env and delivery_full and delivery_full != "unknown":
  2010. try:
  2011. import verification_to_delivery_closure as v2d
  2012. closure = v2d.build_closure(
  2013. repo=root,
  2014. verification_tip=matrix_tip_env,
  2015. delivery_commit=delivery_full,
  2016. matrix_run_id=str(
  2017. os.environ.get("PRODU2_VERIFICATION_RUN_ID", "")
  2018. ).strip()
  2019. or None,
  2020. )
  2021. provenance_artifacts["meta/verification-to-delivery-closure.json"] = (
  2022. handoff.json_bytes(closure)
  2023. )
  2024. if stage_n == "final-review" and not closure.get("closure_ok"):
  2025. raise PackagingError(
  2026. "final-review verification→delivery closure_ok=false: "
  2027. f"{closure.get('forbidden_changed_paths')}"
  2028. )
  2029. except PackagingError:
  2030. raise
  2031. except Exception as exc: # noqa: BLE001
  2032. provenance_artifacts["meta/verification-to-delivery-closure-ERROR.txt"] = (
  2033. f"package-time closure failed: {exc}\n"
  2034. ).encode("utf-8")
  2035. if stage_n == "final-review":
  2036. raise PackagingError(
  2037. f"final-review requires package-time closure: {exc}"
  2038. ) from exc
  2039. items.extend(
  2040. _materialize_bytes_items(
  2041. provenance_artifacts,
  2042. temp_root=temp_root,
  2043. source_id="meta-generated",
  2044. category="meta",
  2045. )
  2046. )
  2047. git_metadata.append(
  2048. {
  2049. "source_id": primary_source_id,
  2050. "status": provenance.get("status"),
  2051. "branch": provenance.get("branch"),
  2052. "head": provenance.get("head"),
  2053. "full_bundle": False,
  2054. "provenance": provenance,
  2055. "td_source_closure_binding": binding,
  2056. }
  2057. )
  2058. resolved_sources, source_warnings = resolve_external_sources(config.external_sources)
  2059. if profile == "code-only":
  2060. resolved_sources = [
  2061. source for source in resolved_sources if source.id != "board-viewer-generated"
  2062. ]
  2063. warnings.extend(source_warnings)
  2064. for source in resolved_sources:
  2065. if unified:
  2066. # Prefer derived board-viewer assets under evidence/.
  2067. if source.kind == "file":
  2068. prefix, category = _unified_layout_prefix(
  2069. source_id=source.id,
  2070. original_relative=source.path.name,
  2071. profile=profile,
  2072. )
  2073. candidate = _candidate_from_path(
  2074. source.path, f"{prefix}/{source.path.name}"
  2075. )
  2076. items.append(
  2077. PackageItem(
  2078. candidate=candidate,
  2079. category=category,
  2080. source_id=source.id,
  2081. original_path=source.path.name,
  2082. scan_archive=source.archive_policy == "inspect",
  2083. )
  2084. )
  2085. else:
  2086. source_items, source_excluded = _collect_directory_items(
  2087. root=source.path,
  2088. source_id=source.id,
  2089. category="evidence",
  2090. prefix="__external__",
  2091. extra_exclusions=config.extra_exclusions,
  2092. profile=profile,
  2093. )
  2094. for item in source_items:
  2095. original = item.original_path
  2096. prefix, category = _unified_layout_prefix(
  2097. source_id=source.id,
  2098. original_relative=original,
  2099. profile=profile,
  2100. )
  2101. items.append(
  2102. PackageItem(
  2103. candidate=_rebase_candidate(
  2104. handoff.Candidate(
  2105. absolute=item.candidate.absolute,
  2106. relative=original,
  2107. size=item.candidate.size,
  2108. mtime_ns=item.candidate.mtime_ns,
  2109. device=item.candidate.device,
  2110. inode=item.candidate.inode,
  2111. mode=item.candidate.mode,
  2112. ),
  2113. prefix,
  2114. ),
  2115. category=category,
  2116. source_id=source.id,
  2117. original_path=original,
  2118. scan_archive=item.scan_archive,
  2119. )
  2120. )
  2121. for entry in source_excluded:
  2122. original_excluded = entry["path"]
  2123. if original_excluded.startswith("__external__/"):
  2124. original_excluded = original_excluded[len("__external__/") :]
  2125. prefix, _category = _unified_layout_prefix(
  2126. source_id=source.id,
  2127. original_relative=original_excluded,
  2128. profile=profile,
  2129. )
  2130. excluded.append(
  2131. {
  2132. "path": f"{prefix}/{original_excluded}",
  2133. "rule": entry["rule"],
  2134. }
  2135. )
  2136. source_snapshots.append(
  2137. _source_snapshot(
  2138. source.path,
  2139. source_id=source.id,
  2140. extra_exclusions=config.extra_exclusions,
  2141. profile=profile,
  2142. )
  2143. )
  2144. else:
  2145. prefix = f"external/{source.id}"
  2146. if source.kind == "file":
  2147. candidate = _candidate_from_path(source.path, f"{prefix}/{source.path.name}")
  2148. items.append(
  2149. PackageItem(
  2150. candidate=candidate,
  2151. category=source.category,
  2152. source_id=source.id,
  2153. original_path=source.path.name,
  2154. scan_archive=source.archive_policy == "inspect",
  2155. )
  2156. )
  2157. else:
  2158. source_items, source_excluded = _collect_directory_items(
  2159. root=source.path,
  2160. source_id=source.id,
  2161. category=source.category,
  2162. prefix=prefix,
  2163. extra_exclusions=config.extra_exclusions,
  2164. profile=profile,
  2165. )
  2166. items.extend(source_items)
  2167. excluded.extend(source_excluded)
  2168. source_snapshots.append(
  2169. _source_snapshot(
  2170. source.path,
  2171. source_id=source.id,
  2172. extra_exclusions=config.extra_exclusions,
  2173. profile=profile,
  2174. )
  2175. )
  2176. sources.append(
  2177. {
  2178. "id": source.id,
  2179. "category": "evidence" if unified else source.category,
  2180. "kind": source.kind,
  2181. "path": str(source.path),
  2182. "status": "pass",
  2183. }
  2184. )
  2185. if source.kind == "git_worktree" and include_git_bundle:
  2186. external_bundle, external_git = _create_git_bundle(
  2187. root=source.path,
  2188. source_id=source.id,
  2189. temp_root=temp_root,
  2190. )
  2191. items.append(external_bundle)
  2192. git_metadata.append(external_git)
  2193. evidence_canon_fields: dict[str, object] | None = None
  2194. include_process = include_process_evidence or profile == "review-debug"
  2195. if unified:
  2196. if evidence_root is not None:
  2197. staged = evidence_canon.stage_evidence_root(
  2198. evidence_root,
  2199. staging_root=temp_root / "canonical-evidence",
  2200. include_process_evidence=include_process,
  2201. )
  2202. for staged_file in staged.staged:
  2203. items.append(
  2204. PackageItem(
  2205. candidate=_candidate_from_path(
  2206. staged_file.absolute,
  2207. staged_file.relative,
  2208. ),
  2209. category="evidence",
  2210. source_id="evidence-root",
  2211. original_path=staged_file.original_path,
  2212. scan_archive=False,
  2213. )
  2214. )
  2215. excluded.extend(staged.excluded)
  2216. sources.append(
  2217. {
  2218. "id": "evidence-root",
  2219. "category": "evidence",
  2220. "kind": "directory",
  2221. "path": str(evidence_root.resolve()),
  2222. "status": "pass",
  2223. }
  2224. )
  2225. evidence_canon_fields = evidence_canon.build_evidence_canon_index_fields(
  2226. catalog=staged.catalog,
  2227. aliases=staged.aliases,
  2228. log_policy_actions=staged.log_policy_actions,
  2229. include_process_evidence=include_process,
  2230. profile=profile,
  2231. )
  2232. tip = os.environ.get("PRODU2_VERIFICATION_TIP", "").strip()
  2233. run_id = os.environ.get("PRODU2_VERIFICATION_RUN_ID", "").strip()
  2234. if tip and run_id:
  2235. try:
  2236. import current_evidence as cur_ev
  2237. staged_cur = cur_ev.stage_current_evidence(
  2238. repo=root,
  2239. staging_root=temp_root / "current-evidence",
  2240. verification_tip=tip,
  2241. run_id=run_id,
  2242. )
  2243. for key, dest in staged_cur.items():
  2244. rel = (
  2245. cur_ev.CANONICAL_MATRIX_REL
  2246. if key == "matrix"
  2247. else cur_ev.CANONICAL_FORMAL_REL
  2248. )
  2249. items.append(
  2250. PackageItem(
  2251. candidate=_candidate_from_path(dest, rel),
  2252. category="evidence",
  2253. source_id="current-evidence",
  2254. original_path=rel,
  2255. scan_archive=False,
  2256. )
  2257. )
  2258. except Exception as exc: # noqa: BLE001
  2259. stage_now = str(package_stage or "").casefold().replace("_", "-")
  2260. if stage_now in {"final", "final-review"}:
  2261. raise PackagingError(
  2262. f"current evidence selection failed: {exc}"
  2263. ) from exc
  2264. warnings.append(
  2265. {"code": "current_evidence_skipped", "detail": str(exc)}
  2266. )
  2267. kept_items, filter_excluded, _remaps = evidence_canon.filter_package_items_for_compact(
  2268. items,
  2269. profile=profile,
  2270. include_process_evidence=include_process,
  2271. )
  2272. items = list(kept_items)
  2273. excluded.extend(filter_excluded)
  2274. # Workspace allowlist remaps + evidence-root staging can both land on the
  2275. # same canonical evidence/ path; keep one physical copy (prefer evidence-root).
  2276. deduped: dict[str, PackageItem] = {}
  2277. for item in items:
  2278. key = handoff.windows_collision_key(item.candidate.relative)
  2279. previous = deduped.get(key)
  2280. if previous is None:
  2281. deduped[key] = item
  2282. continue
  2283. prefer_new = (
  2284. item.source_id == "current-evidence"
  2285. and previous.source_id != "current-evidence"
  2286. ) or (
  2287. item.source_id == "evidence-root"
  2288. and previous.source_id not in {"current-evidence", "evidence-root"}
  2289. )
  2290. keep, drop = (item, previous) if prefer_new else (previous, item)
  2291. deduped[key] = keep
  2292. excluded.append(
  2293. {
  2294. "path": drop.original_path or drop.candidate.relative,
  2295. "rule": "canonical_path_physical_dedup",
  2296. }
  2297. )
  2298. if evidence_canon_fields is not None:
  2299. aliases = list(evidence_canon_fields.get("aliases") or [])
  2300. aliases.append(
  2301. {
  2302. "physical_path": keep.candidate.relative,
  2303. "logical_paths": [
  2304. f"evidence/from/{drop.original_path or drop.candidate.relative}"
  2305. ],
  2306. "reason": "canonical_path_physical_dedup",
  2307. }
  2308. )
  2309. evidence_canon_fields["aliases"] = aliases
  2310. items = list(deduped.values())
  2311. if evidence_canon_fields is None:
  2312. evidence_canon_fields = evidence_canon.build_evidence_canon_index_fields(
  2313. catalog=[
  2314. {
  2315. "key": key,
  2316. "canonical_path": evidence_canon.load_allowlist().by_key[key].canonical_path,
  2317. "role": "compact_default",
  2318. "source_original": None,
  2319. }
  2320. for key in evidence_canon.compact_default_key_list()
  2321. ],
  2322. aliases=[],
  2323. log_policy_actions=[],
  2324. include_process_evidence=include_process,
  2325. profile=profile,
  2326. )
  2327. # Record workspace allowlisted evidence that survived filtering.
  2328. present = {item.candidate.relative.casefold() for item in items}
  2329. catalog = list(evidence_canon_fields.get("catalog", [])) # type: ignore[arg-type]
  2330. allowlist = evidence_canon.load_allowlist()
  2331. for entry in allowlist.canonical_entries:
  2332. if entry.canonical_path.casefold() in present and not any(
  2333. str(row.get("canonical_path", "")).casefold() == entry.canonical_path.casefold()
  2334. for row in catalog
  2335. ):
  2336. catalog.append(
  2337. {
  2338. "key": entry.key,
  2339. "canonical_path": entry.canonical_path,
  2340. "role": "compact_default",
  2341. "source_original": "workspace",
  2342. }
  2343. )
  2344. evidence_canon_fields["catalog"] = sorted(catalog, key=lambda row: str(row["key"]))
  2345. evidence_canon_fields["compact_default_keys"] = sorted(
  2346. {str(row["key"]) for row in catalog if row.get("role") == "compact_default"}
  2347. )
  2348. # Drop any stale embedded final-ZIP selftest receipt (recursive hash hazard).
  2349. filtered_items: list[PackageItem] = []
  2350. for item in items:
  2351. rel = item.candidate.relative.replace("\\", "/")
  2352. if rel == _STALE_EMBEDDED_COMPACT_SELFTEST or rel.endswith(
  2353. "/" + _STALE_EMBEDDED_COMPACT_SELFTEST
  2354. ):
  2355. excluded.append(
  2356. {
  2357. "path": item.original_path or rel,
  2358. "rule": "stale_embedded_compact_selftest_forbidden",
  2359. }
  2360. )
  2361. continue
  2362. if rel.rsplit("/", 1)[-1].casefold() == "compact-package-selftest.json":
  2363. excluded.append(
  2364. {
  2365. "path": item.original_path or rel,
  2366. "rule": "stale_embedded_compact_selftest_forbidden",
  2367. }
  2368. )
  2369. continue
  2370. filtered_items.append(item)
  2371. items = filtered_items
  2372. items.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
  2373. excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
  2374. return AnalysisCollection(
  2375. status="pass_with_warnings" if warnings else "pass",
  2376. items=tuple(items),
  2377. excluded=tuple(excluded),
  2378. warnings=tuple(warnings),
  2379. sources=tuple(sources),
  2380. git=tuple(git_metadata),
  2381. source_snapshots=tuple(source_snapshots),
  2382. evidence_canon=evidence_canon_fields,
  2383. )
  2384. def find_7z() -> Path | None:
  2385. discovered = shutil.which("7z") or shutil.which("7zz")
  2386. candidates = [
  2387. Path(discovered) if discovered else None,
  2388. Path(r"C:\Program Files\7-Zip\7z.exe"),
  2389. Path(r"C:\Program Files (x86)\7-Zip\7z.exe"),
  2390. ]
  2391. for candidate in candidates:
  2392. if candidate is not None and candidate.is_file():
  2393. return candidate.resolve(strict=True)
  2394. return None
  2395. def build_7zip_create_command(archive_path: Path, staging_root: Path) -> list[str]:
  2396. del staging_root
  2397. return [
  2398. "a",
  2399. "-tzip",
  2400. "-mm=Deflate",
  2401. "-mx=9",
  2402. "-mmt",
  2403. "-y",
  2404. "-r",
  2405. str(archive_path),
  2406. "CPLD\\*",
  2407. ]
  2408. def _run_7z(seven_zip: Path, arguments: list[str], *, cwd: Path) -> str:
  2409. try:
  2410. completed = subprocess.run(
  2411. [str(seven_zip), *arguments],
  2412. cwd=cwd,
  2413. stdout=subprocess.PIPE,
  2414. stderr=subprocess.STDOUT,
  2415. text=True,
  2416. encoding="utf-8",
  2417. errors="replace",
  2418. timeout=300,
  2419. check=False,
  2420. )
  2421. except (OSError, subprocess.TimeoutExpired) as exc:
  2422. raise PackagingError("unable to run 7-Zip for archive inspection") from exc
  2423. if completed.returncode != 0:
  2424. detail = completed.stdout.strip().splitlines()
  2425. suffix = f": {detail[-1]}" if detail else ""
  2426. raise PackagingError(f"7-Zip archive inspection failed{suffix}")
  2427. return completed.stdout
  2428. def _rename_archive_entries(
  2429. seven_zip: Path,
  2430. archive_path: Path,
  2431. renames: list[tuple[str, str]],
  2432. ) -> None:
  2433. for offset in range(0, len(renames), 64):
  2434. batch = renames[offset : offset + 64]
  2435. arguments = ["rn", "-y", str(archive_path)]
  2436. for old_name, new_name in batch:
  2437. arguments.extend((old_name, new_name))
  2438. _run_7z(seven_zip, arguments, cwd=archive_path.parent)
  2439. def _parse_7z_members(payload: str, archive_label: str) -> list[dict[str, str]]:
  2440. in_members = False
  2441. current: dict[str, str] = {}
  2442. members: list[dict[str, str]] = []
  2443. for raw_line in payload.splitlines():
  2444. line = raw_line.rstrip("\r\n")
  2445. if line.strip() == "----------":
  2446. in_members = True
  2447. current = {}
  2448. continue
  2449. if not in_members:
  2450. continue
  2451. if not line.strip():
  2452. if current:
  2453. members.append(current)
  2454. current = {}
  2455. continue
  2456. key, separator, value = line.partition(" = ")
  2457. if separator:
  2458. current[key.strip()] = value.strip()
  2459. if current:
  2460. members.append(current)
  2461. for member in members:
  2462. raw_path = member.get("Path", "")
  2463. normalized = raw_path.replace("\\", "/")
  2464. if not normalized or normalized.startswith("/") or re.match(r"^[A-Za-z]:", normalized):
  2465. raise PackagingError(f"unsafe archive member path in {archive_label}")
  2466. handoff.normalize_relative(normalized.split("/"))
  2467. if member.get("Encrypted") not in {None, "", "-"}:
  2468. raise PackagingError(f"encrypted archive member is unsupported in {archive_label}")
  2469. if member.get("Symbolic Link") or member.get("Hard Link"):
  2470. raise PackagingError(f"archive link member is unsupported in {archive_label}")
  2471. if member.get("Alternate Stream") not in {None, "", "-"}:
  2472. raise PackagingError(f"archive alternate stream is unsupported in {archive_label}")
  2473. if member.get("Split Before") not in {None, "", "-"} or member.get("Split After") not in {
  2474. None,
  2475. "",
  2476. "-",
  2477. }:
  2478. raise PackagingError(f"split archive member is unsupported in {archive_label}")
  2479. return members
  2480. def _inspect_and_extract_unsupported_archive(
  2481. item: PackageItem,
  2482. *,
  2483. temp_root: Path,
  2484. seven_zip: Path,
  2485. extra_exclusions: tuple[dict[str, str], ...],
  2486. ) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
  2487. listing = _run_7z(
  2488. seven_zip,
  2489. ["l", "-slt", "-sccUTF-8", str(item.candidate.absolute)],
  2490. cwd=item.candidate.absolute.parent,
  2491. )
  2492. members = _parse_7z_members(listing, item.candidate.relative)
  2493. file_members = [
  2494. member
  2495. for member in members
  2496. if member.get("Folder") != "+" and "D" not in member.get("Attributes", "")
  2497. ]
  2498. expected_bytes = sum(int(member.get("Size") or "0") for member in file_members)
  2499. token = hashlib.sha256(item.candidate.relative.encode("utf-8")).hexdigest()[:16]
  2500. extract_root = temp_root / "expanded-archives" / token
  2501. extract_root.mkdir(parents=True, exist_ok=False)
  2502. _run_7z(
  2503. seven_zip,
  2504. ["x", "-y", "-aoa", "-sccUTF-8", f"-o{extract_root}", str(item.candidate.absolute)],
  2505. cwd=item.candidate.absolute.parent,
  2506. )
  2507. actual_files = [path for path in extract_root.rglob("*") if path.is_file()]
  2508. actual_bytes = sum(path.stat().st_size for path in actual_files)
  2509. if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
  2510. raise PackagingError(
  2511. f"archive extraction inventory mismatch: {item.candidate.relative} "
  2512. f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
  2513. )
  2514. expanded_candidates, expanded_excluded, _ = scan_analysis_root(
  2515. extract_root,
  2516. extra_exclusions=extra_exclusions,
  2517. )
  2518. handoff.audit_candidates(expanded_candidates)
  2519. expanded_prefix = f"{item.candidate.relative}.expanded"
  2520. expanded_items = [
  2521. PackageItem(
  2522. candidate=_rebase_candidate(candidate, expanded_prefix),
  2523. category=item.category,
  2524. source_id=item.source_id,
  2525. original_path=f"{item.original_path}!/{candidate.relative}",
  2526. scan_archive=True,
  2527. )
  2528. for candidate in expanded_candidates
  2529. ]
  2530. rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
  2531. sensitive_rules = {
  2532. "credential_or_license_file",
  2533. "credential_configuration_file",
  2534. "private_key_file",
  2535. "secret_environment_file",
  2536. "cloud_credential_file",
  2537. "container_registry_credential_file",
  2538. }
  2539. contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
  2540. return expanded_items, rebased_excluded, contains_sensitive
  2541. def _inspect_and_extract_zip_archive(
  2542. item: PackageItem,
  2543. *,
  2544. temp_root: Path,
  2545. extra_exclusions: tuple[dict[str, str], ...],
  2546. ) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
  2547. archive_label = item.candidate.relative
  2548. try:
  2549. with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
  2550. file_members: list[zipfile.ZipInfo] = []
  2551. expected_bytes = 0
  2552. for info in archive.infolist():
  2553. normalized = info.filename.replace("\\", "/")
  2554. if (
  2555. not normalized
  2556. or normalized.startswith("/")
  2557. or re.match(r"^[A-Za-z]:", normalized)
  2558. ):
  2559. raise PackagingError(
  2560. f"unsafe archive member path in {archive_label}"
  2561. )
  2562. handoff.normalize_relative(normalized.split("/"))
  2563. if info.flag_bits & 0x1:
  2564. raise PackagingError(
  2565. f"encrypted archive member is unsupported in {archive_label}"
  2566. )
  2567. member_mode = (info.external_attr >> 16) & 0xFFFF
  2568. member_type = stat.S_IFMT(member_mode)
  2569. if info.is_dir():
  2570. if (
  2571. info.file_size != 0
  2572. or info.compress_size != 0
  2573. or member_type not in {0, stat.S_IFDIR}
  2574. ):
  2575. raise PackagingError(
  2576. f"unsafe archive member type in {archive_label}"
  2577. )
  2578. continue
  2579. if member_type not in {0, stat.S_IFREG}:
  2580. raise PackagingError(
  2581. f"unsafe archive member type in {archive_label}"
  2582. )
  2583. file_members.append(info)
  2584. expected_bytes += info.file_size
  2585. except (OSError, zipfile.BadZipFile) as exc:
  2586. raise PackagingError(
  2587. f"unable to inspect source archive: {archive_label}"
  2588. ) from exc
  2589. token = hashlib.sha256(archive_label.encode("utf-8")).hexdigest()[:16]
  2590. extract_root = temp_root / "expanded-archives" / token
  2591. extract_root.mkdir(parents=True, exist_ok=False)
  2592. actual_files: list[Path] = []
  2593. actual_bytes = 0
  2594. try:
  2595. with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
  2596. for info in file_members:
  2597. parts = info.filename.replace("\\", "/").split("/")
  2598. target_path = extract_root / Path(*parts)
  2599. target_path.parent.mkdir(parents=True, exist_ok=True)
  2600. with archive.open(info, "r") as source, target_path.open("wb") as destination:
  2601. shutil.copyfileobj(source, destination, length=1024 * 1024)
  2602. actual_files.append(target_path)
  2603. actual_bytes += target_path.stat().st_size
  2604. except (OSError, zipfile.BadZipFile) as exc:
  2605. raise PackagingError(
  2606. f"unable to extract source archive: {archive_label}"
  2607. ) from exc
  2608. if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
  2609. raise PackagingError(
  2610. f"archive extraction inventory mismatch: {archive_label} "
  2611. f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
  2612. )
  2613. expanded_candidates, expanded_excluded, _ = scan_analysis_root(
  2614. extract_root,
  2615. extra_exclusions=extra_exclusions,
  2616. )
  2617. handoff.audit_candidates(expanded_candidates)
  2618. expanded_prefix = f"{archive_label}.expanded"
  2619. expanded_items = [
  2620. PackageItem(
  2621. candidate=_rebase_candidate(candidate, expanded_prefix),
  2622. category=item.category,
  2623. source_id=item.source_id,
  2624. original_path=f"{item.original_path}!/{candidate.relative}",
  2625. scan_archive=True,
  2626. )
  2627. for candidate in expanded_candidates
  2628. ]
  2629. rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
  2630. sensitive_rules = {
  2631. "credential_or_license_file",
  2632. "credential_configuration_file",
  2633. "private_key_file",
  2634. "secret_environment_file",
  2635. "cloud_credential_file",
  2636. "container_registry_credential_file",
  2637. }
  2638. contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
  2639. return expanded_items, rebased_excluded, contains_sensitive
  2640. def prepare_unsupported_archives(
  2641. items: tuple[PackageItem, ...],
  2642. *,
  2643. temp_root: Path,
  2644. seven_zip: Path | None,
  2645. extra_exclusions: tuple[dict[str, str], ...],
  2646. ) -> ArchivePreparation:
  2647. prepared: list[PackageItem] = []
  2648. excluded: list[dict[str, str]] = []
  2649. warnings: list[dict[str, str]] = []
  2650. temp_root.mkdir(parents=True, exist_ok=True)
  2651. for item in items:
  2652. archive_kind = handoff.archive_kind(item.candidate.relative)
  2653. if archive_kind is None:
  2654. prepared.append(item)
  2655. continue
  2656. if archive_kind == "zip":
  2657. expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_zip_archive(
  2658. item,
  2659. temp_root=temp_root,
  2660. extra_exclusions=extra_exclusions,
  2661. )
  2662. elif seven_zip is None:
  2663. if _is_reference_item(item):
  2664. warnings.append(
  2665. {
  2666. "code": "unsupported_archive_without_7zip",
  2667. "source_id": item.source_id,
  2668. "path": item.candidate.relative,
  2669. "message": "7-Zip is unavailable; unsupported archive kept unexpanded",
  2670. }
  2671. )
  2672. prepared.append(item._replace(scan_archive=False))
  2673. continue
  2674. if item.candidate.absolute.is_file():
  2675. raise PackagingError(
  2676. "7-Zip is required to inspect unsupported source archives"
  2677. )
  2678. prepared.append(item._replace(scan_archive=False))
  2679. continue
  2680. else:
  2681. expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_unsupported_archive(
  2682. item,
  2683. temp_root=temp_root,
  2684. seven_zip=seven_zip,
  2685. extra_exclusions=extra_exclusions,
  2686. )
  2687. has_filtered_members = bool(expanded_excluded)
  2688. if has_filtered_members:
  2689. prepared.extend(expanded_items)
  2690. excluded.extend(expanded_excluded)
  2691. if contains_sensitive:
  2692. excluded.append(
  2693. {
  2694. "path": item.candidate.relative,
  2695. "rule": "unsupported_archive_contains_sensitive_content",
  2696. }
  2697. )
  2698. elif has_filtered_members:
  2699. excluded.append(
  2700. {
  2701. "path": item.candidate.relative,
  2702. "rule": "archive_contains_excluded_members",
  2703. }
  2704. )
  2705. else:
  2706. prepared.append(item._replace(scan_archive=archive_kind != "unsupported"))
  2707. prepared.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
  2708. excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
  2709. return ArchivePreparation(
  2710. items=tuple(prepared),
  2711. excluded=tuple(excluded),
  2712. warnings=tuple(warnings),
  2713. )
  2714. def _utc_now() -> str:
  2715. return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
  2716. def _validate_package_name(package_name: str) -> None:
  2717. try:
  2718. collision_key = handoff.windows_collision_key(package_name)
  2719. except PackagingError as exc:
  2720. raise PackagingError("package name is not a portable Windows file name") from exc
  2721. if (
  2722. not handoff.SAFE_PACKAGE_NAME.fullmatch(package_name)
  2723. or package_name in {".", ".."}
  2724. or not collision_key
  2725. ):
  2726. raise PackagingError("package name is not a portable Windows file name")
  2727. def _item_sort_key(item: PackageItem) -> tuple[int, str, str]:
  2728. return (
  2729. CATEGORY_ORDER.get(item.category, len(CATEGORY_ORDER)),
  2730. item.category.casefold(),
  2731. handoff.windows_collision_key(item.candidate.relative),
  2732. )
  2733. def _path_basename(relative: str) -> str:
  2734. return relative.casefold().rsplit("/", 1)[-1]
  2735. def _is_board_viewer_generated_path(relative: str) -> bool:
  2736. lower = relative.casefold()
  2737. return (
  2738. "board-viewer-generated" in lower
  2739. or handoff.is_under(lower, "evidence/board-viewer")
  2740. or "/tools/board-viewer/generated/" in f"/{lower}/"
  2741. or lower.startswith("tools/board-viewer/generated/")
  2742. )
  2743. def _is_reference_original_path(relative: str) -> bool:
  2744. lower = f"/{relative.casefold()}/"
  2745. return "/reference/original/" in lower or lower.startswith("/reference/original/")
  2746. def _dedup_canonical_path(paths: list[str]) -> str:
  2747. # Prefer compact evidence allowlist canonical paths first (P4).
  2748. try:
  2749. preferred = evidence_canon.prefer_canonical_path(paths)
  2750. if evidence_canon.is_compact_allowlisted(preferred):
  2751. return preferred
  2752. except ValueError:
  2753. pass
  2754. def rank(path: str) -> tuple[int, int, str]:
  2755. name = _path_basename(path)
  2756. in_reference = _is_reference_original_path(path)
  2757. in_generated = _is_board_viewer_generated_path(path)
  2758. if name in BOARD_VIEWER_GENERATED_ASSETS or name in DERIVED_BOARD_VIEWER_ASSETS:
  2759. return (0 if in_generated else 1, 0 if in_reference else 1, path.casefold())
  2760. if name.endswith((".brd", ".pdf", ".dsn", ".sch")):
  2761. return (0 if in_reference else 1, 0 if in_generated else 1, path.casefold())
  2762. return (0 if in_reference else 1, 0 if in_generated else 1, path.casefold())
  2763. return sorted(paths, key=rank)[0]
  2764. def _is_software_source_package_path(relative: str) -> bool:
  2765. """Tracked software under source/ must keep its canonical path (no content-dedup drop)."""
  2766. lower = relative.casefold()
  2767. if not lower.startswith("source/"):
  2768. return False
  2769. # Derived board-viewer / heavy design originals should not live under source/
  2770. # in review-compact; if they do, still protect software extensions.
  2771. name = _path_basename(relative)
  2772. if name in DERIVED_BOARD_VIEWER_ASSETS or name.endswith((".brd", ".pdf", ".dsn")):
  2773. return False
  2774. return True
  2775. def _should_content_dedup(size: int, relative: str) -> bool:
  2776. # Never content-dedup tracked software under source/. A generated SBY/workdir
  2777. # copy with identical bytes must not replace the authoritative source path.
  2778. lower = relative.casefold()
  2779. if _is_software_source_package_path(relative):
  2780. return False
  2781. # Finalize layout requires both canonical and legacy git SHA maps as physical members.
  2782. base = _path_basename(relative)
  2783. if base in {"source-file-sha256.json", "file-sha256.json"} and "/meta/git/" in f"/{lower}":
  2784. return False
  2785. name = base
  2786. if name in DERIVED_BOARD_VIEWER_ASSETS or name.endswith((".brd", ".pdf")):
  2787. return True
  2788. if evidence_canon.is_compact_allowlisted(relative):
  2789. return True
  2790. return size >= CONTENT_DEDUP_MIN_BYTES
  2791. def apply_content_dedup(
  2792. items: tuple[PackageItem, ...],
  2793. inventory: list[dict[str, object]],
  2794. ) -> tuple[tuple[PackageItem, ...], list[dict[str, object]], list[dict[str, str]]]:
  2795. """Keep one physical copy per identical content hash; record logical aliases.
  2796. Content dedup is only for evidence aliases / board-viewer / heavy originals /
  2797. large non-source twins. Authoritative ``source/`` software is never grouped
  2798. (see ``_should_content_dedup``), so generated workdir copies cannot replace it.
  2799. """
  2800. by_path = {str(row["path"]): row for row in inventory}
  2801. groups: dict[str, list[PackageItem]] = {}
  2802. for item in items:
  2803. row = by_path[item.candidate.relative]
  2804. sha = str(row["sha256"])
  2805. size = int(row["size"])
  2806. if not _should_content_dedup(size, item.candidate.relative):
  2807. continue
  2808. groups.setdefault(sha, []).append(item)
  2809. drop_paths: set[str] = set()
  2810. dedup_records: list[dict[str, object]] = []
  2811. excluded: list[dict[str, str]] = []
  2812. for sha, group in sorted(groups.items(), key=lambda pair: pair[0]):
  2813. if len(group) < 2:
  2814. continue
  2815. paths = [item.candidate.relative for item in group]
  2816. canonical = _dedup_canonical_path(paths)
  2817. aliases = sorted(path for path in paths if path != canonical)
  2818. # Absolute guard: never drop software source even if mis-grouped.
  2819. aliases = [path for path in aliases if not _is_software_source_package_path(path)]
  2820. if not aliases:
  2821. continue
  2822. if _is_software_source_package_path(canonical):
  2823. # Prefer keeping software source as physical; aliases are non-source.
  2824. pass
  2825. size = int(by_path[canonical]["size"])
  2826. dedup_records.append(
  2827. {
  2828. "sha256": sha,
  2829. "size": size,
  2830. "physical_path": canonical,
  2831. "logical_paths": aliases,
  2832. "reason": "identical_content_single_physical_copy",
  2833. }
  2834. )
  2835. for alias in aliases:
  2836. drop_paths.add(alias)
  2837. excluded.append(
  2838. {
  2839. "path": alias,
  2840. "rule": "duplicate_content_logical_alias",
  2841. }
  2842. )
  2843. physical_items = tuple(
  2844. item for item in items if item.candidate.relative not in drop_paths
  2845. )
  2846. dedup_records.sort(key=lambda row: str(row["physical_path"]).casefold())
  2847. excluded.sort(key=lambda row: handoff.windows_collision_key(row["path"]))
  2848. return physical_items, dedup_records, excluded
  2849. def classify_derived_evidence(items: tuple[PackageItem, ...]) -> list[dict[str, object]]:
  2850. derived: list[dict[str, object]] = []
  2851. for item in items:
  2852. name = _path_basename(item.candidate.relative)
  2853. if name not in DERIVED_BOARD_VIEWER_ASSETS:
  2854. continue
  2855. if not _is_board_viewer_generated_path(item.candidate.relative):
  2856. continue
  2857. role = "derived_from_brd_visual" if name in BOARD_VIEWER_GENERATED_ASSETS else "derived_from_brd_parsed"
  2858. derived.append(
  2859. {
  2860. "path": item.candidate.relative,
  2861. "asset": name,
  2862. "role": role,
  2863. "authority": "analysis_evidence_not_source_closure",
  2864. "note": "Derived from the original Allegro BRD for remote analysis; not RTL/TD source closure.",
  2865. }
  2866. )
  2867. derived.sort(key=lambda row: str(row["path"]).casefold())
  2868. return derived
  2869. def replay_analysis_package(package_dir: Path, *, extract_root: Path) -> dict[str, object]:
  2870. """Extract a published package and verify SHA256SUMS plus inventory hashes.
  2871. Returns package-content verification plus the four-state replay skeleton:
  2872. ``package_content_replay``, ``detached_software_replay`` (not_run here),
  2873. ``reference_regeneration_replay=not_packaged_by_policy``,
  2874. ``hardware_validation=not_run``. Full detached software orchestration lives in
  2875. ``tools/replay_review_compact.py``.
  2876. """
  2877. package_dir = package_dir.expanduser().resolve(strict=True)
  2878. extract_root = extract_root.expanduser().resolve(strict=False)
  2879. if extract_root.exists():
  2880. raise PackagingError(f"replay extract root already exists: {extract_root}")
  2881. index_path = package_dir / "HANDOFF-INDEX.json"
  2882. sums_path = package_dir / "SHA256SUMS.txt"
  2883. exclusions_path = package_dir / "EXCLUSIONS.txt"
  2884. if not index_path.is_file() or not sums_path.is_file():
  2885. raise PackagingError("package directory is missing HANDOFF-INDEX.json or SHA256SUMS.txt")
  2886. index = json.loads(index_path.read_text(encoding="utf-8"))
  2887. extract_root.mkdir(parents=True, exist_ok=False)
  2888. zip_extract_root = extract_root / "from-zip"
  2889. tar_extract_root = extract_root / "from-tar-zst"
  2890. zip_extract_root.mkdir(parents=True, exist_ok=True)
  2891. verified_volumes: list[dict[str, object]] = []
  2892. verified_sidecars: list[dict[str, object]] = []
  2893. tar_zst_name: str | None = None
  2894. for line in sums_path.read_text(encoding="ascii").splitlines():
  2895. line = line.strip()
  2896. if not line or line.startswith("#"):
  2897. continue
  2898. digest, _, name = line.partition(" ")
  2899. if not digest or not name:
  2900. raise PackagingError(f"invalid SHA256SUMS line: {line}")
  2901. member_path = package_dir / name
  2902. actual = handoff.sha256_file(member_path)
  2903. if actual != digest:
  2904. raise PackagingError(f"SHA256SUMS mismatch for {name}")
  2905. lower = name.casefold()
  2906. if lower.endswith(".zip"):
  2907. with zipfile.ZipFile(member_path, "r", allowZip64=True) as archive:
  2908. archive.extractall(zip_extract_root)
  2909. verified_volumes.append({"file": name, "sha256": actual})
  2910. elif lower.endswith(".tar.zst"):
  2911. tar_zst_name = name
  2912. tar_extract_root.mkdir(parents=True, exist_ok=True)
  2913. completed = subprocess.run(
  2914. ["tar", "--zstd", "-xf", str(member_path), "-C", str(tar_extract_root)],
  2915. stdout=subprocess.PIPE,
  2916. stderr=subprocess.PIPE,
  2917. check=False,
  2918. )
  2919. if completed.returncode != 0:
  2920. raise PackagingError(
  2921. f"unable to extract tar.zst during replay: {name}: "
  2922. f"{completed.stderr.decode('utf-8', errors='replace').strip()}"
  2923. )
  2924. verified_sidecars.append({"file": name, "sha256": actual, "kind": "tar_zst"})
  2925. else:
  2926. verified_sidecars.append({"file": name, "sha256": actual, "kind": "sidecar"})
  2927. checked_files = 0
  2928. for item in index.get("files", []):
  2929. relative = str(item["path"])
  2930. target = zip_extract_root / "CPLD" / Path(*relative.split("/"))
  2931. if not target.is_file():
  2932. raise PackagingError(f"replay missing extracted file: {relative}")
  2933. digest = handoff.sha256_file(target)
  2934. if digest != item["sha256"] or target.stat().st_size != int(item["size"]):
  2935. raise PackagingError(f"replay hash mismatch for {relative}")
  2936. if tar_zst_name is not None:
  2937. # tar.zst is created from ZIP extract roots, so the same CPLD tree must round-trip.
  2938. tar_target = tar_extract_root / "CPLD" / Path(*relative.split("/"))
  2939. if not tar_target.is_file():
  2940. raise PackagingError(f"tar.zst replay missing extracted file: {relative}")
  2941. if handoff.sha256_file(tar_target) != digest:
  2942. raise PackagingError(f"tar.zst replay hash mismatch for {relative}")
  2943. checked_files += 1
  2944. for record in index.get("content_dedup", []):
  2945. physical = zip_extract_root / "CPLD" / Path(*str(record["physical_path"]).split("/"))
  2946. if not physical.is_file():
  2947. raise PackagingError(f"replay missing dedup physical file: {record['physical_path']}")
  2948. for alias in record.get("logical_paths", []):
  2949. alias_path = zip_extract_root / "CPLD" / Path(*str(alias).split("/"))
  2950. if alias_path.exists():
  2951. raise PackagingError(f"replay found duplicated physical alias path: {alias}")
  2952. cpld_root = zip_extract_root / "CPLD"
  2953. return {
  2954. "status": "pass",
  2955. "mode": "package_replay",
  2956. "package_dir": str(package_dir),
  2957. "extract_root": str(extract_root),
  2958. "cpld_root": str(cpld_root) if cpld_root.is_dir() else None,
  2959. "volumes": verified_volumes,
  2960. "sidecars": verified_sidecars,
  2961. "exclusions_present": exclusions_path.is_file(),
  2962. "tar_zst": tar_zst_name,
  2963. "checked_files": checked_files,
  2964. "content_dedup_groups": len(index.get("content_dedup", [])),
  2965. "derived_evidence_count": len(index.get("derived_evidence", [])),
  2966. # Four-state skeleton (content only; software lane filled by replay_review_compact).
  2967. "package_content_replay": "pass",
  2968. "detached_software_replay": "not_run",
  2969. "reference_regeneration_replay": "not_packaged_by_policy",
  2970. "hardware_validation": "not_run",
  2971. }
  2972. def _audit_one_item(item: PackageItem) -> dict[str, object]:
  2973. if item.scan_archive:
  2974. file_inventory = handoff.stream_candidate(item.candidate)
  2975. else:
  2976. file_inventory = handoff.hash_candidate(item.candidate)
  2977. return {
  2978. **file_inventory,
  2979. "archive_path": f"CPLD/{item.candidate.relative}",
  2980. "category": item.category,
  2981. "source_id": item.source_id,
  2982. "original_path": item.original_path,
  2983. }
  2984. def _audit_package_items(items: tuple[PackageItem, ...]) -> list[dict[str, object]]:
  2985. sorted_items = sorted(items, key=_item_sort_key)
  2986. collision_paths: dict[str, str] = {}
  2987. for item in sorted_items:
  2988. key = handoff.windows_collision_key(item.candidate.relative)
  2989. previous = collision_paths.get(key)
  2990. if previous is not None:
  2991. raise PackagingError(
  2992. f"analysis inputs contain a Windows path collision: {previous} and {item.candidate.relative}"
  2993. )
  2994. collision_paths[key] = item.candidate.relative
  2995. max_workers = os.cpu_count() or 1
  2996. with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
  2997. return list(executor.map(_audit_one_item, sorted_items))
  2998. def _write_unscanned_candidate(
  2999. archive: zipfile.ZipFile,
  3000. item: PackageItem,
  3001. ) -> dict[str, object]:
  3002. candidate = item.candidate
  3003. digest = hashlib.sha256()
  3004. total = 0
  3005. secret_tail = b""
  3006. entry_name = f"CPLD/{candidate.relative}"
  3007. try:
  3008. with archive.open(handoff.zip_info(entry_name, candidate.mode), "w", force_zip64=True) as target:
  3009. with handoff.open_candidate(candidate) as source:
  3010. for chunk in iter(lambda: source.read(1024 * 1024), b""):
  3011. secret_tail = handoff.scan_secret_markers(
  3012. chunk,
  3013. secret_tail,
  3014. candidate.relative,
  3015. )
  3016. target.write(chunk)
  3017. digest.update(chunk)
  3018. total += len(chunk)
  3019. except OSError as exc:
  3020. raise PackagingError(f"unable to package {candidate.relative}: {exc}") from exc
  3021. if total != candidate.size:
  3022. raise PackagingError(f"source size changed during packaging: {candidate.relative}")
  3023. return {"path": candidate.relative, "size": total, "sha256": digest.hexdigest()}
  3024. def _write_package_item(
  3025. archive: zipfile.ZipFile,
  3026. item: PackageItem,
  3027. ) -> dict[str, object]:
  3028. if item.scan_archive:
  3029. return handoff.write_candidate(archive, item.candidate)
  3030. return _write_unscanned_candidate(archive, item)
  3031. def _stage_package_item(
  3032. staging_root: Path,
  3033. item: PackageItem,
  3034. staging_name: str,
  3035. ) -> dict[str, object]:
  3036. target = staging_root / "CPLD" / staging_name
  3037. target.parent.mkdir(parents=True, exist_ok=True)
  3038. if item.scan_archive:
  3039. try:
  3040. with target.open("wb") as destination:
  3041. return handoff.stream_candidate(item.candidate, target=destination)
  3042. except OSError as exc:
  3043. raise PackagingError(f"unable to stage {item.candidate.relative}: {exc}") from exc
  3044. digest = hashlib.sha256()
  3045. total = 0
  3046. secret_tail = b""
  3047. try:
  3048. with handoff.open_candidate(item.candidate) as source, target.open("wb") as destination:
  3049. for chunk in iter(lambda: source.read(1024 * 1024), b""):
  3050. secret_tail = handoff.scan_secret_markers(
  3051. chunk,
  3052. secret_tail,
  3053. item.candidate.relative,
  3054. )
  3055. destination.write(chunk)
  3056. digest.update(chunk)
  3057. total += len(chunk)
  3058. except OSError as exc:
  3059. raise PackagingError(f"unable to stage {item.candidate.relative}: {exc}") from exc
  3060. if total != item.candidate.size:
  3061. raise PackagingError(f"source size changed during staging: {item.candidate.relative}")
  3062. return {"path": item.candidate.relative, "size": total, "sha256": digest.hexdigest()}
  3063. def _volume_manifest(
  3064. *,
  3065. run_id: str,
  3066. package_name: str,
  3067. number: int,
  3068. count: int,
  3069. items: list[PackageItem],
  3070. inventory_by_path: dict[str, dict[str, object]],
  3071. ) -> dict[str, object]:
  3072. categories = sorted({item.category for item in items})
  3073. entries = [inventory_by_path[item.candidate.relative] for item in items]
  3074. return {
  3075. "schema": "cpld-agent-analysis-volume-v1",
  3076. "run_id": run_id,
  3077. "package_name": package_name,
  3078. "volume_number": number,
  3079. "volume_count": count,
  3080. "categories": categories,
  3081. "file_count": len(entries),
  3082. "uncompressed_bytes": sum(int(entry["size"]) for entry in entries),
  3083. "files": entries,
  3084. }
  3085. def _write_volume(
  3086. path: Path,
  3087. *,
  3088. run_id: str,
  3089. package_name: str,
  3090. number: int,
  3091. count: int,
  3092. items: list[PackageItem],
  3093. inventory_by_path: dict[str, dict[str, object]],
  3094. ) -> dict[str, object]:
  3095. manifest = _volume_manifest(
  3096. run_id=run_id,
  3097. package_name=package_name,
  3098. number=number,
  3099. count=count,
  3100. items=items,
  3101. inventory_by_path=inventory_by_path,
  3102. )
  3103. manifest_name = "CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json"
  3104. manifest_payload = handoff.json_bytes(manifest)
  3105. written_inventory: list[dict[str, object]] = []
  3106. try:
  3107. with zipfile.ZipFile(
  3108. path,
  3109. "w",
  3110. compression=zipfile.ZIP_DEFLATED,
  3111. compresslevel=9,
  3112. allowZip64=True,
  3113. ) as archive:
  3114. for item in sorted(items, key=_item_sort_key):
  3115. expected = inventory_by_path[item.candidate.relative]
  3116. if item.scan_archive:
  3117. actual = handoff.write_candidate(archive, item.candidate)
  3118. else:
  3119. actual = _write_unscanned_candidate(archive, item)
  3120. if (
  3121. actual["size"] != expected["size"]
  3122. or actual["sha256"] != expected["sha256"]
  3123. ):
  3124. raise PackagingError(
  3125. f"source changed while writing ZIP: {item.candidate.relative}"
  3126. )
  3127. written_inventory.append(actual)
  3128. with archive.open(
  3129. handoff.zip_info(manifest_name), "w", force_zip64=True
  3130. ) as target:
  3131. target.write(manifest_payload)
  3132. except (OSError, zipfile.BadZipFile) as exc:
  3133. raise PackagingError(f"unable to create ZIP volume: {exc}") from exc
  3134. expected_names = {f"CPLD/{item.candidate.relative}" for item in items}
  3135. expected_names.add(manifest_name)
  3136. handoff.verify_archive(
  3137. path,
  3138. expected_names=expected_names,
  3139. inventory=written_inventory,
  3140. expected_payloads={manifest_name: manifest_payload},
  3141. )
  3142. return {
  3143. "file": path.name,
  3144. "volume_number": number,
  3145. "volume_count": count,
  3146. "categories": manifest["categories"],
  3147. "file_count": len(items),
  3148. "uncompressed_bytes": manifest["uncompressed_bytes"],
  3149. "compressed_bytes": path.stat().st_size,
  3150. "sha256": handoff.sha256_file(path),
  3151. }
  3152. def _estimated_item_bytes(item: PackageItem) -> int:
  3153. return item.candidate.size + 512 + (len(item.candidate.relative.encode("utf-8")) * 2)
  3154. def _partition_items(
  3155. items: tuple[PackageItem, ...],
  3156. *,
  3157. target_zip_bytes: int,
  3158. ) -> list[list[PackageItem]]:
  3159. base_overhead = min(64_000, max(1_024, target_zip_bytes // 20))
  3160. groups: list[list[PackageItem]] = []
  3161. current: list[PackageItem] = []
  3162. current_category: str | None = None
  3163. estimated_bytes = base_overhead
  3164. for item in sorted(items, key=_item_sort_key):
  3165. item_estimate = _estimated_item_bytes(item)
  3166. if current and (
  3167. item.category != current_category
  3168. or estimated_bytes + item_estimate > target_zip_bytes
  3169. ):
  3170. groups.append(current)
  3171. current = []
  3172. estimated_bytes = base_overhead
  3173. if not current:
  3174. current_category = item.category
  3175. current.append(item)
  3176. estimated_bytes += item_estimate
  3177. if current:
  3178. groups.append(current)
  3179. return groups
  3180. def _split_oversized_groups(
  3181. staging: Path,
  3182. *,
  3183. run_id: str,
  3184. package_name: str,
  3185. groups: list[list[PackageItem]],
  3186. inventory_by_path: dict[str, dict[str, object]],
  3187. target_zip_bytes: int,
  3188. max_zip_bytes: int,
  3189. ) -> list[list[PackageItem]]:
  3190. pending = list(groups)
  3191. accepted: list[list[PackageItem]] = []
  3192. probe_number = 0
  3193. while pending:
  3194. group = pending.pop(0)
  3195. probe_number += 1
  3196. probe = staging / f".volume-probe-{probe_number:04d}.zip"
  3197. try:
  3198. _write_volume(
  3199. probe,
  3200. run_id=run_id,
  3201. package_name=package_name,
  3202. number=1,
  3203. count=1,
  3204. items=group,
  3205. inventory_by_path=inventory_by_path,
  3206. )
  3207. size = probe.stat().st_size
  3208. finally:
  3209. probe.unlink(missing_ok=True)
  3210. if size < max_zip_bytes and (size <= target_zip_bytes or len(group) == 1):
  3211. accepted.append(group)
  3212. continue
  3213. if len(group) == 1:
  3214. raise PackagingError(
  3215. f"single analysis file requires chunking before ZIP creation: {group[0].candidate.relative}"
  3216. )
  3217. middle = len(group) // 2
  3218. pending[0:0] = [group[:middle], group[middle:]]
  3219. return accepted
  3220. def _prepare_large_file_chunks(
  3221. staging: Path,
  3222. *,
  3223. run_id: str,
  3224. package_name: str,
  3225. items: tuple[PackageItem, ...],
  3226. inventory_by_path: dict[str, dict[str, object]],
  3227. target_zip_bytes: int,
  3228. max_zip_bytes: int,
  3229. ) -> tuple[tuple[PackageItem, ...], list[dict[str, object]], Path | None]:
  3230. packaged_items: list[PackageItem] = []
  3231. large_files: list[dict[str, object]] = []
  3232. chunk_root: Path | None = None
  3233. probe_number = 0
  3234. chunk_payload_bytes = max(1, (target_zip_bytes * 3) // 4)
  3235. for item in sorted(items, key=_item_sort_key):
  3236. must_probe = _estimated_item_bytes(item) > target_zip_bytes
  3237. if must_probe:
  3238. probe_number += 1
  3239. probe = staging / f".large-file-probe-{probe_number:04d}.zip"
  3240. try:
  3241. _write_volume(
  3242. probe,
  3243. run_id=run_id,
  3244. package_name=package_name,
  3245. number=1,
  3246. count=1,
  3247. items=[item],
  3248. inventory_by_path=inventory_by_path,
  3249. )
  3250. probe_size = probe.stat().st_size
  3251. finally:
  3252. probe.unlink(missing_ok=True)
  3253. if probe_size <= target_zip_bytes and probe_size < max_zip_bytes:
  3254. packaged_items.append(item)
  3255. continue
  3256. else:
  3257. packaged_items.append(item)
  3258. continue
  3259. if chunk_root is None:
  3260. chunk_root = staging / ".large-file-chunks"
  3261. chunk_root.mkdir()
  3262. original = inventory_by_path[item.candidate.relative]
  3263. file_id = hashlib.sha256(item.candidate.relative.encode("utf-8")).hexdigest()[:16]
  3264. file_chunk_root = chunk_root / file_id
  3265. file_chunk_root.mkdir()
  3266. file_name = Path(item.candidate.relative).name
  3267. chunks: list[dict[str, object]] = []
  3268. original_digest = hashlib.sha256()
  3269. original_bytes = 0
  3270. secret_tail = b""
  3271. with handoff.open_candidate(item.candidate) as source:
  3272. number = 0
  3273. while True:
  3274. payload = source.read(chunk_payload_bytes)
  3275. if not payload:
  3276. break
  3277. number += 1
  3278. secret_tail = handoff.scan_secret_markers(
  3279. payload,
  3280. secret_tail,
  3281. item.candidate.relative,
  3282. )
  3283. original_digest.update(payload)
  3284. original_bytes += len(payload)
  3285. chunk_name = f"{file_name}.part{number:04d}"
  3286. chunk_path = file_chunk_root / chunk_name
  3287. with chunk_path.open("xb") as handle:
  3288. handle.write(payload)
  3289. chunk_relative = f"HANDOFF-LARGE-FILES/{file_id}/{chunk_name}"
  3290. chunk_item = make_package_item(
  3291. chunk_path,
  3292. relative=chunk_relative,
  3293. category=item.category,
  3294. source_id=item.source_id,
  3295. scan_archive=False,
  3296. )
  3297. packaged_items.append(chunk_item)
  3298. chunks.append(
  3299. {
  3300. "number": number,
  3301. "path": chunk_relative,
  3302. "archive_path": f"CPLD/{chunk_relative}",
  3303. "size": len(payload),
  3304. "sha256": hashlib.sha256(payload).hexdigest(),
  3305. }
  3306. )
  3307. if original_bytes != original["size"] or original_digest.hexdigest() != original["sha256"]:
  3308. raise PackagingError(f"source changed while splitting large file: {item.candidate.relative}")
  3309. if len(chunks) < 2:
  3310. raise PackagingError(f"large file split did not produce multiple chunks: {item.candidate.relative}")
  3311. large_files.append(
  3312. {
  3313. "path": item.candidate.relative,
  3314. "category": item.category,
  3315. "source_id": item.source_id,
  3316. "original_path": item.original_path,
  3317. "size": original["size"],
  3318. "sha256": original["sha256"],
  3319. "chunks": chunks,
  3320. }
  3321. )
  3322. return tuple(packaged_items), large_files, chunk_root
  3323. def _assert_items_unchanged(
  3324. items: tuple[PackageItem, ...],
  3325. inventory_by_path: dict[str, dict[str, object]],
  3326. ) -> None:
  3327. for item in items:
  3328. current = handoff.hash_candidate(item.candidate)
  3329. expected = inventory_by_path[item.candidate.relative]
  3330. if current["size"] != expected["size"] or current["sha256"] != expected["sha256"]:
  3331. raise PackagingError(f"source changed during analysis packaging: {item.candidate.relative}")
  3332. def _assert_source_trees_unchanged(collection: AnalysisCollection, *, profile: str = "full") -> None:
  3333. for snapshot in collection.source_snapshots:
  3334. # Prefer the profile captured at collection time so review-compact
  3335. # snapshots are not re-scanned under the create_analysis_package default.
  3336. check_profile = snapshot.profile or profile
  3337. current = _source_snapshot(
  3338. snapshot.root,
  3339. source_id=snapshot.source_id,
  3340. extra_exclusions=snapshot.extra_exclusions,
  3341. profile=check_profile,
  3342. )
  3343. if (
  3344. current.candidates != snapshot.candidates
  3345. or current.excluded != snapshot.excluded
  3346. ):
  3347. raise PackagingError("source tree changed during analysis packaging: retry from a stable workspace snapshot")
  3348. def _start_here_text(package_name: str, volume_count: int, *, profile: str = "full") -> str:
  3349. base = (
  3350. f"# {package_name} 分析交付包\n\n"
  3351. f"本目录包含 {volume_count} 个互相独立的普通 ZIP,以及可选的 `.tar.zst` 同源归档。"
  3352. "请先核对 `SHA256SUMS.txt`,再把所有 ZIP 解压到同一个目录;"
  3353. "也可用 `tar --zstd -xf <package>.tar.zst` 还原。\n\n"
  3354. "`HANDOFF-INDEX.json` 记录每个原始文件的来源、目标卷、大小和 SHA-256,"
  3355. "`EXCLUSIONS.txt` 列出排除路径与规则,"
  3356. "以及 `excluded`(排除原因)、`derived_evidence`(由原始 BRD 派生的 board-viewer JSON/SVG,"
  3357. "不是 RTL/TD source closure)和 `content_dedup`(相同大文件只保留一份物理副本时的逻辑归属)。\n"
  3358. )
  3359. if handoff.uses_unified_layout(profile):
  3360. return base + (
  3361. "本包为统一布局:`source/` + `evidence/` + `meta/`。\n"
  3362. "`PACKAGE-PURPOSE.txt` 说明上传意图;`size-budget.json` 列出 ≥256KiB 或 >1% 体积的成员。\n"
  3363. "默认 **不含** 完整 Git bundle;`meta/git/` 提供 commit/status/log-20/tree/逐文件 SHA-256 "
  3364. "与 TD source-closure 绑定钩子。\n"
  3365. "成员计数:`member_count.indexed_files` 对应 ZIP 内业务文件;"
  3366. "`self_reference_control_files` 是包目录控制文件(亦列入 SHA256SUMS),"
  3367. "不要把控制文件与 ZIP payload 成员重复加总。\n"
  3368. )
  3369. return base + (
  3370. "完整 full 包必须包含 `git-history/*.bundle`,以便在干净提取后用 commit-to-commit "
  3371. "恢复 source closure 比对。\n"
  3372. )
  3373. def build_member_count_semantics(
  3374. *,
  3375. indexed_files: int,
  3376. zip_file_entries: int,
  3377. control_files: tuple[str, ...] = SELF_REFERENCE_CONTROL_FILES,
  3378. ) -> dict[str, object]:
  3379. return {
  3380. "indexed_files": indexed_files,
  3381. "zip_file_entries": zip_file_entries,
  3382. "self_reference_control_files": list(control_files),
  3383. "note": (
  3384. "indexed_files counts HANDOFF-INDEX files[] (ZIP payload business members). "
  3385. "zip_file_entries counts non-directory ZIP entries including VOLUME-MANIFEST. "
  3386. "self_reference_control_files live in the package directory and appear in "
  3387. "SHA256SUMS; do not add them again to indexed_files."
  3388. ),
  3389. }
  3390. def write_exclusions_text(excluded: list[dict[str, object]]) -> str:
  3391. """Render a portable EXCLUSIONS.txt for the package sidecar layout."""
  3392. lines = [
  3393. "# path<TAB>rule",
  3394. "# Inclusion-first package: only versioned recursive exclusions are listed.",
  3395. ]
  3396. for item in sorted(excluded, key=lambda row: handoff.windows_collision_key(str(row.get("path", "")))):
  3397. path = str(item.get("path", ""))
  3398. rule = str(item.get("rule", item.get("reason", "excluded")))
  3399. lines.append(f"{path}\t{rule}")
  3400. return "\n".join(lines) + "\n"
  3401. def create_tar_zst_archive(source_dir: Path, archive_path: Path) -> str:
  3402. """Create a deterministic-enough tar.zst of source_dir contents; return SHA-256."""
  3403. source_dir = source_dir.resolve(strict=True)
  3404. archive_path = archive_path.resolve(strict=False)
  3405. if archive_path.exists():
  3406. archive_path.unlink()
  3407. zstd = shutil.which("zstd")
  3408. if zstd is None:
  3409. raise PackagingError("zstd is required to create .tar.zst package archives")
  3410. # Prefer GNU tar --zstd when available; fall back to compress-program.
  3411. command = [
  3412. "tar",
  3413. "--zstd",
  3414. "-cf",
  3415. str(archive_path),
  3416. "--sort=name",
  3417. "--mtime=UTC 1980-01-01",
  3418. "--owner=0",
  3419. "--group=0",
  3420. "--numeric-owner",
  3421. "-C",
  3422. str(source_dir),
  3423. ".",
  3424. ]
  3425. completed = subprocess.run(
  3426. command,
  3427. stdout=subprocess.PIPE,
  3428. stderr=subprocess.PIPE,
  3429. check=False,
  3430. )
  3431. if completed.returncode != 0:
  3432. # Older tar without --zstd / --sort: use compress-program path.
  3433. fallback = [
  3434. "tar",
  3435. "-cf",
  3436. str(archive_path),
  3437. "-I",
  3438. zstd,
  3439. "-C",
  3440. str(source_dir),
  3441. ".",
  3442. ]
  3443. completed = subprocess.run(
  3444. fallback,
  3445. stdout=subprocess.PIPE,
  3446. stderr=subprocess.PIPE,
  3447. check=False,
  3448. )
  3449. if completed.returncode != 0:
  3450. detail = completed.stderr.decode("utf-8", errors="replace").strip()
  3451. raise PackagingError(f"unable to create tar.zst archive: {detail or 'tar failed'}")
  3452. return handoff.sha256_file(archive_path)
  3453. def write_package_layout_sidecars(
  3454. staging: Path,
  3455. *,
  3456. index: dict[str, object],
  3457. excluded: list[dict[str, object]],
  3458. package_name: str,
  3459. include_tar_zst: bool = True,
  3460. profile: str = "full",
  3461. size_budget: dict[str, object] | None = None,
  3462. ) -> list[dict[str, object]]:
  3463. """Write index/checksums/exclusions and optional tar.zst; return checksum rows."""
  3464. staging.mkdir(parents=True, exist_ok=True)
  3465. (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
  3466. (staging / "EXCLUSIONS.txt").write_text(
  3467. write_exclusions_text(excluded),
  3468. encoding="utf-8",
  3469. newline="\n",
  3470. )
  3471. (staging / "PACKAGE-PURPOSE.txt").write_text(
  3472. handoff.package_purpose_text(profile, package_name=package_name),
  3473. encoding="utf-8",
  3474. newline="\n",
  3475. )
  3476. (staging / "START-HERE.zh-CN.md").write_text(
  3477. _start_here_text(package_name, len(index.get("volumes", [])), profile=profile),
  3478. encoding="utf-8",
  3479. newline="\n",
  3480. )
  3481. if size_budget is not None:
  3482. (staging / "size-budget.json").write_bytes(handoff.json_bytes(size_budget))
  3483. checksum_rows: list[dict[str, object]] = []
  3484. for info in index.get("volumes", []):
  3485. name = str(info["file"])
  3486. checksum_rows.append({"file": name, "sha256": str(info["sha256"])})
  3487. if include_tar_zst:
  3488. # Stage CPLD tree from ZIP volumes into a temporary extract for tar.zst.
  3489. extract_root = staging / ".tar-zst-staging"
  3490. if extract_root.exists():
  3491. shutil.rmtree(extract_root)
  3492. extract_root.mkdir(parents=True, exist_ok=True)
  3493. for info in index.get("volumes", []):
  3494. volume_path = staging / str(info["file"])
  3495. with zipfile.ZipFile(volume_path, "r", allowZip64=True) as archive:
  3496. archive.extractall(extract_root)
  3497. tar_name = f"{package_name}.tar.zst"
  3498. tar_path = staging / tar_name
  3499. tar_sha = create_tar_zst_archive(extract_root, tar_path)
  3500. shutil.rmtree(extract_root)
  3501. checksum_rows.append({"file": tar_name, "sha256": tar_sha})
  3502. index["formats"] = {
  3503. "zip_volumes": [str(info["file"]) for info in index.get("volumes", [])],
  3504. "tar_zst": tar_name,
  3505. "tar_zst_sha256": tar_sha,
  3506. }
  3507. (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
  3508. sidecar_names = [
  3509. "HANDOFF-INDEX.json",
  3510. "EXCLUSIONS.txt",
  3511. "PACKAGE-PURPOSE.txt",
  3512. "START-HERE.zh-CN.md",
  3513. ]
  3514. if size_budget is not None:
  3515. sidecar_names.append("size-budget.json")
  3516. for sidecar in sidecar_names:
  3517. checksum_rows.append(
  3518. {"file": sidecar, "sha256": handoff.sha256_file(staging / sidecar)}
  3519. )
  3520. checksum_lines = [f"{row['sha256']} {row['file']}" for row in checksum_rows]
  3521. (staging / "SHA256SUMS.txt").write_text(
  3522. "\n".join(checksum_lines) + "\n",
  3523. encoding="ascii",
  3524. newline="\n",
  3525. )
  3526. return checksum_rows
  3527. def _publish_directory_atomically(staging: Path, final: Path, *, force: bool) -> None:
  3528. backup: Path | None = None
  3529. backup_created = False
  3530. new_directory_published = False
  3531. if os.path.lexists(final):
  3532. if not force:
  3533. raise PackagingError(f"package output already exists: {final}")
  3534. file_stat = os.lstat(final)
  3535. if not stat.S_ISDIR(file_stat.st_mode) or handoff.stat_is_reparse_point(file_stat):
  3536. raise PackagingError(f"existing package output is not a regular directory: {final}")
  3537. backup = final.with_name(f".{final.name}.{uuid.uuid4().hex}.backup")
  3538. try:
  3539. if backup is not None:
  3540. os.replace(final, backup)
  3541. backup_created = True
  3542. os.replace(staging, final)
  3543. new_directory_published = True
  3544. except BaseException as exc:
  3545. if new_directory_published and os.path.lexists(final):
  3546. try:
  3547. shutil.rmtree(final)
  3548. except OSError:
  3549. pass
  3550. if backup_created and backup is not None and os.path.lexists(backup):
  3551. try:
  3552. os.replace(backup, final)
  3553. except OSError as rollback_exc:
  3554. raise PackagingError(
  3555. f"package publication failed and rollback was incomplete: {rollback_exc}"
  3556. ) from exc
  3557. if isinstance(exc, PackagingError):
  3558. raise
  3559. raise PackagingError(f"unable to publish package directory atomically: {exc}") from exc
  3560. if backup is not None:
  3561. shutil.rmtree(backup)
  3562. def create_analysis_package(
  3563. *,
  3564. collection: AnalysisCollection,
  3565. output_root: Path,
  3566. package_name: str,
  3567. max_zip_bytes: int,
  3568. target_zip_bytes: int,
  3569. force: bool,
  3570. profile: str = "full",
  3571. ) -> dict[str, object]:
  3572. _validate_package_name(package_name)
  3573. if max_zip_bytes <= 0 or not 0 < target_zip_bytes < max_zip_bytes:
  3574. raise PackagingError("ZIP size limits are invalid")
  3575. if not collection.items:
  3576. raise PackagingError("analysis package has no included files")
  3577. output_root = output_root.expanduser().resolve(strict=False)
  3578. output_root.mkdir(parents=True, exist_ok=True)
  3579. final_dir = output_root / package_name
  3580. if os.path.lexists(final_dir) and not force:
  3581. raise PackagingError(f"package output already exists: {final_dir}")
  3582. run_id = uuid.uuid4().hex
  3583. staging = Path(tempfile.mkdtemp(prefix=f".{package_name}.{run_id}.", dir=output_root))
  3584. try:
  3585. full_inventory = _audit_package_items(collection.items)
  3586. physical_items, content_dedup, dedup_excluded = apply_content_dedup(
  3587. collection.items,
  3588. full_inventory,
  3589. )
  3590. inventory = [
  3591. row
  3592. for row in full_inventory
  3593. if str(row["path"]) in {item.candidate.relative for item in physical_items}
  3594. ]
  3595. inventory_by_path = {str(item["path"]): item for item in inventory}
  3596. package_excluded = list(collection.excluded) + dedup_excluded
  3597. package_excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
  3598. derived_evidence = classify_derived_evidence(physical_items)
  3599. evidence_canon_fields = dict(collection.evidence_canon or {})
  3600. # Merge content_dedup logical aliases into evidence_canon.aliases for HANDOFF-INDEX.
  3601. evidence_aliases = list(evidence_canon_fields.get("aliases", [])) # type: ignore[arg-type]
  3602. for record in content_dedup:
  3603. evidence_aliases.append(
  3604. {
  3605. "key": None,
  3606. "sha256": record["sha256"],
  3607. "size": record["size"],
  3608. "physical_path": record["physical_path"],
  3609. "logical_paths": record["logical_paths"],
  3610. "reason": record["reason"],
  3611. }
  3612. )
  3613. if evidence_canon_fields:
  3614. evidence_canon_fields["aliases"] = evidence_aliases
  3615. package_items = physical_items
  3616. package_inventory = inventory
  3617. package_inventory_by_path = inventory_by_path
  3618. large_files: list[dict[str, object]] = []
  3619. chunk_root: Path | None = None
  3620. single_path = staging / f"{package_name}.zip"
  3621. single_info = _write_volume(
  3622. single_path,
  3623. run_id=run_id,
  3624. package_name=package_name,
  3625. number=1,
  3626. count=1,
  3627. items=list(sorted(physical_items, key=_item_sort_key)),
  3628. inventory_by_path=inventory_by_path,
  3629. )
  3630. if single_path.stat().st_size < max_zip_bytes:
  3631. volume_infos = [single_info]
  3632. groups = [list(sorted(physical_items, key=_item_sort_key))]
  3633. else:
  3634. single_path.unlink()
  3635. package_items, large_files, chunk_root = _prepare_large_file_chunks(
  3636. staging,
  3637. run_id=run_id,
  3638. package_name=package_name,
  3639. items=physical_items,
  3640. inventory_by_path=inventory_by_path,
  3641. target_zip_bytes=target_zip_bytes,
  3642. max_zip_bytes=max_zip_bytes,
  3643. )
  3644. package_inventory = _audit_package_items(package_items)
  3645. package_inventory_by_path = {
  3646. str(item["path"]): item for item in package_inventory
  3647. }
  3648. initial_groups = _partition_items(
  3649. package_items,
  3650. target_zip_bytes=target_zip_bytes,
  3651. )
  3652. groups = _split_oversized_groups(
  3653. staging,
  3654. run_id=run_id,
  3655. package_name=package_name,
  3656. groups=initial_groups,
  3657. inventory_by_path=package_inventory_by_path,
  3658. target_zip_bytes=target_zip_bytes,
  3659. max_zip_bytes=max_zip_bytes,
  3660. )
  3661. volume_infos = []
  3662. count = len(groups)
  3663. for number, group in enumerate(groups, start=1):
  3664. category = group[0].category if len({item.category for item in group}) == 1 else "mixed"
  3665. safe_category = re.sub(r"[^a-z0-9]+", "-", category.casefold()).strip("-") or "data"
  3666. volume_path = staging / f"{package_name}.part{number:03d}-{safe_category}.zip"
  3667. volume_info = _write_volume(
  3668. volume_path,
  3669. run_id=run_id,
  3670. package_name=package_name,
  3671. number=number,
  3672. count=count,
  3673. items=group,
  3674. inventory_by_path=package_inventory_by_path,
  3675. )
  3676. if volume_path.stat().st_size >= max_zip_bytes:
  3677. raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
  3678. volume_infos.append(volume_info)
  3679. volume_by_path: dict[str, str] = {}
  3680. for volume_info, group in zip(volume_infos, groups, strict=True):
  3681. for item in group:
  3682. volume_by_path[item.candidate.relative] = str(volume_info["file"])
  3683. large_paths = {str(item["path"]) for item in large_files}
  3684. indexed_files = [
  3685. {**item, "volume": volume_by_path[str(item["path"])]}
  3686. for item in inventory
  3687. if str(item["path"]) not in large_paths
  3688. ]
  3689. for large_file in large_files:
  3690. for chunk in large_file["chunks"]:
  3691. chunk["volume"] = volume_by_path[str(chunk["path"])]
  3692. zip_entry_count = 0
  3693. for info in volume_infos:
  3694. volume_path = staging / str(info["file"])
  3695. with zipfile.ZipFile(volume_path, "r", allowZip64=True) as archive:
  3696. zip_entry_count += sum(1 for name in archive.namelist() if not name.endswith("/"))
  3697. size_budget = handoff.build_size_budget(
  3698. inventory,
  3699. zip_total_bytes=sum(int(info["compressed_bytes"]) for info in volume_infos),
  3700. )
  3701. member_count = build_member_count_semantics(
  3702. indexed_files=len(indexed_files),
  3703. zip_file_entries=zip_entry_count,
  3704. )
  3705. index = {
  3706. "schema": "cpld-agent-analysis-index-v1",
  3707. "run_id": run_id,
  3708. "created_at_utc": _utc_now(),
  3709. "package_name": package_name,
  3710. "status": collection.status,
  3711. "profile": profile,
  3712. "delivery_policy": handoff.delivery_policy_for_profile(profile),
  3713. "max_zip_bytes": max_zip_bytes,
  3714. "target_zip_bytes": target_zip_bytes,
  3715. "sources": list(collection.sources),
  3716. "git": list(collection.git),
  3717. "warnings": list(collection.warnings),
  3718. "excluded": package_excluded,
  3719. "content_dedup": content_dedup,
  3720. "derived_evidence": derived_evidence,
  3721. "evidence_canon": evidence_canon_fields if evidence_canon_fields else None,
  3722. "evidence_aliases": evidence_aliases,
  3723. "member_count": member_count,
  3724. "size_budget": size_budget,
  3725. "volumes": volume_infos,
  3726. "files": indexed_files,
  3727. "large_files": large_files,
  3728. }
  3729. if large_files:
  3730. (staging / "reassemble_large_files.py").write_text(
  3731. REASSEMBLER_SCRIPT,
  3732. encoding="utf-8",
  3733. newline="\n",
  3734. )
  3735. for info in volume_infos:
  3736. volume_path = staging / str(info["file"])
  3737. if volume_path.stat().st_size >= max_zip_bytes:
  3738. raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
  3739. if handoff.sha256_file(volume_path) != info["sha256"]:
  3740. raise PackagingError(f"ZIP volume hash changed after verification: {volume_path.name}")
  3741. checksum_rows = write_package_layout_sidecars(
  3742. staging,
  3743. index=index,
  3744. excluded=package_excluded,
  3745. package_name=package_name,
  3746. include_tar_zst=True,
  3747. profile=profile,
  3748. size_budget=size_budget if handoff.uses_unified_layout(profile) else None,
  3749. )
  3750. full_inventory_by_path = {str(item["path"]): item for item in full_inventory}
  3751. _assert_items_unchanged(collection.items, full_inventory_by_path)
  3752. _assert_source_trees_unchanged(collection, profile=profile)
  3753. # Fail-closed for final-review: stage-aware ZIP selftest must pass in
  3754. # staging before any final-looking artifact is published atomically.
  3755. # Intermediate-review keeps structure checks but is not a final gate.
  3756. if profile == "review-compact":
  3757. from compact_package_selftest import ( # noqa: WPS433
  3758. PACKAGE_STAGE_FINAL,
  3759. run_compact_package_selftest,
  3760. )
  3761. staged_report = run_compact_package_selftest(
  3762. staging,
  3763. skip_software=True,
  3764. write_evidence=False,
  3765. package_stage=None,
  3766. )
  3767. if (
  3768. staged_report.get("package_stage") == PACKAGE_STAGE_FINAL
  3769. and staged_report.get("status") != "pass"
  3770. ):
  3771. raise PackagingError(
  3772. "review-compact final-review staging selftest failed before publish: "
  3773. + ", ".join(staged_report.get("failures") or ["unknown"])
  3774. )
  3775. if chunk_root is not None:
  3776. shutil.rmtree(chunk_root)
  3777. _publish_directory_atomically(staging, final_dir, force=force)
  3778. except BaseException:
  3779. if os.path.lexists(staging):
  3780. shutil.rmtree(staging, ignore_errors=True)
  3781. raise
  3782. formats = {}
  3783. index_path = final_dir / "HANDOFF-INDEX.json"
  3784. if index_path.is_file():
  3785. formats = json.loads(index_path.read_text(encoding="utf-8")).get("formats", {})
  3786. return {
  3787. "status": collection.status,
  3788. "mode": "package",
  3789. "profile": profile,
  3790. "delivery_policy": handoff.delivery_policy_for_profile(profile),
  3791. "run_id": run_id,
  3792. "output_dir": str(final_dir),
  3793. "volumes": volume_infos,
  3794. "formats": formats,
  3795. "checksum_entries": len(checksum_rows),
  3796. "included_file_count": len(inventory),
  3797. "included_bytes": sum(int(item["size"]) for item in inventory),
  3798. "excluded_entry_count": len(package_excluded),
  3799. "content_dedup_groups": len(content_dedup),
  3800. "derived_evidence_count": len(derived_evidence),
  3801. "member_count": member_count,
  3802. "warning_count": len(collection.warnings),
  3803. }
  3804. def _reference_fingerprint(inventory: list[dict[str, object]]) -> str:
  3805. digest = hashlib.sha256()
  3806. for item in sorted(inventory, key=lambda row: str(row["path"])):
  3807. path = str(item["path"])
  3808. size = str(item["size"])
  3809. sha = str(item["sha256"])
  3810. digest.update(f"{path}|{size}|{sha}\n".encode("utf-8"))
  3811. return digest.hexdigest()
  3812. def _create_reference_package_with_cache(
  3813. *,
  3814. collection: AnalysisCollection,
  3815. output_root: Path,
  3816. package_name: str,
  3817. max_zip_bytes: int,
  3818. target_zip_bytes: int,
  3819. force: bool,
  3820. repo_root: Path | None = None,
  3821. refresh_reference_inventory: bool = False,
  3822. ) -> dict[str, object]:
  3823. reference_package_name = f"{package_name}-reference"
  3824. reference_dir = output_root / reference_package_name
  3825. fingerprint_path = reference_dir / "REFERENCE-FINGERPRINT"
  3826. inventory_hook: dict[str, object] | None = None
  3827. if refresh_reference_inventory and repo_root is not None:
  3828. # Order: staging of reference sources is complete before this call; refresh
  3829. # inventory now so the package includes a fresh REFERENCE-INVENTORY.
  3830. inventory_hook = handoff.run_post_staging_reference_inventory_hook(
  3831. repo_root,
  3832. staging_complete=True,
  3833. enabled=True,
  3834. )
  3835. if inventory_hook.get("status") not in {"pass", "skipped_disabled"}:
  3836. raise PackagingError(
  3837. "post-staging reference inventory refresh failed: "
  3838. f"{inventory_hook.get('status')}"
  3839. )
  3840. inventory = _audit_package_items(collection.items)
  3841. fingerprint = _reference_fingerprint(inventory)
  3842. if not force and fingerprint_path.exists():
  3843. previous = fingerprint_path.read_text(encoding="ascii").strip()
  3844. if previous == fingerprint:
  3845. index_path = reference_dir / "HANDOFF-INDEX.json"
  3846. if index_path.exists():
  3847. index = json.loads(index_path.read_text(encoding="utf-8"))
  3848. return {
  3849. "status": collection.status,
  3850. "mode": "reference_cached",
  3851. "package_name": reference_package_name,
  3852. "output_dir": str(reference_dir),
  3853. "volumes": index.get("volumes", []),
  3854. "included_file_count": len(inventory),
  3855. "included_bytes": sum(int(item["size"]) for item in inventory),
  3856. "fingerprint": fingerprint,
  3857. "skipped": True,
  3858. "reference_inventory_hook": inventory_hook,
  3859. }
  3860. payload = create_analysis_package(
  3861. collection=collection,
  3862. output_root=output_root,
  3863. package_name=reference_package_name,
  3864. max_zip_bytes=max_zip_bytes,
  3865. target_zip_bytes=target_zip_bytes,
  3866. force=force,
  3867. )
  3868. reference_dir = Path(payload["output_dir"])
  3869. fingerprint_path = reference_dir / "REFERENCE-FINGERPRINT"
  3870. fingerprint_path.write_text(fingerprint + "\n", encoding="ascii")
  3871. payload["fingerprint"] = fingerprint
  3872. payload["skipped"] = False
  3873. payload["reference_inventory_hook"] = inventory_hook
  3874. return payload
  3875. def merge_archive_preparation(
  3876. collection: AnalysisCollection,
  3877. preparation: ArchivePreparation,
  3878. ) -> AnalysisCollection:
  3879. warnings = (*collection.warnings, *preparation.warnings)
  3880. excluded = sorted(
  3881. (*collection.excluded, *preparation.excluded),
  3882. key=lambda item: handoff.windows_collision_key(item["path"]),
  3883. )
  3884. return AnalysisCollection(
  3885. status="pass_with_warnings" if warnings else "pass",
  3886. items=preparation.items,
  3887. excluded=tuple(excluded),
  3888. warnings=tuple(warnings),
  3889. sources=collection.sources,
  3890. git=collection.git,
  3891. source_snapshots=collection.source_snapshots,
  3892. evidence_canon=collection.evidence_canon,
  3893. )
  3894. def explain_analysis_path(
  3895. path: Path,
  3896. *,
  3897. repo_root: Path,
  3898. config: HandoffConfig,
  3899. profile: str = "full",
  3900. ) -> dict[str, object]:
  3901. root = repo_root.resolve(strict=True)
  3902. requested = path if path.is_absolute() else root / path
  3903. target = requested.expanduser().resolve(strict=False)
  3904. resolved_sources, warnings = resolve_external_sources(config.external_sources)
  3905. source_roots: list[tuple[str, str, Path, Path | None]] = [
  3906. ("workspace-current", "core", root, None)
  3907. ]
  3908. for source in resolved_sources:
  3909. if source.kind == "file":
  3910. source_roots.append((source.id, source.category, source.path.parent, source.path))
  3911. else:
  3912. source_roots.append((source.id, source.category, source.path, None))
  3913. matches: list[tuple[int, str, str, Path, Path | None]] = []
  3914. for source_id, category, source_root, exact_file in source_roots:
  3915. if exact_file is not None and target != exact_file:
  3916. continue
  3917. try:
  3918. target.relative_to(source_root)
  3919. except ValueError:
  3920. continue
  3921. matches.append((len(source_root.parts), source_id, category, source_root, exact_file))
  3922. if not matches:
  3923. raise PackagingError("path is outside the current repository and configured external sources")
  3924. _, source_id, category, source_root, exact_file = max(matches, key=lambda item: item[0])
  3925. relative = exact_file.name if exact_file is not None else target.relative_to(source_root).as_posix()
  3926. if not relative:
  3927. relative = "."
  3928. is_dir = target.is_dir()
  3929. context = handoff.load_scan_context(source_root)
  3930. reason = analysis_exclusion_reason(
  3931. relative,
  3932. is_dir=is_dir,
  3933. context=context,
  3934. extra_exclusions=config.extra_exclusions,
  3935. profile=profile,
  3936. )
  3937. archive_relative = (
  3938. f"workspace-current/{relative}"
  3939. if source_id == "workspace-current"
  3940. else f"external/{source_id}/{relative}"
  3941. )
  3942. return {
  3943. "status": "pass_with_warnings" if warnings else "pass",
  3944. "mode": "explain",
  3945. "path": str(target),
  3946. "exists": target.exists(),
  3947. "source_id": source_id,
  3948. "category": category,
  3949. "source_relative_path": relative,
  3950. "archive_path": f"CPLD/{archive_relative}",
  3951. "decision": "exclude" if reason else "include",
  3952. "reason": reason,
  3953. "content_scan": "not_run",
  3954. "warnings": warnings,
  3955. }
  3956. def audit_analysis_collection(collection: AnalysisCollection) -> dict[str, object]:
  3957. inventory = _audit_package_items(collection.items)
  3958. inventory_by_path = {str(item["path"]): item for item in inventory}
  3959. _assert_items_unchanged(collection.items, inventory_by_path)
  3960. return {
  3961. "status": collection.status,
  3962. "mode": "audit_only",
  3963. "included_file_count": len(inventory),
  3964. "included_bytes": sum(int(item["size"]) for item in inventory),
  3965. "excluded_entry_count": len(collection.excluded),
  3966. "warning_count": len(collection.warnings),
  3967. "warnings": list(collection.warnings),
  3968. "sources": list(collection.sources),
  3969. "git": list(collection.git),
  3970. }
  3971. def _validate_output_root(
  3972. output_root: Path,
  3973. *,
  3974. repo_root: Path,
  3975. config: HandoffConfig,
  3976. ) -> Path:
  3977. output = output_root.expanduser().resolve(strict=False)
  3978. source_paths = [repo_root.resolve(strict=True)]
  3979. resolved_sources, _ = resolve_external_sources(config.external_sources)
  3980. source_paths.extend(source.path if source.kind != "file" else source.path.parent for source in resolved_sources)
  3981. for source_path in source_paths:
  3982. try:
  3983. output.relative_to(source_path)
  3984. except ValueError:
  3985. continue
  3986. raise PackagingError(f"output directory must be outside every packaged source root: {source_path}")
  3987. return output
  3988. def build_parser() -> argparse.ArgumentParser:
  3989. parser = argparse.ArgumentParser(description=__doc__)
  3990. parser.add_argument("--audit-only", action="store_true", help="scan and verify inputs without creating ZIP files")
  3991. parser.add_argument("--explain", type=Path, metavar="PATH", help="explain whether one path is included or excluded")
  3992. parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG, help="source and exclusion configuration JSON")
  3993. parser.add_argument("--source-root", type=Path, default=ROOT, help="root directory to package as the primary source")
  3994. parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR, help="parent directory for the package directory")
  3995. parser.add_argument("--package-name", help="portable package directory and ZIP base name")
  3996. parser.add_argument("--force-overwrite", action="store_true", help="atomically replace an existing package directory")
  3997. parser.add_argument("--no-git-bundle", action="store_true", help="omit the git history bundle from the package")
  3998. parser.add_argument(
  3999. "--include-full-history",
  4000. action="store_true",
  4001. help="include a full git bundle (archive-local / explicit override; ignored as default for review-compact)",
  4002. )
  4003. parser.add_argument(
  4004. "--include-sanitized-git-snapshot",
  4005. action="store_true",
  4006. help=(
  4007. "include sanitized synthetic single-commit git snapshot under meta/git "
  4008. "(records synthetic→original mapping; does not impersonate the original tip)"
  4009. ),
  4010. )
  4011. parser.add_argument(
  4012. "--evidence-root",
  4013. type=Path,
  4014. help=(
  4015. "optional delivery/run evidence tree to stage into canonical evidence/ paths "
  4016. "(final matrix, Formal/TD receipts, bitstream, selftests, deep-review summary, IO/hardware notes)"
  4017. ),
  4018. )
  4019. parser.add_argument(
  4020. "--include-process-evidence",
  4021. action="store_true",
  4022. help=(
  4023. "include lane receipts, matrix reruns, and other process evidence "
  4024. "(implied by review-debug; off by default for review-compact)"
  4025. ),
  4026. )
  4027. parser.add_argument(
  4028. "--profile",
  4029. choices=sorted(handoff.HANDOFF_PROFILES),
  4030. default=handoff.DEFAULT_HANDOFF_PROFILE,
  4031. help=(
  4032. "review-compact (default upload: unified source/evidence/meta, no full git bundle); "
  4033. "review-debug; archive-local; legacy full (core/reference split) / code-only"
  4034. ),
  4035. )
  4036. parser.add_argument(
  4037. "--replay-package",
  4038. type=Path,
  4039. metavar="DIR",
  4040. help="verify SHA256SUMS and replay-extract an existing package directory (selftest)",
  4041. )
  4042. parser.add_argument(
  4043. "--replay-extract-dir",
  4044. type=Path,
  4045. help="extract target for --replay-package (must not already exist)",
  4046. )
  4047. parser.add_argument(
  4048. "--bitstream",
  4049. type=Path,
  4050. help=(
  4051. "optional real bitstream to bind into meta/td-source-closure-binding.json "
  4052. "(full SHA-256; integrator supplies tip bit later)"
  4053. ),
  4054. )
  4055. parser.add_argument(
  4056. "--td-report",
  4057. type=Path,
  4058. action="append",
  4059. default=[],
  4060. dest="td_reports",
  4061. help="optional TD report/receipt to bind (repeatable)",
  4062. )
  4063. parser.add_argument(
  4064. "--binding-commit",
  4065. help="optional full 40-char commit override for TD source-closure binding",
  4066. )
  4067. parser.add_argument(
  4068. "--require-bitstream-binding",
  4069. action="store_true",
  4070. help="fail binding (status=bind_failed) when no bitstream is available",
  4071. )
  4072. parser.add_argument(
  4073. "--package-stage",
  4074. choices=("intermediate-review", "final-review"),
  4075. default="final-review",
  4076. help=(
  4077. "intermediate-review: non-final code review without fresh TD/bitstream; "
  4078. "final-review: fail-closed on missing canonical TD/bitstream evidence"
  4079. ),
  4080. )
  4081. parser.add_argument(
  4082. "--refresh-reference-inventory-after-staging",
  4083. action="store_true",
  4084. help=(
  4085. "for full-profile reference volume: refresh docs/REFERENCE-INVENTORY "
  4086. "after staging completes (Lane D order hook; Lane E owns generator honesty)"
  4087. ),
  4088. )
  4089. parser.add_argument(
  4090. "--target",
  4091. default="mrdimm",
  4092. help="historical default package-name label only; does not select firmware or product (default mrdimm)",
  4093. )
  4094. return parser
  4095. def main(argv: list[str] | None = None) -> int:
  4096. args = build_parser().parse_args(argv)
  4097. package_name = args.package_name or datetime.now(timezone.utc).strftime(
  4098. f"cpld-agent-analysis-{getattr(args, 'target', 'mrdimm')}-%Y%m%dT%H%M%SZ"
  4099. )
  4100. try:
  4101. if args.replay_package is not None:
  4102. extract_root = args.replay_extract_dir or (
  4103. Path(tempfile.mkdtemp(prefix="prod2u-package-replay-", dir=os.environ.get("TMPDIR", "/tmp")))
  4104. / "extracted"
  4105. )
  4106. payload = replay_analysis_package(args.replay_package, extract_root=extract_root)
  4107. print(json.dumps(payload, ensure_ascii=False, indent=2))
  4108. return 0
  4109. source_root = args.source_root.expanduser().resolve(strict=True)
  4110. if args.profile not in handoff.HANDOFF_PROFILES:
  4111. raise PackagingError(f"unsupported handoff profile: {args.profile}")
  4112. config = load_config(args.config, repo_root=source_root)
  4113. if args.explain is not None:
  4114. payload = explain_analysis_path(
  4115. args.explain,
  4116. repo_root=source_root,
  4117. config=config,
  4118. profile=args.profile,
  4119. )
  4120. else:
  4121. seven_zip = find_7z()
  4122. _validate_package_name(package_name)
  4123. output_root = _validate_output_root(args.output_dir, repo_root=source_root, config=config)
  4124. if args.profile == "archive-local":
  4125. include_git_bundle = not args.no_git_bundle or args.include_full_history
  4126. if args.include_full_history:
  4127. include_git_bundle = True
  4128. elif args.profile in {"review-compact", "review-debug"}:
  4129. include_git_bundle = False
  4130. else:
  4131. include_git_bundle = not args.no_git_bundle
  4132. with tempfile.TemporaryDirectory(prefix="ca-") as temporary:
  4133. temp_root = Path(temporary)
  4134. collection = collect_analysis_inputs(
  4135. repo_root=source_root,
  4136. config=config,
  4137. temp_root=temp_root / "inputs",
  4138. include_git_bundle=include_git_bundle,
  4139. profile=args.profile,
  4140. include_sanitized_git_snapshot=args.include_sanitized_git_snapshot,
  4141. package_name=package_name,
  4142. evidence_root=args.evidence_root.expanduser().resolve(strict=True)
  4143. if args.evidence_root is not None
  4144. else None,
  4145. include_process_evidence=args.include_process_evidence,
  4146. bitstream_path=args.bitstream.expanduser().resolve(strict=True)
  4147. if args.bitstream is not None
  4148. else None,
  4149. td_report_paths=[
  4150. path.expanduser().resolve(strict=True) for path in args.td_reports
  4151. ],
  4152. binding_commit=args.binding_commit,
  4153. require_bitstream_binding=args.require_bitstream_binding,
  4154. package_stage=args.package_stage,
  4155. )
  4156. preparation = prepare_unsupported_archives(
  4157. collection.items,
  4158. temp_root=temp_root / "archives",
  4159. seven_zip=seven_zip,
  4160. extra_exclusions=config.extra_exclusions,
  4161. )
  4162. prepared_collection = merge_archive_preparation(collection, preparation)
  4163. if args.audit_only:
  4164. payload = audit_analysis_collection(prepared_collection)
  4165. payload["profile"] = args.profile
  4166. payload["delivery_policy"] = handoff.delivery_policy_for_profile(args.profile)
  4167. elif handoff.uses_unified_layout(args.profile) or args.profile == "code-only":
  4168. if not prepared_collection.items:
  4169. raise PackagingError("analysis package has no included files")
  4170. payload = create_analysis_package(
  4171. collection=prepared_collection,
  4172. output_root=output_root,
  4173. package_name=package_name,
  4174. max_zip_bytes=config.max_zip_bytes,
  4175. target_zip_bytes=config.target_zip_bytes,
  4176. force=args.force_overwrite,
  4177. profile=args.profile,
  4178. )
  4179. else:
  4180. core_collection, reference_collection = _split_collection_by_reference(
  4181. prepared_collection
  4182. )
  4183. if not core_collection.items and not reference_collection.items:
  4184. raise PackagingError("analysis package has no included files")
  4185. payload = {}
  4186. if core_collection.items:
  4187. payload["core"] = create_analysis_package(
  4188. collection=core_collection,
  4189. output_root=output_root,
  4190. package_name=package_name,
  4191. max_zip_bytes=config.max_zip_bytes,
  4192. target_zip_bytes=config.target_zip_bytes,
  4193. force=args.force_overwrite,
  4194. profile=args.profile,
  4195. )
  4196. if reference_collection.items:
  4197. payload["reference"] = _create_reference_package_with_cache(
  4198. collection=reference_collection,
  4199. output_root=output_root,
  4200. package_name=package_name,
  4201. max_zip_bytes=config.max_zip_bytes,
  4202. target_zip_bytes=config.target_zip_bytes,
  4203. force=args.force_overwrite,
  4204. repo_root=source_root,
  4205. refresh_reference_inventory=args.refresh_reference_inventory_after_staging,
  4206. )
  4207. except (PackagingError, OSError, ValueError) as exc:
  4208. print(f"error: {exc}", file=sys.stderr)
  4209. return 1
  4210. print(json.dumps(payload, ensure_ascii=False, indent=2))
  4211. return 0
  4212. if __name__ == "__main__":
  4213. raise SystemExit(main())