package_for_agent_analysis.py 125 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213
  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 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. "dist": "generated_delivery_output",
  444. "log": "runtime_log_directory",
  445. "runs": "run_state_directory",
  446. "td/build": "td_build_output",
  447. "reference/historical": "reference_historical_material",
  448. "reference/original/legacy_rtl": "reference_legacy_rtl",
  449. "receipts/local": "local_runtime_receipt",
  450. # Packaged once via external source board-viewer-generated (derived evidence).
  451. "tools/board-viewer/generated": "board_viewer_generated_packaged_via_external_source",
  452. "anlogic_cd": "vendor_installer_payload",
  453. "node_modules": "node_modules_runtime",
  454. }
  455. for prefix, reason in explicit_roots.items():
  456. if handoff.is_under(lower, prefix):
  457. return reason
  458. if handoff.is_under(lower, "tmp/edge-headless-profile"):
  459. return "browser_runtime_profile"
  460. if handoff.is_under(lower, "tmp/rtl_sim"):
  461. return "compiled_rtl_simulation"
  462. if handoff.is_under(lower, "tmp/toolchain_probe"):
  463. return "toolchain_probe_runtime"
  464. if handoff.is_under(lower, "tmp/td"):
  465. return "td_runtime_snapshot"
  466. if handoff.is_under(lower, "tmp/refactor"):
  467. return "compiled_refactor_probe"
  468. if any(component.endswith("_Runs") for component in raw_parts):
  469. return "generated_run_directory"
  470. if re.match(r"^tmp/pytest-[^/]+$", lower):
  471. return "temporary_tool_runtime"
  472. if handoff.is_under(lower, "tmp"):
  473. return "temporary_workspace_directory"
  474. if handoff.is_under(lower, "td/project/log"):
  475. return "td_gui_runtime_log"
  476. if handoff.is_under(lower, "td/project") and len(parts) >= 3 and parts[2].endswith("_runs"):
  477. return "td_gui_runtime_run"
  478. if lower in {
  479. "td/project/.lock.f",
  480. "td/project/.recent_user_depot.ini",
  481. }:
  482. return "td_gui_runtime_state"
  483. if handoff.is_under(lower, ".git"):
  484. return "raw_git_metadata"
  485. if handoff.is_under(lower, ".omo"):
  486. return "agent_session_runtime"
  487. cache_components = {
  488. ".git": "raw_git_metadata",
  489. ".codegraph": "declared_external_reparse_alias",
  490. ".codex": "codex_session_runtime",
  491. "__pycache__": "python_bytecode_cache",
  492. ".pytest_cache": "pytest_cache",
  493. ".hypothesis": "hypothesis_cache",
  494. ".mypy_cache": "mypy_cache",
  495. ".ruff_cache": "ruff_cache",
  496. ".tox": "tox_environment",
  497. ".nox": "nox_environment",
  498. ".venv": "virtual_environment",
  499. "venv": "virtual_environment",
  500. "htmlcov": "coverage_report",
  501. "build": "build_output",
  502. "runs": "run_state_directory",
  503. "node_modules": "node_modules_runtime",
  504. ".playwright-browsers": "browser_runtime_cache",
  505. }
  506. for component in parts:
  507. if component in cache_components:
  508. return cache_components[component]
  509. if component == "dist":
  510. return "generated_delivery_output"
  511. if component.endswith(".egg-info"):
  512. return "python_package_metadata"
  513. if not is_dir:
  514. suffix = Path(name).suffix.casefold()
  515. if suffix in GENERATED_BINARY_SUFFIXES:
  516. return "generated_binary_artifact"
  517. if suffix in ARCHIVE_SUFFIXES:
  518. return "archive_file_not_source"
  519. if suffix in RUNTIME_EVIDENCE_SUFFIXES:
  520. return "runtime_evidence_or_waveform"
  521. if suffix in BOARD_DESIGN_SUFFIXES:
  522. if handoff.is_board_viewer_fixture_path(relative):
  523. return None
  524. if handoff.is_review_profile(profile):
  525. return "heavy_design_original_not_packaged"
  526. if "reference" in parts:
  527. return None
  528. return "board_design_file"
  529. if suffix in IMAGE_SUFFIXES:
  530. if name in BOARD_VIEWER_GENERATED_ASSETS or name in DERIVED_BOARD_VIEWER_ASSETS:
  531. return None
  532. if handoff.is_board_viewer_fixture_path(relative):
  533. return None
  534. if handoff.is_review_profile(profile) and suffix == ".pdf":
  535. return "heavy_design_original_not_packaged"
  536. if "reference" in parts:
  537. return None
  538. return "image_file"
  539. if name in STRAY_FILENAMES:
  540. return "stray_or_temporary_file"
  541. if suffix in TRANSIENT_SUFFIXES or name.endswith("~"):
  542. return "temporary_file"
  543. if suffix == ".dmp" or name.startswith("minidump-"):
  544. return "crash_dump"
  545. if name in {".ds_store", "thumbs.db", "desktop.ini"}:
  546. return "os_metadata_cache"
  547. return None
  548. def scan_analysis_root(
  549. root: Path,
  550. *,
  551. extra_exclusions: tuple[dict[str, str], ...] = (),
  552. profile: str = "full",
  553. ) -> tuple[list[handoff.Candidate], list[dict[str, str]], handoff.ScanContext]:
  554. def resolve(relative: str, *, is_dir: bool, context: handoff.ScanContext) -> str | None:
  555. return analysis_exclusion_reason(
  556. relative,
  557. is_dir=is_dir,
  558. context=context,
  559. extra_exclusions=extra_exclusions,
  560. profile=profile,
  561. )
  562. return handoff.scan_tree(root, exclusion_resolver=resolve, profile=profile)
  563. def resolve_external_sources(
  564. sources: tuple[ExternalSource, ...],
  565. ) -> tuple[list[ResolvedSource], list[dict[str, str]]]:
  566. resolved: list[ResolvedSource] = []
  567. warnings: list[dict[str, str]] = []
  568. for source in sources:
  569. selected: Path | None = None
  570. for candidate in source.path_candidates:
  571. if source.kind == "file" and candidate.is_file():
  572. selected = candidate.resolve(strict=True)
  573. break
  574. if source.kind in {"directory", "git_worktree"} and candidate.is_dir():
  575. selected = candidate.resolve(strict=True)
  576. break
  577. if selected is None:
  578. warnings.append(
  579. {
  580. "code": "missing_external_source",
  581. "source_id": source.id,
  582. "message": "no configured path candidate is available",
  583. }
  584. )
  585. continue
  586. resolved.append(
  587. ResolvedSource(
  588. id=source.id,
  589. category=source.category,
  590. kind=source.kind,
  591. path=selected,
  592. archive_policy=source.archive_policy,
  593. )
  594. )
  595. return resolved, warnings
  596. def _candidate_from_path(path: Path, relative: str) -> handoff.Candidate:
  597. try:
  598. file_stat = os.lstat(path)
  599. except OSError as exc:
  600. raise PackagingError(f"unable to inspect generated analysis input: {relative}") from exc
  601. if not stat.S_ISREG(file_stat.st_mode) or handoff.stat_is_reparse_point(file_stat):
  602. raise PackagingError(f"analysis input is not a regular file: {relative}")
  603. return handoff.Candidate(
  604. absolute=path,
  605. relative=handoff.normalize_relative(relative.split("/")),
  606. size=file_stat.st_size,
  607. mtime_ns=file_stat.st_mtime_ns,
  608. device=int(file_stat.st_dev),
  609. inode=int(file_stat.st_ino),
  610. mode=int(file_stat.st_mode),
  611. )
  612. def make_package_item(
  613. path: Path,
  614. *,
  615. relative: str,
  616. category: str,
  617. source_id: str,
  618. scan_archive: bool = True,
  619. ) -> PackageItem:
  620. return PackageItem(
  621. candidate=_candidate_from_path(path, relative),
  622. category=category,
  623. source_id=source_id,
  624. original_path=path.name,
  625. scan_archive=scan_archive,
  626. )
  627. def _rebase_candidate(candidate: handoff.Candidate, prefix: str) -> handoff.Candidate:
  628. return handoff.Candidate(
  629. absolute=candidate.absolute,
  630. relative=handoff.normalize_relative([*prefix.split("/"), *candidate.relative.split("/")]),
  631. size=candidate.size,
  632. mtime_ns=candidate.mtime_ns,
  633. device=candidate.device,
  634. inode=candidate.inode,
  635. mode=candidate.mode,
  636. )
  637. def _rebase_exclusions(excluded: list[dict[str, str]], prefix: str) -> list[dict[str, str]]:
  638. return [
  639. {
  640. "path": handoff.normalize_relative([*prefix.split("/"), *item["path"].split("/")]),
  641. "rule": item["rule"],
  642. }
  643. for item in excluded
  644. ]
  645. def _collect_directory_items(
  646. *,
  647. root: Path,
  648. source_id: str,
  649. category: str,
  650. prefix: str,
  651. extra_exclusions: tuple[dict[str, str], ...],
  652. profile: str = "full",
  653. ) -> tuple[list[PackageItem], list[dict[str, str]]]:
  654. candidates, excluded, _ = scan_analysis_root(
  655. root,
  656. extra_exclusions=extra_exclusions,
  657. profile=profile,
  658. )
  659. items = [
  660. PackageItem(
  661. candidate=_rebase_candidate(candidate, prefix),
  662. category=category,
  663. source_id=source_id,
  664. original_path=candidate.relative,
  665. scan_archive=True,
  666. )
  667. for candidate in candidates
  668. ]
  669. return items, _rebase_exclusions(excluded, prefix)
  670. def _run_git(command: list[str], *, cwd: Path, timeout: int = 300) -> str:
  671. try:
  672. completed = subprocess.run(
  673. command,
  674. cwd=cwd,
  675. stdout=subprocess.PIPE,
  676. stderr=subprocess.STDOUT,
  677. text=True,
  678. encoding="utf-8",
  679. errors="replace",
  680. timeout=timeout,
  681. check=False,
  682. )
  683. except (OSError, subprocess.TimeoutExpired) as exc:
  684. raise PackagingError(f"unable to run Git for {cwd.name}") from exc
  685. if completed.returncode != 0:
  686. detail = completed.stdout.strip().splitlines()
  687. suffix = f": {detail[-1]}" if detail else ""
  688. raise PackagingError(f"Git command failed for {cwd.name}{suffix}")
  689. return completed.stdout
  690. def _is_evidence_source_path(relative: str) -> bool:
  691. lower = relative.casefold()
  692. if evidence_canon.workspace_canonical_path(relative) is not None:
  693. return True
  694. if handoff.is_under(lower, "receipts"):
  695. return True
  696. if handoff.is_under(lower, "tools/board-viewer/generated"):
  697. return True
  698. name = lower.rsplit("/", 1)[-1]
  699. if name in DERIVED_BOARD_VIEWER_ASSETS and "board-viewer" in lower:
  700. return True
  701. return False
  702. def _unified_item_placement(
  703. *,
  704. source_id: str,
  705. original_relative: str,
  706. profile: str,
  707. ) -> tuple[str, str]:
  708. """Return (package_relative_or_prefix, category) for unified review layouts.
  709. When the workspace path matches the compact evidence allowlist, the first
  710. element is the full canonical package path (not merely a directory prefix).
  711. """
  712. del profile
  713. if source_id == "board-viewer-generated" or source_id.startswith("board-viewer"):
  714. return "evidence/board-viewer", "evidence"
  715. canon = evidence_canon.workspace_canonical_path(original_relative)
  716. if canon is not None and source_id in {"workspace-current", "source"}:
  717. return canon, "evidence"
  718. if source_id != "workspace-current" and source_id != "source":
  719. if _is_evidence_source_path(original_relative):
  720. return f"evidence/external/{source_id}", "evidence"
  721. return f"source/external/{source_id}", "source"
  722. if _is_evidence_source_path(original_relative):
  723. return "evidence", "evidence"
  724. return "source", "source"
  725. def _unified_layout_prefix(
  726. *,
  727. source_id: str,
  728. original_relative: str,
  729. profile: str,
  730. ) -> tuple[str, str]:
  731. """Compatibility wrapper: directory prefix + category for unified layouts."""
  732. placed, category = _unified_item_placement(
  733. source_id=source_id,
  734. original_relative=original_relative,
  735. profile=profile,
  736. )
  737. if placed.startswith("evidence/") and placed.count("/") >= 2 and not placed.endswith("/"):
  738. # Full canonical path — expose parent as prefix for exclusion rewriting.
  739. if evidence_canon.workspace_canonical_path(original_relative) == placed:
  740. parent = placed.rsplit("/", 1)[0]
  741. return parent, category
  742. return placed, category
  743. def _package_relative_for_unified(
  744. *,
  745. source_id: str,
  746. original_relative: str,
  747. profile: str,
  748. ) -> tuple[str, str]:
  749. placed, category = _unified_item_placement(
  750. source_id=source_id,
  751. original_relative=original_relative,
  752. profile=profile,
  753. )
  754. if evidence_canon.workspace_canonical_path(original_relative) == placed:
  755. return placed, category
  756. if original_relative in {".", ""}:
  757. return placed, category
  758. return f"{placed}/{original_relative}", category
  759. # Workspace paths remapped into evidence/ that must also remain under source/ for
  760. # detached software replay (imports / generators that resolve repo-relative paths).
  761. _SOFTWARE_MIRROR_UNDER_SOURCE = frozenset(
  762. {
  763. "config/source_closure.json",
  764. }
  765. )
  766. def _materialize_bytes_items(
  767. payloads: dict[str, bytes],
  768. *,
  769. temp_root: Path,
  770. source_id: str,
  771. category: str,
  772. ) -> list[PackageItem]:
  773. items: list[PackageItem] = []
  774. root = temp_root / "generated-meta"
  775. root.mkdir(parents=True, exist_ok=True)
  776. for relative, payload in sorted(payloads.items()):
  777. path = root / Path(*relative.split("/"))
  778. path.parent.mkdir(parents=True, exist_ok=True)
  779. path.write_bytes(payload)
  780. items.append(
  781. make_package_item(
  782. path,
  783. relative=relative,
  784. category=category,
  785. source_id=source_id,
  786. scan_archive=False,
  787. )
  788. )
  789. return items
  790. def _create_git_bundle(
  791. *,
  792. root: Path,
  793. source_id: str,
  794. temp_root: Path,
  795. ) -> tuple[PackageItem, dict[str, object]]:
  796. git = shutil.which("git")
  797. if not git:
  798. raise PackagingError("Git is required to create complete analysis history bundles")
  799. bundle_dir = temp_root / "git-bundles"
  800. bundle_dir.mkdir(parents=True, exist_ok=True)
  801. bundle_path = bundle_dir / f"{source_id}.bundle"
  802. _run_git([git, "bundle", "create", str(bundle_path), "--all"], cwd=root)
  803. verify_output = _run_git([git, "bundle", "verify", str(bundle_path)], cwd=root)
  804. head = _run_git([git, "rev-parse", "HEAD"], cwd=root).strip()
  805. branch = _run_git([git, "branch", "--show-current"], cwd=root).strip() or None
  806. status = _run_git(
  807. [
  808. git,
  809. "--no-optional-locks",
  810. "-c",
  811. "core.fsmonitor=false",
  812. "-c",
  813. "core.untrackedCache=false",
  814. "status",
  815. "--short",
  816. "--branch",
  817. "--untracked-files=all",
  818. ],
  819. cwd=root,
  820. )
  821. ref_lines = [line for line in verify_output.splitlines() if " refs/" in line or line.rstrip().endswith(" HEAD")]
  822. candidate = _candidate_from_path(bundle_path, f"git-history/{source_id}.bundle")
  823. item = PackageItem(
  824. candidate=candidate,
  825. category="core",
  826. source_id=source_id,
  827. original_path=".git",
  828. scan_archive=False,
  829. )
  830. metadata = {
  831. "source_id": source_id,
  832. "branch": branch,
  833. "head": head,
  834. "working_tree_clean": not any(
  835. line and not line.startswith("##") for line in status.splitlines()
  836. ),
  837. "status": "pass",
  838. "bundle_path": candidate.relative,
  839. "bundle_ref_count": len(ref_lines),
  840. "bundle_verify": "pass",
  841. }
  842. return item, metadata
  843. def collect_analysis_inputs(
  844. *,
  845. repo_root: Path,
  846. config: HandoffConfig,
  847. temp_root: Path,
  848. include_git_bundle: bool = True,
  849. profile: str = "full",
  850. include_sanitized_git_snapshot: bool = False,
  851. package_name: str = "pending",
  852. evidence_root: Path | None = None,
  853. include_process_evidence: bool = False,
  854. ) -> AnalysisCollection:
  855. root = repo_root.resolve(strict=True)
  856. temp_root.mkdir(parents=True, exist_ok=True)
  857. if profile not in handoff.HANDOFF_PROFILES:
  858. raise PackagingError(f"unsupported handoff profile: {profile}")
  859. if profile == "full" and not include_git_bundle:
  860. raise PackagingError(
  861. "full inclusion-first packages require a git bundle so replay can restore "
  862. "commit-to-commit source closure comparison"
  863. )
  864. unified = handoff.uses_unified_layout(profile)
  865. # review-compact / review-debug never ship a full bundle unless explicitly forced later.
  866. if profile in {"review-compact", "review-debug"}:
  867. include_git_bundle = False
  868. items: list[PackageItem] = []
  869. excluded: list[dict[str, str]] = []
  870. warnings: list[dict[str, str]] = []
  871. sources: list[dict[str, object]] = []
  872. git_metadata: list[dict[str, object]] = []
  873. source_snapshots: list[SourceSnapshot] = []
  874. primary_source_id = "workspace-current"
  875. if unified:
  876. # Collect with a temporary prefix, then remap into source/ or evidence/.
  877. root_items, root_excluded = _collect_directory_items(
  878. root=root,
  879. source_id=primary_source_id,
  880. category="source",
  881. prefix="__workspace__",
  882. extra_exclusions=config.extra_exclusions,
  883. profile=profile,
  884. )
  885. remapped: list[PackageItem] = []
  886. for item in root_items:
  887. original = item.original_path
  888. package_relative, category = _package_relative_for_unified(
  889. source_id=primary_source_id,
  890. original_relative=original,
  891. profile=profile,
  892. )
  893. remapped.append(
  894. PackageItem(
  895. candidate=handoff.Candidate(
  896. absolute=item.candidate.absolute,
  897. relative=package_relative,
  898. size=item.candidate.size,
  899. mtime_ns=item.candidate.mtime_ns,
  900. device=item.candidate.device,
  901. inode=item.candidate.inode,
  902. mode=item.candidate.mode,
  903. ),
  904. category=category,
  905. source_id=primary_source_id,
  906. original_path=original,
  907. scan_archive=item.scan_archive,
  908. )
  909. )
  910. if original in _SOFTWARE_MIRROR_UNDER_SOURCE and not package_relative.startswith(
  911. "source/"
  912. ):
  913. remapped.append(
  914. PackageItem(
  915. candidate=handoff.Candidate(
  916. absolute=item.candidate.absolute,
  917. relative=f"source/{original}",
  918. size=item.candidate.size,
  919. mtime_ns=item.candidate.mtime_ns,
  920. device=item.candidate.device,
  921. inode=item.candidate.inode,
  922. mode=item.candidate.mode,
  923. ),
  924. category="source",
  925. source_id=primary_source_id,
  926. original_path=original,
  927. scan_archive=item.scan_archive,
  928. )
  929. )
  930. items.extend(remapped)
  931. for entry in root_excluded:
  932. original_excluded = entry["path"]
  933. if original_excluded.startswith("__workspace__/"):
  934. original_excluded = original_excluded[len("__workspace__/") :]
  935. elif original_excluded == "__workspace__":
  936. original_excluded = "."
  937. package_relative, _category = _package_relative_for_unified(
  938. source_id=primary_source_id,
  939. original_relative=original_excluded,
  940. profile=profile,
  941. )
  942. excluded.append(
  943. {
  944. "path": (
  945. original_excluded
  946. if original_excluded == "."
  947. else package_relative
  948. ),
  949. "rule": entry["rule"],
  950. }
  951. )
  952. else:
  953. root_items, root_excluded = _collect_directory_items(
  954. root=root,
  955. source_id=primary_source_id,
  956. category="core",
  957. prefix="workspace-current",
  958. extra_exclusions=config.extra_exclusions,
  959. profile=profile,
  960. )
  961. items.extend(root_items)
  962. excluded.extend(root_excluded)
  963. source_snapshots.append(
  964. _source_snapshot(
  965. root,
  966. source_id=primary_source_id,
  967. extra_exclusions=config.extra_exclusions,
  968. profile=profile,
  969. )
  970. )
  971. sources.append(
  972. {
  973. "id": primary_source_id,
  974. "category": "source" if unified else "core",
  975. "kind": "git_worktree",
  976. "path": str(root),
  977. "status": "pass",
  978. }
  979. )
  980. if include_git_bundle:
  981. bundle_item, bundle_metadata = _create_git_bundle(
  982. root=root,
  983. source_id=primary_source_id,
  984. temp_root=temp_root,
  985. )
  986. if unified:
  987. # Keep bundle under meta/git-history for archive-local.
  988. bundle_rel = f"meta/git-history/{primary_source_id}.bundle"
  989. bundle_item = PackageItem(
  990. candidate=handoff.Candidate(
  991. absolute=bundle_item.candidate.absolute,
  992. relative=bundle_rel,
  993. size=bundle_item.candidate.size,
  994. mtime_ns=bundle_item.candidate.mtime_ns,
  995. device=bundle_item.candidate.device,
  996. inode=bundle_item.candidate.inode,
  997. mode=bundle_item.candidate.mode,
  998. ),
  999. category="meta",
  1000. source_id=primary_source_id,
  1001. original_path=".git",
  1002. scan_archive=False,
  1003. )
  1004. bundle_metadata = {**bundle_metadata, "bundle_path": bundle_rel}
  1005. items.append(bundle_item)
  1006. git_metadata.append(bundle_metadata)
  1007. elif unified:
  1008. provenance, provenance_artifacts = handoff.collect_review_git_provenance(
  1009. root,
  1010. include_sanitized_git_snapshot=include_sanitized_git_snapshot,
  1011. meta_prefix="meta/git",
  1012. temp_root=temp_root / "sanitized-git",
  1013. )
  1014. binding = handoff.build_td_source_closure_binding_hook(root)
  1015. provenance_artifacts["meta/td-source-closure-binding.json"] = handoff.json_bytes(binding)
  1016. purpose = handoff.package_purpose_text(profile, package_name=package_name)
  1017. provenance_artifacts["meta/PACKAGE-PURPOSE.txt"] = purpose.encode("utf-8")
  1018. items.extend(
  1019. _materialize_bytes_items(
  1020. provenance_artifacts,
  1021. temp_root=temp_root,
  1022. source_id="meta-generated",
  1023. category="meta",
  1024. )
  1025. )
  1026. git_metadata.append(
  1027. {
  1028. "source_id": primary_source_id,
  1029. "status": provenance.get("status"),
  1030. "branch": provenance.get("branch"),
  1031. "head": provenance.get("head"),
  1032. "full_bundle": False,
  1033. "provenance": provenance,
  1034. "td_source_closure_binding": binding,
  1035. }
  1036. )
  1037. resolved_sources, source_warnings = resolve_external_sources(config.external_sources)
  1038. if profile == "code-only":
  1039. resolved_sources = [
  1040. source for source in resolved_sources if source.id != "board-viewer-generated"
  1041. ]
  1042. warnings.extend(source_warnings)
  1043. for source in resolved_sources:
  1044. if unified:
  1045. # Prefer derived board-viewer assets under evidence/.
  1046. if source.kind == "file":
  1047. prefix, category = _unified_layout_prefix(
  1048. source_id=source.id,
  1049. original_relative=source.path.name,
  1050. profile=profile,
  1051. )
  1052. candidate = _candidate_from_path(
  1053. source.path, f"{prefix}/{source.path.name}"
  1054. )
  1055. items.append(
  1056. PackageItem(
  1057. candidate=candidate,
  1058. category=category,
  1059. source_id=source.id,
  1060. original_path=source.path.name,
  1061. scan_archive=source.archive_policy == "inspect",
  1062. )
  1063. )
  1064. else:
  1065. source_items, source_excluded = _collect_directory_items(
  1066. root=source.path,
  1067. source_id=source.id,
  1068. category="evidence",
  1069. prefix="__external__",
  1070. extra_exclusions=config.extra_exclusions,
  1071. profile=profile,
  1072. )
  1073. for item in source_items:
  1074. original = item.original_path
  1075. prefix, category = _unified_layout_prefix(
  1076. source_id=source.id,
  1077. original_relative=original,
  1078. profile=profile,
  1079. )
  1080. items.append(
  1081. PackageItem(
  1082. candidate=_rebase_candidate(
  1083. handoff.Candidate(
  1084. absolute=item.candidate.absolute,
  1085. relative=original,
  1086. size=item.candidate.size,
  1087. mtime_ns=item.candidate.mtime_ns,
  1088. device=item.candidate.device,
  1089. inode=item.candidate.inode,
  1090. mode=item.candidate.mode,
  1091. ),
  1092. prefix,
  1093. ),
  1094. category=category,
  1095. source_id=source.id,
  1096. original_path=original,
  1097. scan_archive=item.scan_archive,
  1098. )
  1099. )
  1100. for entry in source_excluded:
  1101. original_excluded = entry["path"]
  1102. if original_excluded.startswith("__external__/"):
  1103. original_excluded = original_excluded[len("__external__/") :]
  1104. prefix, _category = _unified_layout_prefix(
  1105. source_id=source.id,
  1106. original_relative=original_excluded,
  1107. profile=profile,
  1108. )
  1109. excluded.append(
  1110. {
  1111. "path": f"{prefix}/{original_excluded}",
  1112. "rule": entry["rule"],
  1113. }
  1114. )
  1115. source_snapshots.append(
  1116. _source_snapshot(
  1117. source.path,
  1118. source_id=source.id,
  1119. extra_exclusions=config.extra_exclusions,
  1120. profile=profile,
  1121. )
  1122. )
  1123. else:
  1124. prefix = f"external/{source.id}"
  1125. if source.kind == "file":
  1126. candidate = _candidate_from_path(source.path, f"{prefix}/{source.path.name}")
  1127. items.append(
  1128. PackageItem(
  1129. candidate=candidate,
  1130. category=source.category,
  1131. source_id=source.id,
  1132. original_path=source.path.name,
  1133. scan_archive=source.archive_policy == "inspect",
  1134. )
  1135. )
  1136. else:
  1137. source_items, source_excluded = _collect_directory_items(
  1138. root=source.path,
  1139. source_id=source.id,
  1140. category=source.category,
  1141. prefix=prefix,
  1142. extra_exclusions=config.extra_exclusions,
  1143. profile=profile,
  1144. )
  1145. items.extend(source_items)
  1146. excluded.extend(source_excluded)
  1147. source_snapshots.append(
  1148. _source_snapshot(
  1149. source.path,
  1150. source_id=source.id,
  1151. extra_exclusions=config.extra_exclusions,
  1152. profile=profile,
  1153. )
  1154. )
  1155. sources.append(
  1156. {
  1157. "id": source.id,
  1158. "category": "evidence" if unified else source.category,
  1159. "kind": source.kind,
  1160. "path": str(source.path),
  1161. "status": "pass",
  1162. }
  1163. )
  1164. if source.kind == "git_worktree" and include_git_bundle:
  1165. external_bundle, external_git = _create_git_bundle(
  1166. root=source.path,
  1167. source_id=source.id,
  1168. temp_root=temp_root,
  1169. )
  1170. items.append(external_bundle)
  1171. git_metadata.append(external_git)
  1172. evidence_canon_fields: dict[str, object] | None = None
  1173. include_process = include_process_evidence or profile == "review-debug"
  1174. if unified:
  1175. if evidence_root is not None:
  1176. staged = evidence_canon.stage_evidence_root(
  1177. evidence_root,
  1178. staging_root=temp_root / "canonical-evidence",
  1179. include_process_evidence=include_process,
  1180. )
  1181. for staged_file in staged.staged:
  1182. items.append(
  1183. PackageItem(
  1184. candidate=_candidate_from_path(
  1185. staged_file.absolute,
  1186. staged_file.relative,
  1187. ),
  1188. category="evidence",
  1189. source_id="evidence-root",
  1190. original_path=staged_file.original_path,
  1191. scan_archive=False,
  1192. )
  1193. )
  1194. excluded.extend(staged.excluded)
  1195. sources.append(
  1196. {
  1197. "id": "evidence-root",
  1198. "category": "evidence",
  1199. "kind": "directory",
  1200. "path": str(evidence_root.resolve()),
  1201. "status": "pass",
  1202. }
  1203. )
  1204. evidence_canon_fields = evidence_canon.build_evidence_canon_index_fields(
  1205. catalog=staged.catalog,
  1206. aliases=staged.aliases,
  1207. log_policy_actions=staged.log_policy_actions,
  1208. include_process_evidence=include_process,
  1209. profile=profile,
  1210. )
  1211. kept_items, filter_excluded, _remaps = evidence_canon.filter_package_items_for_compact(
  1212. items,
  1213. profile=profile,
  1214. include_process_evidence=include_process,
  1215. )
  1216. items = list(kept_items)
  1217. excluded.extend(filter_excluded)
  1218. # Workspace allowlist remaps + evidence-root staging can both land on the
  1219. # same canonical evidence/ path; keep one physical copy (prefer evidence-root).
  1220. deduped: dict[str, PackageItem] = {}
  1221. for item in items:
  1222. key = handoff.windows_collision_key(item.candidate.relative)
  1223. previous = deduped.get(key)
  1224. if previous is None:
  1225. deduped[key] = item
  1226. continue
  1227. prefer_new = item.source_id == "evidence-root" and previous.source_id != "evidence-root"
  1228. keep, drop = (item, previous) if prefer_new else (previous, item)
  1229. deduped[key] = keep
  1230. excluded.append(
  1231. {
  1232. "path": drop.original_path or drop.candidate.relative,
  1233. "rule": "canonical_path_physical_dedup",
  1234. }
  1235. )
  1236. if evidence_canon_fields is not None:
  1237. aliases = list(evidence_canon_fields.get("aliases") or [])
  1238. aliases.append(
  1239. {
  1240. "physical_path": keep.candidate.relative,
  1241. "logical_paths": [
  1242. f"evidence/from/{drop.original_path or drop.candidate.relative}"
  1243. ],
  1244. "reason": "canonical_path_physical_dedup",
  1245. }
  1246. )
  1247. evidence_canon_fields["aliases"] = aliases
  1248. items = list(deduped.values())
  1249. if evidence_canon_fields is None:
  1250. evidence_canon_fields = evidence_canon.build_evidence_canon_index_fields(
  1251. catalog=[
  1252. {
  1253. "key": key,
  1254. "canonical_path": evidence_canon.load_allowlist().by_key[key].canonical_path,
  1255. "role": "compact_default",
  1256. "source_original": None,
  1257. }
  1258. for key in evidence_canon.compact_default_key_list()
  1259. ],
  1260. aliases=[],
  1261. log_policy_actions=[],
  1262. include_process_evidence=include_process,
  1263. profile=profile,
  1264. )
  1265. # Record workspace allowlisted evidence that survived filtering.
  1266. present = {item.candidate.relative.casefold() for item in items}
  1267. catalog = list(evidence_canon_fields.get("catalog", [])) # type: ignore[arg-type]
  1268. allowlist = evidence_canon.load_allowlist()
  1269. for entry in allowlist.canonical_entries:
  1270. if entry.canonical_path.casefold() in present and not any(
  1271. str(row.get("canonical_path", "")).casefold() == entry.canonical_path.casefold()
  1272. for row in catalog
  1273. ):
  1274. catalog.append(
  1275. {
  1276. "key": entry.key,
  1277. "canonical_path": entry.canonical_path,
  1278. "role": "compact_default",
  1279. "source_original": "workspace",
  1280. }
  1281. )
  1282. evidence_canon_fields["catalog"] = sorted(catalog, key=lambda row: str(row["key"]))
  1283. evidence_canon_fields["compact_default_keys"] = sorted(
  1284. {str(row["key"]) for row in catalog if row.get("role") == "compact_default"}
  1285. )
  1286. items.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
  1287. excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
  1288. return AnalysisCollection(
  1289. status="pass_with_warnings" if warnings else "pass",
  1290. items=tuple(items),
  1291. excluded=tuple(excluded),
  1292. warnings=tuple(warnings),
  1293. sources=tuple(sources),
  1294. git=tuple(git_metadata),
  1295. source_snapshots=tuple(source_snapshots),
  1296. evidence_canon=evidence_canon_fields,
  1297. )
  1298. def find_7z() -> Path | None:
  1299. discovered = shutil.which("7z") or shutil.which("7zz")
  1300. candidates = [
  1301. Path(discovered) if discovered else None,
  1302. Path(r"C:\Program Files\7-Zip\7z.exe"),
  1303. Path(r"C:\Program Files (x86)\7-Zip\7z.exe"),
  1304. ]
  1305. for candidate in candidates:
  1306. if candidate is not None and candidate.is_file():
  1307. return candidate.resolve(strict=True)
  1308. return None
  1309. def build_7zip_create_command(archive_path: Path, staging_root: Path) -> list[str]:
  1310. del staging_root
  1311. return [
  1312. "a",
  1313. "-tzip",
  1314. "-mm=Deflate",
  1315. "-mx=9",
  1316. "-mmt",
  1317. "-y",
  1318. "-r",
  1319. str(archive_path),
  1320. "CPLD\\*",
  1321. ]
  1322. def _run_7z(seven_zip: Path, arguments: list[str], *, cwd: Path) -> str:
  1323. try:
  1324. completed = subprocess.run(
  1325. [str(seven_zip), *arguments],
  1326. cwd=cwd,
  1327. stdout=subprocess.PIPE,
  1328. stderr=subprocess.STDOUT,
  1329. text=True,
  1330. encoding="utf-8",
  1331. errors="replace",
  1332. timeout=300,
  1333. check=False,
  1334. )
  1335. except (OSError, subprocess.TimeoutExpired) as exc:
  1336. raise PackagingError("unable to run 7-Zip for archive inspection") from exc
  1337. if completed.returncode != 0:
  1338. detail = completed.stdout.strip().splitlines()
  1339. suffix = f": {detail[-1]}" if detail else ""
  1340. raise PackagingError(f"7-Zip archive inspection failed{suffix}")
  1341. return completed.stdout
  1342. def _rename_archive_entries(
  1343. seven_zip: Path,
  1344. archive_path: Path,
  1345. renames: list[tuple[str, str]],
  1346. ) -> None:
  1347. for offset in range(0, len(renames), 64):
  1348. batch = renames[offset : offset + 64]
  1349. arguments = ["rn", "-y", str(archive_path)]
  1350. for old_name, new_name in batch:
  1351. arguments.extend((old_name, new_name))
  1352. _run_7z(seven_zip, arguments, cwd=archive_path.parent)
  1353. def _parse_7z_members(payload: str, archive_label: str) -> list[dict[str, str]]:
  1354. in_members = False
  1355. current: dict[str, str] = {}
  1356. members: list[dict[str, str]] = []
  1357. for raw_line in payload.splitlines():
  1358. line = raw_line.rstrip("\r\n")
  1359. if line.strip() == "----------":
  1360. in_members = True
  1361. current = {}
  1362. continue
  1363. if not in_members:
  1364. continue
  1365. if not line.strip():
  1366. if current:
  1367. members.append(current)
  1368. current = {}
  1369. continue
  1370. key, separator, value = line.partition(" = ")
  1371. if separator:
  1372. current[key.strip()] = value.strip()
  1373. if current:
  1374. members.append(current)
  1375. for member in members:
  1376. raw_path = member.get("Path", "")
  1377. normalized = raw_path.replace("\\", "/")
  1378. if not normalized or normalized.startswith("/") or re.match(r"^[A-Za-z]:", normalized):
  1379. raise PackagingError(f"unsafe archive member path in {archive_label}")
  1380. handoff.normalize_relative(normalized.split("/"))
  1381. if member.get("Encrypted") not in {None, "", "-"}:
  1382. raise PackagingError(f"encrypted archive member is unsupported in {archive_label}")
  1383. if member.get("Symbolic Link") or member.get("Hard Link"):
  1384. raise PackagingError(f"archive link member is unsupported in {archive_label}")
  1385. if member.get("Alternate Stream") not in {None, "", "-"}:
  1386. raise PackagingError(f"archive alternate stream is unsupported in {archive_label}")
  1387. if member.get("Split Before") not in {None, "", "-"} or member.get("Split After") not in {
  1388. None,
  1389. "",
  1390. "-",
  1391. }:
  1392. raise PackagingError(f"split archive member is unsupported in {archive_label}")
  1393. return members
  1394. def _inspect_and_extract_unsupported_archive(
  1395. item: PackageItem,
  1396. *,
  1397. temp_root: Path,
  1398. seven_zip: Path,
  1399. extra_exclusions: tuple[dict[str, str], ...],
  1400. ) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
  1401. listing = _run_7z(
  1402. seven_zip,
  1403. ["l", "-slt", "-sccUTF-8", str(item.candidate.absolute)],
  1404. cwd=item.candidate.absolute.parent,
  1405. )
  1406. members = _parse_7z_members(listing, item.candidate.relative)
  1407. file_members = [
  1408. member
  1409. for member in members
  1410. if member.get("Folder") != "+" and "D" not in member.get("Attributes", "")
  1411. ]
  1412. expected_bytes = sum(int(member.get("Size") or "0") for member in file_members)
  1413. token = hashlib.sha256(item.candidate.relative.encode("utf-8")).hexdigest()[:16]
  1414. extract_root = temp_root / "expanded-archives" / token
  1415. extract_root.mkdir(parents=True, exist_ok=False)
  1416. _run_7z(
  1417. seven_zip,
  1418. ["x", "-y", "-aoa", "-sccUTF-8", f"-o{extract_root}", str(item.candidate.absolute)],
  1419. cwd=item.candidate.absolute.parent,
  1420. )
  1421. actual_files = [path for path in extract_root.rglob("*") if path.is_file()]
  1422. actual_bytes = sum(path.stat().st_size for path in actual_files)
  1423. if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
  1424. raise PackagingError(
  1425. f"archive extraction inventory mismatch: {item.candidate.relative} "
  1426. f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
  1427. )
  1428. expanded_candidates, expanded_excluded, _ = scan_analysis_root(
  1429. extract_root,
  1430. extra_exclusions=extra_exclusions,
  1431. )
  1432. handoff.audit_candidates(expanded_candidates)
  1433. expanded_prefix = f"{item.candidate.relative}.expanded"
  1434. expanded_items = [
  1435. PackageItem(
  1436. candidate=_rebase_candidate(candidate, expanded_prefix),
  1437. category=item.category,
  1438. source_id=item.source_id,
  1439. original_path=f"{item.original_path}!/{candidate.relative}",
  1440. scan_archive=True,
  1441. )
  1442. for candidate in expanded_candidates
  1443. ]
  1444. rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
  1445. sensitive_rules = {
  1446. "credential_or_license_file",
  1447. "credential_configuration_file",
  1448. "private_key_file",
  1449. "secret_environment_file",
  1450. "cloud_credential_file",
  1451. "container_registry_credential_file",
  1452. }
  1453. contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
  1454. return expanded_items, rebased_excluded, contains_sensitive
  1455. def _inspect_and_extract_zip_archive(
  1456. item: PackageItem,
  1457. *,
  1458. temp_root: Path,
  1459. extra_exclusions: tuple[dict[str, str], ...],
  1460. ) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
  1461. archive_label = item.candidate.relative
  1462. try:
  1463. with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
  1464. file_members: list[zipfile.ZipInfo] = []
  1465. expected_bytes = 0
  1466. for info in archive.infolist():
  1467. normalized = info.filename.replace("\\", "/")
  1468. if (
  1469. not normalized
  1470. or normalized.startswith("/")
  1471. or re.match(r"^[A-Za-z]:", normalized)
  1472. ):
  1473. raise PackagingError(
  1474. f"unsafe archive member path in {archive_label}"
  1475. )
  1476. handoff.normalize_relative(normalized.split("/"))
  1477. if info.flag_bits & 0x1:
  1478. raise PackagingError(
  1479. f"encrypted archive member is unsupported in {archive_label}"
  1480. )
  1481. member_mode = (info.external_attr >> 16) & 0xFFFF
  1482. member_type = stat.S_IFMT(member_mode)
  1483. if info.is_dir():
  1484. if (
  1485. info.file_size != 0
  1486. or info.compress_size != 0
  1487. or member_type not in {0, stat.S_IFDIR}
  1488. ):
  1489. raise PackagingError(
  1490. f"unsafe archive member type in {archive_label}"
  1491. )
  1492. continue
  1493. if member_type not in {0, stat.S_IFREG}:
  1494. raise PackagingError(
  1495. f"unsafe archive member type in {archive_label}"
  1496. )
  1497. file_members.append(info)
  1498. expected_bytes += info.file_size
  1499. except (OSError, zipfile.BadZipFile) as exc:
  1500. raise PackagingError(
  1501. f"unable to inspect source archive: {archive_label}"
  1502. ) from exc
  1503. token = hashlib.sha256(archive_label.encode("utf-8")).hexdigest()[:16]
  1504. extract_root = temp_root / "expanded-archives" / token
  1505. extract_root.mkdir(parents=True, exist_ok=False)
  1506. actual_files: list[Path] = []
  1507. actual_bytes = 0
  1508. try:
  1509. with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
  1510. for info in file_members:
  1511. parts = info.filename.replace("\\", "/").split("/")
  1512. target_path = extract_root / Path(*parts)
  1513. target_path.parent.mkdir(parents=True, exist_ok=True)
  1514. with archive.open(info, "r") as source, target_path.open("wb") as destination:
  1515. shutil.copyfileobj(source, destination, length=1024 * 1024)
  1516. actual_files.append(target_path)
  1517. actual_bytes += target_path.stat().st_size
  1518. except (OSError, zipfile.BadZipFile) as exc:
  1519. raise PackagingError(
  1520. f"unable to extract source archive: {archive_label}"
  1521. ) from exc
  1522. if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
  1523. raise PackagingError(
  1524. f"archive extraction inventory mismatch: {archive_label} "
  1525. f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
  1526. )
  1527. expanded_candidates, expanded_excluded, _ = scan_analysis_root(
  1528. extract_root,
  1529. extra_exclusions=extra_exclusions,
  1530. )
  1531. handoff.audit_candidates(expanded_candidates)
  1532. expanded_prefix = f"{archive_label}.expanded"
  1533. expanded_items = [
  1534. PackageItem(
  1535. candidate=_rebase_candidate(candidate, expanded_prefix),
  1536. category=item.category,
  1537. source_id=item.source_id,
  1538. original_path=f"{item.original_path}!/{candidate.relative}",
  1539. scan_archive=True,
  1540. )
  1541. for candidate in expanded_candidates
  1542. ]
  1543. rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
  1544. sensitive_rules = {
  1545. "credential_or_license_file",
  1546. "credential_configuration_file",
  1547. "private_key_file",
  1548. "secret_environment_file",
  1549. "cloud_credential_file",
  1550. "container_registry_credential_file",
  1551. }
  1552. contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
  1553. return expanded_items, rebased_excluded, contains_sensitive
  1554. def prepare_unsupported_archives(
  1555. items: tuple[PackageItem, ...],
  1556. *,
  1557. temp_root: Path,
  1558. seven_zip: Path | None,
  1559. extra_exclusions: tuple[dict[str, str], ...],
  1560. ) -> ArchivePreparation:
  1561. prepared: list[PackageItem] = []
  1562. excluded: list[dict[str, str]] = []
  1563. warnings: list[dict[str, str]] = []
  1564. temp_root.mkdir(parents=True, exist_ok=True)
  1565. for item in items:
  1566. archive_kind = handoff.archive_kind(item.candidate.relative)
  1567. if archive_kind is None:
  1568. prepared.append(item)
  1569. continue
  1570. if archive_kind == "zip":
  1571. expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_zip_archive(
  1572. item,
  1573. temp_root=temp_root,
  1574. extra_exclusions=extra_exclusions,
  1575. )
  1576. elif seven_zip is None:
  1577. if _is_reference_item(item):
  1578. warnings.append(
  1579. {
  1580. "code": "unsupported_archive_without_7zip",
  1581. "source_id": item.source_id,
  1582. "path": item.candidate.relative,
  1583. "message": "7-Zip is unavailable; unsupported archive kept unexpanded",
  1584. }
  1585. )
  1586. prepared.append(item._replace(scan_archive=False))
  1587. continue
  1588. if item.candidate.absolute.is_file():
  1589. raise PackagingError(
  1590. "7-Zip is required to inspect unsupported source archives"
  1591. )
  1592. prepared.append(item._replace(scan_archive=False))
  1593. continue
  1594. else:
  1595. expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_unsupported_archive(
  1596. item,
  1597. temp_root=temp_root,
  1598. seven_zip=seven_zip,
  1599. extra_exclusions=extra_exclusions,
  1600. )
  1601. has_filtered_members = bool(expanded_excluded)
  1602. if has_filtered_members:
  1603. prepared.extend(expanded_items)
  1604. excluded.extend(expanded_excluded)
  1605. if contains_sensitive:
  1606. excluded.append(
  1607. {
  1608. "path": item.candidate.relative,
  1609. "rule": "unsupported_archive_contains_sensitive_content",
  1610. }
  1611. )
  1612. elif has_filtered_members:
  1613. excluded.append(
  1614. {
  1615. "path": item.candidate.relative,
  1616. "rule": "archive_contains_excluded_members",
  1617. }
  1618. )
  1619. else:
  1620. prepared.append(item._replace(scan_archive=archive_kind != "unsupported"))
  1621. prepared.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
  1622. excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
  1623. return ArchivePreparation(
  1624. items=tuple(prepared),
  1625. excluded=tuple(excluded),
  1626. warnings=tuple(warnings),
  1627. )
  1628. def _utc_now() -> str:
  1629. return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
  1630. def _validate_package_name(package_name: str) -> None:
  1631. try:
  1632. collision_key = handoff.windows_collision_key(package_name)
  1633. except PackagingError as exc:
  1634. raise PackagingError("package name is not a portable Windows file name") from exc
  1635. if (
  1636. not handoff.SAFE_PACKAGE_NAME.fullmatch(package_name)
  1637. or package_name in {".", ".."}
  1638. or not collision_key
  1639. ):
  1640. raise PackagingError("package name is not a portable Windows file name")
  1641. def _item_sort_key(item: PackageItem) -> tuple[int, str, str]:
  1642. return (
  1643. CATEGORY_ORDER.get(item.category, len(CATEGORY_ORDER)),
  1644. item.category.casefold(),
  1645. handoff.windows_collision_key(item.candidate.relative),
  1646. )
  1647. def _path_basename(relative: str) -> str:
  1648. return relative.casefold().rsplit("/", 1)[-1]
  1649. def _is_board_viewer_generated_path(relative: str) -> bool:
  1650. lower = relative.casefold()
  1651. return (
  1652. "board-viewer-generated" in lower
  1653. or handoff.is_under(lower, "evidence/board-viewer")
  1654. or "/tools/board-viewer/generated/" in f"/{lower}/"
  1655. or lower.startswith("tools/board-viewer/generated/")
  1656. )
  1657. def _is_reference_original_path(relative: str) -> bool:
  1658. lower = f"/{relative.casefold()}/"
  1659. return "/reference/original/" in lower or lower.startswith("/reference/original/")
  1660. def _dedup_canonical_path(paths: list[str]) -> str:
  1661. # Prefer compact evidence allowlist canonical paths first (P4).
  1662. try:
  1663. preferred = evidence_canon.prefer_canonical_path(paths)
  1664. if evidence_canon.is_compact_allowlisted(preferred):
  1665. return preferred
  1666. except ValueError:
  1667. pass
  1668. def rank(path: str) -> tuple[int, int, str]:
  1669. name = _path_basename(path)
  1670. in_reference = _is_reference_original_path(path)
  1671. in_generated = _is_board_viewer_generated_path(path)
  1672. if name in BOARD_VIEWER_GENERATED_ASSETS or name in DERIVED_BOARD_VIEWER_ASSETS:
  1673. return (0 if in_generated else 1, 0 if in_reference else 1, path.casefold())
  1674. if name.endswith((".brd", ".pdf", ".dsn", ".sch")):
  1675. return (0 if in_reference else 1, 0 if in_generated else 1, path.casefold())
  1676. return (0 if in_reference else 1, 0 if in_generated else 1, path.casefold())
  1677. return sorted(paths, key=rank)[0]
  1678. def _should_content_dedup(size: int, relative: str) -> bool:
  1679. # Keep software mirrors under source/ even when an evidence/ twin exists.
  1680. stripped = relative
  1681. lower = relative.casefold()
  1682. if lower.startswith("source/"):
  1683. stripped = relative[len("source/") :]
  1684. if stripped in _SOFTWARE_MIRROR_UNDER_SOURCE:
  1685. return False
  1686. name = _path_basename(relative)
  1687. if name in DERIVED_BOARD_VIEWER_ASSETS or name.endswith((".brd", ".pdf")):
  1688. return True
  1689. if evidence_canon.is_compact_allowlisted(relative):
  1690. return True
  1691. return size >= CONTENT_DEDUP_MIN_BYTES
  1692. def apply_content_dedup(
  1693. items: tuple[PackageItem, ...],
  1694. inventory: list[dict[str, object]],
  1695. ) -> tuple[tuple[PackageItem, ...], list[dict[str, object]], list[dict[str, str]]]:
  1696. """Keep one physical copy per identical content hash; record logical aliases."""
  1697. by_path = {str(row["path"]): row for row in inventory}
  1698. groups: dict[str, list[PackageItem]] = {}
  1699. for item in items:
  1700. row = by_path[item.candidate.relative]
  1701. sha = str(row["sha256"])
  1702. size = int(row["size"])
  1703. if not _should_content_dedup(size, item.candidate.relative):
  1704. continue
  1705. groups.setdefault(sha, []).append(item)
  1706. drop_paths: set[str] = set()
  1707. dedup_records: list[dict[str, object]] = []
  1708. excluded: list[dict[str, str]] = []
  1709. for sha, group in sorted(groups.items(), key=lambda pair: pair[0]):
  1710. if len(group) < 2:
  1711. continue
  1712. paths = [item.candidate.relative for item in group]
  1713. canonical = _dedup_canonical_path(paths)
  1714. aliases = sorted(path for path in paths if path != canonical)
  1715. if not aliases:
  1716. continue
  1717. size = int(by_path[canonical]["size"])
  1718. dedup_records.append(
  1719. {
  1720. "sha256": sha,
  1721. "size": size,
  1722. "physical_path": canonical,
  1723. "logical_paths": aliases,
  1724. "reason": "identical_content_single_physical_copy",
  1725. }
  1726. )
  1727. for alias in aliases:
  1728. drop_paths.add(alias)
  1729. excluded.append(
  1730. {
  1731. "path": alias,
  1732. "rule": "duplicate_content_logical_alias",
  1733. }
  1734. )
  1735. physical_items = tuple(
  1736. item for item in items if item.candidate.relative not in drop_paths
  1737. )
  1738. dedup_records.sort(key=lambda row: str(row["physical_path"]).casefold())
  1739. excluded.sort(key=lambda row: handoff.windows_collision_key(row["path"]))
  1740. return physical_items, dedup_records, excluded
  1741. def classify_derived_evidence(items: tuple[PackageItem, ...]) -> list[dict[str, object]]:
  1742. derived: list[dict[str, object]] = []
  1743. for item in items:
  1744. name = _path_basename(item.candidate.relative)
  1745. if name not in DERIVED_BOARD_VIEWER_ASSETS:
  1746. continue
  1747. if not _is_board_viewer_generated_path(item.candidate.relative):
  1748. continue
  1749. role = "derived_from_brd_visual" if name in BOARD_VIEWER_GENERATED_ASSETS else "derived_from_brd_parsed"
  1750. derived.append(
  1751. {
  1752. "path": item.candidate.relative,
  1753. "asset": name,
  1754. "role": role,
  1755. "authority": "analysis_evidence_not_source_closure",
  1756. "note": "Derived from the original Allegro BRD for remote analysis; not RTL/TD source closure.",
  1757. }
  1758. )
  1759. derived.sort(key=lambda row: str(row["path"]).casefold())
  1760. return derived
  1761. def replay_analysis_package(package_dir: Path, *, extract_root: Path) -> dict[str, object]:
  1762. """Extract a published package and verify SHA256SUMS plus inventory hashes.
  1763. Returns package-content verification plus the four-state replay skeleton:
  1764. ``package_content_replay``, ``detached_software_replay`` (not_run here),
  1765. ``reference_regeneration_replay=not_packaged_by_policy``,
  1766. ``hardware_validation=not_run``. Full detached software orchestration lives in
  1767. ``tools/replay_review_compact.py``.
  1768. """
  1769. package_dir = package_dir.expanduser().resolve(strict=True)
  1770. extract_root = extract_root.expanduser().resolve(strict=False)
  1771. if extract_root.exists():
  1772. raise PackagingError(f"replay extract root already exists: {extract_root}")
  1773. index_path = package_dir / "HANDOFF-INDEX.json"
  1774. sums_path = package_dir / "SHA256SUMS.txt"
  1775. exclusions_path = package_dir / "EXCLUSIONS.txt"
  1776. if not index_path.is_file() or not sums_path.is_file():
  1777. raise PackagingError("package directory is missing HANDOFF-INDEX.json or SHA256SUMS.txt")
  1778. index = json.loads(index_path.read_text(encoding="utf-8"))
  1779. extract_root.mkdir(parents=True, exist_ok=False)
  1780. zip_extract_root = extract_root / "from-zip"
  1781. tar_extract_root = extract_root / "from-tar-zst"
  1782. zip_extract_root.mkdir(parents=True, exist_ok=True)
  1783. verified_volumes: list[dict[str, object]] = []
  1784. verified_sidecars: list[dict[str, object]] = []
  1785. tar_zst_name: str | None = None
  1786. for line in sums_path.read_text(encoding="ascii").splitlines():
  1787. line = line.strip()
  1788. if not line or line.startswith("#"):
  1789. continue
  1790. digest, _, name = line.partition(" ")
  1791. if not digest or not name:
  1792. raise PackagingError(f"invalid SHA256SUMS line: {line}")
  1793. member_path = package_dir / name
  1794. actual = handoff.sha256_file(member_path)
  1795. if actual != digest:
  1796. raise PackagingError(f"SHA256SUMS mismatch for {name}")
  1797. lower = name.casefold()
  1798. if lower.endswith(".zip"):
  1799. with zipfile.ZipFile(member_path, "r", allowZip64=True) as archive:
  1800. archive.extractall(zip_extract_root)
  1801. verified_volumes.append({"file": name, "sha256": actual})
  1802. elif lower.endswith(".tar.zst"):
  1803. tar_zst_name = name
  1804. tar_extract_root.mkdir(parents=True, exist_ok=True)
  1805. completed = subprocess.run(
  1806. ["tar", "--zstd", "-xf", str(member_path), "-C", str(tar_extract_root)],
  1807. stdout=subprocess.PIPE,
  1808. stderr=subprocess.PIPE,
  1809. check=False,
  1810. )
  1811. if completed.returncode != 0:
  1812. raise PackagingError(
  1813. f"unable to extract tar.zst during replay: {name}: "
  1814. f"{completed.stderr.decode('utf-8', errors='replace').strip()}"
  1815. )
  1816. verified_sidecars.append({"file": name, "sha256": actual, "kind": "tar_zst"})
  1817. else:
  1818. verified_sidecars.append({"file": name, "sha256": actual, "kind": "sidecar"})
  1819. checked_files = 0
  1820. for item in index.get("files", []):
  1821. relative = str(item["path"])
  1822. target = zip_extract_root / "CPLD" / Path(*relative.split("/"))
  1823. if not target.is_file():
  1824. raise PackagingError(f"replay missing extracted file: {relative}")
  1825. digest = handoff.sha256_file(target)
  1826. if digest != item["sha256"] or target.stat().st_size != int(item["size"]):
  1827. raise PackagingError(f"replay hash mismatch for {relative}")
  1828. if tar_zst_name is not None:
  1829. # tar.zst is created from ZIP extract roots, so the same CPLD tree must round-trip.
  1830. tar_target = tar_extract_root / "CPLD" / Path(*relative.split("/"))
  1831. if not tar_target.is_file():
  1832. raise PackagingError(f"tar.zst replay missing extracted file: {relative}")
  1833. if handoff.sha256_file(tar_target) != digest:
  1834. raise PackagingError(f"tar.zst replay hash mismatch for {relative}")
  1835. checked_files += 1
  1836. for record in index.get("content_dedup", []):
  1837. physical = zip_extract_root / "CPLD" / Path(*str(record["physical_path"]).split("/"))
  1838. if not physical.is_file():
  1839. raise PackagingError(f"replay missing dedup physical file: {record['physical_path']}")
  1840. for alias in record.get("logical_paths", []):
  1841. alias_path = zip_extract_root / "CPLD" / Path(*str(alias).split("/"))
  1842. if alias_path.exists():
  1843. raise PackagingError(f"replay found duplicated physical alias path: {alias}")
  1844. cpld_root = zip_extract_root / "CPLD"
  1845. return {
  1846. "status": "pass",
  1847. "mode": "package_replay",
  1848. "package_dir": str(package_dir),
  1849. "extract_root": str(extract_root),
  1850. "cpld_root": str(cpld_root) if cpld_root.is_dir() else None,
  1851. "volumes": verified_volumes,
  1852. "sidecars": verified_sidecars,
  1853. "exclusions_present": exclusions_path.is_file(),
  1854. "tar_zst": tar_zst_name,
  1855. "checked_files": checked_files,
  1856. "content_dedup_groups": len(index.get("content_dedup", [])),
  1857. "derived_evidence_count": len(index.get("derived_evidence", [])),
  1858. # Four-state skeleton (content only; software lane filled by replay_review_compact).
  1859. "package_content_replay": "pass",
  1860. "detached_software_replay": "not_run",
  1861. "reference_regeneration_replay": "not_packaged_by_policy",
  1862. "hardware_validation": "not_run",
  1863. }
  1864. def _audit_one_item(item: PackageItem) -> dict[str, object]:
  1865. if item.scan_archive:
  1866. file_inventory = handoff.stream_candidate(item.candidate)
  1867. else:
  1868. file_inventory = handoff.hash_candidate(item.candidate)
  1869. return {
  1870. **file_inventory,
  1871. "archive_path": f"CPLD/{item.candidate.relative}",
  1872. "category": item.category,
  1873. "source_id": item.source_id,
  1874. "original_path": item.original_path,
  1875. }
  1876. def _audit_package_items(items: tuple[PackageItem, ...]) -> list[dict[str, object]]:
  1877. sorted_items = sorted(items, key=_item_sort_key)
  1878. collision_paths: dict[str, str] = {}
  1879. for item in sorted_items:
  1880. key = handoff.windows_collision_key(item.candidate.relative)
  1881. previous = collision_paths.get(key)
  1882. if previous is not None:
  1883. raise PackagingError(
  1884. f"analysis inputs contain a Windows path collision: {previous} and {item.candidate.relative}"
  1885. )
  1886. collision_paths[key] = item.candidate.relative
  1887. max_workers = os.cpu_count() or 1
  1888. with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
  1889. return list(executor.map(_audit_one_item, sorted_items))
  1890. def _write_unscanned_candidate(
  1891. archive: zipfile.ZipFile,
  1892. item: PackageItem,
  1893. ) -> dict[str, object]:
  1894. candidate = item.candidate
  1895. digest = hashlib.sha256()
  1896. total = 0
  1897. secret_tail = b""
  1898. entry_name = f"CPLD/{candidate.relative}"
  1899. try:
  1900. with archive.open(handoff.zip_info(entry_name, candidate.mode), "w", force_zip64=True) as target:
  1901. with handoff.open_candidate(candidate) as source:
  1902. for chunk in iter(lambda: source.read(1024 * 1024), b""):
  1903. secret_tail = handoff.scan_secret_markers(
  1904. chunk,
  1905. secret_tail,
  1906. candidate.relative,
  1907. )
  1908. target.write(chunk)
  1909. digest.update(chunk)
  1910. total += len(chunk)
  1911. except OSError as exc:
  1912. raise PackagingError(f"unable to package {candidate.relative}: {exc}") from exc
  1913. if total != candidate.size:
  1914. raise PackagingError(f"source size changed during packaging: {candidate.relative}")
  1915. return {"path": candidate.relative, "size": total, "sha256": digest.hexdigest()}
  1916. def _write_package_item(
  1917. archive: zipfile.ZipFile,
  1918. item: PackageItem,
  1919. ) -> dict[str, object]:
  1920. if item.scan_archive:
  1921. return handoff.write_candidate(archive, item.candidate)
  1922. return _write_unscanned_candidate(archive, item)
  1923. def _stage_package_item(
  1924. staging_root: Path,
  1925. item: PackageItem,
  1926. staging_name: str,
  1927. ) -> dict[str, object]:
  1928. target = staging_root / "CPLD" / staging_name
  1929. target.parent.mkdir(parents=True, exist_ok=True)
  1930. if item.scan_archive:
  1931. try:
  1932. with target.open("wb") as destination:
  1933. return handoff.stream_candidate(item.candidate, target=destination)
  1934. except OSError as exc:
  1935. raise PackagingError(f"unable to stage {item.candidate.relative}: {exc}") from exc
  1936. digest = hashlib.sha256()
  1937. total = 0
  1938. secret_tail = b""
  1939. try:
  1940. with handoff.open_candidate(item.candidate) as source, target.open("wb") as destination:
  1941. for chunk in iter(lambda: source.read(1024 * 1024), b""):
  1942. secret_tail = handoff.scan_secret_markers(
  1943. chunk,
  1944. secret_tail,
  1945. item.candidate.relative,
  1946. )
  1947. destination.write(chunk)
  1948. digest.update(chunk)
  1949. total += len(chunk)
  1950. except OSError as exc:
  1951. raise PackagingError(f"unable to stage {item.candidate.relative}: {exc}") from exc
  1952. if total != item.candidate.size:
  1953. raise PackagingError(f"source size changed during staging: {item.candidate.relative}")
  1954. return {"path": item.candidate.relative, "size": total, "sha256": digest.hexdigest()}
  1955. def _volume_manifest(
  1956. *,
  1957. run_id: str,
  1958. package_name: str,
  1959. number: int,
  1960. count: int,
  1961. items: list[PackageItem],
  1962. inventory_by_path: dict[str, dict[str, object]],
  1963. ) -> dict[str, object]:
  1964. categories = sorted({item.category for item in items})
  1965. entries = [inventory_by_path[item.candidate.relative] for item in items]
  1966. return {
  1967. "schema": "cpld-agent-analysis-volume-v1",
  1968. "run_id": run_id,
  1969. "package_name": package_name,
  1970. "volume_number": number,
  1971. "volume_count": count,
  1972. "categories": categories,
  1973. "file_count": len(entries),
  1974. "uncompressed_bytes": sum(int(entry["size"]) for entry in entries),
  1975. "files": entries,
  1976. }
  1977. def _write_volume(
  1978. path: Path,
  1979. *,
  1980. run_id: str,
  1981. package_name: str,
  1982. number: int,
  1983. count: int,
  1984. items: list[PackageItem],
  1985. inventory_by_path: dict[str, dict[str, object]],
  1986. ) -> dict[str, object]:
  1987. manifest = _volume_manifest(
  1988. run_id=run_id,
  1989. package_name=package_name,
  1990. number=number,
  1991. count=count,
  1992. items=items,
  1993. inventory_by_path=inventory_by_path,
  1994. )
  1995. manifest_name = "CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json"
  1996. manifest_payload = handoff.json_bytes(manifest)
  1997. written_inventory: list[dict[str, object]] = []
  1998. try:
  1999. with zipfile.ZipFile(
  2000. path,
  2001. "w",
  2002. compression=zipfile.ZIP_DEFLATED,
  2003. compresslevel=9,
  2004. allowZip64=True,
  2005. ) as archive:
  2006. for item in sorted(items, key=_item_sort_key):
  2007. expected = inventory_by_path[item.candidate.relative]
  2008. if item.scan_archive:
  2009. actual = handoff.write_candidate(archive, item.candidate)
  2010. else:
  2011. actual = _write_unscanned_candidate(archive, item)
  2012. if (
  2013. actual["size"] != expected["size"]
  2014. or actual["sha256"] != expected["sha256"]
  2015. ):
  2016. raise PackagingError(
  2017. f"source changed while writing ZIP: {item.candidate.relative}"
  2018. )
  2019. written_inventory.append(actual)
  2020. with archive.open(
  2021. handoff.zip_info(manifest_name), "w", force_zip64=True
  2022. ) as target:
  2023. target.write(manifest_payload)
  2024. except (OSError, zipfile.BadZipFile) as exc:
  2025. raise PackagingError(f"unable to create ZIP volume: {exc}") from exc
  2026. expected_names = {f"CPLD/{item.candidate.relative}" for item in items}
  2027. expected_names.add(manifest_name)
  2028. handoff.verify_archive(
  2029. path,
  2030. expected_names=expected_names,
  2031. inventory=written_inventory,
  2032. expected_payloads={manifest_name: manifest_payload},
  2033. )
  2034. return {
  2035. "file": path.name,
  2036. "volume_number": number,
  2037. "volume_count": count,
  2038. "categories": manifest["categories"],
  2039. "file_count": len(items),
  2040. "uncompressed_bytes": manifest["uncompressed_bytes"],
  2041. "compressed_bytes": path.stat().st_size,
  2042. "sha256": handoff.sha256_file(path),
  2043. }
  2044. def _estimated_item_bytes(item: PackageItem) -> int:
  2045. return item.candidate.size + 512 + (len(item.candidate.relative.encode("utf-8")) * 2)
  2046. def _partition_items(
  2047. items: tuple[PackageItem, ...],
  2048. *,
  2049. target_zip_bytes: int,
  2050. ) -> list[list[PackageItem]]:
  2051. base_overhead = min(64_000, max(1_024, target_zip_bytes // 20))
  2052. groups: list[list[PackageItem]] = []
  2053. current: list[PackageItem] = []
  2054. current_category: str | None = None
  2055. estimated_bytes = base_overhead
  2056. for item in sorted(items, key=_item_sort_key):
  2057. item_estimate = _estimated_item_bytes(item)
  2058. if current and (
  2059. item.category != current_category
  2060. or estimated_bytes + item_estimate > target_zip_bytes
  2061. ):
  2062. groups.append(current)
  2063. current = []
  2064. estimated_bytes = base_overhead
  2065. if not current:
  2066. current_category = item.category
  2067. current.append(item)
  2068. estimated_bytes += item_estimate
  2069. if current:
  2070. groups.append(current)
  2071. return groups
  2072. def _split_oversized_groups(
  2073. staging: Path,
  2074. *,
  2075. run_id: str,
  2076. package_name: str,
  2077. groups: list[list[PackageItem]],
  2078. inventory_by_path: dict[str, dict[str, object]],
  2079. target_zip_bytes: int,
  2080. max_zip_bytes: int,
  2081. ) -> list[list[PackageItem]]:
  2082. pending = list(groups)
  2083. accepted: list[list[PackageItem]] = []
  2084. probe_number = 0
  2085. while pending:
  2086. group = pending.pop(0)
  2087. probe_number += 1
  2088. probe = staging / f".volume-probe-{probe_number:04d}.zip"
  2089. try:
  2090. _write_volume(
  2091. probe,
  2092. run_id=run_id,
  2093. package_name=package_name,
  2094. number=1,
  2095. count=1,
  2096. items=group,
  2097. inventory_by_path=inventory_by_path,
  2098. )
  2099. size = probe.stat().st_size
  2100. finally:
  2101. probe.unlink(missing_ok=True)
  2102. if size < max_zip_bytes and (size <= target_zip_bytes or len(group) == 1):
  2103. accepted.append(group)
  2104. continue
  2105. if len(group) == 1:
  2106. raise PackagingError(
  2107. f"single analysis file requires chunking before ZIP creation: {group[0].candidate.relative}"
  2108. )
  2109. middle = len(group) // 2
  2110. pending[0:0] = [group[:middle], group[middle:]]
  2111. return accepted
  2112. def _prepare_large_file_chunks(
  2113. staging: Path,
  2114. *,
  2115. run_id: str,
  2116. package_name: str,
  2117. items: tuple[PackageItem, ...],
  2118. inventory_by_path: dict[str, dict[str, object]],
  2119. target_zip_bytes: int,
  2120. max_zip_bytes: int,
  2121. ) -> tuple[tuple[PackageItem, ...], list[dict[str, object]], Path | None]:
  2122. packaged_items: list[PackageItem] = []
  2123. large_files: list[dict[str, object]] = []
  2124. chunk_root: Path | None = None
  2125. probe_number = 0
  2126. chunk_payload_bytes = max(1, (target_zip_bytes * 3) // 4)
  2127. for item in sorted(items, key=_item_sort_key):
  2128. must_probe = _estimated_item_bytes(item) > target_zip_bytes
  2129. if must_probe:
  2130. probe_number += 1
  2131. probe = staging / f".large-file-probe-{probe_number:04d}.zip"
  2132. try:
  2133. _write_volume(
  2134. probe,
  2135. run_id=run_id,
  2136. package_name=package_name,
  2137. number=1,
  2138. count=1,
  2139. items=[item],
  2140. inventory_by_path=inventory_by_path,
  2141. )
  2142. probe_size = probe.stat().st_size
  2143. finally:
  2144. probe.unlink(missing_ok=True)
  2145. if probe_size <= target_zip_bytes and probe_size < max_zip_bytes:
  2146. packaged_items.append(item)
  2147. continue
  2148. else:
  2149. packaged_items.append(item)
  2150. continue
  2151. if chunk_root is None:
  2152. chunk_root = staging / ".large-file-chunks"
  2153. chunk_root.mkdir()
  2154. original = inventory_by_path[item.candidate.relative]
  2155. file_id = hashlib.sha256(item.candidate.relative.encode("utf-8")).hexdigest()[:16]
  2156. file_chunk_root = chunk_root / file_id
  2157. file_chunk_root.mkdir()
  2158. file_name = Path(item.candidate.relative).name
  2159. chunks: list[dict[str, object]] = []
  2160. original_digest = hashlib.sha256()
  2161. original_bytes = 0
  2162. secret_tail = b""
  2163. with handoff.open_candidate(item.candidate) as source:
  2164. number = 0
  2165. while True:
  2166. payload = source.read(chunk_payload_bytes)
  2167. if not payload:
  2168. break
  2169. number += 1
  2170. secret_tail = handoff.scan_secret_markers(
  2171. payload,
  2172. secret_tail,
  2173. item.candidate.relative,
  2174. )
  2175. original_digest.update(payload)
  2176. original_bytes += len(payload)
  2177. chunk_name = f"{file_name}.part{number:04d}"
  2178. chunk_path = file_chunk_root / chunk_name
  2179. with chunk_path.open("xb") as handle:
  2180. handle.write(payload)
  2181. chunk_relative = f"HANDOFF-LARGE-FILES/{file_id}/{chunk_name}"
  2182. chunk_item = make_package_item(
  2183. chunk_path,
  2184. relative=chunk_relative,
  2185. category=item.category,
  2186. source_id=item.source_id,
  2187. scan_archive=False,
  2188. )
  2189. packaged_items.append(chunk_item)
  2190. chunks.append(
  2191. {
  2192. "number": number,
  2193. "path": chunk_relative,
  2194. "archive_path": f"CPLD/{chunk_relative}",
  2195. "size": len(payload),
  2196. "sha256": hashlib.sha256(payload).hexdigest(),
  2197. }
  2198. )
  2199. if original_bytes != original["size"] or original_digest.hexdigest() != original["sha256"]:
  2200. raise PackagingError(f"source changed while splitting large file: {item.candidate.relative}")
  2201. if len(chunks) < 2:
  2202. raise PackagingError(f"large file split did not produce multiple chunks: {item.candidate.relative}")
  2203. large_files.append(
  2204. {
  2205. "path": item.candidate.relative,
  2206. "category": item.category,
  2207. "source_id": item.source_id,
  2208. "original_path": item.original_path,
  2209. "size": original["size"],
  2210. "sha256": original["sha256"],
  2211. "chunks": chunks,
  2212. }
  2213. )
  2214. return tuple(packaged_items), large_files, chunk_root
  2215. def _assert_items_unchanged(
  2216. items: tuple[PackageItem, ...],
  2217. inventory_by_path: dict[str, dict[str, object]],
  2218. ) -> None:
  2219. for item in items:
  2220. current = handoff.hash_candidate(item.candidate)
  2221. expected = inventory_by_path[item.candidate.relative]
  2222. if current["size"] != expected["size"] or current["sha256"] != expected["sha256"]:
  2223. raise PackagingError(f"source changed during analysis packaging: {item.candidate.relative}")
  2224. def _assert_source_trees_unchanged(collection: AnalysisCollection, *, profile: str = "full") -> None:
  2225. for snapshot in collection.source_snapshots:
  2226. # Prefer the profile captured at collection time so review-compact
  2227. # snapshots are not re-scanned under the create_analysis_package default.
  2228. check_profile = snapshot.profile or profile
  2229. current = _source_snapshot(
  2230. snapshot.root,
  2231. source_id=snapshot.source_id,
  2232. extra_exclusions=snapshot.extra_exclusions,
  2233. profile=check_profile,
  2234. )
  2235. if (
  2236. current.candidates != snapshot.candidates
  2237. or current.excluded != snapshot.excluded
  2238. ):
  2239. raise PackagingError("source tree changed during analysis packaging: retry from a stable workspace snapshot")
  2240. def _start_here_text(package_name: str, volume_count: int, *, profile: str = "full") -> str:
  2241. base = (
  2242. f"# {package_name} 分析交付包\n\n"
  2243. f"本目录包含 {volume_count} 个互相独立的普通 ZIP,以及可选的 `.tar.zst` 同源归档。"
  2244. "请先核对 `SHA256SUMS.txt`,再把所有 ZIP 解压到同一个目录;"
  2245. "也可用 `tar --zstd -xf <package>.tar.zst` 还原。\n\n"
  2246. "`HANDOFF-INDEX.json` 记录每个原始文件的来源、目标卷、大小和 SHA-256,"
  2247. "`EXCLUSIONS.txt` 列出排除路径与规则,"
  2248. "以及 `excluded`(排除原因)、`derived_evidence`(由原始 BRD 派生的 board-viewer JSON/SVG,"
  2249. "不是 RTL/TD source closure)和 `content_dedup`(相同大文件只保留一份物理副本时的逻辑归属)。\n"
  2250. )
  2251. if handoff.uses_unified_layout(profile):
  2252. return base + (
  2253. "本包为统一布局:`source/` + `evidence/` + `meta/`。\n"
  2254. "`PACKAGE-PURPOSE.txt` 说明上传意图;`size-budget.json` 列出 ≥256KiB 或 >1% 体积的成员。\n"
  2255. "默认 **不含** 完整 Git bundle;`meta/git/` 提供 commit/status/log-20/tree/逐文件 SHA-256 "
  2256. "与 TD source-closure 绑定钩子。\n"
  2257. "成员计数:`member_count.indexed_files` 对应 ZIP 内业务文件;"
  2258. "`self_reference_control_files` 是包目录控制文件(亦列入 SHA256SUMS),"
  2259. "不要把控制文件与 ZIP payload 成员重复加总。\n"
  2260. )
  2261. return base + (
  2262. "完整 full 包必须包含 `git-history/*.bundle`,以便在干净提取后用 commit-to-commit "
  2263. "恢复 source closure 比对。\n"
  2264. )
  2265. def build_member_count_semantics(
  2266. *,
  2267. indexed_files: int,
  2268. zip_file_entries: int,
  2269. control_files: tuple[str, ...] = SELF_REFERENCE_CONTROL_FILES,
  2270. ) -> dict[str, object]:
  2271. return {
  2272. "indexed_files": indexed_files,
  2273. "zip_file_entries": zip_file_entries,
  2274. "self_reference_control_files": list(control_files),
  2275. "note": (
  2276. "indexed_files counts HANDOFF-INDEX files[] (ZIP payload business members). "
  2277. "zip_file_entries counts non-directory ZIP entries including VOLUME-MANIFEST. "
  2278. "self_reference_control_files live in the package directory and appear in "
  2279. "SHA256SUMS; do not add them again to indexed_files."
  2280. ),
  2281. }
  2282. def write_exclusions_text(excluded: list[dict[str, object]]) -> str:
  2283. """Render a portable EXCLUSIONS.txt for the package sidecar layout."""
  2284. lines = [
  2285. "# path<TAB>rule",
  2286. "# Inclusion-first package: only versioned recursive exclusions are listed.",
  2287. ]
  2288. for item in sorted(excluded, key=lambda row: handoff.windows_collision_key(str(row.get("path", "")))):
  2289. path = str(item.get("path", ""))
  2290. rule = str(item.get("rule", item.get("reason", "excluded")))
  2291. lines.append(f"{path}\t{rule}")
  2292. return "\n".join(lines) + "\n"
  2293. def create_tar_zst_archive(source_dir: Path, archive_path: Path) -> str:
  2294. """Create a deterministic-enough tar.zst of source_dir contents; return SHA-256."""
  2295. source_dir = source_dir.resolve(strict=True)
  2296. archive_path = archive_path.resolve(strict=False)
  2297. if archive_path.exists():
  2298. archive_path.unlink()
  2299. zstd = shutil.which("zstd")
  2300. if zstd is None:
  2301. raise PackagingError("zstd is required to create .tar.zst package archives")
  2302. # Prefer GNU tar --zstd when available; fall back to compress-program.
  2303. command = [
  2304. "tar",
  2305. "--zstd",
  2306. "-cf",
  2307. str(archive_path),
  2308. "--sort=name",
  2309. "--mtime=UTC 1980-01-01",
  2310. "--owner=0",
  2311. "--group=0",
  2312. "--numeric-owner",
  2313. "-C",
  2314. str(source_dir),
  2315. ".",
  2316. ]
  2317. completed = subprocess.run(
  2318. command,
  2319. stdout=subprocess.PIPE,
  2320. stderr=subprocess.PIPE,
  2321. check=False,
  2322. )
  2323. if completed.returncode != 0:
  2324. # Older tar without --zstd / --sort: use compress-program path.
  2325. fallback = [
  2326. "tar",
  2327. "-cf",
  2328. str(archive_path),
  2329. "-I",
  2330. zstd,
  2331. "-C",
  2332. str(source_dir),
  2333. ".",
  2334. ]
  2335. completed = subprocess.run(
  2336. fallback,
  2337. stdout=subprocess.PIPE,
  2338. stderr=subprocess.PIPE,
  2339. check=False,
  2340. )
  2341. if completed.returncode != 0:
  2342. detail = completed.stderr.decode("utf-8", errors="replace").strip()
  2343. raise PackagingError(f"unable to create tar.zst archive: {detail or 'tar failed'}")
  2344. return handoff.sha256_file(archive_path)
  2345. def write_package_layout_sidecars(
  2346. staging: Path,
  2347. *,
  2348. index: dict[str, object],
  2349. excluded: list[dict[str, object]],
  2350. package_name: str,
  2351. include_tar_zst: bool = True,
  2352. profile: str = "full",
  2353. size_budget: dict[str, object] | None = None,
  2354. ) -> list[dict[str, object]]:
  2355. """Write index/checksums/exclusions and optional tar.zst; return checksum rows."""
  2356. staging.mkdir(parents=True, exist_ok=True)
  2357. (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
  2358. (staging / "EXCLUSIONS.txt").write_text(
  2359. write_exclusions_text(excluded),
  2360. encoding="utf-8",
  2361. newline="\n",
  2362. )
  2363. (staging / "PACKAGE-PURPOSE.txt").write_text(
  2364. handoff.package_purpose_text(profile, package_name=package_name),
  2365. encoding="utf-8",
  2366. newline="\n",
  2367. )
  2368. (staging / "START-HERE.zh-CN.md").write_text(
  2369. _start_here_text(package_name, len(index.get("volumes", [])), profile=profile),
  2370. encoding="utf-8",
  2371. newline="\n",
  2372. )
  2373. if size_budget is not None:
  2374. (staging / "size-budget.json").write_bytes(handoff.json_bytes(size_budget))
  2375. checksum_rows: list[dict[str, object]] = []
  2376. for info in index.get("volumes", []):
  2377. name = str(info["file"])
  2378. checksum_rows.append({"file": name, "sha256": str(info["sha256"])})
  2379. if include_tar_zst:
  2380. # Stage CPLD tree from ZIP volumes into a temporary extract for tar.zst.
  2381. extract_root = staging / ".tar-zst-staging"
  2382. if extract_root.exists():
  2383. shutil.rmtree(extract_root)
  2384. extract_root.mkdir(parents=True, exist_ok=True)
  2385. for info in index.get("volumes", []):
  2386. volume_path = staging / str(info["file"])
  2387. with zipfile.ZipFile(volume_path, "r", allowZip64=True) as archive:
  2388. archive.extractall(extract_root)
  2389. tar_name = f"{package_name}.tar.zst"
  2390. tar_path = staging / tar_name
  2391. tar_sha = create_tar_zst_archive(extract_root, tar_path)
  2392. shutil.rmtree(extract_root)
  2393. checksum_rows.append({"file": tar_name, "sha256": tar_sha})
  2394. index["formats"] = {
  2395. "zip_volumes": [str(info["file"]) for info in index.get("volumes", [])],
  2396. "tar_zst": tar_name,
  2397. "tar_zst_sha256": tar_sha,
  2398. }
  2399. (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
  2400. sidecar_names = [
  2401. "HANDOFF-INDEX.json",
  2402. "EXCLUSIONS.txt",
  2403. "PACKAGE-PURPOSE.txt",
  2404. "START-HERE.zh-CN.md",
  2405. ]
  2406. if size_budget is not None:
  2407. sidecar_names.append("size-budget.json")
  2408. for sidecar in sidecar_names:
  2409. checksum_rows.append(
  2410. {"file": sidecar, "sha256": handoff.sha256_file(staging / sidecar)}
  2411. )
  2412. checksum_lines = [f"{row['sha256']} {row['file']}" for row in checksum_rows]
  2413. (staging / "SHA256SUMS.txt").write_text(
  2414. "\n".join(checksum_lines) + "\n",
  2415. encoding="ascii",
  2416. newline="\n",
  2417. )
  2418. return checksum_rows
  2419. def _publish_directory_atomically(staging: Path, final: Path, *, force: bool) -> None:
  2420. backup: Path | None = None
  2421. backup_created = False
  2422. new_directory_published = False
  2423. if os.path.lexists(final):
  2424. if not force:
  2425. raise PackagingError(f"package output already exists: {final}")
  2426. file_stat = os.lstat(final)
  2427. if not stat.S_ISDIR(file_stat.st_mode) or handoff.stat_is_reparse_point(file_stat):
  2428. raise PackagingError(f"existing package output is not a regular directory: {final}")
  2429. backup = final.with_name(f".{final.name}.{uuid.uuid4().hex}.backup")
  2430. try:
  2431. if backup is not None:
  2432. os.replace(final, backup)
  2433. backup_created = True
  2434. os.replace(staging, final)
  2435. new_directory_published = True
  2436. except BaseException as exc:
  2437. if new_directory_published and os.path.lexists(final):
  2438. try:
  2439. shutil.rmtree(final)
  2440. except OSError:
  2441. pass
  2442. if backup_created and backup is not None and os.path.lexists(backup):
  2443. try:
  2444. os.replace(backup, final)
  2445. except OSError as rollback_exc:
  2446. raise PackagingError(
  2447. f"package publication failed and rollback was incomplete: {rollback_exc}"
  2448. ) from exc
  2449. if isinstance(exc, PackagingError):
  2450. raise
  2451. raise PackagingError(f"unable to publish package directory atomically: {exc}") from exc
  2452. if backup is not None:
  2453. shutil.rmtree(backup)
  2454. def create_analysis_package(
  2455. *,
  2456. collection: AnalysisCollection,
  2457. output_root: Path,
  2458. package_name: str,
  2459. max_zip_bytes: int,
  2460. target_zip_bytes: int,
  2461. force: bool,
  2462. profile: str = "full",
  2463. ) -> dict[str, object]:
  2464. _validate_package_name(package_name)
  2465. if max_zip_bytes <= 0 or not 0 < target_zip_bytes < max_zip_bytes:
  2466. raise PackagingError("ZIP size limits are invalid")
  2467. if not collection.items:
  2468. raise PackagingError("analysis package has no included files")
  2469. output_root = output_root.expanduser().resolve(strict=False)
  2470. output_root.mkdir(parents=True, exist_ok=True)
  2471. final_dir = output_root / package_name
  2472. if os.path.lexists(final_dir) and not force:
  2473. raise PackagingError(f"package output already exists: {final_dir}")
  2474. run_id = uuid.uuid4().hex
  2475. staging = Path(tempfile.mkdtemp(prefix=f".{package_name}.{run_id}.", dir=output_root))
  2476. try:
  2477. full_inventory = _audit_package_items(collection.items)
  2478. physical_items, content_dedup, dedup_excluded = apply_content_dedup(
  2479. collection.items,
  2480. full_inventory,
  2481. )
  2482. inventory = [
  2483. row
  2484. for row in full_inventory
  2485. if str(row["path"]) in {item.candidate.relative for item in physical_items}
  2486. ]
  2487. inventory_by_path = {str(item["path"]): item for item in inventory}
  2488. package_excluded = list(collection.excluded) + dedup_excluded
  2489. package_excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
  2490. derived_evidence = classify_derived_evidence(physical_items)
  2491. evidence_canon_fields = dict(collection.evidence_canon or {})
  2492. # Merge content_dedup logical aliases into evidence_canon.aliases for HANDOFF-INDEX.
  2493. evidence_aliases = list(evidence_canon_fields.get("aliases", [])) # type: ignore[arg-type]
  2494. for record in content_dedup:
  2495. evidence_aliases.append(
  2496. {
  2497. "key": None,
  2498. "sha256": record["sha256"],
  2499. "size": record["size"],
  2500. "physical_path": record["physical_path"],
  2501. "logical_paths": record["logical_paths"],
  2502. "reason": record["reason"],
  2503. }
  2504. )
  2505. if evidence_canon_fields:
  2506. evidence_canon_fields["aliases"] = evidence_aliases
  2507. package_items = physical_items
  2508. package_inventory = inventory
  2509. package_inventory_by_path = inventory_by_path
  2510. large_files: list[dict[str, object]] = []
  2511. chunk_root: Path | None = None
  2512. single_path = staging / f"{package_name}.zip"
  2513. single_info = _write_volume(
  2514. single_path,
  2515. run_id=run_id,
  2516. package_name=package_name,
  2517. number=1,
  2518. count=1,
  2519. items=list(sorted(physical_items, key=_item_sort_key)),
  2520. inventory_by_path=inventory_by_path,
  2521. )
  2522. if single_path.stat().st_size < max_zip_bytes:
  2523. volume_infos = [single_info]
  2524. groups = [list(sorted(physical_items, key=_item_sort_key))]
  2525. else:
  2526. single_path.unlink()
  2527. package_items, large_files, chunk_root = _prepare_large_file_chunks(
  2528. staging,
  2529. run_id=run_id,
  2530. package_name=package_name,
  2531. items=physical_items,
  2532. inventory_by_path=inventory_by_path,
  2533. target_zip_bytes=target_zip_bytes,
  2534. max_zip_bytes=max_zip_bytes,
  2535. )
  2536. package_inventory = _audit_package_items(package_items)
  2537. package_inventory_by_path = {
  2538. str(item["path"]): item for item in package_inventory
  2539. }
  2540. initial_groups = _partition_items(
  2541. package_items,
  2542. target_zip_bytes=target_zip_bytes,
  2543. )
  2544. groups = _split_oversized_groups(
  2545. staging,
  2546. run_id=run_id,
  2547. package_name=package_name,
  2548. groups=initial_groups,
  2549. inventory_by_path=package_inventory_by_path,
  2550. target_zip_bytes=target_zip_bytes,
  2551. max_zip_bytes=max_zip_bytes,
  2552. )
  2553. volume_infos = []
  2554. count = len(groups)
  2555. for number, group in enumerate(groups, start=1):
  2556. category = group[0].category if len({item.category for item in group}) == 1 else "mixed"
  2557. safe_category = re.sub(r"[^a-z0-9]+", "-", category.casefold()).strip("-") or "data"
  2558. volume_path = staging / f"{package_name}.part{number:03d}-{safe_category}.zip"
  2559. volume_info = _write_volume(
  2560. volume_path,
  2561. run_id=run_id,
  2562. package_name=package_name,
  2563. number=number,
  2564. count=count,
  2565. items=group,
  2566. inventory_by_path=package_inventory_by_path,
  2567. )
  2568. if volume_path.stat().st_size >= max_zip_bytes:
  2569. raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
  2570. volume_infos.append(volume_info)
  2571. volume_by_path: dict[str, str] = {}
  2572. for volume_info, group in zip(volume_infos, groups, strict=True):
  2573. for item in group:
  2574. volume_by_path[item.candidate.relative] = str(volume_info["file"])
  2575. large_paths = {str(item["path"]) for item in large_files}
  2576. indexed_files = [
  2577. {**item, "volume": volume_by_path[str(item["path"])]}
  2578. for item in inventory
  2579. if str(item["path"]) not in large_paths
  2580. ]
  2581. for large_file in large_files:
  2582. for chunk in large_file["chunks"]:
  2583. chunk["volume"] = volume_by_path[str(chunk["path"])]
  2584. zip_entry_count = 0
  2585. for info in volume_infos:
  2586. volume_path = staging / str(info["file"])
  2587. with zipfile.ZipFile(volume_path, "r", allowZip64=True) as archive:
  2588. zip_entry_count += sum(1 for name in archive.namelist() if not name.endswith("/"))
  2589. size_budget = handoff.build_size_budget(
  2590. inventory,
  2591. zip_total_bytes=sum(int(info["compressed_bytes"]) for info in volume_infos),
  2592. )
  2593. member_count = build_member_count_semantics(
  2594. indexed_files=len(indexed_files),
  2595. zip_file_entries=zip_entry_count,
  2596. )
  2597. index = {
  2598. "schema": "cpld-agent-analysis-index-v1",
  2599. "run_id": run_id,
  2600. "created_at_utc": _utc_now(),
  2601. "package_name": package_name,
  2602. "status": collection.status,
  2603. "profile": profile,
  2604. "delivery_policy": handoff.delivery_policy_for_profile(profile),
  2605. "max_zip_bytes": max_zip_bytes,
  2606. "target_zip_bytes": target_zip_bytes,
  2607. "sources": list(collection.sources),
  2608. "git": list(collection.git),
  2609. "warnings": list(collection.warnings),
  2610. "excluded": package_excluded,
  2611. "content_dedup": content_dedup,
  2612. "derived_evidence": derived_evidence,
  2613. "evidence_canon": evidence_canon_fields if evidence_canon_fields else None,
  2614. "evidence_aliases": evidence_aliases,
  2615. "member_count": member_count,
  2616. "size_budget": size_budget,
  2617. "volumes": volume_infos,
  2618. "files": indexed_files,
  2619. "large_files": large_files,
  2620. }
  2621. if large_files:
  2622. (staging / "reassemble_large_files.py").write_text(
  2623. REASSEMBLER_SCRIPT,
  2624. encoding="utf-8",
  2625. newline="\n",
  2626. )
  2627. for info in volume_infos:
  2628. volume_path = staging / str(info["file"])
  2629. if volume_path.stat().st_size >= max_zip_bytes:
  2630. raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
  2631. if handoff.sha256_file(volume_path) != info["sha256"]:
  2632. raise PackagingError(f"ZIP volume hash changed after verification: {volume_path.name}")
  2633. checksum_rows = write_package_layout_sidecars(
  2634. staging,
  2635. index=index,
  2636. excluded=package_excluded,
  2637. package_name=package_name,
  2638. include_tar_zst=True,
  2639. profile=profile,
  2640. size_budget=size_budget if handoff.uses_unified_layout(profile) else None,
  2641. )
  2642. full_inventory_by_path = {str(item["path"]): item for item in full_inventory}
  2643. _assert_items_unchanged(collection.items, full_inventory_by_path)
  2644. _assert_source_trees_unchanged(collection, profile=profile)
  2645. if chunk_root is not None:
  2646. shutil.rmtree(chunk_root)
  2647. _publish_directory_atomically(staging, final_dir, force=force)
  2648. except BaseException:
  2649. if os.path.lexists(staging):
  2650. shutil.rmtree(staging, ignore_errors=True)
  2651. raise
  2652. formats = {}
  2653. index_path = final_dir / "HANDOFF-INDEX.json"
  2654. if index_path.is_file():
  2655. formats = json.loads(index_path.read_text(encoding="utf-8")).get("formats", {})
  2656. return {
  2657. "status": collection.status,
  2658. "mode": "package",
  2659. "profile": profile,
  2660. "delivery_policy": handoff.delivery_policy_for_profile(profile),
  2661. "run_id": run_id,
  2662. "output_dir": str(final_dir),
  2663. "volumes": volume_infos,
  2664. "formats": formats,
  2665. "checksum_entries": len(checksum_rows),
  2666. "included_file_count": len(inventory),
  2667. "included_bytes": sum(int(item["size"]) for item in inventory),
  2668. "excluded_entry_count": len(package_excluded),
  2669. "content_dedup_groups": len(content_dedup),
  2670. "derived_evidence_count": len(derived_evidence),
  2671. "member_count": member_count,
  2672. "warning_count": len(collection.warnings),
  2673. }
  2674. def _reference_fingerprint(inventory: list[dict[str, object]]) -> str:
  2675. digest = hashlib.sha256()
  2676. for item in sorted(inventory, key=lambda row: str(row["path"])):
  2677. path = str(item["path"])
  2678. size = str(item["size"])
  2679. sha = str(item["sha256"])
  2680. digest.update(f"{path}|{size}|{sha}\n".encode("utf-8"))
  2681. return digest.hexdigest()
  2682. def _create_reference_package_with_cache(
  2683. *,
  2684. collection: AnalysisCollection,
  2685. output_root: Path,
  2686. package_name: str,
  2687. max_zip_bytes: int,
  2688. target_zip_bytes: int,
  2689. force: bool,
  2690. ) -> dict[str, object]:
  2691. reference_package_name = f"{package_name}-reference"
  2692. reference_dir = output_root / reference_package_name
  2693. fingerprint_path = reference_dir / "REFERENCE-FINGERPRINT"
  2694. inventory = _audit_package_items(collection.items)
  2695. fingerprint = _reference_fingerprint(inventory)
  2696. if not force and fingerprint_path.exists():
  2697. previous = fingerprint_path.read_text(encoding="ascii").strip()
  2698. if previous == fingerprint:
  2699. index_path = reference_dir / "HANDOFF-INDEX.json"
  2700. if index_path.exists():
  2701. index = json.loads(index_path.read_text(encoding="utf-8"))
  2702. return {
  2703. "status": collection.status,
  2704. "mode": "reference_cached",
  2705. "package_name": reference_package_name,
  2706. "output_dir": str(reference_dir),
  2707. "volumes": index.get("volumes", []),
  2708. "included_file_count": len(inventory),
  2709. "included_bytes": sum(int(item["size"]) for item in inventory),
  2710. "fingerprint": fingerprint,
  2711. "skipped": True,
  2712. }
  2713. payload = create_analysis_package(
  2714. collection=collection,
  2715. output_root=output_root,
  2716. package_name=reference_package_name,
  2717. max_zip_bytes=max_zip_bytes,
  2718. target_zip_bytes=target_zip_bytes,
  2719. force=force,
  2720. )
  2721. reference_dir = Path(payload["output_dir"])
  2722. fingerprint_path = reference_dir / "REFERENCE-FINGERPRINT"
  2723. fingerprint_path.write_text(fingerprint + "\n", encoding="ascii")
  2724. payload["fingerprint"] = fingerprint
  2725. payload["skipped"] = False
  2726. return payload
  2727. def merge_archive_preparation(
  2728. collection: AnalysisCollection,
  2729. preparation: ArchivePreparation,
  2730. ) -> AnalysisCollection:
  2731. warnings = (*collection.warnings, *preparation.warnings)
  2732. excluded = sorted(
  2733. (*collection.excluded, *preparation.excluded),
  2734. key=lambda item: handoff.windows_collision_key(item["path"]),
  2735. )
  2736. return AnalysisCollection(
  2737. status="pass_with_warnings" if warnings else "pass",
  2738. items=preparation.items,
  2739. excluded=tuple(excluded),
  2740. warnings=tuple(warnings),
  2741. sources=collection.sources,
  2742. git=collection.git,
  2743. source_snapshots=collection.source_snapshots,
  2744. )
  2745. def explain_analysis_path(
  2746. path: Path,
  2747. *,
  2748. repo_root: Path,
  2749. config: HandoffConfig,
  2750. profile: str = "full",
  2751. ) -> dict[str, object]:
  2752. root = repo_root.resolve(strict=True)
  2753. requested = path if path.is_absolute() else root / path
  2754. target = requested.expanduser().resolve(strict=False)
  2755. resolved_sources, warnings = resolve_external_sources(config.external_sources)
  2756. source_roots: list[tuple[str, str, Path, Path | None]] = [
  2757. ("workspace-current", "core", root, None)
  2758. ]
  2759. for source in resolved_sources:
  2760. if source.kind == "file":
  2761. source_roots.append((source.id, source.category, source.path.parent, source.path))
  2762. else:
  2763. source_roots.append((source.id, source.category, source.path, None))
  2764. matches: list[tuple[int, str, str, Path, Path | None]] = []
  2765. for source_id, category, source_root, exact_file in source_roots:
  2766. if exact_file is not None and target != exact_file:
  2767. continue
  2768. try:
  2769. target.relative_to(source_root)
  2770. except ValueError:
  2771. continue
  2772. matches.append((len(source_root.parts), source_id, category, source_root, exact_file))
  2773. if not matches:
  2774. raise PackagingError("path is outside the current repository and configured external sources")
  2775. _, source_id, category, source_root, exact_file = max(matches, key=lambda item: item[0])
  2776. relative = exact_file.name if exact_file is not None else target.relative_to(source_root).as_posix()
  2777. if not relative:
  2778. relative = "."
  2779. is_dir = target.is_dir()
  2780. context = handoff.load_scan_context(source_root)
  2781. reason = analysis_exclusion_reason(
  2782. relative,
  2783. is_dir=is_dir,
  2784. context=context,
  2785. extra_exclusions=config.extra_exclusions,
  2786. profile=profile,
  2787. )
  2788. archive_relative = (
  2789. f"workspace-current/{relative}"
  2790. if source_id == "workspace-current"
  2791. else f"external/{source_id}/{relative}"
  2792. )
  2793. return {
  2794. "status": "pass_with_warnings" if warnings else "pass",
  2795. "mode": "explain",
  2796. "path": str(target),
  2797. "exists": target.exists(),
  2798. "source_id": source_id,
  2799. "category": category,
  2800. "source_relative_path": relative,
  2801. "archive_path": f"CPLD/{archive_relative}",
  2802. "decision": "exclude" if reason else "include",
  2803. "reason": reason,
  2804. "content_scan": "not_run",
  2805. "warnings": warnings,
  2806. }
  2807. def audit_analysis_collection(collection: AnalysisCollection) -> dict[str, object]:
  2808. inventory = _audit_package_items(collection.items)
  2809. inventory_by_path = {str(item["path"]): item for item in inventory}
  2810. _assert_items_unchanged(collection.items, inventory_by_path)
  2811. return {
  2812. "status": collection.status,
  2813. "mode": "audit_only",
  2814. "included_file_count": len(inventory),
  2815. "included_bytes": sum(int(item["size"]) for item in inventory),
  2816. "excluded_entry_count": len(collection.excluded),
  2817. "warning_count": len(collection.warnings),
  2818. "warnings": list(collection.warnings),
  2819. "sources": list(collection.sources),
  2820. "git": list(collection.git),
  2821. }
  2822. def _validate_output_root(
  2823. output_root: Path,
  2824. *,
  2825. repo_root: Path,
  2826. config: HandoffConfig,
  2827. ) -> Path:
  2828. output = output_root.expanduser().resolve(strict=False)
  2829. source_paths = [repo_root.resolve(strict=True)]
  2830. resolved_sources, _ = resolve_external_sources(config.external_sources)
  2831. source_paths.extend(source.path if source.kind != "file" else source.path.parent for source in resolved_sources)
  2832. for source_path in source_paths:
  2833. try:
  2834. output.relative_to(source_path)
  2835. except ValueError:
  2836. continue
  2837. raise PackagingError(f"output directory must be outside every packaged source root: {source_path}")
  2838. return output
  2839. def build_parser() -> argparse.ArgumentParser:
  2840. parser = argparse.ArgumentParser(description=__doc__)
  2841. parser.add_argument("--audit-only", action="store_true", help="scan and verify inputs without creating ZIP files")
  2842. parser.add_argument("--explain", type=Path, metavar="PATH", help="explain whether one path is included or excluded")
  2843. parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG, help="source and exclusion configuration JSON")
  2844. parser.add_argument("--source-root", type=Path, default=ROOT, help="root directory to package as the primary source")
  2845. parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR, help="parent directory for the package directory")
  2846. parser.add_argument("--package-name", help="portable package directory and ZIP base name")
  2847. parser.add_argument("--force-overwrite", action="store_true", help="atomically replace an existing package directory")
  2848. parser.add_argument("--no-git-bundle", action="store_true", help="omit the git history bundle from the package")
  2849. parser.add_argument(
  2850. "--include-full-history",
  2851. action="store_true",
  2852. help="include a full git bundle (archive-local / explicit override; ignored as default for review-compact)",
  2853. )
  2854. parser.add_argument(
  2855. "--include-sanitized-git-snapshot",
  2856. action="store_true",
  2857. help=(
  2858. "include sanitized synthetic single-commit git snapshot under meta/git "
  2859. "(records synthetic→original mapping; does not impersonate the original tip)"
  2860. ),
  2861. )
  2862. parser.add_argument(
  2863. "--evidence-root",
  2864. type=Path,
  2865. help=(
  2866. "optional delivery/run evidence tree to stage into canonical evidence/ paths "
  2867. "(final matrix, Formal/TD receipts, bitstream, selftests, deep-review summary, IO/hardware notes)"
  2868. ),
  2869. )
  2870. parser.add_argument(
  2871. "--include-process-evidence",
  2872. action="store_true",
  2873. help=(
  2874. "include lane receipts, matrix reruns, and other process evidence "
  2875. "(implied by review-debug; off by default for review-compact)"
  2876. ),
  2877. )
  2878. parser.add_argument(
  2879. "--profile",
  2880. choices=sorted(handoff.HANDOFF_PROFILES),
  2881. default=handoff.DEFAULT_HANDOFF_PROFILE,
  2882. help=(
  2883. "review-compact (default upload: unified source/evidence/meta, no full git bundle); "
  2884. "review-debug; archive-local; legacy full (core/reference split) / code-only"
  2885. ),
  2886. )
  2887. parser.add_argument(
  2888. "--replay-package",
  2889. type=Path,
  2890. metavar="DIR",
  2891. help="verify SHA256SUMS and replay-extract an existing package directory (selftest)",
  2892. )
  2893. parser.add_argument(
  2894. "--replay-extract-dir",
  2895. type=Path,
  2896. help="extract target for --replay-package (must not already exist)",
  2897. )
  2898. return parser
  2899. def main(argv: list[str] | None = None) -> int:
  2900. args = build_parser().parse_args(argv)
  2901. package_name = args.package_name or datetime.now(timezone.utc).strftime(
  2902. "cpld-agent-analysis-%Y%m%dT%H%M%SZ"
  2903. )
  2904. try:
  2905. if args.replay_package is not None:
  2906. extract_root = args.replay_extract_dir or Path(
  2907. tempfile.mkdtemp(prefix="prod2u-package-replay-", dir=os.environ.get("TMPDIR", "/tmp"))
  2908. )
  2909. payload = replay_analysis_package(args.replay_package, extract_root=extract_root)
  2910. print(json.dumps(payload, ensure_ascii=False, indent=2))
  2911. return 0
  2912. source_root = args.source_root.expanduser().resolve(strict=True)
  2913. if args.profile not in handoff.HANDOFF_PROFILES:
  2914. raise PackagingError(f"unsupported handoff profile: {args.profile}")
  2915. config = load_config(args.config, repo_root=source_root)
  2916. if args.explain is not None:
  2917. payload = explain_analysis_path(
  2918. args.explain,
  2919. repo_root=source_root,
  2920. config=config,
  2921. profile=args.profile,
  2922. )
  2923. else:
  2924. seven_zip = find_7z()
  2925. _validate_package_name(package_name)
  2926. output_root = _validate_output_root(args.output_dir, repo_root=source_root, config=config)
  2927. if args.profile == "archive-local":
  2928. include_git_bundle = not args.no_git_bundle or args.include_full_history
  2929. if args.include_full_history:
  2930. include_git_bundle = True
  2931. elif args.profile in {"review-compact", "review-debug"}:
  2932. include_git_bundle = False
  2933. else:
  2934. include_git_bundle = not args.no_git_bundle
  2935. with tempfile.TemporaryDirectory(prefix="ca-") as temporary:
  2936. temp_root = Path(temporary)
  2937. collection = collect_analysis_inputs(
  2938. repo_root=source_root,
  2939. config=config,
  2940. temp_root=temp_root / "inputs",
  2941. include_git_bundle=include_git_bundle,
  2942. profile=args.profile,
  2943. include_sanitized_git_snapshot=args.include_sanitized_git_snapshot,
  2944. package_name=package_name,
  2945. evidence_root=args.evidence_root.expanduser().resolve(strict=True)
  2946. if args.evidence_root is not None
  2947. else None,
  2948. include_process_evidence=args.include_process_evidence,
  2949. )
  2950. preparation = prepare_unsupported_archives(
  2951. collection.items,
  2952. temp_root=temp_root / "archives",
  2953. seven_zip=seven_zip,
  2954. extra_exclusions=config.extra_exclusions,
  2955. )
  2956. prepared_collection = merge_archive_preparation(collection, preparation)
  2957. if args.audit_only:
  2958. payload = audit_analysis_collection(prepared_collection)
  2959. payload["profile"] = args.profile
  2960. payload["delivery_policy"] = handoff.delivery_policy_for_profile(args.profile)
  2961. elif handoff.uses_unified_layout(args.profile) or args.profile == "code-only":
  2962. if not prepared_collection.items:
  2963. raise PackagingError("analysis package has no included files")
  2964. payload = create_analysis_package(
  2965. collection=prepared_collection,
  2966. output_root=output_root,
  2967. package_name=package_name,
  2968. max_zip_bytes=config.max_zip_bytes,
  2969. target_zip_bytes=config.target_zip_bytes,
  2970. force=args.force_overwrite,
  2971. profile=args.profile,
  2972. )
  2973. else:
  2974. core_collection, reference_collection = _split_collection_by_reference(
  2975. prepared_collection
  2976. )
  2977. if not core_collection.items and not reference_collection.items:
  2978. raise PackagingError("analysis package has no included files")
  2979. payload = {}
  2980. if core_collection.items:
  2981. payload["core"] = create_analysis_package(
  2982. collection=core_collection,
  2983. output_root=output_root,
  2984. package_name=package_name,
  2985. max_zip_bytes=config.max_zip_bytes,
  2986. target_zip_bytes=config.target_zip_bytes,
  2987. force=args.force_overwrite,
  2988. profile=args.profile,
  2989. )
  2990. if reference_collection.items:
  2991. payload["reference"] = _create_reference_package_with_cache(
  2992. collection=reference_collection,
  2993. output_root=output_root,
  2994. package_name=package_name,
  2995. max_zip_bytes=config.max_zip_bytes,
  2996. target_zip_bytes=config.target_zip_bytes,
  2997. force=args.force_overwrite,
  2998. )
  2999. except (PackagingError, OSError, ValueError) as exc:
  3000. print(f"error: {exc}", file=sys.stderr)
  3001. return 1
  3002. print(json.dumps(payload, ensure_ascii=False, indent=2))
  3003. return 0
  3004. if __name__ == "__main__":
  3005. raise SystemExit(main())