package_for_agent_analysis.py 180 KB

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