package_for_agent_analysis.py 139 KB

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