package_for_agent_analysis.py 173 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269
  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 pkg_prov.ARTIFACT_DEFAULT
  1467. or ""
  1468. ).strip()
  1469. # Reused TD-bound production tip when unchanged; never silently equal delivery.
  1470. artifact = td_bound_candidate or delivery
  1471. ref_pointer = pkg_prov.build_reference_pointer(
  1472. artifact_commit=artifact,
  1473. delivery_commit=delivery,
  1474. reference_changed=False,
  1475. reference_reused=True,
  1476. repo_root=root,
  1477. summary_only=False,
  1478. )
  1479. relations = pkg_prov.build_source_closure_relations(
  1480. old_baseline_commit=pkg_prov.BASE_DEV_COMMIT_DEFAULT,
  1481. artifact_commit=artifact,
  1482. delivery_commit=delivery,
  1483. old_to_artifact_unchanged=None,
  1484. artifact_to_delivery_unchanged=None,
  1485. old_to_artifact_changed_paths=[],
  1486. artifact_to_delivery_changed_paths=[],
  1487. comparison_mode="snapshot_hash",
  1488. )
  1489. # Annotate MSE intermediate identity without inventing a false unchanged edge.
  1490. relations["verification_tip"] = verification_tip or None
  1491. relations["delivery_commit"] = delivery
  1492. relations["td_bound_candidate"] = td_bound_candidate or None
  1493. relations["reused_artifact_source"] = td_bound_candidate or None
  1494. relations["note"] = (
  1495. "INTERMEDIATE MSE review-debug: verification_tip / delivery / "
  1496. "td_bound_candidate are explicit; do not treat artifact_source_commit "
  1497. "as package HEAD unless they match."
  1498. )
  1499. sibling = pkg_prov.sibling_role_stub(
  1500. role="review-compact",
  1501. expected_filename=(
  1502. os.environ.get("PRODU2_PACKAGE_EXPECTED_FIRMWARE_NAME", "").strip()
  1503. or f"prod2u-mse-firmware-deferred-{delivery[:8]}.zip"
  1504. ),
  1505. release_set_id=f"intermediate-nonfinal-{delivery[:8]}",
  1506. )
  1507. polarity = motor_polarity_config_identity(root)
  1508. release_identity = {
  1509. "schema": "prod2u-release-set-identity-v1",
  1510. "algorithm_version": "prod2u-release-set-id-v1",
  1511. "package_stage": "intermediate-review",
  1512. "non_final": True,
  1513. "release_set_id": f"intermediate-nonfinal-{delivery[:8]}",
  1514. "base_dev_commit": pkg_prov.BASE_DEV_COMMIT_DEFAULT,
  1515. "verification_tip": verification_tip or None,
  1516. "td_bound_candidate": td_bound_candidate or None,
  1517. "reused_artifact_source": td_bound_candidate or None,
  1518. "artifact_source_commit": artifact,
  1519. "delivery_commit": delivery,
  1520. "bitstream_sha256": "b4b0eda4ee8d774109eff83b519bdaa19d5e73d770562983121a596df00952d0",
  1521. "matrix_verification_tip": verification_tip or None,
  1522. "td_bound_commit": td_bound_candidate or None,
  1523. "verification_run_id": "mse-r7-20260812T132652Z",
  1524. "td_binding_status": "pass",
  1525. "production_binding": "37/37/0/0",
  1526. "production_polarity_config": {
  1527. "limit_active_high": polarity.get("limit_active_high"),
  1528. "dir_close_level": polarity.get("dir_close_level"),
  1529. "close_limit_is_ls": polarity.get("close_limit_is_ls"),
  1530. "generated_masks": polarity.get("generated_masks")
  1531. or polarity.get("masks"),
  1532. "config_fingerprint": polarity.get("sha256"),
  1533. },
  1534. "verification_run_id": None,
  1535. "td_artifact_run_id": None,
  1536. "td_receipt_sha256": None,
  1537. "reference_set_fingerprint": pkg_prov.reference_set_fingerprint(root)[
  1538. "sha256"
  1539. ],
  1540. "hardware_validation": "not_run",
  1541. "note": (
  1542. "INTERMEDIATE / NON-FINAL MSE A1 verification closure package. "
  1543. "No fresh TD/bitstream claimed this round unless receipts say so. "
  1544. "Do not treat as final release set."
  1545. ),
  1546. }
  1547. provenance_artifacts["meta/REFERENCE-POINTER.json"] = handoff.json_bytes(
  1548. ref_pointer
  1549. )
  1550. provenance_artifacts["meta/source-closure-relations.json"] = (
  1551. handoff.json_bytes(relations)
  1552. )
  1553. provenance_artifacts["meta/release-set-sibling.json"] = handoff.json_bytes(
  1554. sibling
  1555. )
  1556. provenance_artifacts["meta/release-set-identity.json"] = (
  1557. handoff.json_bytes(release_identity)
  1558. )
  1559. provenance_artifacts["meta/release-set-id.txt"] = (
  1560. f"intermediate-nonfinal-{delivery[:8]}\n"
  1561. ).encode("ascii")
  1562. if packaged_source_manifest is not None:
  1563. provenance_artifacts["meta/git/packaged-source-manifest.json"] = (
  1564. handoff.json_bytes(packaged_source_manifest)
  1565. )
  1566. raise _IntermediateProvenanceDone()
  1567. report_artifact = str(
  1568. td_report_payload.get("commit_full")
  1569. or td_report_payload.get("commit")
  1570. or ""
  1571. )
  1572. # DELIVERY is the package tip (git HEAD / --binding-commit). Never fall
  1573. # back to ARTIFACT or sibling filenames collapse to the wrong tip.
  1574. delivery = str(head or binding_commit or "").strip()
  1575. artifact = str(
  1576. binding.get("artifact_source_commit")
  1577. or report_artifact
  1578. or pkg_prov.ARTIFACT_DEFAULT
  1579. or ""
  1580. ).strip()
  1581. if not delivery:
  1582. raise PackagingError(
  1583. "review-compact delivery commit unavailable "
  1584. "(git head and --binding-commit both empty)"
  1585. )
  1586. if not artifact:
  1587. raise PackagingError(
  1588. "review-compact artifact_source_commit unavailable "
  1589. "(TD report commit / ARTIFACT_DEFAULT missing)"
  1590. )
  1591. # Prefer TD production tip when binder incorrectly equates ARTIFACT to DELIVERY.
  1592. if report_artifact and artifact == delivery and report_artifact != delivery:
  1593. artifact = report_artifact
  1594. ref_pointer = pkg_prov.build_reference_pointer(
  1595. artifact_commit=artifact,
  1596. delivery_commit=delivery,
  1597. reference_changed=False,
  1598. reference_reused=True,
  1599. repo_root=root,
  1600. summary_only=False,
  1601. )
  1602. bit_sha = str(
  1603. binding.get("bitstream_sha256")
  1604. or bitstream_obj.get("sha256")
  1605. or td_report_payload.get("bitstream_sha256")
  1606. or ""
  1607. )
  1608. # Config fingerprint is motor-polarity masks, not project_config_sha256.
  1609. config_fp = motor_polarity_config_identity(root)["sha256"]
  1610. td_run = str(
  1611. binding.get("td_run_id")
  1612. or binding.get("run_id")
  1613. or td_report_payload.get("run_id")
  1614. or td_report_payload.get("td_run_id")
  1615. or ""
  1616. )
  1617. ref_fp = pkg_prov.reference_set_fingerprint(root)
  1618. if not bit_sha:
  1619. raise PackagingError("release_set_id requires bound bitstream sha256")
  1620. if not td_run:
  1621. raise PackagingError("release_set_id requires td run_id from bound receipt")
  1622. release_set_id = pkg_prov.compute_release_set_id(
  1623. artifact_commit=artifact,
  1624. delivery_commit=delivery,
  1625. bitstream_sha256=bit_sha,
  1626. config_fingerprint=config_fp,
  1627. td_run_id=td_run,
  1628. reference_set_fingerprint_sha256=ref_fp["sha256"],
  1629. )
  1630. art_to_del = generate_source_closure_comparison(
  1631. td_report=td_report_payload,
  1632. artifact_commit=artifact,
  1633. matrix_commit=artifact,
  1634. final_dev_commit=delivery,
  1635. repo_root=root,
  1636. )
  1637. old_to_art = generate_source_closure_comparison(
  1638. td_report=td_report_payload,
  1639. artifact_commit=OLD_BASELINE_COMMIT_DEFAULT,
  1640. matrix_commit=OLD_BASELINE_COMMIT_DEFAULT,
  1641. final_dev_commit=artifact,
  1642. repo_root=root,
  1643. )
  1644. comparison_mode = str(art_to_del.get("mode") or "commit_compare")
  1645. if comparison_mode == "comparison_unavailable_without_git":
  1646. relations = pkg_prov.build_source_closure_relations(
  1647. old_baseline_commit=pkg_prov.OLD_BASELINE_DEFAULT,
  1648. artifact_commit=artifact,
  1649. delivery_commit=delivery,
  1650. old_to_artifact_unchanged=None,
  1651. artifact_to_delivery_unchanged=None,
  1652. old_to_artifact_changed_paths=[],
  1653. artifact_to_delivery_changed_paths=[],
  1654. comparison_mode="comparison_unavailable",
  1655. )
  1656. else:
  1657. relations = pkg_prov.build_source_closure_relations(
  1658. old_baseline_commit=pkg_prov.OLD_BASELINE_DEFAULT,
  1659. artifact_commit=artifact,
  1660. delivery_commit=delivery,
  1661. old_to_artifact_unchanged=bool(
  1662. old_to_art.get("source_closure_equal")
  1663. ),
  1664. artifact_to_delivery_unchanged=bool(
  1665. art_to_del.get("source_closure_equal")
  1666. ),
  1667. old_to_artifact_changed_paths=list(
  1668. old_to_art.get("production_changed_paths") or []
  1669. ),
  1670. artifact_to_delivery_changed_paths=list(
  1671. art_to_del.get("production_changed_paths") or []
  1672. ),
  1673. comparison_mode=comparison_mode,
  1674. )
  1675. rel_check = pkg_prov.validate_source_closure_relations(relations)
  1676. if rel_check["status"] != "pass":
  1677. raise PackagingError(
  1678. f"source-closure relations inconsistent: {rel_check['failures']}"
  1679. )
  1680. # Explicit dual-commit fields (keep commit_full for compatibility).
  1681. binding["artifact_source_commit"] = artifact
  1682. binding["delivery_commit"] = delivery
  1683. binding["artifact_to_delivery_unchanged"] = bool(
  1684. art_to_del.get("source_closure_equal")
  1685. )
  1686. binding["td_run_id"] = td_run
  1687. if binding.get("commit_full") in {None, "", artifact} and delivery:
  1688. binding["commit_full"] = delivery
  1689. binding["commit_short"] = delivery[:8]
  1690. # Re-encode binding after enriching identity fields.
  1691. binding_bytes = handoff.json_bytes(binding)
  1692. provenance_artifacts["meta/td/td-source-closure-binding.json"] = binding_bytes
  1693. provenance_artifacts["meta/td-source-closure-binding.json"] = binding_bytes
  1694. provenance_artifacts["meta/SOURCE-CLOSURE-COMPARISON-ART-TO-DEL.json"] = (
  1695. handoff.json_bytes(art_to_del)
  1696. )
  1697. provenance_artifacts["meta/SOURCE-CLOSURE-COMPARISON-OLD-TO-ART.json"] = (
  1698. handoff.json_bytes(old_to_art)
  1699. )
  1700. sibling = pkg_prov.sibling_role_stub(
  1701. role="review-compact",
  1702. expected_filename=pkg_prov.release_sibling_filename("firmware", delivery),
  1703. release_set_id=release_set_id,
  1704. )
  1705. provenance_artifacts["meta/REFERENCE-POINTER.json"] = handoff.json_bytes(ref_pointer)
  1706. provenance_artifacts["meta/source-closure-relations.json"] = handoff.json_bytes(
  1707. relations
  1708. )
  1709. provenance_artifacts["meta/release-set-sibling.json"] = handoff.json_bytes(sibling)
  1710. provenance_artifacts["meta/release-set-id.txt"] = (release_set_id + "\n").encode(
  1711. "ascii"
  1712. )
  1713. # Dual run-id semantics: TD verification vs TD artifact workspace.
  1714. # release_set_id already binds td_run (= TD receipt run_id / artifact run).
  1715. td_verification_run_id = str(
  1716. binding.get("verification_run_id")
  1717. or td_report_payload.get("verification_run_id")
  1718. or ""
  1719. )
  1720. td_artifact_run_id = str(
  1721. binding.get("td_artifact_run_id")
  1722. or td_report_payload.get("td_artifact_run_id")
  1723. or td_report_payload.get("artifact_run_id")
  1724. or td_report_payload.get("run_id")
  1725. or td_run
  1726. or ""
  1727. )
  1728. if not td_artifact_run_id:
  1729. # Recover from known receipt path shape .../runs/<id>/...
  1730. for report_meta in binding.get("td_reports") or []:
  1731. if not isinstance(report_meta, dict):
  1732. continue
  1733. report_path = str(report_meta.get("path") or "")
  1734. marker = "/runs/"
  1735. if marker in report_path.replace("\\", "/"):
  1736. part = report_path.replace("\\", "/").split(marker, 1)[1]
  1737. td_artifact_run_id = part.split("/", 1)[0]
  1738. break
  1739. if not td_artifact_run_id:
  1740. raise PackagingError(
  1741. "final-review requires td_artifact_run_id from bound TD receipt "
  1742. "(no hardcoded historical fallback)"
  1743. )
  1744. if td_artifact_run_id == "20260806T112210Z-3f2f5f2f":
  1745. raise PackagingError(
  1746. "refusing Round-10 hardcoded td_artifact_run_id fallback "
  1747. "20260806T112210Z-3f2f5f2f"
  1748. )
  1749. binding["verification_run_id"] = td_verification_run_id or td_run
  1750. binding["td_artifact_run_id"] = td_artifact_run_id
  1751. binding["td_run_id_semantics"] = {
  1752. "verification_run_id": td_verification_run_id or td_run,
  1753. "td_artifact_run_id": td_artifact_run_id,
  1754. "release_set_id_uses": "td_artifact_run_id",
  1755. }
  1756. binding_bytes = handoff.json_bytes(binding)
  1757. provenance_artifacts["meta/td/td-source-closure-binding.json"] = binding_bytes
  1758. provenance_artifacts["meta/td-source-closure-binding.json"] = binding_bytes
  1759. polarity = motor_polarity_config_identity(root)
  1760. matrix_tip = str(
  1761. os.environ.get("PRODU2_VERIFICATION_TIP", "").strip()
  1762. or binding.get("matrix_verification_tip")
  1763. or binding.get("verification_tip")
  1764. or ""
  1765. ).strip()
  1766. matrix_run = str(
  1767. os.environ.get("PRODU2_VERIFICATION_RUN_ID", "").strip()
  1768. or binding.get("matrix_verification_run_id")
  1769. or binding.get("software_verification_run_id")
  1770. or ""
  1771. ).strip()
  1772. td_bound = str(
  1773. binding.get("td_bound_commit")
  1774. or binding.get("artifact_source_commit")
  1775. or artifact
  1776. ).strip()
  1777. release_identity = {
  1778. "schema": "prod2u-release-set-identity-v1",
  1779. "algorithm_version": "prod2u-release-set-id-v1",
  1780. "package_stage": stage_n,
  1781. "non_final": stage_n != "final-review",
  1782. "release_set_id": release_set_id,
  1783. "base_dev_commit": pkg_prov.BASE_DEV_COMMIT_DEFAULT,
  1784. "matrix_verification_tip": matrix_tip or None,
  1785. "verification_tip": matrix_tip or None,
  1786. "verification_run_id": matrix_run or td_verification_run_id or td_run,
  1787. "td_bound_commit": td_bound,
  1788. "artifact_source_commit": artifact,
  1789. "delivery_commit": delivery,
  1790. "bitstream_sha256": bit_sha,
  1791. "td_binding_status": "pass",
  1792. "td_policy": "reused_exact_source_bound_td",
  1793. "production_binding": "37/37/0/0",
  1794. "production_polarity_config": {
  1795. "limit_active_high": polarity.get("limit_active_high"),
  1796. "dir_close_level": polarity.get("dir_close_level"),
  1797. "close_limit_is_ls": polarity.get("close_limit_is_ls"),
  1798. "generated_masks": polarity.get("generated_masks")
  1799. or polarity.get("masks"),
  1800. "config_fingerprint": config_fp,
  1801. },
  1802. "td_verification_run_id": td_verification_run_id or td_run,
  1803. "td_artifact_run_id": td_artifact_run_id,
  1804. "td_receipt_sha256": None,
  1805. "reference_fingerprint_schema": ref_fp.get("schema"),
  1806. "reference_set_fingerprint": ref_fp["sha256"],
  1807. "polarity_fingerprint": config_fp,
  1808. "hardware_validation": "not_run",
  1809. "note": (
  1810. "release_set_id is independently recomputable from these fields; "
  1811. "td_artifact_run_id (TD receipt run_id) feeds release_set_id; "
  1812. "verification_run_id is the software matrix run id when set. "
  1813. "Sibling ZIP SHAs live only in the external release-set JSON."
  1814. ),
  1815. }
  1816. for report_meta in binding.get("td_reports") or []:
  1817. if isinstance(report_meta, dict) and report_meta.get("sha256"):
  1818. release_identity["td_receipt_sha256"] = report_meta.get("sha256")
  1819. break
  1820. provenance_artifacts["meta/release-set-identity.json"] = handoff.json_bytes(
  1821. release_identity
  1822. )
  1823. if packaged_source_manifest is not None:
  1824. provenance_artifacts["meta/git/packaged-source-manifest.json"] = (
  1825. handoff.json_bytes(packaged_source_manifest)
  1826. )
  1827. except _IntermediateProvenanceDone:
  1828. pass
  1829. except Exception as exc: # noqa: BLE001 - surface helper failure in meta, fail later selftest
  1830. provenance_artifacts["meta/REFERENCE-POINTER-ERROR.txt"] = (
  1831. f"reference pointer build failed: {exc}\n"
  1832. ).encode("utf-8")
  1833. # Even when provenance helpers fail, still emit packaged-source-manifest if built.
  1834. if (
  1835. packaged_source_manifest is not None
  1836. and "meta/git/packaged-source-manifest.json" not in provenance_artifacts
  1837. ):
  1838. provenance_artifacts["meta/git/packaged-source-manifest.json"] = (
  1839. handoff.json_bytes(packaged_source_manifest)
  1840. )
  1841. # External selftest sidecar certifies the final ZIP; never embed a recursive
  1842. # compact-package-selftest.json that claims to authenticate this archive.
  1843. delivery_full = str(provenance.get("head") or binding_commit or "unknown").strip()
  1844. delivery_short = delivery_full[:8]
  1845. topic_slug = pkg_prov.release_task_slug()
  1846. expected_selftest = pkg_prov.release_sibling_filename(
  1847. "review-selftest", delivery_full, slug=topic_slug
  1848. )
  1849. provenance_artifacts[_COMPACT_SELFTEST_POINTER] = handoff.json_bytes(
  1850. {
  1851. "schema": "cpld-review-compact-selftest-pointer-v1",
  1852. "role": "external_sidecar_only",
  1853. "topic": topic_slug,
  1854. "package_stage": stage_n if "stage_n" in locals() else None,
  1855. "delivery_commit": delivery_full,
  1856. "expected_external_selftest_filename": expected_selftest,
  1857. "deprecated_alias_filename": pkg_prov.deprecated_door_percent_alias(
  1858. "review-selftest", delivery_full
  1859. ),
  1860. "note": (
  1861. "Final review ZIP SHA / member_count are certified only by the "
  1862. "external sibling selftest sidecar listed above. This archive does "
  1863. "not embed compact-package-selftest.json (avoids cyclic self-hash). "
  1864. "door-percent alias is deprecated and not final authority."
  1865. ),
  1866. }
  1867. )
  1868. # Package-time actual-HEAD closure (never pre-committed self-hash).
  1869. matrix_tip_env = str(
  1870. os.environ.get("PRODU2_VERIFICATION_TIP", "").strip()
  1871. or "21ed755ad2ddb6689bca88a9a037b391372a060e"
  1872. ).strip()
  1873. if matrix_tip_env and delivery_full and delivery_full != "unknown":
  1874. try:
  1875. import verification_to_delivery_closure as v2d
  1876. closure = v2d.build_closure(
  1877. repo=root,
  1878. verification_tip=matrix_tip_env,
  1879. delivery_commit=delivery_full,
  1880. matrix_run_id=str(
  1881. os.environ.get("PRODU2_VERIFICATION_RUN_ID", "")
  1882. ).strip()
  1883. or None,
  1884. )
  1885. provenance_artifacts["meta/verification-to-delivery-closure.json"] = (
  1886. handoff.json_bytes(closure)
  1887. )
  1888. if stage_n == "final-review" and not closure.get("closure_ok"):
  1889. raise PackagingError(
  1890. "final-review verification→delivery closure_ok=false: "
  1891. f"{closure.get('forbidden_changed_paths')}"
  1892. )
  1893. except PackagingError:
  1894. raise
  1895. except Exception as exc: # noqa: BLE001
  1896. provenance_artifacts["meta/verification-to-delivery-closure-ERROR.txt"] = (
  1897. f"package-time closure failed: {exc}\n"
  1898. ).encode("utf-8")
  1899. if stage_n == "final-review":
  1900. raise PackagingError(
  1901. f"final-review requires package-time closure: {exc}"
  1902. ) from exc
  1903. items.extend(
  1904. _materialize_bytes_items(
  1905. provenance_artifacts,
  1906. temp_root=temp_root,
  1907. source_id="meta-generated",
  1908. category="meta",
  1909. )
  1910. )
  1911. git_metadata.append(
  1912. {
  1913. "source_id": primary_source_id,
  1914. "status": provenance.get("status"),
  1915. "branch": provenance.get("branch"),
  1916. "head": provenance.get("head"),
  1917. "full_bundle": False,
  1918. "provenance": provenance,
  1919. "td_source_closure_binding": binding,
  1920. }
  1921. )
  1922. resolved_sources, source_warnings = resolve_external_sources(config.external_sources)
  1923. if profile == "code-only":
  1924. resolved_sources = [
  1925. source for source in resolved_sources if source.id != "board-viewer-generated"
  1926. ]
  1927. warnings.extend(source_warnings)
  1928. for source in resolved_sources:
  1929. if unified:
  1930. # Prefer derived board-viewer assets under evidence/.
  1931. if source.kind == "file":
  1932. prefix, category = _unified_layout_prefix(
  1933. source_id=source.id,
  1934. original_relative=source.path.name,
  1935. profile=profile,
  1936. )
  1937. candidate = _candidate_from_path(
  1938. source.path, f"{prefix}/{source.path.name}"
  1939. )
  1940. items.append(
  1941. PackageItem(
  1942. candidate=candidate,
  1943. category=category,
  1944. source_id=source.id,
  1945. original_path=source.path.name,
  1946. scan_archive=source.archive_policy == "inspect",
  1947. )
  1948. )
  1949. else:
  1950. source_items, source_excluded = _collect_directory_items(
  1951. root=source.path,
  1952. source_id=source.id,
  1953. category="evidence",
  1954. prefix="__external__",
  1955. extra_exclusions=config.extra_exclusions,
  1956. profile=profile,
  1957. )
  1958. for item in source_items:
  1959. original = item.original_path
  1960. prefix, category = _unified_layout_prefix(
  1961. source_id=source.id,
  1962. original_relative=original,
  1963. profile=profile,
  1964. )
  1965. items.append(
  1966. PackageItem(
  1967. candidate=_rebase_candidate(
  1968. handoff.Candidate(
  1969. absolute=item.candidate.absolute,
  1970. relative=original,
  1971. size=item.candidate.size,
  1972. mtime_ns=item.candidate.mtime_ns,
  1973. device=item.candidate.device,
  1974. inode=item.candidate.inode,
  1975. mode=item.candidate.mode,
  1976. ),
  1977. prefix,
  1978. ),
  1979. category=category,
  1980. source_id=source.id,
  1981. original_path=original,
  1982. scan_archive=item.scan_archive,
  1983. )
  1984. )
  1985. for entry in source_excluded:
  1986. original_excluded = entry["path"]
  1987. if original_excluded.startswith("__external__/"):
  1988. original_excluded = original_excluded[len("__external__/") :]
  1989. prefix, _category = _unified_layout_prefix(
  1990. source_id=source.id,
  1991. original_relative=original_excluded,
  1992. profile=profile,
  1993. )
  1994. excluded.append(
  1995. {
  1996. "path": f"{prefix}/{original_excluded}",
  1997. "rule": entry["rule"],
  1998. }
  1999. )
  2000. source_snapshots.append(
  2001. _source_snapshot(
  2002. source.path,
  2003. source_id=source.id,
  2004. extra_exclusions=config.extra_exclusions,
  2005. profile=profile,
  2006. )
  2007. )
  2008. else:
  2009. prefix = f"external/{source.id}"
  2010. if source.kind == "file":
  2011. candidate = _candidate_from_path(source.path, f"{prefix}/{source.path.name}")
  2012. items.append(
  2013. PackageItem(
  2014. candidate=candidate,
  2015. category=source.category,
  2016. source_id=source.id,
  2017. original_path=source.path.name,
  2018. scan_archive=source.archive_policy == "inspect",
  2019. )
  2020. )
  2021. else:
  2022. source_items, source_excluded = _collect_directory_items(
  2023. root=source.path,
  2024. source_id=source.id,
  2025. category=source.category,
  2026. prefix=prefix,
  2027. extra_exclusions=config.extra_exclusions,
  2028. profile=profile,
  2029. )
  2030. items.extend(source_items)
  2031. excluded.extend(source_excluded)
  2032. source_snapshots.append(
  2033. _source_snapshot(
  2034. source.path,
  2035. source_id=source.id,
  2036. extra_exclusions=config.extra_exclusions,
  2037. profile=profile,
  2038. )
  2039. )
  2040. sources.append(
  2041. {
  2042. "id": source.id,
  2043. "category": "evidence" if unified else source.category,
  2044. "kind": source.kind,
  2045. "path": str(source.path),
  2046. "status": "pass",
  2047. }
  2048. )
  2049. if source.kind == "git_worktree" and include_git_bundle:
  2050. external_bundle, external_git = _create_git_bundle(
  2051. root=source.path,
  2052. source_id=source.id,
  2053. temp_root=temp_root,
  2054. )
  2055. items.append(external_bundle)
  2056. git_metadata.append(external_git)
  2057. evidence_canon_fields: dict[str, object] | None = None
  2058. include_process = include_process_evidence or profile == "review-debug"
  2059. if unified:
  2060. if evidence_root is not None:
  2061. staged = evidence_canon.stage_evidence_root(
  2062. evidence_root,
  2063. staging_root=temp_root / "canonical-evidence",
  2064. include_process_evidence=include_process,
  2065. )
  2066. for staged_file in staged.staged:
  2067. items.append(
  2068. PackageItem(
  2069. candidate=_candidate_from_path(
  2070. staged_file.absolute,
  2071. staged_file.relative,
  2072. ),
  2073. category="evidence",
  2074. source_id="evidence-root",
  2075. original_path=staged_file.original_path,
  2076. scan_archive=False,
  2077. )
  2078. )
  2079. excluded.extend(staged.excluded)
  2080. sources.append(
  2081. {
  2082. "id": "evidence-root",
  2083. "category": "evidence",
  2084. "kind": "directory",
  2085. "path": str(evidence_root.resolve()),
  2086. "status": "pass",
  2087. }
  2088. )
  2089. evidence_canon_fields = evidence_canon.build_evidence_canon_index_fields(
  2090. catalog=staged.catalog,
  2091. aliases=staged.aliases,
  2092. log_policy_actions=staged.log_policy_actions,
  2093. include_process_evidence=include_process,
  2094. profile=profile,
  2095. )
  2096. kept_items, filter_excluded, _remaps = evidence_canon.filter_package_items_for_compact(
  2097. items,
  2098. profile=profile,
  2099. include_process_evidence=include_process,
  2100. )
  2101. items = list(kept_items)
  2102. excluded.extend(filter_excluded)
  2103. # Workspace allowlist remaps + evidence-root staging can both land on the
  2104. # same canonical evidence/ path; keep one physical copy (prefer evidence-root).
  2105. deduped: dict[str, PackageItem] = {}
  2106. for item in items:
  2107. key = handoff.windows_collision_key(item.candidate.relative)
  2108. previous = deduped.get(key)
  2109. if previous is None:
  2110. deduped[key] = item
  2111. continue
  2112. prefer_new = item.source_id == "evidence-root" and previous.source_id != "evidence-root"
  2113. keep, drop = (item, previous) if prefer_new else (previous, item)
  2114. deduped[key] = keep
  2115. excluded.append(
  2116. {
  2117. "path": drop.original_path or drop.candidate.relative,
  2118. "rule": "canonical_path_physical_dedup",
  2119. }
  2120. )
  2121. if evidence_canon_fields is not None:
  2122. aliases = list(evidence_canon_fields.get("aliases") or [])
  2123. aliases.append(
  2124. {
  2125. "physical_path": keep.candidate.relative,
  2126. "logical_paths": [
  2127. f"evidence/from/{drop.original_path or drop.candidate.relative}"
  2128. ],
  2129. "reason": "canonical_path_physical_dedup",
  2130. }
  2131. )
  2132. evidence_canon_fields["aliases"] = aliases
  2133. items = list(deduped.values())
  2134. if evidence_canon_fields is None:
  2135. evidence_canon_fields = evidence_canon.build_evidence_canon_index_fields(
  2136. catalog=[
  2137. {
  2138. "key": key,
  2139. "canonical_path": evidence_canon.load_allowlist().by_key[key].canonical_path,
  2140. "role": "compact_default",
  2141. "source_original": None,
  2142. }
  2143. for key in evidence_canon.compact_default_key_list()
  2144. ],
  2145. aliases=[],
  2146. log_policy_actions=[],
  2147. include_process_evidence=include_process,
  2148. profile=profile,
  2149. )
  2150. # Record workspace allowlisted evidence that survived filtering.
  2151. present = {item.candidate.relative.casefold() for item in items}
  2152. catalog = list(evidence_canon_fields.get("catalog", [])) # type: ignore[arg-type]
  2153. allowlist = evidence_canon.load_allowlist()
  2154. for entry in allowlist.canonical_entries:
  2155. if entry.canonical_path.casefold() in present and not any(
  2156. str(row.get("canonical_path", "")).casefold() == entry.canonical_path.casefold()
  2157. for row in catalog
  2158. ):
  2159. catalog.append(
  2160. {
  2161. "key": entry.key,
  2162. "canonical_path": entry.canonical_path,
  2163. "role": "compact_default",
  2164. "source_original": "workspace",
  2165. }
  2166. )
  2167. evidence_canon_fields["catalog"] = sorted(catalog, key=lambda row: str(row["key"]))
  2168. evidence_canon_fields["compact_default_keys"] = sorted(
  2169. {str(row["key"]) for row in catalog if row.get("role") == "compact_default"}
  2170. )
  2171. # Drop any stale embedded final-ZIP selftest receipt (recursive hash hazard).
  2172. filtered_items: list[PackageItem] = []
  2173. for item in items:
  2174. rel = item.candidate.relative.replace("\\", "/")
  2175. if rel == _STALE_EMBEDDED_COMPACT_SELFTEST or rel.endswith(
  2176. "/" + _STALE_EMBEDDED_COMPACT_SELFTEST
  2177. ):
  2178. excluded.append(
  2179. {
  2180. "path": item.original_path or rel,
  2181. "rule": "stale_embedded_compact_selftest_forbidden",
  2182. }
  2183. )
  2184. continue
  2185. if rel.rsplit("/", 1)[-1].casefold() == "compact-package-selftest.json":
  2186. excluded.append(
  2187. {
  2188. "path": item.original_path or rel,
  2189. "rule": "stale_embedded_compact_selftest_forbidden",
  2190. }
  2191. )
  2192. continue
  2193. filtered_items.append(item)
  2194. items = filtered_items
  2195. items.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
  2196. excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
  2197. return AnalysisCollection(
  2198. status="pass_with_warnings" if warnings else "pass",
  2199. items=tuple(items),
  2200. excluded=tuple(excluded),
  2201. warnings=tuple(warnings),
  2202. sources=tuple(sources),
  2203. git=tuple(git_metadata),
  2204. source_snapshots=tuple(source_snapshots),
  2205. evidence_canon=evidence_canon_fields,
  2206. )
  2207. def find_7z() -> Path | None:
  2208. discovered = shutil.which("7z") or shutil.which("7zz")
  2209. candidates = [
  2210. Path(discovered) if discovered else None,
  2211. Path(r"C:\Program Files\7-Zip\7z.exe"),
  2212. Path(r"C:\Program Files (x86)\7-Zip\7z.exe"),
  2213. ]
  2214. for candidate in candidates:
  2215. if candidate is not None and candidate.is_file():
  2216. return candidate.resolve(strict=True)
  2217. return None
  2218. def build_7zip_create_command(archive_path: Path, staging_root: Path) -> list[str]:
  2219. del staging_root
  2220. return [
  2221. "a",
  2222. "-tzip",
  2223. "-mm=Deflate",
  2224. "-mx=9",
  2225. "-mmt",
  2226. "-y",
  2227. "-r",
  2228. str(archive_path),
  2229. "CPLD\\*",
  2230. ]
  2231. def _run_7z(seven_zip: Path, arguments: list[str], *, cwd: Path) -> str:
  2232. try:
  2233. completed = subprocess.run(
  2234. [str(seven_zip), *arguments],
  2235. cwd=cwd,
  2236. stdout=subprocess.PIPE,
  2237. stderr=subprocess.STDOUT,
  2238. text=True,
  2239. encoding="utf-8",
  2240. errors="replace",
  2241. timeout=300,
  2242. check=False,
  2243. )
  2244. except (OSError, subprocess.TimeoutExpired) as exc:
  2245. raise PackagingError("unable to run 7-Zip for archive inspection") from exc
  2246. if completed.returncode != 0:
  2247. detail = completed.stdout.strip().splitlines()
  2248. suffix = f": {detail[-1]}" if detail else ""
  2249. raise PackagingError(f"7-Zip archive inspection failed{suffix}")
  2250. return completed.stdout
  2251. def _rename_archive_entries(
  2252. seven_zip: Path,
  2253. archive_path: Path,
  2254. renames: list[tuple[str, str]],
  2255. ) -> None:
  2256. for offset in range(0, len(renames), 64):
  2257. batch = renames[offset : offset + 64]
  2258. arguments = ["rn", "-y", str(archive_path)]
  2259. for old_name, new_name in batch:
  2260. arguments.extend((old_name, new_name))
  2261. _run_7z(seven_zip, arguments, cwd=archive_path.parent)
  2262. def _parse_7z_members(payload: str, archive_label: str) -> list[dict[str, str]]:
  2263. in_members = False
  2264. current: dict[str, str] = {}
  2265. members: list[dict[str, str]] = []
  2266. for raw_line in payload.splitlines():
  2267. line = raw_line.rstrip("\r\n")
  2268. if line.strip() == "----------":
  2269. in_members = True
  2270. current = {}
  2271. continue
  2272. if not in_members:
  2273. continue
  2274. if not line.strip():
  2275. if current:
  2276. members.append(current)
  2277. current = {}
  2278. continue
  2279. key, separator, value = line.partition(" = ")
  2280. if separator:
  2281. current[key.strip()] = value.strip()
  2282. if current:
  2283. members.append(current)
  2284. for member in members:
  2285. raw_path = member.get("Path", "")
  2286. normalized = raw_path.replace("\\", "/")
  2287. if not normalized or normalized.startswith("/") or re.match(r"^[A-Za-z]:", normalized):
  2288. raise PackagingError(f"unsafe archive member path in {archive_label}")
  2289. handoff.normalize_relative(normalized.split("/"))
  2290. if member.get("Encrypted") not in {None, "", "-"}:
  2291. raise PackagingError(f"encrypted archive member is unsupported in {archive_label}")
  2292. if member.get("Symbolic Link") or member.get("Hard Link"):
  2293. raise PackagingError(f"archive link member is unsupported in {archive_label}")
  2294. if member.get("Alternate Stream") not in {None, "", "-"}:
  2295. raise PackagingError(f"archive alternate stream is unsupported in {archive_label}")
  2296. if member.get("Split Before") not in {None, "", "-"} or member.get("Split After") not in {
  2297. None,
  2298. "",
  2299. "-",
  2300. }:
  2301. raise PackagingError(f"split archive member is unsupported in {archive_label}")
  2302. return members
  2303. def _inspect_and_extract_unsupported_archive(
  2304. item: PackageItem,
  2305. *,
  2306. temp_root: Path,
  2307. seven_zip: Path,
  2308. extra_exclusions: tuple[dict[str, str], ...],
  2309. ) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
  2310. listing = _run_7z(
  2311. seven_zip,
  2312. ["l", "-slt", "-sccUTF-8", str(item.candidate.absolute)],
  2313. cwd=item.candidate.absolute.parent,
  2314. )
  2315. members = _parse_7z_members(listing, item.candidate.relative)
  2316. file_members = [
  2317. member
  2318. for member in members
  2319. if member.get("Folder") != "+" and "D" not in member.get("Attributes", "")
  2320. ]
  2321. expected_bytes = sum(int(member.get("Size") or "0") for member in file_members)
  2322. token = hashlib.sha256(item.candidate.relative.encode("utf-8")).hexdigest()[:16]
  2323. extract_root = temp_root / "expanded-archives" / token
  2324. extract_root.mkdir(parents=True, exist_ok=False)
  2325. _run_7z(
  2326. seven_zip,
  2327. ["x", "-y", "-aoa", "-sccUTF-8", f"-o{extract_root}", str(item.candidate.absolute)],
  2328. cwd=item.candidate.absolute.parent,
  2329. )
  2330. actual_files = [path for path in extract_root.rglob("*") if path.is_file()]
  2331. actual_bytes = sum(path.stat().st_size for path in actual_files)
  2332. if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
  2333. raise PackagingError(
  2334. f"archive extraction inventory mismatch: {item.candidate.relative} "
  2335. f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
  2336. )
  2337. expanded_candidates, expanded_excluded, _ = scan_analysis_root(
  2338. extract_root,
  2339. extra_exclusions=extra_exclusions,
  2340. )
  2341. handoff.audit_candidates(expanded_candidates)
  2342. expanded_prefix = f"{item.candidate.relative}.expanded"
  2343. expanded_items = [
  2344. PackageItem(
  2345. candidate=_rebase_candidate(candidate, expanded_prefix),
  2346. category=item.category,
  2347. source_id=item.source_id,
  2348. original_path=f"{item.original_path}!/{candidate.relative}",
  2349. scan_archive=True,
  2350. )
  2351. for candidate in expanded_candidates
  2352. ]
  2353. rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
  2354. sensitive_rules = {
  2355. "credential_or_license_file",
  2356. "credential_configuration_file",
  2357. "private_key_file",
  2358. "secret_environment_file",
  2359. "cloud_credential_file",
  2360. "container_registry_credential_file",
  2361. }
  2362. contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
  2363. return expanded_items, rebased_excluded, contains_sensitive
  2364. def _inspect_and_extract_zip_archive(
  2365. item: PackageItem,
  2366. *,
  2367. temp_root: Path,
  2368. extra_exclusions: tuple[dict[str, str], ...],
  2369. ) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
  2370. archive_label = item.candidate.relative
  2371. try:
  2372. with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
  2373. file_members: list[zipfile.ZipInfo] = []
  2374. expected_bytes = 0
  2375. for info in archive.infolist():
  2376. normalized = info.filename.replace("\\", "/")
  2377. if (
  2378. not normalized
  2379. or normalized.startswith("/")
  2380. or re.match(r"^[A-Za-z]:", normalized)
  2381. ):
  2382. raise PackagingError(
  2383. f"unsafe archive member path in {archive_label}"
  2384. )
  2385. handoff.normalize_relative(normalized.split("/"))
  2386. if info.flag_bits & 0x1:
  2387. raise PackagingError(
  2388. f"encrypted archive member is unsupported in {archive_label}"
  2389. )
  2390. member_mode = (info.external_attr >> 16) & 0xFFFF
  2391. member_type = stat.S_IFMT(member_mode)
  2392. if info.is_dir():
  2393. if (
  2394. info.file_size != 0
  2395. or info.compress_size != 0
  2396. or member_type not in {0, stat.S_IFDIR}
  2397. ):
  2398. raise PackagingError(
  2399. f"unsafe archive member type in {archive_label}"
  2400. )
  2401. continue
  2402. if member_type not in {0, stat.S_IFREG}:
  2403. raise PackagingError(
  2404. f"unsafe archive member type in {archive_label}"
  2405. )
  2406. file_members.append(info)
  2407. expected_bytes += info.file_size
  2408. except (OSError, zipfile.BadZipFile) as exc:
  2409. raise PackagingError(
  2410. f"unable to inspect source archive: {archive_label}"
  2411. ) from exc
  2412. token = hashlib.sha256(archive_label.encode("utf-8")).hexdigest()[:16]
  2413. extract_root = temp_root / "expanded-archives" / token
  2414. extract_root.mkdir(parents=True, exist_ok=False)
  2415. actual_files: list[Path] = []
  2416. actual_bytes = 0
  2417. try:
  2418. with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
  2419. for info in file_members:
  2420. parts = info.filename.replace("\\", "/").split("/")
  2421. target_path = extract_root / Path(*parts)
  2422. target_path.parent.mkdir(parents=True, exist_ok=True)
  2423. with archive.open(info, "r") as source, target_path.open("wb") as destination:
  2424. shutil.copyfileobj(source, destination, length=1024 * 1024)
  2425. actual_files.append(target_path)
  2426. actual_bytes += target_path.stat().st_size
  2427. except (OSError, zipfile.BadZipFile) as exc:
  2428. raise PackagingError(
  2429. f"unable to extract source archive: {archive_label}"
  2430. ) from exc
  2431. if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
  2432. raise PackagingError(
  2433. f"archive extraction inventory mismatch: {archive_label} "
  2434. f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
  2435. )
  2436. expanded_candidates, expanded_excluded, _ = scan_analysis_root(
  2437. extract_root,
  2438. extra_exclusions=extra_exclusions,
  2439. )
  2440. handoff.audit_candidates(expanded_candidates)
  2441. expanded_prefix = f"{archive_label}.expanded"
  2442. expanded_items = [
  2443. PackageItem(
  2444. candidate=_rebase_candidate(candidate, expanded_prefix),
  2445. category=item.category,
  2446. source_id=item.source_id,
  2447. original_path=f"{item.original_path}!/{candidate.relative}",
  2448. scan_archive=True,
  2449. )
  2450. for candidate in expanded_candidates
  2451. ]
  2452. rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
  2453. sensitive_rules = {
  2454. "credential_or_license_file",
  2455. "credential_configuration_file",
  2456. "private_key_file",
  2457. "secret_environment_file",
  2458. "cloud_credential_file",
  2459. "container_registry_credential_file",
  2460. }
  2461. contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
  2462. return expanded_items, rebased_excluded, contains_sensitive
  2463. def prepare_unsupported_archives(
  2464. items: tuple[PackageItem, ...],
  2465. *,
  2466. temp_root: Path,
  2467. seven_zip: Path | None,
  2468. extra_exclusions: tuple[dict[str, str], ...],
  2469. ) -> ArchivePreparation:
  2470. prepared: list[PackageItem] = []
  2471. excluded: list[dict[str, str]] = []
  2472. warnings: list[dict[str, str]] = []
  2473. temp_root.mkdir(parents=True, exist_ok=True)
  2474. for item in items:
  2475. archive_kind = handoff.archive_kind(item.candidate.relative)
  2476. if archive_kind is None:
  2477. prepared.append(item)
  2478. continue
  2479. if archive_kind == "zip":
  2480. expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_zip_archive(
  2481. item,
  2482. temp_root=temp_root,
  2483. extra_exclusions=extra_exclusions,
  2484. )
  2485. elif seven_zip is None:
  2486. if _is_reference_item(item):
  2487. warnings.append(
  2488. {
  2489. "code": "unsupported_archive_without_7zip",
  2490. "source_id": item.source_id,
  2491. "path": item.candidate.relative,
  2492. "message": "7-Zip is unavailable; unsupported archive kept unexpanded",
  2493. }
  2494. )
  2495. prepared.append(item._replace(scan_archive=False))
  2496. continue
  2497. if item.candidate.absolute.is_file():
  2498. raise PackagingError(
  2499. "7-Zip is required to inspect unsupported source archives"
  2500. )
  2501. prepared.append(item._replace(scan_archive=False))
  2502. continue
  2503. else:
  2504. expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_unsupported_archive(
  2505. item,
  2506. temp_root=temp_root,
  2507. seven_zip=seven_zip,
  2508. extra_exclusions=extra_exclusions,
  2509. )
  2510. has_filtered_members = bool(expanded_excluded)
  2511. if has_filtered_members:
  2512. prepared.extend(expanded_items)
  2513. excluded.extend(expanded_excluded)
  2514. if contains_sensitive:
  2515. excluded.append(
  2516. {
  2517. "path": item.candidate.relative,
  2518. "rule": "unsupported_archive_contains_sensitive_content",
  2519. }
  2520. )
  2521. elif has_filtered_members:
  2522. excluded.append(
  2523. {
  2524. "path": item.candidate.relative,
  2525. "rule": "archive_contains_excluded_members",
  2526. }
  2527. )
  2528. else:
  2529. prepared.append(item._replace(scan_archive=archive_kind != "unsupported"))
  2530. prepared.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
  2531. excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
  2532. return ArchivePreparation(
  2533. items=tuple(prepared),
  2534. excluded=tuple(excluded),
  2535. warnings=tuple(warnings),
  2536. )
  2537. def _utc_now() -> str:
  2538. return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
  2539. def _validate_package_name(package_name: str) -> None:
  2540. try:
  2541. collision_key = handoff.windows_collision_key(package_name)
  2542. except PackagingError as exc:
  2543. raise PackagingError("package name is not a portable Windows file name") from exc
  2544. if (
  2545. not handoff.SAFE_PACKAGE_NAME.fullmatch(package_name)
  2546. or package_name in {".", ".."}
  2547. or not collision_key
  2548. ):
  2549. raise PackagingError("package name is not a portable Windows file name")
  2550. def _item_sort_key(item: PackageItem) -> tuple[int, str, str]:
  2551. return (
  2552. CATEGORY_ORDER.get(item.category, len(CATEGORY_ORDER)),
  2553. item.category.casefold(),
  2554. handoff.windows_collision_key(item.candidate.relative),
  2555. )
  2556. def _path_basename(relative: str) -> str:
  2557. return relative.casefold().rsplit("/", 1)[-1]
  2558. def _is_board_viewer_generated_path(relative: str) -> bool:
  2559. lower = relative.casefold()
  2560. return (
  2561. "board-viewer-generated" in lower
  2562. or handoff.is_under(lower, "evidence/board-viewer")
  2563. or "/tools/board-viewer/generated/" in f"/{lower}/"
  2564. or lower.startswith("tools/board-viewer/generated/")
  2565. )
  2566. def _is_reference_original_path(relative: str) -> bool:
  2567. lower = f"/{relative.casefold()}/"
  2568. return "/reference/original/" in lower or lower.startswith("/reference/original/")
  2569. def _dedup_canonical_path(paths: list[str]) -> str:
  2570. # Prefer compact evidence allowlist canonical paths first (P4).
  2571. try:
  2572. preferred = evidence_canon.prefer_canonical_path(paths)
  2573. if evidence_canon.is_compact_allowlisted(preferred):
  2574. return preferred
  2575. except ValueError:
  2576. pass
  2577. def rank(path: str) -> tuple[int, int, str]:
  2578. name = _path_basename(path)
  2579. in_reference = _is_reference_original_path(path)
  2580. in_generated = _is_board_viewer_generated_path(path)
  2581. if name in BOARD_VIEWER_GENERATED_ASSETS or name in DERIVED_BOARD_VIEWER_ASSETS:
  2582. return (0 if in_generated else 1, 0 if in_reference else 1, path.casefold())
  2583. if name.endswith((".brd", ".pdf", ".dsn", ".sch")):
  2584. return (0 if in_reference else 1, 0 if in_generated else 1, path.casefold())
  2585. return (0 if in_reference else 1, 0 if in_generated else 1, path.casefold())
  2586. return sorted(paths, key=rank)[0]
  2587. def _is_software_source_package_path(relative: str) -> bool:
  2588. """Tracked software under source/ must keep its canonical path (no content-dedup drop)."""
  2589. lower = relative.casefold()
  2590. if not lower.startswith("source/"):
  2591. return False
  2592. # Derived board-viewer / heavy design originals should not live under source/
  2593. # in review-compact; if they do, still protect software extensions.
  2594. name = _path_basename(relative)
  2595. if name in DERIVED_BOARD_VIEWER_ASSETS or name.endswith((".brd", ".pdf", ".dsn")):
  2596. return False
  2597. return True
  2598. def _should_content_dedup(size: int, relative: str) -> bool:
  2599. # Never content-dedup tracked software under source/. A generated SBY/workdir
  2600. # copy with identical bytes must not replace the authoritative source path.
  2601. lower = relative.casefold()
  2602. if _is_software_source_package_path(relative):
  2603. return False
  2604. # Finalize layout requires both canonical and legacy git SHA maps as physical members.
  2605. base = _path_basename(relative)
  2606. if base in {"source-file-sha256.json", "file-sha256.json"} and "/meta/git/" in f"/{lower}":
  2607. return False
  2608. name = base
  2609. if name in DERIVED_BOARD_VIEWER_ASSETS or name.endswith((".brd", ".pdf")):
  2610. return True
  2611. if evidence_canon.is_compact_allowlisted(relative):
  2612. return True
  2613. return size >= CONTENT_DEDUP_MIN_BYTES
  2614. def apply_content_dedup(
  2615. items: tuple[PackageItem, ...],
  2616. inventory: list[dict[str, object]],
  2617. ) -> tuple[tuple[PackageItem, ...], list[dict[str, object]], list[dict[str, str]]]:
  2618. """Keep one physical copy per identical content hash; record logical aliases.
  2619. Content dedup is only for evidence aliases / board-viewer / heavy originals /
  2620. large non-source twins. Authoritative ``source/`` software is never grouped
  2621. (see ``_should_content_dedup``), so generated workdir copies cannot replace it.
  2622. """
  2623. by_path = {str(row["path"]): row for row in inventory}
  2624. groups: dict[str, list[PackageItem]] = {}
  2625. for item in items:
  2626. row = by_path[item.candidate.relative]
  2627. sha = str(row["sha256"])
  2628. size = int(row["size"])
  2629. if not _should_content_dedup(size, item.candidate.relative):
  2630. continue
  2631. groups.setdefault(sha, []).append(item)
  2632. drop_paths: set[str] = set()
  2633. dedup_records: list[dict[str, object]] = []
  2634. excluded: list[dict[str, str]] = []
  2635. for sha, group in sorted(groups.items(), key=lambda pair: pair[0]):
  2636. if len(group) < 2:
  2637. continue
  2638. paths = [item.candidate.relative for item in group]
  2639. canonical = _dedup_canonical_path(paths)
  2640. aliases = sorted(path for path in paths if path != canonical)
  2641. # Absolute guard: never drop software source even if mis-grouped.
  2642. aliases = [path for path in aliases if not _is_software_source_package_path(path)]
  2643. if not aliases:
  2644. continue
  2645. if _is_software_source_package_path(canonical):
  2646. # Prefer keeping software source as physical; aliases are non-source.
  2647. pass
  2648. size = int(by_path[canonical]["size"])
  2649. dedup_records.append(
  2650. {
  2651. "sha256": sha,
  2652. "size": size,
  2653. "physical_path": canonical,
  2654. "logical_paths": aliases,
  2655. "reason": "identical_content_single_physical_copy",
  2656. }
  2657. )
  2658. for alias in aliases:
  2659. drop_paths.add(alias)
  2660. excluded.append(
  2661. {
  2662. "path": alias,
  2663. "rule": "duplicate_content_logical_alias",
  2664. }
  2665. )
  2666. physical_items = tuple(
  2667. item for item in items if item.candidate.relative not in drop_paths
  2668. )
  2669. dedup_records.sort(key=lambda row: str(row["physical_path"]).casefold())
  2670. excluded.sort(key=lambda row: handoff.windows_collision_key(row["path"]))
  2671. return physical_items, dedup_records, excluded
  2672. def classify_derived_evidence(items: tuple[PackageItem, ...]) -> list[dict[str, object]]:
  2673. derived: list[dict[str, object]] = []
  2674. for item in items:
  2675. name = _path_basename(item.candidate.relative)
  2676. if name not in DERIVED_BOARD_VIEWER_ASSETS:
  2677. continue
  2678. if not _is_board_viewer_generated_path(item.candidate.relative):
  2679. continue
  2680. role = "derived_from_brd_visual" if name in BOARD_VIEWER_GENERATED_ASSETS else "derived_from_brd_parsed"
  2681. derived.append(
  2682. {
  2683. "path": item.candidate.relative,
  2684. "asset": name,
  2685. "role": role,
  2686. "authority": "analysis_evidence_not_source_closure",
  2687. "note": "Derived from the original Allegro BRD for remote analysis; not RTL/TD source closure.",
  2688. }
  2689. )
  2690. derived.sort(key=lambda row: str(row["path"]).casefold())
  2691. return derived
  2692. def replay_analysis_package(package_dir: Path, *, extract_root: Path) -> dict[str, object]:
  2693. """Extract a published package and verify SHA256SUMS plus inventory hashes.
  2694. Returns package-content verification plus the four-state replay skeleton:
  2695. ``package_content_replay``, ``detached_software_replay`` (not_run here),
  2696. ``reference_regeneration_replay=not_packaged_by_policy``,
  2697. ``hardware_validation=not_run``. Full detached software orchestration lives in
  2698. ``tools/replay_review_compact.py``.
  2699. """
  2700. package_dir = package_dir.expanduser().resolve(strict=True)
  2701. extract_root = extract_root.expanduser().resolve(strict=False)
  2702. if extract_root.exists():
  2703. raise PackagingError(f"replay extract root already exists: {extract_root}")
  2704. index_path = package_dir / "HANDOFF-INDEX.json"
  2705. sums_path = package_dir / "SHA256SUMS.txt"
  2706. exclusions_path = package_dir / "EXCLUSIONS.txt"
  2707. if not index_path.is_file() or not sums_path.is_file():
  2708. raise PackagingError("package directory is missing HANDOFF-INDEX.json or SHA256SUMS.txt")
  2709. index = json.loads(index_path.read_text(encoding="utf-8"))
  2710. extract_root.mkdir(parents=True, exist_ok=False)
  2711. zip_extract_root = extract_root / "from-zip"
  2712. tar_extract_root = extract_root / "from-tar-zst"
  2713. zip_extract_root.mkdir(parents=True, exist_ok=True)
  2714. verified_volumes: list[dict[str, object]] = []
  2715. verified_sidecars: list[dict[str, object]] = []
  2716. tar_zst_name: str | None = None
  2717. for line in sums_path.read_text(encoding="ascii").splitlines():
  2718. line = line.strip()
  2719. if not line or line.startswith("#"):
  2720. continue
  2721. digest, _, name = line.partition(" ")
  2722. if not digest or not name:
  2723. raise PackagingError(f"invalid SHA256SUMS line: {line}")
  2724. member_path = package_dir / name
  2725. actual = handoff.sha256_file(member_path)
  2726. if actual != digest:
  2727. raise PackagingError(f"SHA256SUMS mismatch for {name}")
  2728. lower = name.casefold()
  2729. if lower.endswith(".zip"):
  2730. with zipfile.ZipFile(member_path, "r", allowZip64=True) as archive:
  2731. archive.extractall(zip_extract_root)
  2732. verified_volumes.append({"file": name, "sha256": actual})
  2733. elif lower.endswith(".tar.zst"):
  2734. tar_zst_name = name
  2735. tar_extract_root.mkdir(parents=True, exist_ok=True)
  2736. completed = subprocess.run(
  2737. ["tar", "--zstd", "-xf", str(member_path), "-C", str(tar_extract_root)],
  2738. stdout=subprocess.PIPE,
  2739. stderr=subprocess.PIPE,
  2740. check=False,
  2741. )
  2742. if completed.returncode != 0:
  2743. raise PackagingError(
  2744. f"unable to extract tar.zst during replay: {name}: "
  2745. f"{completed.stderr.decode('utf-8', errors='replace').strip()}"
  2746. )
  2747. verified_sidecars.append({"file": name, "sha256": actual, "kind": "tar_zst"})
  2748. else:
  2749. verified_sidecars.append({"file": name, "sha256": actual, "kind": "sidecar"})
  2750. checked_files = 0
  2751. for item in index.get("files", []):
  2752. relative = str(item["path"])
  2753. target = zip_extract_root / "CPLD" / Path(*relative.split("/"))
  2754. if not target.is_file():
  2755. raise PackagingError(f"replay missing extracted file: {relative}")
  2756. digest = handoff.sha256_file(target)
  2757. if digest != item["sha256"] or target.stat().st_size != int(item["size"]):
  2758. raise PackagingError(f"replay hash mismatch for {relative}")
  2759. if tar_zst_name is not None:
  2760. # tar.zst is created from ZIP extract roots, so the same CPLD tree must round-trip.
  2761. tar_target = tar_extract_root / "CPLD" / Path(*relative.split("/"))
  2762. if not tar_target.is_file():
  2763. raise PackagingError(f"tar.zst replay missing extracted file: {relative}")
  2764. if handoff.sha256_file(tar_target) != digest:
  2765. raise PackagingError(f"tar.zst replay hash mismatch for {relative}")
  2766. checked_files += 1
  2767. for record in index.get("content_dedup", []):
  2768. physical = zip_extract_root / "CPLD" / Path(*str(record["physical_path"]).split("/"))
  2769. if not physical.is_file():
  2770. raise PackagingError(f"replay missing dedup physical file: {record['physical_path']}")
  2771. for alias in record.get("logical_paths", []):
  2772. alias_path = zip_extract_root / "CPLD" / Path(*str(alias).split("/"))
  2773. if alias_path.exists():
  2774. raise PackagingError(f"replay found duplicated physical alias path: {alias}")
  2775. cpld_root = zip_extract_root / "CPLD"
  2776. return {
  2777. "status": "pass",
  2778. "mode": "package_replay",
  2779. "package_dir": str(package_dir),
  2780. "extract_root": str(extract_root),
  2781. "cpld_root": str(cpld_root) if cpld_root.is_dir() else None,
  2782. "volumes": verified_volumes,
  2783. "sidecars": verified_sidecars,
  2784. "exclusions_present": exclusions_path.is_file(),
  2785. "tar_zst": tar_zst_name,
  2786. "checked_files": checked_files,
  2787. "content_dedup_groups": len(index.get("content_dedup", [])),
  2788. "derived_evidence_count": len(index.get("derived_evidence", [])),
  2789. # Four-state skeleton (content only; software lane filled by replay_review_compact).
  2790. "package_content_replay": "pass",
  2791. "detached_software_replay": "not_run",
  2792. "reference_regeneration_replay": "not_packaged_by_policy",
  2793. "hardware_validation": "not_run",
  2794. }
  2795. def _audit_one_item(item: PackageItem) -> dict[str, object]:
  2796. if item.scan_archive:
  2797. file_inventory = handoff.stream_candidate(item.candidate)
  2798. else:
  2799. file_inventory = handoff.hash_candidate(item.candidate)
  2800. return {
  2801. **file_inventory,
  2802. "archive_path": f"CPLD/{item.candidate.relative}",
  2803. "category": item.category,
  2804. "source_id": item.source_id,
  2805. "original_path": item.original_path,
  2806. }
  2807. def _audit_package_items(items: tuple[PackageItem, ...]) -> list[dict[str, object]]:
  2808. sorted_items = sorted(items, key=_item_sort_key)
  2809. collision_paths: dict[str, str] = {}
  2810. for item in sorted_items:
  2811. key = handoff.windows_collision_key(item.candidate.relative)
  2812. previous = collision_paths.get(key)
  2813. if previous is not None:
  2814. raise PackagingError(
  2815. f"analysis inputs contain a Windows path collision: {previous} and {item.candidate.relative}"
  2816. )
  2817. collision_paths[key] = item.candidate.relative
  2818. max_workers = os.cpu_count() or 1
  2819. with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
  2820. return list(executor.map(_audit_one_item, sorted_items))
  2821. def _write_unscanned_candidate(
  2822. archive: zipfile.ZipFile,
  2823. item: PackageItem,
  2824. ) -> dict[str, object]:
  2825. candidate = item.candidate
  2826. digest = hashlib.sha256()
  2827. total = 0
  2828. secret_tail = b""
  2829. entry_name = f"CPLD/{candidate.relative}"
  2830. try:
  2831. with archive.open(handoff.zip_info(entry_name, candidate.mode), "w", force_zip64=True) as target:
  2832. with handoff.open_candidate(candidate) as source:
  2833. for chunk in iter(lambda: source.read(1024 * 1024), b""):
  2834. secret_tail = handoff.scan_secret_markers(
  2835. chunk,
  2836. secret_tail,
  2837. candidate.relative,
  2838. )
  2839. target.write(chunk)
  2840. digest.update(chunk)
  2841. total += len(chunk)
  2842. except OSError as exc:
  2843. raise PackagingError(f"unable to package {candidate.relative}: {exc}") from exc
  2844. if total != candidate.size:
  2845. raise PackagingError(f"source size changed during packaging: {candidate.relative}")
  2846. return {"path": candidate.relative, "size": total, "sha256": digest.hexdigest()}
  2847. def _write_package_item(
  2848. archive: zipfile.ZipFile,
  2849. item: PackageItem,
  2850. ) -> dict[str, object]:
  2851. if item.scan_archive:
  2852. return handoff.write_candidate(archive, item.candidate)
  2853. return _write_unscanned_candidate(archive, item)
  2854. def _stage_package_item(
  2855. staging_root: Path,
  2856. item: PackageItem,
  2857. staging_name: str,
  2858. ) -> dict[str, object]:
  2859. target = staging_root / "CPLD" / staging_name
  2860. target.parent.mkdir(parents=True, exist_ok=True)
  2861. if item.scan_archive:
  2862. try:
  2863. with target.open("wb") as destination:
  2864. return handoff.stream_candidate(item.candidate, target=destination)
  2865. except OSError as exc:
  2866. raise PackagingError(f"unable to stage {item.candidate.relative}: {exc}") from exc
  2867. digest = hashlib.sha256()
  2868. total = 0
  2869. secret_tail = b""
  2870. try:
  2871. with handoff.open_candidate(item.candidate) as source, target.open("wb") as destination:
  2872. for chunk in iter(lambda: source.read(1024 * 1024), b""):
  2873. secret_tail = handoff.scan_secret_markers(
  2874. chunk,
  2875. secret_tail,
  2876. item.candidate.relative,
  2877. )
  2878. destination.write(chunk)
  2879. digest.update(chunk)
  2880. total += len(chunk)
  2881. except OSError as exc:
  2882. raise PackagingError(f"unable to stage {item.candidate.relative}: {exc}") from exc
  2883. if total != item.candidate.size:
  2884. raise PackagingError(f"source size changed during staging: {item.candidate.relative}")
  2885. return {"path": item.candidate.relative, "size": total, "sha256": digest.hexdigest()}
  2886. def _volume_manifest(
  2887. *,
  2888. run_id: str,
  2889. package_name: str,
  2890. number: int,
  2891. count: int,
  2892. items: list[PackageItem],
  2893. inventory_by_path: dict[str, dict[str, object]],
  2894. ) -> dict[str, object]:
  2895. categories = sorted({item.category for item in items})
  2896. entries = [inventory_by_path[item.candidate.relative] for item in items]
  2897. return {
  2898. "schema": "cpld-agent-analysis-volume-v1",
  2899. "run_id": run_id,
  2900. "package_name": package_name,
  2901. "volume_number": number,
  2902. "volume_count": count,
  2903. "categories": categories,
  2904. "file_count": len(entries),
  2905. "uncompressed_bytes": sum(int(entry["size"]) for entry in entries),
  2906. "files": entries,
  2907. }
  2908. def _write_volume(
  2909. path: Path,
  2910. *,
  2911. run_id: str,
  2912. package_name: str,
  2913. number: int,
  2914. count: int,
  2915. items: list[PackageItem],
  2916. inventory_by_path: dict[str, dict[str, object]],
  2917. ) -> dict[str, object]:
  2918. manifest = _volume_manifest(
  2919. run_id=run_id,
  2920. package_name=package_name,
  2921. number=number,
  2922. count=count,
  2923. items=items,
  2924. inventory_by_path=inventory_by_path,
  2925. )
  2926. manifest_name = "CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json"
  2927. manifest_payload = handoff.json_bytes(manifest)
  2928. written_inventory: list[dict[str, object]] = []
  2929. try:
  2930. with zipfile.ZipFile(
  2931. path,
  2932. "w",
  2933. compression=zipfile.ZIP_DEFLATED,
  2934. compresslevel=9,
  2935. allowZip64=True,
  2936. ) as archive:
  2937. for item in sorted(items, key=_item_sort_key):
  2938. expected = inventory_by_path[item.candidate.relative]
  2939. if item.scan_archive:
  2940. actual = handoff.write_candidate(archive, item.candidate)
  2941. else:
  2942. actual = _write_unscanned_candidate(archive, item)
  2943. if (
  2944. actual["size"] != expected["size"]
  2945. or actual["sha256"] != expected["sha256"]
  2946. ):
  2947. raise PackagingError(
  2948. f"source changed while writing ZIP: {item.candidate.relative}"
  2949. )
  2950. written_inventory.append(actual)
  2951. with archive.open(
  2952. handoff.zip_info(manifest_name), "w", force_zip64=True
  2953. ) as target:
  2954. target.write(manifest_payload)
  2955. except (OSError, zipfile.BadZipFile) as exc:
  2956. raise PackagingError(f"unable to create ZIP volume: {exc}") from exc
  2957. expected_names = {f"CPLD/{item.candidate.relative}" for item in items}
  2958. expected_names.add(manifest_name)
  2959. handoff.verify_archive(
  2960. path,
  2961. expected_names=expected_names,
  2962. inventory=written_inventory,
  2963. expected_payloads={manifest_name: manifest_payload},
  2964. )
  2965. return {
  2966. "file": path.name,
  2967. "volume_number": number,
  2968. "volume_count": count,
  2969. "categories": manifest["categories"],
  2970. "file_count": len(items),
  2971. "uncompressed_bytes": manifest["uncompressed_bytes"],
  2972. "compressed_bytes": path.stat().st_size,
  2973. "sha256": handoff.sha256_file(path),
  2974. }
  2975. def _estimated_item_bytes(item: PackageItem) -> int:
  2976. return item.candidate.size + 512 + (len(item.candidate.relative.encode("utf-8")) * 2)
  2977. def _partition_items(
  2978. items: tuple[PackageItem, ...],
  2979. *,
  2980. target_zip_bytes: int,
  2981. ) -> list[list[PackageItem]]:
  2982. base_overhead = min(64_000, max(1_024, target_zip_bytes // 20))
  2983. groups: list[list[PackageItem]] = []
  2984. current: list[PackageItem] = []
  2985. current_category: str | None = None
  2986. estimated_bytes = base_overhead
  2987. for item in sorted(items, key=_item_sort_key):
  2988. item_estimate = _estimated_item_bytes(item)
  2989. if current and (
  2990. item.category != current_category
  2991. or estimated_bytes + item_estimate > target_zip_bytes
  2992. ):
  2993. groups.append(current)
  2994. current = []
  2995. estimated_bytes = base_overhead
  2996. if not current:
  2997. current_category = item.category
  2998. current.append(item)
  2999. estimated_bytes += item_estimate
  3000. if current:
  3001. groups.append(current)
  3002. return groups
  3003. def _split_oversized_groups(
  3004. staging: Path,
  3005. *,
  3006. run_id: str,
  3007. package_name: str,
  3008. groups: list[list[PackageItem]],
  3009. inventory_by_path: dict[str, dict[str, object]],
  3010. target_zip_bytes: int,
  3011. max_zip_bytes: int,
  3012. ) -> list[list[PackageItem]]:
  3013. pending = list(groups)
  3014. accepted: list[list[PackageItem]] = []
  3015. probe_number = 0
  3016. while pending:
  3017. group = pending.pop(0)
  3018. probe_number += 1
  3019. probe = staging / f".volume-probe-{probe_number:04d}.zip"
  3020. try:
  3021. _write_volume(
  3022. probe,
  3023. run_id=run_id,
  3024. package_name=package_name,
  3025. number=1,
  3026. count=1,
  3027. items=group,
  3028. inventory_by_path=inventory_by_path,
  3029. )
  3030. size = probe.stat().st_size
  3031. finally:
  3032. probe.unlink(missing_ok=True)
  3033. if size < max_zip_bytes and (size <= target_zip_bytes or len(group) == 1):
  3034. accepted.append(group)
  3035. continue
  3036. if len(group) == 1:
  3037. raise PackagingError(
  3038. f"single analysis file requires chunking before ZIP creation: {group[0].candidate.relative}"
  3039. )
  3040. middle = len(group) // 2
  3041. pending[0:0] = [group[:middle], group[middle:]]
  3042. return accepted
  3043. def _prepare_large_file_chunks(
  3044. staging: Path,
  3045. *,
  3046. run_id: str,
  3047. package_name: str,
  3048. items: tuple[PackageItem, ...],
  3049. inventory_by_path: dict[str, dict[str, object]],
  3050. target_zip_bytes: int,
  3051. max_zip_bytes: int,
  3052. ) -> tuple[tuple[PackageItem, ...], list[dict[str, object]], Path | None]:
  3053. packaged_items: list[PackageItem] = []
  3054. large_files: list[dict[str, object]] = []
  3055. chunk_root: Path | None = None
  3056. probe_number = 0
  3057. chunk_payload_bytes = max(1, (target_zip_bytes * 3) // 4)
  3058. for item in sorted(items, key=_item_sort_key):
  3059. must_probe = _estimated_item_bytes(item) > target_zip_bytes
  3060. if must_probe:
  3061. probe_number += 1
  3062. probe = staging / f".large-file-probe-{probe_number:04d}.zip"
  3063. try:
  3064. _write_volume(
  3065. probe,
  3066. run_id=run_id,
  3067. package_name=package_name,
  3068. number=1,
  3069. count=1,
  3070. items=[item],
  3071. inventory_by_path=inventory_by_path,
  3072. )
  3073. probe_size = probe.stat().st_size
  3074. finally:
  3075. probe.unlink(missing_ok=True)
  3076. if probe_size <= target_zip_bytes and probe_size < max_zip_bytes:
  3077. packaged_items.append(item)
  3078. continue
  3079. else:
  3080. packaged_items.append(item)
  3081. continue
  3082. if chunk_root is None:
  3083. chunk_root = staging / ".large-file-chunks"
  3084. chunk_root.mkdir()
  3085. original = inventory_by_path[item.candidate.relative]
  3086. file_id = hashlib.sha256(item.candidate.relative.encode("utf-8")).hexdigest()[:16]
  3087. file_chunk_root = chunk_root / file_id
  3088. file_chunk_root.mkdir()
  3089. file_name = Path(item.candidate.relative).name
  3090. chunks: list[dict[str, object]] = []
  3091. original_digest = hashlib.sha256()
  3092. original_bytes = 0
  3093. secret_tail = b""
  3094. with handoff.open_candidate(item.candidate) as source:
  3095. number = 0
  3096. while True:
  3097. payload = source.read(chunk_payload_bytes)
  3098. if not payload:
  3099. break
  3100. number += 1
  3101. secret_tail = handoff.scan_secret_markers(
  3102. payload,
  3103. secret_tail,
  3104. item.candidate.relative,
  3105. )
  3106. original_digest.update(payload)
  3107. original_bytes += len(payload)
  3108. chunk_name = f"{file_name}.part{number:04d}"
  3109. chunk_path = file_chunk_root / chunk_name
  3110. with chunk_path.open("xb") as handle:
  3111. handle.write(payload)
  3112. chunk_relative = f"HANDOFF-LARGE-FILES/{file_id}/{chunk_name}"
  3113. chunk_item = make_package_item(
  3114. chunk_path,
  3115. relative=chunk_relative,
  3116. category=item.category,
  3117. source_id=item.source_id,
  3118. scan_archive=False,
  3119. )
  3120. packaged_items.append(chunk_item)
  3121. chunks.append(
  3122. {
  3123. "number": number,
  3124. "path": chunk_relative,
  3125. "archive_path": f"CPLD/{chunk_relative}",
  3126. "size": len(payload),
  3127. "sha256": hashlib.sha256(payload).hexdigest(),
  3128. }
  3129. )
  3130. if original_bytes != original["size"] or original_digest.hexdigest() != original["sha256"]:
  3131. raise PackagingError(f"source changed while splitting large file: {item.candidate.relative}")
  3132. if len(chunks) < 2:
  3133. raise PackagingError(f"large file split did not produce multiple chunks: {item.candidate.relative}")
  3134. large_files.append(
  3135. {
  3136. "path": item.candidate.relative,
  3137. "category": item.category,
  3138. "source_id": item.source_id,
  3139. "original_path": item.original_path,
  3140. "size": original["size"],
  3141. "sha256": original["sha256"],
  3142. "chunks": chunks,
  3143. }
  3144. )
  3145. return tuple(packaged_items), large_files, chunk_root
  3146. def _assert_items_unchanged(
  3147. items: tuple[PackageItem, ...],
  3148. inventory_by_path: dict[str, dict[str, object]],
  3149. ) -> None:
  3150. for item in items:
  3151. current = handoff.hash_candidate(item.candidate)
  3152. expected = inventory_by_path[item.candidate.relative]
  3153. if current["size"] != expected["size"] or current["sha256"] != expected["sha256"]:
  3154. raise PackagingError(f"source changed during analysis packaging: {item.candidate.relative}")
  3155. def _assert_source_trees_unchanged(collection: AnalysisCollection, *, profile: str = "full") -> None:
  3156. for snapshot in collection.source_snapshots:
  3157. # Prefer the profile captured at collection time so review-compact
  3158. # snapshots are not re-scanned under the create_analysis_package default.
  3159. check_profile = snapshot.profile or profile
  3160. current = _source_snapshot(
  3161. snapshot.root,
  3162. source_id=snapshot.source_id,
  3163. extra_exclusions=snapshot.extra_exclusions,
  3164. profile=check_profile,
  3165. )
  3166. if (
  3167. current.candidates != snapshot.candidates
  3168. or current.excluded != snapshot.excluded
  3169. ):
  3170. raise PackagingError("source tree changed during analysis packaging: retry from a stable workspace snapshot")
  3171. def _start_here_text(package_name: str, volume_count: int, *, profile: str = "full") -> str:
  3172. base = (
  3173. f"# {package_name} 分析交付包\n\n"
  3174. f"本目录包含 {volume_count} 个互相独立的普通 ZIP,以及可选的 `.tar.zst` 同源归档。"
  3175. "请先核对 `SHA256SUMS.txt`,再把所有 ZIP 解压到同一个目录;"
  3176. "也可用 `tar --zstd -xf <package>.tar.zst` 还原。\n\n"
  3177. "`HANDOFF-INDEX.json` 记录每个原始文件的来源、目标卷、大小和 SHA-256,"
  3178. "`EXCLUSIONS.txt` 列出排除路径与规则,"
  3179. "以及 `excluded`(排除原因)、`derived_evidence`(由原始 BRD 派生的 board-viewer JSON/SVG,"
  3180. "不是 RTL/TD source closure)和 `content_dedup`(相同大文件只保留一份物理副本时的逻辑归属)。\n"
  3181. )
  3182. if handoff.uses_unified_layout(profile):
  3183. return base + (
  3184. "本包为统一布局:`source/` + `evidence/` + `meta/`。\n"
  3185. "`PACKAGE-PURPOSE.txt` 说明上传意图;`size-budget.json` 列出 ≥256KiB 或 >1% 体积的成员。\n"
  3186. "默认 **不含** 完整 Git bundle;`meta/git/` 提供 commit/status/log-20/tree/逐文件 SHA-256 "
  3187. "与 TD source-closure 绑定钩子。\n"
  3188. "成员计数:`member_count.indexed_files` 对应 ZIP 内业务文件;"
  3189. "`self_reference_control_files` 是包目录控制文件(亦列入 SHA256SUMS),"
  3190. "不要把控制文件与 ZIP payload 成员重复加总。\n"
  3191. )
  3192. return base + (
  3193. "完整 full 包必须包含 `git-history/*.bundle`,以便在干净提取后用 commit-to-commit "
  3194. "恢复 source closure 比对。\n"
  3195. )
  3196. def build_member_count_semantics(
  3197. *,
  3198. indexed_files: int,
  3199. zip_file_entries: int,
  3200. control_files: tuple[str, ...] = SELF_REFERENCE_CONTROL_FILES,
  3201. ) -> dict[str, object]:
  3202. return {
  3203. "indexed_files": indexed_files,
  3204. "zip_file_entries": zip_file_entries,
  3205. "self_reference_control_files": list(control_files),
  3206. "note": (
  3207. "indexed_files counts HANDOFF-INDEX files[] (ZIP payload business members). "
  3208. "zip_file_entries counts non-directory ZIP entries including VOLUME-MANIFEST. "
  3209. "self_reference_control_files live in the package directory and appear in "
  3210. "SHA256SUMS; do not add them again to indexed_files."
  3211. ),
  3212. }
  3213. def write_exclusions_text(excluded: list[dict[str, object]]) -> str:
  3214. """Render a portable EXCLUSIONS.txt for the package sidecar layout."""
  3215. lines = [
  3216. "# path<TAB>rule",
  3217. "# Inclusion-first package: only versioned recursive exclusions are listed.",
  3218. ]
  3219. for item in sorted(excluded, key=lambda row: handoff.windows_collision_key(str(row.get("path", "")))):
  3220. path = str(item.get("path", ""))
  3221. rule = str(item.get("rule", item.get("reason", "excluded")))
  3222. lines.append(f"{path}\t{rule}")
  3223. return "\n".join(lines) + "\n"
  3224. def create_tar_zst_archive(source_dir: Path, archive_path: Path) -> str:
  3225. """Create a deterministic-enough tar.zst of source_dir contents; return SHA-256."""
  3226. source_dir = source_dir.resolve(strict=True)
  3227. archive_path = archive_path.resolve(strict=False)
  3228. if archive_path.exists():
  3229. archive_path.unlink()
  3230. zstd = shutil.which("zstd")
  3231. if zstd is None:
  3232. raise PackagingError("zstd is required to create .tar.zst package archives")
  3233. # Prefer GNU tar --zstd when available; fall back to compress-program.
  3234. command = [
  3235. "tar",
  3236. "--zstd",
  3237. "-cf",
  3238. str(archive_path),
  3239. "--sort=name",
  3240. "--mtime=UTC 1980-01-01",
  3241. "--owner=0",
  3242. "--group=0",
  3243. "--numeric-owner",
  3244. "-C",
  3245. str(source_dir),
  3246. ".",
  3247. ]
  3248. completed = subprocess.run(
  3249. command,
  3250. stdout=subprocess.PIPE,
  3251. stderr=subprocess.PIPE,
  3252. check=False,
  3253. )
  3254. if completed.returncode != 0:
  3255. # Older tar without --zstd / --sort: use compress-program path.
  3256. fallback = [
  3257. "tar",
  3258. "-cf",
  3259. str(archive_path),
  3260. "-I",
  3261. zstd,
  3262. "-C",
  3263. str(source_dir),
  3264. ".",
  3265. ]
  3266. completed = subprocess.run(
  3267. fallback,
  3268. stdout=subprocess.PIPE,
  3269. stderr=subprocess.PIPE,
  3270. check=False,
  3271. )
  3272. if completed.returncode != 0:
  3273. detail = completed.stderr.decode("utf-8", errors="replace").strip()
  3274. raise PackagingError(f"unable to create tar.zst archive: {detail or 'tar failed'}")
  3275. return handoff.sha256_file(archive_path)
  3276. def write_package_layout_sidecars(
  3277. staging: Path,
  3278. *,
  3279. index: dict[str, object],
  3280. excluded: list[dict[str, object]],
  3281. package_name: str,
  3282. include_tar_zst: bool = True,
  3283. profile: str = "full",
  3284. size_budget: dict[str, object] | None = None,
  3285. ) -> list[dict[str, object]]:
  3286. """Write index/checksums/exclusions and optional tar.zst; return checksum rows."""
  3287. staging.mkdir(parents=True, exist_ok=True)
  3288. (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
  3289. (staging / "EXCLUSIONS.txt").write_text(
  3290. write_exclusions_text(excluded),
  3291. encoding="utf-8",
  3292. newline="\n",
  3293. )
  3294. (staging / "PACKAGE-PURPOSE.txt").write_text(
  3295. handoff.package_purpose_text(profile, package_name=package_name),
  3296. encoding="utf-8",
  3297. newline="\n",
  3298. )
  3299. (staging / "START-HERE.zh-CN.md").write_text(
  3300. _start_here_text(package_name, len(index.get("volumes", [])), profile=profile),
  3301. encoding="utf-8",
  3302. newline="\n",
  3303. )
  3304. if size_budget is not None:
  3305. (staging / "size-budget.json").write_bytes(handoff.json_bytes(size_budget))
  3306. checksum_rows: list[dict[str, object]] = []
  3307. for info in index.get("volumes", []):
  3308. name = str(info["file"])
  3309. checksum_rows.append({"file": name, "sha256": str(info["sha256"])})
  3310. if include_tar_zst:
  3311. # Stage CPLD tree from ZIP volumes into a temporary extract for tar.zst.
  3312. extract_root = staging / ".tar-zst-staging"
  3313. if extract_root.exists():
  3314. shutil.rmtree(extract_root)
  3315. extract_root.mkdir(parents=True, exist_ok=True)
  3316. for info in index.get("volumes", []):
  3317. volume_path = staging / str(info["file"])
  3318. with zipfile.ZipFile(volume_path, "r", allowZip64=True) as archive:
  3319. archive.extractall(extract_root)
  3320. tar_name = f"{package_name}.tar.zst"
  3321. tar_path = staging / tar_name
  3322. tar_sha = create_tar_zst_archive(extract_root, tar_path)
  3323. shutil.rmtree(extract_root)
  3324. checksum_rows.append({"file": tar_name, "sha256": tar_sha})
  3325. index["formats"] = {
  3326. "zip_volumes": [str(info["file"]) for info in index.get("volumes", [])],
  3327. "tar_zst": tar_name,
  3328. "tar_zst_sha256": tar_sha,
  3329. }
  3330. (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
  3331. sidecar_names = [
  3332. "HANDOFF-INDEX.json",
  3333. "EXCLUSIONS.txt",
  3334. "PACKAGE-PURPOSE.txt",
  3335. "START-HERE.zh-CN.md",
  3336. ]
  3337. if size_budget is not None:
  3338. sidecar_names.append("size-budget.json")
  3339. for sidecar in sidecar_names:
  3340. checksum_rows.append(
  3341. {"file": sidecar, "sha256": handoff.sha256_file(staging / sidecar)}
  3342. )
  3343. checksum_lines = [f"{row['sha256']} {row['file']}" for row in checksum_rows]
  3344. (staging / "SHA256SUMS.txt").write_text(
  3345. "\n".join(checksum_lines) + "\n",
  3346. encoding="ascii",
  3347. newline="\n",
  3348. )
  3349. return checksum_rows
  3350. def _publish_directory_atomically(staging: Path, final: Path, *, force: bool) -> None:
  3351. backup: Path | None = None
  3352. backup_created = False
  3353. new_directory_published = False
  3354. if os.path.lexists(final):
  3355. if not force:
  3356. raise PackagingError(f"package output already exists: {final}")
  3357. file_stat = os.lstat(final)
  3358. if not stat.S_ISDIR(file_stat.st_mode) or handoff.stat_is_reparse_point(file_stat):
  3359. raise PackagingError(f"existing package output is not a regular directory: {final}")
  3360. backup = final.with_name(f".{final.name}.{uuid.uuid4().hex}.backup")
  3361. try:
  3362. if backup is not None:
  3363. os.replace(final, backup)
  3364. backup_created = True
  3365. os.replace(staging, final)
  3366. new_directory_published = True
  3367. except BaseException as exc:
  3368. if new_directory_published and os.path.lexists(final):
  3369. try:
  3370. shutil.rmtree(final)
  3371. except OSError:
  3372. pass
  3373. if backup_created and backup is not None and os.path.lexists(backup):
  3374. try:
  3375. os.replace(backup, final)
  3376. except OSError as rollback_exc:
  3377. raise PackagingError(
  3378. f"package publication failed and rollback was incomplete: {rollback_exc}"
  3379. ) from exc
  3380. if isinstance(exc, PackagingError):
  3381. raise
  3382. raise PackagingError(f"unable to publish package directory atomically: {exc}") from exc
  3383. if backup is not None:
  3384. shutil.rmtree(backup)
  3385. def create_analysis_package(
  3386. *,
  3387. collection: AnalysisCollection,
  3388. output_root: Path,
  3389. package_name: str,
  3390. max_zip_bytes: int,
  3391. target_zip_bytes: int,
  3392. force: bool,
  3393. profile: str = "full",
  3394. ) -> dict[str, object]:
  3395. _validate_package_name(package_name)
  3396. if max_zip_bytes <= 0 or not 0 < target_zip_bytes < max_zip_bytes:
  3397. raise PackagingError("ZIP size limits are invalid")
  3398. if not collection.items:
  3399. raise PackagingError("analysis package has no included files")
  3400. output_root = output_root.expanduser().resolve(strict=False)
  3401. output_root.mkdir(parents=True, exist_ok=True)
  3402. final_dir = output_root / package_name
  3403. if os.path.lexists(final_dir) and not force:
  3404. raise PackagingError(f"package output already exists: {final_dir}")
  3405. run_id = uuid.uuid4().hex
  3406. staging = Path(tempfile.mkdtemp(prefix=f".{package_name}.{run_id}.", dir=output_root))
  3407. try:
  3408. full_inventory = _audit_package_items(collection.items)
  3409. physical_items, content_dedup, dedup_excluded = apply_content_dedup(
  3410. collection.items,
  3411. full_inventory,
  3412. )
  3413. inventory = [
  3414. row
  3415. for row in full_inventory
  3416. if str(row["path"]) in {item.candidate.relative for item in physical_items}
  3417. ]
  3418. inventory_by_path = {str(item["path"]): item for item in inventory}
  3419. package_excluded = list(collection.excluded) + dedup_excluded
  3420. package_excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
  3421. derived_evidence = classify_derived_evidence(physical_items)
  3422. evidence_canon_fields = dict(collection.evidence_canon or {})
  3423. # Merge content_dedup logical aliases into evidence_canon.aliases for HANDOFF-INDEX.
  3424. evidence_aliases = list(evidence_canon_fields.get("aliases", [])) # type: ignore[arg-type]
  3425. for record in content_dedup:
  3426. evidence_aliases.append(
  3427. {
  3428. "key": None,
  3429. "sha256": record["sha256"],
  3430. "size": record["size"],
  3431. "physical_path": record["physical_path"],
  3432. "logical_paths": record["logical_paths"],
  3433. "reason": record["reason"],
  3434. }
  3435. )
  3436. if evidence_canon_fields:
  3437. evidence_canon_fields["aliases"] = evidence_aliases
  3438. package_items = physical_items
  3439. package_inventory = inventory
  3440. package_inventory_by_path = inventory_by_path
  3441. large_files: list[dict[str, object]] = []
  3442. chunk_root: Path | None = None
  3443. single_path = staging / f"{package_name}.zip"
  3444. single_info = _write_volume(
  3445. single_path,
  3446. run_id=run_id,
  3447. package_name=package_name,
  3448. number=1,
  3449. count=1,
  3450. items=list(sorted(physical_items, key=_item_sort_key)),
  3451. inventory_by_path=inventory_by_path,
  3452. )
  3453. if single_path.stat().st_size < max_zip_bytes:
  3454. volume_infos = [single_info]
  3455. groups = [list(sorted(physical_items, key=_item_sort_key))]
  3456. else:
  3457. single_path.unlink()
  3458. package_items, large_files, chunk_root = _prepare_large_file_chunks(
  3459. staging,
  3460. run_id=run_id,
  3461. package_name=package_name,
  3462. items=physical_items,
  3463. inventory_by_path=inventory_by_path,
  3464. target_zip_bytes=target_zip_bytes,
  3465. max_zip_bytes=max_zip_bytes,
  3466. )
  3467. package_inventory = _audit_package_items(package_items)
  3468. package_inventory_by_path = {
  3469. str(item["path"]): item for item in package_inventory
  3470. }
  3471. initial_groups = _partition_items(
  3472. package_items,
  3473. target_zip_bytes=target_zip_bytes,
  3474. )
  3475. groups = _split_oversized_groups(
  3476. staging,
  3477. run_id=run_id,
  3478. package_name=package_name,
  3479. groups=initial_groups,
  3480. inventory_by_path=package_inventory_by_path,
  3481. target_zip_bytes=target_zip_bytes,
  3482. max_zip_bytes=max_zip_bytes,
  3483. )
  3484. volume_infos = []
  3485. count = len(groups)
  3486. for number, group in enumerate(groups, start=1):
  3487. category = group[0].category if len({item.category for item in group}) == 1 else "mixed"
  3488. safe_category = re.sub(r"[^a-z0-9]+", "-", category.casefold()).strip("-") or "data"
  3489. volume_path = staging / f"{package_name}.part{number:03d}-{safe_category}.zip"
  3490. volume_info = _write_volume(
  3491. volume_path,
  3492. run_id=run_id,
  3493. package_name=package_name,
  3494. number=number,
  3495. count=count,
  3496. items=group,
  3497. inventory_by_path=package_inventory_by_path,
  3498. )
  3499. if volume_path.stat().st_size >= max_zip_bytes:
  3500. raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
  3501. volume_infos.append(volume_info)
  3502. volume_by_path: dict[str, str] = {}
  3503. for volume_info, group in zip(volume_infos, groups, strict=True):
  3504. for item in group:
  3505. volume_by_path[item.candidate.relative] = str(volume_info["file"])
  3506. large_paths = {str(item["path"]) for item in large_files}
  3507. indexed_files = [
  3508. {**item, "volume": volume_by_path[str(item["path"])]}
  3509. for item in inventory
  3510. if str(item["path"]) not in large_paths
  3511. ]
  3512. for large_file in large_files:
  3513. for chunk in large_file["chunks"]:
  3514. chunk["volume"] = volume_by_path[str(chunk["path"])]
  3515. zip_entry_count = 0
  3516. for info in volume_infos:
  3517. volume_path = staging / str(info["file"])
  3518. with zipfile.ZipFile(volume_path, "r", allowZip64=True) as archive:
  3519. zip_entry_count += sum(1 for name in archive.namelist() if not name.endswith("/"))
  3520. size_budget = handoff.build_size_budget(
  3521. inventory,
  3522. zip_total_bytes=sum(int(info["compressed_bytes"]) for info in volume_infos),
  3523. )
  3524. member_count = build_member_count_semantics(
  3525. indexed_files=len(indexed_files),
  3526. zip_file_entries=zip_entry_count,
  3527. )
  3528. index = {
  3529. "schema": "cpld-agent-analysis-index-v1",
  3530. "run_id": run_id,
  3531. "created_at_utc": _utc_now(),
  3532. "package_name": package_name,
  3533. "status": collection.status,
  3534. "profile": profile,
  3535. "delivery_policy": handoff.delivery_policy_for_profile(profile),
  3536. "max_zip_bytes": max_zip_bytes,
  3537. "target_zip_bytes": target_zip_bytes,
  3538. "sources": list(collection.sources),
  3539. "git": list(collection.git),
  3540. "warnings": list(collection.warnings),
  3541. "excluded": package_excluded,
  3542. "content_dedup": content_dedup,
  3543. "derived_evidence": derived_evidence,
  3544. "evidence_canon": evidence_canon_fields if evidence_canon_fields else None,
  3545. "evidence_aliases": evidence_aliases,
  3546. "member_count": member_count,
  3547. "size_budget": size_budget,
  3548. "volumes": volume_infos,
  3549. "files": indexed_files,
  3550. "large_files": large_files,
  3551. }
  3552. if large_files:
  3553. (staging / "reassemble_large_files.py").write_text(
  3554. REASSEMBLER_SCRIPT,
  3555. encoding="utf-8",
  3556. newline="\n",
  3557. )
  3558. for info in volume_infos:
  3559. volume_path = staging / str(info["file"])
  3560. if volume_path.stat().st_size >= max_zip_bytes:
  3561. raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
  3562. if handoff.sha256_file(volume_path) != info["sha256"]:
  3563. raise PackagingError(f"ZIP volume hash changed after verification: {volume_path.name}")
  3564. checksum_rows = write_package_layout_sidecars(
  3565. staging,
  3566. index=index,
  3567. excluded=package_excluded,
  3568. package_name=package_name,
  3569. include_tar_zst=True,
  3570. profile=profile,
  3571. size_budget=size_budget if handoff.uses_unified_layout(profile) else None,
  3572. )
  3573. full_inventory_by_path = {str(item["path"]): item for item in full_inventory}
  3574. _assert_items_unchanged(collection.items, full_inventory_by_path)
  3575. _assert_source_trees_unchanged(collection, profile=profile)
  3576. # Fail-closed for final-review: stage-aware ZIP selftest must pass in
  3577. # staging before any final-looking artifact is published atomically.
  3578. # Intermediate-review keeps structure checks but is not a final gate.
  3579. if profile == "review-compact":
  3580. from compact_package_selftest import ( # noqa: WPS433
  3581. PACKAGE_STAGE_FINAL,
  3582. run_compact_package_selftest,
  3583. )
  3584. staged_report = run_compact_package_selftest(
  3585. staging,
  3586. skip_software=True,
  3587. write_evidence=False,
  3588. package_stage=None,
  3589. )
  3590. if (
  3591. staged_report.get("package_stage") == PACKAGE_STAGE_FINAL
  3592. and staged_report.get("status") != "pass"
  3593. ):
  3594. raise PackagingError(
  3595. "review-compact final-review staging selftest failed before publish: "
  3596. + ", ".join(staged_report.get("failures") or ["unknown"])
  3597. )
  3598. if chunk_root is not None:
  3599. shutil.rmtree(chunk_root)
  3600. _publish_directory_atomically(staging, final_dir, force=force)
  3601. except BaseException:
  3602. if os.path.lexists(staging):
  3603. shutil.rmtree(staging, ignore_errors=True)
  3604. raise
  3605. formats = {}
  3606. index_path = final_dir / "HANDOFF-INDEX.json"
  3607. if index_path.is_file():
  3608. formats = json.loads(index_path.read_text(encoding="utf-8")).get("formats", {})
  3609. return {
  3610. "status": collection.status,
  3611. "mode": "package",
  3612. "profile": profile,
  3613. "delivery_policy": handoff.delivery_policy_for_profile(profile),
  3614. "run_id": run_id,
  3615. "output_dir": str(final_dir),
  3616. "volumes": volume_infos,
  3617. "formats": formats,
  3618. "checksum_entries": len(checksum_rows),
  3619. "included_file_count": len(inventory),
  3620. "included_bytes": sum(int(item["size"]) for item in inventory),
  3621. "excluded_entry_count": len(package_excluded),
  3622. "content_dedup_groups": len(content_dedup),
  3623. "derived_evidence_count": len(derived_evidence),
  3624. "member_count": member_count,
  3625. "warning_count": len(collection.warnings),
  3626. }
  3627. def _reference_fingerprint(inventory: list[dict[str, object]]) -> str:
  3628. digest = hashlib.sha256()
  3629. for item in sorted(inventory, key=lambda row: str(row["path"])):
  3630. path = str(item["path"])
  3631. size = str(item["size"])
  3632. sha = str(item["sha256"])
  3633. digest.update(f"{path}|{size}|{sha}\n".encode("utf-8"))
  3634. return digest.hexdigest()
  3635. def _create_reference_package_with_cache(
  3636. *,
  3637. collection: AnalysisCollection,
  3638. output_root: Path,
  3639. package_name: str,
  3640. max_zip_bytes: int,
  3641. target_zip_bytes: int,
  3642. force: bool,
  3643. repo_root: Path | None = None,
  3644. refresh_reference_inventory: bool = False,
  3645. ) -> dict[str, object]:
  3646. reference_package_name = f"{package_name}-reference"
  3647. reference_dir = output_root / reference_package_name
  3648. fingerprint_path = reference_dir / "REFERENCE-FINGERPRINT"
  3649. inventory_hook: dict[str, object] | None = None
  3650. if refresh_reference_inventory and repo_root is not None:
  3651. # Order: staging of reference sources is complete before this call; refresh
  3652. # inventory now so the package includes a fresh REFERENCE-INVENTORY.
  3653. inventory_hook = handoff.run_post_staging_reference_inventory_hook(
  3654. repo_root,
  3655. staging_complete=True,
  3656. enabled=True,
  3657. )
  3658. if inventory_hook.get("status") not in {"pass", "skipped_disabled"}:
  3659. raise PackagingError(
  3660. "post-staging reference inventory refresh failed: "
  3661. f"{inventory_hook.get('status')}"
  3662. )
  3663. inventory = _audit_package_items(collection.items)
  3664. fingerprint = _reference_fingerprint(inventory)
  3665. if not force and fingerprint_path.exists():
  3666. previous = fingerprint_path.read_text(encoding="ascii").strip()
  3667. if previous == fingerprint:
  3668. index_path = reference_dir / "HANDOFF-INDEX.json"
  3669. if index_path.exists():
  3670. index = json.loads(index_path.read_text(encoding="utf-8"))
  3671. return {
  3672. "status": collection.status,
  3673. "mode": "reference_cached",
  3674. "package_name": reference_package_name,
  3675. "output_dir": str(reference_dir),
  3676. "volumes": index.get("volumes", []),
  3677. "included_file_count": len(inventory),
  3678. "included_bytes": sum(int(item["size"]) for item in inventory),
  3679. "fingerprint": fingerprint,
  3680. "skipped": True,
  3681. "reference_inventory_hook": inventory_hook,
  3682. }
  3683. payload = create_analysis_package(
  3684. collection=collection,
  3685. output_root=output_root,
  3686. package_name=reference_package_name,
  3687. max_zip_bytes=max_zip_bytes,
  3688. target_zip_bytes=target_zip_bytes,
  3689. force=force,
  3690. )
  3691. reference_dir = Path(payload["output_dir"])
  3692. fingerprint_path = reference_dir / "REFERENCE-FINGERPRINT"
  3693. fingerprint_path.write_text(fingerprint + "\n", encoding="ascii")
  3694. payload["fingerprint"] = fingerprint
  3695. payload["skipped"] = False
  3696. payload["reference_inventory_hook"] = inventory_hook
  3697. return payload
  3698. def merge_archive_preparation(
  3699. collection: AnalysisCollection,
  3700. preparation: ArchivePreparation,
  3701. ) -> AnalysisCollection:
  3702. warnings = (*collection.warnings, *preparation.warnings)
  3703. excluded = sorted(
  3704. (*collection.excluded, *preparation.excluded),
  3705. key=lambda item: handoff.windows_collision_key(item["path"]),
  3706. )
  3707. return AnalysisCollection(
  3708. status="pass_with_warnings" if warnings else "pass",
  3709. items=preparation.items,
  3710. excluded=tuple(excluded),
  3711. warnings=tuple(warnings),
  3712. sources=collection.sources,
  3713. git=collection.git,
  3714. source_snapshots=collection.source_snapshots,
  3715. )
  3716. def explain_analysis_path(
  3717. path: Path,
  3718. *,
  3719. repo_root: Path,
  3720. config: HandoffConfig,
  3721. profile: str = "full",
  3722. ) -> dict[str, object]:
  3723. root = repo_root.resolve(strict=True)
  3724. requested = path if path.is_absolute() else root / path
  3725. target = requested.expanduser().resolve(strict=False)
  3726. resolved_sources, warnings = resolve_external_sources(config.external_sources)
  3727. source_roots: list[tuple[str, str, Path, Path | None]] = [
  3728. ("workspace-current", "core", root, None)
  3729. ]
  3730. for source in resolved_sources:
  3731. if source.kind == "file":
  3732. source_roots.append((source.id, source.category, source.path.parent, source.path))
  3733. else:
  3734. source_roots.append((source.id, source.category, source.path, None))
  3735. matches: list[tuple[int, str, str, Path, Path | None]] = []
  3736. for source_id, category, source_root, exact_file in source_roots:
  3737. if exact_file is not None and target != exact_file:
  3738. continue
  3739. try:
  3740. target.relative_to(source_root)
  3741. except ValueError:
  3742. continue
  3743. matches.append((len(source_root.parts), source_id, category, source_root, exact_file))
  3744. if not matches:
  3745. raise PackagingError("path is outside the current repository and configured external sources")
  3746. _, source_id, category, source_root, exact_file = max(matches, key=lambda item: item[0])
  3747. relative = exact_file.name if exact_file is not None else target.relative_to(source_root).as_posix()
  3748. if not relative:
  3749. relative = "."
  3750. is_dir = target.is_dir()
  3751. context = handoff.load_scan_context(source_root)
  3752. reason = analysis_exclusion_reason(
  3753. relative,
  3754. is_dir=is_dir,
  3755. context=context,
  3756. extra_exclusions=config.extra_exclusions,
  3757. profile=profile,
  3758. )
  3759. archive_relative = (
  3760. f"workspace-current/{relative}"
  3761. if source_id == "workspace-current"
  3762. else f"external/{source_id}/{relative}"
  3763. )
  3764. return {
  3765. "status": "pass_with_warnings" if warnings else "pass",
  3766. "mode": "explain",
  3767. "path": str(target),
  3768. "exists": target.exists(),
  3769. "source_id": source_id,
  3770. "category": category,
  3771. "source_relative_path": relative,
  3772. "archive_path": f"CPLD/{archive_relative}",
  3773. "decision": "exclude" if reason else "include",
  3774. "reason": reason,
  3775. "content_scan": "not_run",
  3776. "warnings": warnings,
  3777. }
  3778. def audit_analysis_collection(collection: AnalysisCollection) -> dict[str, object]:
  3779. inventory = _audit_package_items(collection.items)
  3780. inventory_by_path = {str(item["path"]): item for item in inventory}
  3781. _assert_items_unchanged(collection.items, inventory_by_path)
  3782. return {
  3783. "status": collection.status,
  3784. "mode": "audit_only",
  3785. "included_file_count": len(inventory),
  3786. "included_bytes": sum(int(item["size"]) for item in inventory),
  3787. "excluded_entry_count": len(collection.excluded),
  3788. "warning_count": len(collection.warnings),
  3789. "warnings": list(collection.warnings),
  3790. "sources": list(collection.sources),
  3791. "git": list(collection.git),
  3792. }
  3793. def _validate_output_root(
  3794. output_root: Path,
  3795. *,
  3796. repo_root: Path,
  3797. config: HandoffConfig,
  3798. ) -> Path:
  3799. output = output_root.expanduser().resolve(strict=False)
  3800. source_paths = [repo_root.resolve(strict=True)]
  3801. resolved_sources, _ = resolve_external_sources(config.external_sources)
  3802. source_paths.extend(source.path if source.kind != "file" else source.path.parent for source in resolved_sources)
  3803. for source_path in source_paths:
  3804. try:
  3805. output.relative_to(source_path)
  3806. except ValueError:
  3807. continue
  3808. raise PackagingError(f"output directory must be outside every packaged source root: {source_path}")
  3809. return output
  3810. def build_parser() -> argparse.ArgumentParser:
  3811. parser = argparse.ArgumentParser(description=__doc__)
  3812. parser.add_argument("--audit-only", action="store_true", help="scan and verify inputs without creating ZIP files")
  3813. parser.add_argument("--explain", type=Path, metavar="PATH", help="explain whether one path is included or excluded")
  3814. parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG, help="source and exclusion configuration JSON")
  3815. parser.add_argument("--source-root", type=Path, default=ROOT, help="root directory to package as the primary source")
  3816. parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR, help="parent directory for the package directory")
  3817. parser.add_argument("--package-name", help="portable package directory and ZIP base name")
  3818. parser.add_argument("--force-overwrite", action="store_true", help="atomically replace an existing package directory")
  3819. parser.add_argument("--no-git-bundle", action="store_true", help="omit the git history bundle from the package")
  3820. parser.add_argument(
  3821. "--include-full-history",
  3822. action="store_true",
  3823. help="include a full git bundle (archive-local / explicit override; ignored as default for review-compact)",
  3824. )
  3825. parser.add_argument(
  3826. "--include-sanitized-git-snapshot",
  3827. action="store_true",
  3828. help=(
  3829. "include sanitized synthetic single-commit git snapshot under meta/git "
  3830. "(records synthetic→original mapping; does not impersonate the original tip)"
  3831. ),
  3832. )
  3833. parser.add_argument(
  3834. "--evidence-root",
  3835. type=Path,
  3836. help=(
  3837. "optional delivery/run evidence tree to stage into canonical evidence/ paths "
  3838. "(final matrix, Formal/TD receipts, bitstream, selftests, deep-review summary, IO/hardware notes)"
  3839. ),
  3840. )
  3841. parser.add_argument(
  3842. "--include-process-evidence",
  3843. action="store_true",
  3844. help=(
  3845. "include lane receipts, matrix reruns, and other process evidence "
  3846. "(implied by review-debug; off by default for review-compact)"
  3847. ),
  3848. )
  3849. parser.add_argument(
  3850. "--profile",
  3851. choices=sorted(handoff.HANDOFF_PROFILES),
  3852. default=handoff.DEFAULT_HANDOFF_PROFILE,
  3853. help=(
  3854. "review-compact (default upload: unified source/evidence/meta, no full git bundle); "
  3855. "review-debug; archive-local; legacy full (core/reference split) / code-only"
  3856. ),
  3857. )
  3858. parser.add_argument(
  3859. "--replay-package",
  3860. type=Path,
  3861. metavar="DIR",
  3862. help="verify SHA256SUMS and replay-extract an existing package directory (selftest)",
  3863. )
  3864. parser.add_argument(
  3865. "--replay-extract-dir",
  3866. type=Path,
  3867. help="extract target for --replay-package (must not already exist)",
  3868. )
  3869. parser.add_argument(
  3870. "--bitstream",
  3871. type=Path,
  3872. help=(
  3873. "optional real bitstream to bind into meta/td-source-closure-binding.json "
  3874. "(full SHA-256; integrator supplies tip bit later)"
  3875. ),
  3876. )
  3877. parser.add_argument(
  3878. "--td-report",
  3879. type=Path,
  3880. action="append",
  3881. default=[],
  3882. dest="td_reports",
  3883. help="optional TD report/receipt to bind (repeatable)",
  3884. )
  3885. parser.add_argument(
  3886. "--binding-commit",
  3887. help="optional full 40-char commit override for TD source-closure binding",
  3888. )
  3889. parser.add_argument(
  3890. "--require-bitstream-binding",
  3891. action="store_true",
  3892. help="fail binding (status=bind_failed) when no bitstream is available",
  3893. )
  3894. parser.add_argument(
  3895. "--package-stage",
  3896. choices=("intermediate-review", "final-review"),
  3897. default="final-review",
  3898. help=(
  3899. "intermediate-review: non-final code review without fresh TD/bitstream; "
  3900. "final-review: fail-closed on missing canonical TD/bitstream evidence"
  3901. ),
  3902. )
  3903. parser.add_argument(
  3904. "--refresh-reference-inventory-after-staging",
  3905. action="store_true",
  3906. help=(
  3907. "for full-profile reference volume: refresh docs/REFERENCE-INVENTORY "
  3908. "after staging completes (Lane D order hook; Lane E owns generator honesty)"
  3909. ),
  3910. )
  3911. return parser
  3912. def main(argv: list[str] | None = None) -> int:
  3913. args = build_parser().parse_args(argv)
  3914. package_name = args.package_name or datetime.now(timezone.utc).strftime(
  3915. "cpld-agent-analysis-%Y%m%dT%H%M%SZ"
  3916. )
  3917. try:
  3918. if args.replay_package is not None:
  3919. extract_root = args.replay_extract_dir or Path(
  3920. tempfile.mkdtemp(prefix="prod2u-package-replay-", dir=os.environ.get("TMPDIR", "/tmp"))
  3921. )
  3922. payload = replay_analysis_package(args.replay_package, extract_root=extract_root)
  3923. print(json.dumps(payload, ensure_ascii=False, indent=2))
  3924. return 0
  3925. source_root = args.source_root.expanduser().resolve(strict=True)
  3926. if args.profile not in handoff.HANDOFF_PROFILES:
  3927. raise PackagingError(f"unsupported handoff profile: {args.profile}")
  3928. config = load_config(args.config, repo_root=source_root)
  3929. if args.explain is not None:
  3930. payload = explain_analysis_path(
  3931. args.explain,
  3932. repo_root=source_root,
  3933. config=config,
  3934. profile=args.profile,
  3935. )
  3936. else:
  3937. seven_zip = find_7z()
  3938. _validate_package_name(package_name)
  3939. output_root = _validate_output_root(args.output_dir, repo_root=source_root, config=config)
  3940. if args.profile == "archive-local":
  3941. include_git_bundle = not args.no_git_bundle or args.include_full_history
  3942. if args.include_full_history:
  3943. include_git_bundle = True
  3944. elif args.profile in {"review-compact", "review-debug"}:
  3945. include_git_bundle = False
  3946. else:
  3947. include_git_bundle = not args.no_git_bundle
  3948. with tempfile.TemporaryDirectory(prefix="ca-") as temporary:
  3949. temp_root = Path(temporary)
  3950. collection = collect_analysis_inputs(
  3951. repo_root=source_root,
  3952. config=config,
  3953. temp_root=temp_root / "inputs",
  3954. include_git_bundle=include_git_bundle,
  3955. profile=args.profile,
  3956. include_sanitized_git_snapshot=args.include_sanitized_git_snapshot,
  3957. package_name=package_name,
  3958. evidence_root=args.evidence_root.expanduser().resolve(strict=True)
  3959. if args.evidence_root is not None
  3960. else None,
  3961. include_process_evidence=args.include_process_evidence,
  3962. bitstream_path=args.bitstream.expanduser().resolve(strict=True)
  3963. if args.bitstream is not None
  3964. else None,
  3965. td_report_paths=[
  3966. path.expanduser().resolve(strict=True) for path in args.td_reports
  3967. ],
  3968. binding_commit=args.binding_commit,
  3969. require_bitstream_binding=args.require_bitstream_binding,
  3970. package_stage=args.package_stage,
  3971. )
  3972. preparation = prepare_unsupported_archives(
  3973. collection.items,
  3974. temp_root=temp_root / "archives",
  3975. seven_zip=seven_zip,
  3976. extra_exclusions=config.extra_exclusions,
  3977. )
  3978. prepared_collection = merge_archive_preparation(collection, preparation)
  3979. if args.audit_only:
  3980. payload = audit_analysis_collection(prepared_collection)
  3981. payload["profile"] = args.profile
  3982. payload["delivery_policy"] = handoff.delivery_policy_for_profile(args.profile)
  3983. elif handoff.uses_unified_layout(args.profile) or args.profile == "code-only":
  3984. if not prepared_collection.items:
  3985. raise PackagingError("analysis package has no included files")
  3986. payload = create_analysis_package(
  3987. collection=prepared_collection,
  3988. output_root=output_root,
  3989. package_name=package_name,
  3990. max_zip_bytes=config.max_zip_bytes,
  3991. target_zip_bytes=config.target_zip_bytes,
  3992. force=args.force_overwrite,
  3993. profile=args.profile,
  3994. )
  3995. else:
  3996. core_collection, reference_collection = _split_collection_by_reference(
  3997. prepared_collection
  3998. )
  3999. if not core_collection.items and not reference_collection.items:
  4000. raise PackagingError("analysis package has no included files")
  4001. payload = {}
  4002. if core_collection.items:
  4003. payload["core"] = create_analysis_package(
  4004. collection=core_collection,
  4005. output_root=output_root,
  4006. package_name=package_name,
  4007. max_zip_bytes=config.max_zip_bytes,
  4008. target_zip_bytes=config.target_zip_bytes,
  4009. force=args.force_overwrite,
  4010. profile=args.profile,
  4011. )
  4012. if reference_collection.items:
  4013. payload["reference"] = _create_reference_package_with_cache(
  4014. collection=reference_collection,
  4015. output_root=output_root,
  4016. package_name=package_name,
  4017. max_zip_bytes=config.max_zip_bytes,
  4018. target_zip_bytes=config.target_zip_bytes,
  4019. force=args.force_overwrite,
  4020. repo_root=source_root,
  4021. refresh_reference_inventory=args.refresh_reference_inventory_after_staging,
  4022. )
  4023. except (PackagingError, OSError, ValueError) as exc:
  4024. print(f"error: {exc}", file=sys.stderr)
  4025. return 1
  4026. print(json.dumps(payload, ensure_ascii=False, indent=2))
  4027. return 0
  4028. if __name__ == "__main__":
  4029. raise SystemExit(main())