package_for_agent_analysis.py 181 KB

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