package_for_agent_analysis.py 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088
  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. PackagingError = handoff.PackagingError
  26. CONFIG_SCHEMA = "cpld-agent-analysis-sources-v1"
  27. DEFAULT_CONFIG = ROOT / "config" / "agent_analysis_handoff_sources.json"
  28. DEFAULT_OUTPUT_DIR = Path.home() / "Downloads" / "CPLD-agent-analysis"
  29. CATEGORY_ORDER = {
  30. "core": 0,
  31. "hardware": 1,
  32. "td-docs": 2,
  33. "evidence": 3,
  34. }
  35. GENERATED_BINARY_SUFFIXES = {
  36. ".bit",
  37. ".bid",
  38. ".data",
  39. ".db",
  40. ".timing",
  41. ".rpt",
  42. ".area",
  43. ".qor",
  44. ".vvp",
  45. }
  46. TRANSIENT_SUFFIXES = {".pyc", ".pyo", ".tmp", ".partial", ".part", ".swp", ".swo"}
  47. ARCHIVE_SUFFIXES = {".zip", ".rar", ".7z"}
  48. RUNTIME_EVIDENCE_SUFFIXES = {".log", ".logw", ".vcd", ".fst", ".lxt", ".gtkw", ".raw", ".bin"}
  49. BOARD_DESIGN_SUFFIXES = {".brd", ".sch", ".kicad_pcb", ".kicad_sch", ".kicad_pro", ".kicad_prl", ".dsn"}
  50. IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".webp", ".svg"}
  51. STRAY_FILENAMES = {"-", "a.out"}
  52. REASSEMBLER_SCRIPT = '''#!/usr/bin/env python3
  53. """Reassemble files that were split across analysis ZIP volumes."""
  54. from __future__ import annotations
  55. import argparse
  56. import hashlib
  57. import json
  58. import shutil
  59. import sys
  60. import zipfile
  61. from pathlib import Path, PurePosixPath
  62. def safe_output_path(root: Path, relative: str) -> Path:
  63. portable = PurePosixPath(relative)
  64. if portable.is_absolute() or not portable.parts or any(part in {"", ".", ".."} for part in portable.parts):
  65. raise RuntimeError(f"unsafe output path: {relative}")
  66. target = (root / Path(*portable.parts)).resolve(strict=False)
  67. try:
  68. target.relative_to(root.resolve(strict=False))
  69. except ValueError as exc:
  70. raise RuntimeError(f"output path escapes target directory: {relative}") from exc
  71. return target
  72. def sha256_path(path: Path) -> str:
  73. digest = hashlib.sha256()
  74. with path.open("rb") as handle:
  75. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  76. digest.update(chunk)
  77. return digest.hexdigest()
  78. def main() -> int:
  79. parser = argparse.ArgumentParser(description=__doc__)
  80. parser.add_argument("--package-dir", type=Path, default=Path(__file__).resolve().parent)
  81. parser.add_argument("--output-dir", type=Path, default=Path("reassembled"))
  82. args = parser.parse_args()
  83. package_dir = args.package_dir.resolve(strict=True)
  84. output_dir = args.output_dir.resolve(strict=False)
  85. index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
  86. output_dir.mkdir(parents=True, exist_ok=True)
  87. for item in index.get("large_files", []):
  88. target = safe_output_path(output_dir, item["path"])
  89. target.parent.mkdir(parents=True, exist_ok=True)
  90. temporary = target.with_name(target.name + ".partial")
  91. temporary.unlink(missing_ok=True)
  92. total = 0
  93. with temporary.open("xb") as destination:
  94. for chunk in sorted(item["chunks"], key=lambda value: value["number"]):
  95. volume = package_dir / chunk["volume"]
  96. with zipfile.ZipFile(volume, "r") as archive:
  97. with archive.open(chunk["archive_path"], "r") as source:
  98. digest = hashlib.sha256()
  99. chunk_bytes = 0
  100. while True:
  101. payload = source.read(1024 * 1024)
  102. if not payload:
  103. break
  104. destination.write(payload)
  105. digest.update(payload)
  106. chunk_bytes += len(payload)
  107. if chunk_bytes != chunk["size"] or digest.hexdigest() != chunk["sha256"]:
  108. raise RuntimeError(f"chunk verification failed: {chunk['archive_path']}")
  109. total += chunk_bytes
  110. if total != item["size"] or sha256_path(temporary) != item["sha256"]:
  111. temporary.unlink(missing_ok=True)
  112. raise RuntimeError(f"reassembled file verification failed: {item['path']}")
  113. temporary.replace(target)
  114. print(f"reassembled: {target}")
  115. return 0
  116. if __name__ == "__main__":
  117. try:
  118. raise SystemExit(main())
  119. except (OSError, RuntimeError, KeyError, ValueError, json.JSONDecodeError, zipfile.BadZipFile) as exc:
  120. print(f"error: {exc}", file=sys.stderr)
  121. raise SystemExit(1)
  122. '''
  123. class ExternalSource(NamedTuple):
  124. id: str
  125. category: str
  126. kind: str
  127. path_candidates: tuple[Path, ...]
  128. archive_policy: str
  129. class HandoffConfig(NamedTuple):
  130. max_zip_bytes: int
  131. target_zip_bytes: int
  132. external_sources: tuple[ExternalSource, ...]
  133. extra_exclusions: tuple[dict[str, str], ...]
  134. class ResolvedSource(NamedTuple):
  135. id: str
  136. category: str
  137. kind: str
  138. path: Path
  139. archive_policy: str
  140. class PackageItem(NamedTuple):
  141. candidate: handoff.Candidate
  142. category: str
  143. source_id: str
  144. original_path: str
  145. scan_archive: bool
  146. class SourceSnapshot(NamedTuple):
  147. source_id: str
  148. root: Path
  149. extra_exclusions: tuple[dict[str, str], ...]
  150. candidates: tuple[tuple[object, ...], ...]
  151. excluded: tuple[tuple[str, str], ...]
  152. class AnalysisCollection(NamedTuple):
  153. status: str
  154. items: tuple[PackageItem, ...]
  155. excluded: tuple[dict[str, str], ...]
  156. warnings: tuple[dict[str, str], ...]
  157. sources: tuple[dict[str, object], ...]
  158. git: tuple[dict[str, object], ...]
  159. source_snapshots: tuple[SourceSnapshot, ...] = ()
  160. def _is_reference_path(item: PackageItem) -> bool:
  161. parts = item.candidate.relative.casefold().split("/")
  162. for index, part in enumerate(parts):
  163. if part == "reference":
  164. next_part = parts[index + 1] if index + 1 < len(parts) else ""
  165. if next_part == "historical":
  166. return False
  167. return True
  168. return False
  169. def _is_reference_item(item: PackageItem) -> bool:
  170. return item.category == "td-docs" or _is_reference_path(item)
  171. def _split_collection_by_reference(
  172. collection: AnalysisCollection,
  173. ) -> tuple[AnalysisCollection, AnalysisCollection]:
  174. core_items: list[PackageItem] = []
  175. reference_items: list[PackageItem] = []
  176. for item in collection.items:
  177. if _is_reference_item(item):
  178. if item.category == "core" and _is_reference_path(item):
  179. item = item._replace(category="reference")
  180. reference_items.append(item)
  181. else:
  182. core_items.append(item)
  183. reference_items_tuple = tuple(reference_items)
  184. core_items_tuple = tuple(core_items)
  185. reference_source_ids = {item.source_id for item in reference_items_tuple}
  186. core_source_ids = {item.source_id for item in core_items_tuple}
  187. def _filter_sources(
  188. sources: tuple[dict[str, object], ...], source_ids: set[str]
  189. ) -> tuple[dict[str, object], ...]:
  190. return tuple(s for s in sources if s.get("id") in source_ids)
  191. def _filter_git(
  192. git: tuple[dict[str, object], ...], source_ids: set[str]
  193. ) -> tuple[dict[str, object], ...]:
  194. return tuple(g for g in git if g.get("source_id") in source_ids)
  195. def _filter_snapshots(
  196. snapshots: tuple[SourceSnapshot, ...], source_ids: set[str]
  197. ) -> tuple[SourceSnapshot, ...]:
  198. return tuple(ss for ss in snapshots if ss.source_id in source_ids)
  199. core_collection = AnalysisCollection(
  200. status=collection.status,
  201. items=core_items_tuple,
  202. excluded=collection.excluded,
  203. warnings=collection.warnings,
  204. sources=_filter_sources(collection.sources, core_source_ids),
  205. git=_filter_git(collection.git, core_source_ids),
  206. source_snapshots=_filter_snapshots(collection.source_snapshots, core_source_ids),
  207. )
  208. reference_collection = AnalysisCollection(
  209. status=collection.status,
  210. items=reference_items_tuple,
  211. excluded=collection.excluded,
  212. warnings=collection.warnings,
  213. sources=_filter_sources(collection.sources, reference_source_ids),
  214. git=_filter_git(collection.git, reference_source_ids),
  215. source_snapshots=_filter_snapshots(collection.source_snapshots, reference_source_ids),
  216. )
  217. return core_collection, reference_collection
  218. class ArchivePreparation(NamedTuple):
  219. items: tuple[PackageItem, ...]
  220. excluded: tuple[dict[str, str], ...]
  221. warnings: tuple[dict[str, str], ...]
  222. def _source_snapshot(
  223. root: Path,
  224. *,
  225. source_id: str,
  226. extra_exclusions: tuple[dict[str, str], ...],
  227. ) -> SourceSnapshot:
  228. candidates, excluded, _ = scan_analysis_root(
  229. root,
  230. extra_exclusions=extra_exclusions,
  231. )
  232. return SourceSnapshot(
  233. source_id=source_id,
  234. root=root.resolve(strict=True),
  235. extra_exclusions=extra_exclusions,
  236. candidates=tuple(
  237. (
  238. candidate.relative,
  239. candidate.size,
  240. candidate.mtime_ns,
  241. candidate.device,
  242. candidate.inode,
  243. candidate.mode,
  244. )
  245. for candidate in candidates
  246. ),
  247. excluded=tuple((item["path"], item["rule"]) for item in excluded),
  248. )
  249. def _require_keys(payload: dict[str, object], allowed: set[str], label: str) -> None:
  250. unknown = sorted(set(payload) - allowed)
  251. if unknown:
  252. if any("include" in item.casefold() for item in unknown):
  253. raise PackagingError(f"positive include rules are forbidden in {label}: {unknown}")
  254. raise PackagingError(f"unsupported fields in {label}: {unknown}")
  255. def _expand_path(value: str, *, repo_root: Path, user_profile: Path) -> Path:
  256. tokens = {
  257. "repo_root": str(repo_root),
  258. "user_profile": str(user_profile),
  259. "codex_temp": str(user_profile / "CodexTemp"),
  260. }
  261. try:
  262. expanded = value.format_map(tokens)
  263. except (KeyError, ValueError) as exc:
  264. raise PackagingError(f"unsupported path token in external source: {value}") from exc
  265. return Path(expanded).expanduser()
  266. def load_config(
  267. path: Path,
  268. *,
  269. repo_root: Path = ROOT,
  270. user_profile: Path | None = None,
  271. ) -> HandoffConfig:
  272. try:
  273. payload = json.loads(path.read_text(encoding="utf-8-sig"))
  274. except (OSError, UnicodeError, json.JSONDecodeError) as exc:
  275. raise PackagingError(f"unable to read analysis source config: {path}") from exc
  276. if not isinstance(payload, dict):
  277. raise PackagingError("analysis source config must be a JSON object")
  278. _require_keys(
  279. payload,
  280. {
  281. "schema",
  282. "max_zip_bytes",
  283. "target_zip_bytes",
  284. "external_sources",
  285. "extra_exclusions",
  286. },
  287. "config",
  288. )
  289. if payload.get("schema") != CONFIG_SCHEMA:
  290. raise PackagingError(f"unsupported analysis source config schema: {payload.get('schema')}")
  291. max_zip_bytes = payload.get("max_zip_bytes")
  292. target_zip_bytes = payload.get("target_zip_bytes")
  293. if not isinstance(max_zip_bytes, int) or max_zip_bytes <= 0:
  294. raise PackagingError("max_zip_bytes must be a positive integer")
  295. if not isinstance(target_zip_bytes, int) or not 0 < target_zip_bytes < max_zip_bytes:
  296. raise PackagingError("target_zip_bytes must be positive and smaller than max_zip_bytes")
  297. raw_sources = payload.get("external_sources")
  298. if not isinstance(raw_sources, list):
  299. raise PackagingError("external_sources must be an array")
  300. profile = user_profile or Path.home()
  301. sources: list[ExternalSource] = []
  302. seen_ids: set[str] = set()
  303. for index, raw_source in enumerate(raw_sources):
  304. if not isinstance(raw_source, dict):
  305. raise PackagingError(f"external_sources[{index}] must be an object")
  306. _require_keys(
  307. raw_source,
  308. {"id", "category", "kind", "path_candidates", "archive_policy"},
  309. f"external_sources[{index}]",
  310. )
  311. source_id = raw_source.get("id")
  312. category = raw_source.get("category")
  313. kind = raw_source.get("kind")
  314. archive_policy = raw_source.get("archive_policy")
  315. raw_paths = raw_source.get("path_candidates")
  316. if not isinstance(source_id, str) or not source_id or source_id in seen_ids:
  317. raise PackagingError(f"external source id is missing or duplicated: {source_id}")
  318. if not isinstance(category, str) or not category:
  319. raise PackagingError(f"external source category is invalid: {source_id}")
  320. if kind not in {"directory", "file", "git_worktree"}:
  321. raise PackagingError(f"external source kind is invalid: {source_id}")
  322. if archive_policy not in {"inspect", "copy"}:
  323. raise PackagingError(f"external archive policy is invalid: {source_id}")
  324. if not isinstance(raw_paths, list) or not raw_paths or not all(isinstance(item, str) for item in raw_paths):
  325. raise PackagingError(f"external source path_candidates are invalid: {source_id}")
  326. seen_ids.add(source_id)
  327. sources.append(
  328. ExternalSource(
  329. id=source_id,
  330. category=category,
  331. kind=kind,
  332. path_candidates=tuple(
  333. _expand_path(item, repo_root=repo_root, user_profile=profile)
  334. for item in raw_paths
  335. ),
  336. archive_policy=archive_policy,
  337. )
  338. )
  339. raw_exclusions = payload.get("extra_exclusions")
  340. if not isinstance(raw_exclusions, list) or not all(isinstance(item, dict) for item in raw_exclusions):
  341. raise PackagingError("extra_exclusions must be an array of objects")
  342. exclusions: list[dict[str, str]] = []
  343. for index, raw_exclusion in enumerate(raw_exclusions):
  344. _require_keys(raw_exclusion, {"path", "reason"}, f"extra_exclusions[{index}]")
  345. exclusion_path = raw_exclusion.get("path")
  346. reason = raw_exclusion.get("reason")
  347. if not isinstance(exclusion_path, str) or not exclusion_path or "\\" in exclusion_path:
  348. raise PackagingError(f"extra exclusion path is invalid: {index}")
  349. if not isinstance(reason, str) or not reason.strip():
  350. raise PackagingError(f"extra exclusion reason is invalid: {index}")
  351. normalized_path = handoff.normalize_relative(exclusion_path.strip("/").split("/"))
  352. exclusions.append({"path": normalized_path, "reason": reason.strip()})
  353. return HandoffConfig(
  354. max_zip_bytes=max_zip_bytes,
  355. target_zip_bytes=target_zip_bytes,
  356. external_sources=tuple(sources),
  357. extra_exclusions=tuple(exclusions),
  358. )
  359. def analysis_exclusion_reason(
  360. relative: str,
  361. *,
  362. is_dir: bool,
  363. context: handoff.ScanContext,
  364. extra_exclusions: tuple[dict[str, str], ...] = (),
  365. ) -> str | None:
  366. del context
  367. lower = relative.casefold()
  368. parts = lower.split("/")
  369. raw_parts = relative.split("/")
  370. name = parts[-1]
  371. secret_reason = handoff.secret_path_reason(relative, is_dir=is_dir)
  372. if secret_reason:
  373. return secret_reason
  374. for item in extra_exclusions:
  375. prefix = str(item.get("path", "")).casefold().strip("/")
  376. if prefix and handoff.is_under(lower, prefix):
  377. return str(item.get("reason") or "configured_analysis_exclusion")
  378. explicit_roots = {
  379. ".git": "raw_git_metadata",
  380. ".codegraph": "declared_external_reparse_alias",
  381. ".codex": "codex_session_runtime",
  382. ".hypothesis": "hypothesis_cache",
  383. ".ruff_cache": "ruff_cache",
  384. ".pytest_cache": "pytest_cache",
  385. "dist": "generated_delivery_output",
  386. "log": "runtime_log_directory",
  387. "runs": "run_state_directory",
  388. "td/build": "td_build_output",
  389. "reference/historical": "reference_historical_material",
  390. "reference/original/legacy_rtl": "reference_legacy_rtl",
  391. "receipts/local": "local_runtime_receipt",
  392. "tools/board-viewer/generated": "generated_board_viewer_output",
  393. "anlogic_cd": "vendor_installer_payload",
  394. }
  395. for prefix, reason in explicit_roots.items():
  396. if handoff.is_under(lower, prefix):
  397. return reason
  398. if handoff.is_under(lower, "tmp/edge-headless-profile"):
  399. return "browser_runtime_profile"
  400. if handoff.is_under(lower, "tmp/rtl_sim"):
  401. return "compiled_rtl_simulation"
  402. if handoff.is_under(lower, "tmp/toolchain_probe"):
  403. return "toolchain_probe_runtime"
  404. if handoff.is_under(lower, "tmp/td"):
  405. return "td_runtime_snapshot"
  406. if handoff.is_under(lower, "tmp/refactor"):
  407. return "compiled_refactor_probe"
  408. if any(component.endswith("_Runs") for component in raw_parts):
  409. return "generated_run_directory"
  410. if re.match(r"^tmp/pytest-[^/]+$", lower):
  411. return "temporary_tool_runtime"
  412. if handoff.is_under(lower, "tmp"):
  413. return "temporary_workspace_directory"
  414. if handoff.is_under(lower, "td/project/log"):
  415. return "td_gui_runtime_log"
  416. if handoff.is_under(lower, "td/project") and len(parts) >= 3 and parts[2].endswith("_runs"):
  417. return "td_gui_runtime_run"
  418. if lower in {
  419. "td/project/.lock.f",
  420. "td/project/.recent_user_depot.ini",
  421. }:
  422. return "td_gui_runtime_state"
  423. if handoff.is_under(lower, ".git"):
  424. return "raw_git_metadata"
  425. if handoff.is_under(lower, ".omo"):
  426. return "agent_session_runtime"
  427. cache_components = {
  428. ".git": "raw_git_metadata",
  429. ".codegraph": "declared_external_reparse_alias",
  430. ".codex": "codex_session_runtime",
  431. "__pycache__": "python_bytecode_cache",
  432. ".pytest_cache": "pytest_cache",
  433. ".hypothesis": "hypothesis_cache",
  434. ".mypy_cache": "mypy_cache",
  435. ".ruff_cache": "ruff_cache",
  436. ".tox": "tox_environment",
  437. ".nox": "nox_environment",
  438. ".venv": "virtual_environment",
  439. "venv": "virtual_environment",
  440. "htmlcov": "coverage_report",
  441. "build": "build_output",
  442. "runs": "run_state_directory",
  443. }
  444. for component in parts:
  445. if component in cache_components:
  446. return cache_components[component]
  447. if component == "dist":
  448. return "generated_delivery_output"
  449. if not is_dir:
  450. suffix = Path(name).suffix.casefold()
  451. if suffix in GENERATED_BINARY_SUFFIXES:
  452. return "generated_binary_artifact"
  453. if suffix in ARCHIVE_SUFFIXES:
  454. return "archive_file_not_source"
  455. if suffix in RUNTIME_EVIDENCE_SUFFIXES:
  456. return "runtime_evidence_or_waveform"
  457. if suffix in BOARD_DESIGN_SUFFIXES:
  458. if "reference" in parts:
  459. return None
  460. return "board_design_file"
  461. if suffix in IMAGE_SUFFIXES:
  462. if "reference" in parts:
  463. return None
  464. return "image_file"
  465. if name in STRAY_FILENAMES:
  466. return "stray_or_temporary_file"
  467. if suffix in TRANSIENT_SUFFIXES or name.endswith("~"):
  468. return "temporary_file"
  469. if suffix == ".dmp" or name.startswith("minidump-"):
  470. return "crash_dump"
  471. if name in {".ds_store", "thumbs.db", "desktop.ini"}:
  472. return "os_metadata_cache"
  473. return None
  474. def scan_analysis_root(
  475. root: Path,
  476. *,
  477. extra_exclusions: tuple[dict[str, str], ...] = (),
  478. ) -> tuple[list[handoff.Candidate], list[dict[str, str]], handoff.ScanContext]:
  479. def resolve(relative: str, *, is_dir: bool, context: handoff.ScanContext) -> str | None:
  480. return analysis_exclusion_reason(
  481. relative,
  482. is_dir=is_dir,
  483. context=context,
  484. extra_exclusions=extra_exclusions,
  485. )
  486. return handoff.scan_tree(root, exclusion_resolver=resolve)
  487. def resolve_external_sources(
  488. sources: tuple[ExternalSource, ...],
  489. ) -> tuple[list[ResolvedSource], list[dict[str, str]]]:
  490. resolved: list[ResolvedSource] = []
  491. warnings: list[dict[str, str]] = []
  492. for source in sources:
  493. selected: Path | None = None
  494. for candidate in source.path_candidates:
  495. if source.kind == "file" and candidate.is_file():
  496. selected = candidate.resolve(strict=True)
  497. break
  498. if source.kind in {"directory", "git_worktree"} and candidate.is_dir():
  499. selected = candidate.resolve(strict=True)
  500. break
  501. if selected is None:
  502. warnings.append(
  503. {
  504. "code": "missing_external_source",
  505. "source_id": source.id,
  506. "message": "no configured path candidate is available",
  507. }
  508. )
  509. continue
  510. resolved.append(
  511. ResolvedSource(
  512. id=source.id,
  513. category=source.category,
  514. kind=source.kind,
  515. path=selected,
  516. archive_policy=source.archive_policy,
  517. )
  518. )
  519. return resolved, warnings
  520. def _candidate_from_path(path: Path, relative: str) -> handoff.Candidate:
  521. try:
  522. file_stat = os.lstat(path)
  523. except OSError as exc:
  524. raise PackagingError(f"unable to inspect generated analysis input: {relative}") from exc
  525. if not stat.S_ISREG(file_stat.st_mode) or handoff.stat_is_reparse_point(file_stat):
  526. raise PackagingError(f"analysis input is not a regular file: {relative}")
  527. return handoff.Candidate(
  528. absolute=path,
  529. relative=handoff.normalize_relative(relative.split("/")),
  530. size=file_stat.st_size,
  531. mtime_ns=file_stat.st_mtime_ns,
  532. device=int(file_stat.st_dev),
  533. inode=int(file_stat.st_ino),
  534. mode=int(file_stat.st_mode),
  535. )
  536. def make_package_item(
  537. path: Path,
  538. *,
  539. relative: str,
  540. category: str,
  541. source_id: str,
  542. scan_archive: bool = True,
  543. ) -> PackageItem:
  544. return PackageItem(
  545. candidate=_candidate_from_path(path, relative),
  546. category=category,
  547. source_id=source_id,
  548. original_path=path.name,
  549. scan_archive=scan_archive,
  550. )
  551. def _rebase_candidate(candidate: handoff.Candidate, prefix: str) -> handoff.Candidate:
  552. return handoff.Candidate(
  553. absolute=candidate.absolute,
  554. relative=handoff.normalize_relative([*prefix.split("/"), *candidate.relative.split("/")]),
  555. size=candidate.size,
  556. mtime_ns=candidate.mtime_ns,
  557. device=candidate.device,
  558. inode=candidate.inode,
  559. mode=candidate.mode,
  560. )
  561. def _rebase_exclusions(excluded: list[dict[str, str]], prefix: str) -> list[dict[str, str]]:
  562. return [
  563. {
  564. "path": handoff.normalize_relative([*prefix.split("/"), *item["path"].split("/")]),
  565. "rule": item["rule"],
  566. }
  567. for item in excluded
  568. ]
  569. def _collect_directory_items(
  570. *,
  571. root: Path,
  572. source_id: str,
  573. category: str,
  574. prefix: str,
  575. extra_exclusions: tuple[dict[str, str], ...],
  576. ) -> tuple[list[PackageItem], list[dict[str, str]]]:
  577. candidates, excluded, _ = scan_analysis_root(root, extra_exclusions=extra_exclusions)
  578. items = [
  579. PackageItem(
  580. candidate=_rebase_candidate(candidate, prefix),
  581. category=category,
  582. source_id=source_id,
  583. original_path=candidate.relative,
  584. scan_archive=True,
  585. )
  586. for candidate in candidates
  587. ]
  588. return items, _rebase_exclusions(excluded, prefix)
  589. def _run_git(command: list[str], *, cwd: Path, timeout: int = 300) -> str:
  590. try:
  591. completed = subprocess.run(
  592. command,
  593. cwd=cwd,
  594. stdout=subprocess.PIPE,
  595. stderr=subprocess.STDOUT,
  596. text=True,
  597. encoding="utf-8",
  598. errors="replace",
  599. timeout=timeout,
  600. check=False,
  601. )
  602. except (OSError, subprocess.TimeoutExpired) as exc:
  603. raise PackagingError(f"unable to run Git for {cwd.name}") from exc
  604. if completed.returncode != 0:
  605. detail = completed.stdout.strip().splitlines()
  606. suffix = f": {detail[-1]}" if detail else ""
  607. raise PackagingError(f"Git command failed for {cwd.name}{suffix}")
  608. return completed.stdout
  609. def _create_git_bundle(
  610. *,
  611. root: Path,
  612. source_id: str,
  613. temp_root: Path,
  614. ) -> tuple[PackageItem, dict[str, object]]:
  615. git = shutil.which("git")
  616. if not git:
  617. raise PackagingError("Git is required to create complete analysis history bundles")
  618. bundle_dir = temp_root / "git-bundles"
  619. bundle_dir.mkdir(parents=True, exist_ok=True)
  620. bundle_path = bundle_dir / f"{source_id}.bundle"
  621. _run_git([git, "bundle", "create", str(bundle_path), "--all"], cwd=root)
  622. verify_output = _run_git([git, "bundle", "verify", str(bundle_path)], cwd=root)
  623. head = _run_git([git, "rev-parse", "HEAD"], cwd=root).strip()
  624. branch = _run_git([git, "branch", "--show-current"], cwd=root).strip() or None
  625. status = _run_git(
  626. [
  627. git,
  628. "--no-optional-locks",
  629. "-c",
  630. "core.fsmonitor=false",
  631. "-c",
  632. "core.untrackedCache=false",
  633. "status",
  634. "--short",
  635. "--branch",
  636. "--untracked-files=all",
  637. ],
  638. cwd=root,
  639. )
  640. ref_lines = [line for line in verify_output.splitlines() if " refs/" in line or line.rstrip().endswith(" HEAD")]
  641. candidate = _candidate_from_path(bundle_path, f"git-history/{source_id}.bundle")
  642. item = PackageItem(
  643. candidate=candidate,
  644. category="core",
  645. source_id=source_id,
  646. original_path=".git",
  647. scan_archive=False,
  648. )
  649. metadata = {
  650. "source_id": source_id,
  651. "branch": branch,
  652. "head": head,
  653. "working_tree_clean": not any(
  654. line and not line.startswith("##") for line in status.splitlines()
  655. ),
  656. "status": "pass",
  657. "bundle_path": candidate.relative,
  658. "bundle_ref_count": len(ref_lines),
  659. "bundle_verify": "pass",
  660. }
  661. return item, metadata
  662. def collect_analysis_inputs(
  663. *,
  664. repo_root: Path,
  665. config: HandoffConfig,
  666. temp_root: Path,
  667. include_git_bundle: bool = True,
  668. ) -> AnalysisCollection:
  669. root = repo_root.resolve(strict=True)
  670. temp_root.mkdir(parents=True, exist_ok=True)
  671. items: list[PackageItem] = []
  672. excluded: list[dict[str, str]] = []
  673. warnings: list[dict[str, str]] = []
  674. sources: list[dict[str, object]] = []
  675. git_metadata: list[dict[str, object]] = []
  676. source_snapshots: list[SourceSnapshot] = []
  677. root_items, root_excluded = _collect_directory_items(
  678. root=root,
  679. source_id="workspace-current",
  680. category="core",
  681. prefix="workspace-current",
  682. extra_exclusions=config.extra_exclusions,
  683. )
  684. items.extend(root_items)
  685. excluded.extend(root_excluded)
  686. source_snapshots.append(
  687. _source_snapshot(
  688. root,
  689. source_id="workspace-current",
  690. extra_exclusions=config.extra_exclusions,
  691. )
  692. )
  693. sources.append(
  694. {
  695. "id": "workspace-current",
  696. "category": "core",
  697. "kind": "git_worktree",
  698. "path": str(root),
  699. "status": "pass",
  700. }
  701. )
  702. if include_git_bundle:
  703. bundle_item, bundle_metadata = _create_git_bundle(
  704. root=root,
  705. source_id="workspace-current",
  706. temp_root=temp_root,
  707. )
  708. items.append(bundle_item)
  709. git_metadata.append(bundle_metadata)
  710. resolved_sources, source_warnings = resolve_external_sources(config.external_sources)
  711. warnings.extend(source_warnings)
  712. for source in resolved_sources:
  713. prefix = f"external/{source.id}"
  714. if source.kind == "file":
  715. candidate = _candidate_from_path(source.path, f"{prefix}/{source.path.name}")
  716. items.append(
  717. PackageItem(
  718. candidate=candidate,
  719. category=source.category,
  720. source_id=source.id,
  721. original_path=source.path.name,
  722. scan_archive=source.archive_policy == "inspect",
  723. )
  724. )
  725. else:
  726. source_items, source_excluded = _collect_directory_items(
  727. root=source.path,
  728. source_id=source.id,
  729. category=source.category,
  730. prefix=prefix,
  731. extra_exclusions=config.extra_exclusions,
  732. )
  733. items.extend(source_items)
  734. excluded.extend(source_excluded)
  735. source_snapshots.append(
  736. _source_snapshot(
  737. source.path,
  738. source_id=source.id,
  739. extra_exclusions=config.extra_exclusions,
  740. )
  741. )
  742. sources.append(
  743. {
  744. "id": source.id,
  745. "category": source.category,
  746. "kind": source.kind,
  747. "path": str(source.path),
  748. "status": "pass",
  749. }
  750. )
  751. if source.kind == "git_worktree":
  752. external_bundle, external_git = _create_git_bundle(
  753. root=source.path,
  754. source_id=source.id,
  755. temp_root=temp_root,
  756. )
  757. items.append(external_bundle)
  758. git_metadata.append(external_git)
  759. items.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
  760. excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
  761. return AnalysisCollection(
  762. status="pass_with_warnings" if warnings else "pass",
  763. items=tuple(items),
  764. excluded=tuple(excluded),
  765. warnings=tuple(warnings),
  766. sources=tuple(sources),
  767. git=tuple(git_metadata),
  768. source_snapshots=tuple(source_snapshots),
  769. )
  770. def find_7z() -> Path | None:
  771. discovered = shutil.which("7z") or shutil.which("7zz")
  772. candidates = [
  773. Path(discovered) if discovered else None,
  774. Path(r"C:\Program Files\7-Zip\7z.exe"),
  775. Path(r"C:\Program Files (x86)\7-Zip\7z.exe"),
  776. ]
  777. for candidate in candidates:
  778. if candidate is not None and candidate.is_file():
  779. return candidate.resolve(strict=True)
  780. return None
  781. def build_7zip_create_command(archive_path: Path, staging_root: Path) -> list[str]:
  782. del staging_root
  783. return [
  784. "a",
  785. "-tzip",
  786. "-mm=Deflate",
  787. "-mx=9",
  788. "-mmt",
  789. "-y",
  790. "-r",
  791. str(archive_path),
  792. "CPLD\\*",
  793. ]
  794. def _run_7z(seven_zip: Path, arguments: list[str], *, cwd: Path) -> str:
  795. try:
  796. completed = subprocess.run(
  797. [str(seven_zip), *arguments],
  798. cwd=cwd,
  799. stdout=subprocess.PIPE,
  800. stderr=subprocess.STDOUT,
  801. text=True,
  802. encoding="utf-8",
  803. errors="replace",
  804. timeout=300,
  805. check=False,
  806. )
  807. except (OSError, subprocess.TimeoutExpired) as exc:
  808. raise PackagingError("unable to run 7-Zip for archive inspection") from exc
  809. if completed.returncode != 0:
  810. detail = completed.stdout.strip().splitlines()
  811. suffix = f": {detail[-1]}" if detail else ""
  812. raise PackagingError(f"7-Zip archive inspection failed{suffix}")
  813. return completed.stdout
  814. def _rename_archive_entries(
  815. seven_zip: Path,
  816. archive_path: Path,
  817. renames: list[tuple[str, str]],
  818. ) -> None:
  819. for offset in range(0, len(renames), 64):
  820. batch = renames[offset : offset + 64]
  821. arguments = ["rn", "-y", str(archive_path)]
  822. for old_name, new_name in batch:
  823. arguments.extend((old_name, new_name))
  824. _run_7z(seven_zip, arguments, cwd=archive_path.parent)
  825. def _parse_7z_members(payload: str, archive_label: str) -> list[dict[str, str]]:
  826. in_members = False
  827. current: dict[str, str] = {}
  828. members: list[dict[str, str]] = []
  829. for raw_line in payload.splitlines():
  830. line = raw_line.rstrip("\r\n")
  831. if line.strip() == "----------":
  832. in_members = True
  833. current = {}
  834. continue
  835. if not in_members:
  836. continue
  837. if not line.strip():
  838. if current:
  839. members.append(current)
  840. current = {}
  841. continue
  842. key, separator, value = line.partition(" = ")
  843. if separator:
  844. current[key.strip()] = value.strip()
  845. if current:
  846. members.append(current)
  847. for member in members:
  848. raw_path = member.get("Path", "")
  849. normalized = raw_path.replace("\\", "/")
  850. if not normalized or normalized.startswith("/") or re.match(r"^[A-Za-z]:", normalized):
  851. raise PackagingError(f"unsafe archive member path in {archive_label}")
  852. handoff.normalize_relative(normalized.split("/"))
  853. if member.get("Encrypted") not in {None, "", "-"}:
  854. raise PackagingError(f"encrypted archive member is unsupported in {archive_label}")
  855. if member.get("Symbolic Link") or member.get("Hard Link"):
  856. raise PackagingError(f"archive link member is unsupported in {archive_label}")
  857. if member.get("Alternate Stream") not in {None, "", "-"}:
  858. raise PackagingError(f"archive alternate stream is unsupported in {archive_label}")
  859. if member.get("Split Before") not in {None, "", "-"} or member.get("Split After") not in {
  860. None,
  861. "",
  862. "-",
  863. }:
  864. raise PackagingError(f"split archive member is unsupported in {archive_label}")
  865. return members
  866. def _inspect_and_extract_unsupported_archive(
  867. item: PackageItem,
  868. *,
  869. temp_root: Path,
  870. seven_zip: Path,
  871. extra_exclusions: tuple[dict[str, str], ...],
  872. ) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
  873. listing = _run_7z(
  874. seven_zip,
  875. ["l", "-slt", "-sccUTF-8", str(item.candidate.absolute)],
  876. cwd=item.candidate.absolute.parent,
  877. )
  878. members = _parse_7z_members(listing, item.candidate.relative)
  879. file_members = [
  880. member
  881. for member in members
  882. if member.get("Folder") != "+" and "D" not in member.get("Attributes", "")
  883. ]
  884. expected_bytes = sum(int(member.get("Size") or "0") for member in file_members)
  885. token = hashlib.sha256(item.candidate.relative.encode("utf-8")).hexdigest()[:16]
  886. extract_root = temp_root / "expanded-archives" / token
  887. extract_root.mkdir(parents=True, exist_ok=False)
  888. _run_7z(
  889. seven_zip,
  890. ["x", "-y", "-aoa", "-sccUTF-8", f"-o{extract_root}", str(item.candidate.absolute)],
  891. cwd=item.candidate.absolute.parent,
  892. )
  893. actual_files = [path for path in extract_root.rglob("*") if path.is_file()]
  894. actual_bytes = sum(path.stat().st_size for path in actual_files)
  895. if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
  896. raise PackagingError(
  897. f"archive extraction inventory mismatch: {item.candidate.relative} "
  898. f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
  899. )
  900. expanded_candidates, expanded_excluded, _ = scan_analysis_root(
  901. extract_root,
  902. extra_exclusions=extra_exclusions,
  903. )
  904. handoff.audit_candidates(expanded_candidates)
  905. expanded_prefix = f"{item.candidate.relative}.expanded"
  906. expanded_items = [
  907. PackageItem(
  908. candidate=_rebase_candidate(candidate, expanded_prefix),
  909. category=item.category,
  910. source_id=item.source_id,
  911. original_path=f"{item.original_path}!/{candidate.relative}",
  912. scan_archive=True,
  913. )
  914. for candidate in expanded_candidates
  915. ]
  916. rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
  917. sensitive_rules = {
  918. "credential_or_license_file",
  919. "credential_configuration_file",
  920. "private_key_file",
  921. "secret_environment_file",
  922. "cloud_credential_file",
  923. "container_registry_credential_file",
  924. }
  925. contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
  926. return expanded_items, rebased_excluded, contains_sensitive
  927. def _inspect_and_extract_zip_archive(
  928. item: PackageItem,
  929. *,
  930. temp_root: Path,
  931. extra_exclusions: tuple[dict[str, str], ...],
  932. ) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
  933. archive_label = item.candidate.relative
  934. try:
  935. with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
  936. file_members: list[zipfile.ZipInfo] = []
  937. expected_bytes = 0
  938. for info in archive.infolist():
  939. normalized = info.filename.replace("\\", "/")
  940. if (
  941. not normalized
  942. or normalized.startswith("/")
  943. or re.match(r"^[A-Za-z]:", normalized)
  944. ):
  945. raise PackagingError(
  946. f"unsafe archive member path in {archive_label}"
  947. )
  948. handoff.normalize_relative(normalized.split("/"))
  949. if info.flag_bits & 0x1:
  950. raise PackagingError(
  951. f"encrypted archive member is unsupported in {archive_label}"
  952. )
  953. member_mode = (info.external_attr >> 16) & 0xFFFF
  954. member_type = stat.S_IFMT(member_mode)
  955. if info.is_dir():
  956. if (
  957. info.file_size != 0
  958. or info.compress_size != 0
  959. or member_type not in {0, stat.S_IFDIR}
  960. ):
  961. raise PackagingError(
  962. f"unsafe archive member type in {archive_label}"
  963. )
  964. continue
  965. if member_type not in {0, stat.S_IFREG}:
  966. raise PackagingError(
  967. f"unsafe archive member type in {archive_label}"
  968. )
  969. file_members.append(info)
  970. expected_bytes += info.file_size
  971. except (OSError, zipfile.BadZipFile) as exc:
  972. raise PackagingError(
  973. f"unable to inspect source archive: {archive_label}"
  974. ) from exc
  975. token = hashlib.sha256(archive_label.encode("utf-8")).hexdigest()[:16]
  976. extract_root = temp_root / "expanded-archives" / token
  977. extract_root.mkdir(parents=True, exist_ok=False)
  978. actual_files: list[Path] = []
  979. actual_bytes = 0
  980. try:
  981. with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
  982. for info in file_members:
  983. parts = info.filename.replace("\\", "/").split("/")
  984. target_path = extract_root / Path(*parts)
  985. target_path.parent.mkdir(parents=True, exist_ok=True)
  986. with archive.open(info, "r") as source, target_path.open("wb") as destination:
  987. shutil.copyfileobj(source, destination, length=1024 * 1024)
  988. actual_files.append(target_path)
  989. actual_bytes += target_path.stat().st_size
  990. except (OSError, zipfile.BadZipFile) as exc:
  991. raise PackagingError(
  992. f"unable to extract source archive: {archive_label}"
  993. ) from exc
  994. if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
  995. raise PackagingError(
  996. f"archive extraction inventory mismatch: {archive_label} "
  997. f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
  998. )
  999. expanded_candidates, expanded_excluded, _ = scan_analysis_root(
  1000. extract_root,
  1001. extra_exclusions=extra_exclusions,
  1002. )
  1003. handoff.audit_candidates(expanded_candidates)
  1004. expanded_prefix = f"{archive_label}.expanded"
  1005. expanded_items = [
  1006. PackageItem(
  1007. candidate=_rebase_candidate(candidate, expanded_prefix),
  1008. category=item.category,
  1009. source_id=item.source_id,
  1010. original_path=f"{item.original_path}!/{candidate.relative}",
  1011. scan_archive=True,
  1012. )
  1013. for candidate in expanded_candidates
  1014. ]
  1015. rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
  1016. sensitive_rules = {
  1017. "credential_or_license_file",
  1018. "credential_configuration_file",
  1019. "private_key_file",
  1020. "secret_environment_file",
  1021. "cloud_credential_file",
  1022. "container_registry_credential_file",
  1023. }
  1024. contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
  1025. return expanded_items, rebased_excluded, contains_sensitive
  1026. def prepare_unsupported_archives(
  1027. items: tuple[PackageItem, ...],
  1028. *,
  1029. temp_root: Path,
  1030. seven_zip: Path | None,
  1031. extra_exclusions: tuple[dict[str, str], ...],
  1032. ) -> ArchivePreparation:
  1033. prepared: list[PackageItem] = []
  1034. excluded: list[dict[str, str]] = []
  1035. warnings: list[dict[str, str]] = []
  1036. temp_root.mkdir(parents=True, exist_ok=True)
  1037. for item in items:
  1038. archive_kind = handoff.archive_kind(item.candidate.relative)
  1039. if archive_kind is None:
  1040. prepared.append(item)
  1041. continue
  1042. if archive_kind == "zip":
  1043. expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_zip_archive(
  1044. item,
  1045. temp_root=temp_root,
  1046. extra_exclusions=extra_exclusions,
  1047. )
  1048. elif seven_zip is None:
  1049. if _is_reference_item(item):
  1050. warnings.append(
  1051. {
  1052. "code": "unsupported_archive_without_7zip",
  1053. "source_id": item.source_id,
  1054. "path": item.candidate.relative,
  1055. "message": "7-Zip is unavailable; unsupported archive kept unexpanded",
  1056. }
  1057. )
  1058. prepared.append(item._replace(scan_archive=False))
  1059. continue
  1060. if item.candidate.absolute.is_file():
  1061. raise PackagingError(
  1062. "7-Zip is required to inspect unsupported source archives"
  1063. )
  1064. prepared.append(item._replace(scan_archive=False))
  1065. continue
  1066. else:
  1067. expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_unsupported_archive(
  1068. item,
  1069. temp_root=temp_root,
  1070. seven_zip=seven_zip,
  1071. extra_exclusions=extra_exclusions,
  1072. )
  1073. has_filtered_members = bool(expanded_excluded)
  1074. if has_filtered_members:
  1075. prepared.extend(expanded_items)
  1076. excluded.extend(expanded_excluded)
  1077. if contains_sensitive:
  1078. excluded.append(
  1079. {
  1080. "path": item.candidate.relative,
  1081. "rule": "unsupported_archive_contains_sensitive_content",
  1082. }
  1083. )
  1084. elif has_filtered_members:
  1085. excluded.append(
  1086. {
  1087. "path": item.candidate.relative,
  1088. "rule": "archive_contains_excluded_members",
  1089. }
  1090. )
  1091. else:
  1092. prepared.append(item._replace(scan_archive=archive_kind != "unsupported"))
  1093. prepared.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
  1094. excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
  1095. return ArchivePreparation(
  1096. items=tuple(prepared),
  1097. excluded=tuple(excluded),
  1098. warnings=tuple(warnings),
  1099. )
  1100. def _utc_now() -> str:
  1101. return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
  1102. def _validate_package_name(package_name: str) -> None:
  1103. try:
  1104. collision_key = handoff.windows_collision_key(package_name)
  1105. except PackagingError as exc:
  1106. raise PackagingError("package name is not a portable Windows file name") from exc
  1107. if (
  1108. not handoff.SAFE_PACKAGE_NAME.fullmatch(package_name)
  1109. or package_name in {".", ".."}
  1110. or not collision_key
  1111. ):
  1112. raise PackagingError("package name is not a portable Windows file name")
  1113. def _item_sort_key(item: PackageItem) -> tuple[int, str, str]:
  1114. return (
  1115. CATEGORY_ORDER.get(item.category, len(CATEGORY_ORDER)),
  1116. item.category.casefold(),
  1117. handoff.windows_collision_key(item.candidate.relative),
  1118. )
  1119. def _audit_one_item(item: PackageItem) -> dict[str, object]:
  1120. if item.scan_archive:
  1121. file_inventory = handoff.stream_candidate(item.candidate)
  1122. else:
  1123. file_inventory = handoff.hash_candidate(item.candidate)
  1124. return {
  1125. **file_inventory,
  1126. "archive_path": f"CPLD/{item.candidate.relative}",
  1127. "category": item.category,
  1128. "source_id": item.source_id,
  1129. "original_path": item.original_path,
  1130. }
  1131. def _audit_package_items(items: tuple[PackageItem, ...]) -> list[dict[str, object]]:
  1132. sorted_items = sorted(items, key=_item_sort_key)
  1133. collision_paths: dict[str, str] = {}
  1134. for item in sorted_items:
  1135. key = handoff.windows_collision_key(item.candidate.relative)
  1136. previous = collision_paths.get(key)
  1137. if previous is not None:
  1138. raise PackagingError(
  1139. f"analysis inputs contain a Windows path collision: {previous} and {item.candidate.relative}"
  1140. )
  1141. collision_paths[key] = item.candidate.relative
  1142. max_workers = os.cpu_count() or 1
  1143. with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
  1144. return list(executor.map(_audit_one_item, sorted_items))
  1145. def _write_unscanned_candidate(
  1146. archive: zipfile.ZipFile,
  1147. item: PackageItem,
  1148. ) -> dict[str, object]:
  1149. candidate = item.candidate
  1150. digest = hashlib.sha256()
  1151. total = 0
  1152. secret_tail = b""
  1153. entry_name = f"CPLD/{candidate.relative}"
  1154. try:
  1155. with archive.open(handoff.zip_info(entry_name, candidate.mode), "w", force_zip64=True) as target:
  1156. with handoff.open_candidate(candidate) as source:
  1157. for chunk in iter(lambda: source.read(1024 * 1024), b""):
  1158. secret_tail = handoff.scan_secret_markers(
  1159. chunk,
  1160. secret_tail,
  1161. candidate.relative,
  1162. )
  1163. target.write(chunk)
  1164. digest.update(chunk)
  1165. total += len(chunk)
  1166. except OSError as exc:
  1167. raise PackagingError(f"unable to package {candidate.relative}: {exc}") from exc
  1168. if total != candidate.size:
  1169. raise PackagingError(f"source size changed during packaging: {candidate.relative}")
  1170. return {"path": candidate.relative, "size": total, "sha256": digest.hexdigest()}
  1171. def _write_package_item(
  1172. archive: zipfile.ZipFile,
  1173. item: PackageItem,
  1174. ) -> dict[str, object]:
  1175. if item.scan_archive:
  1176. return handoff.write_candidate(archive, item.candidate)
  1177. return _write_unscanned_candidate(archive, item)
  1178. def _stage_package_item(
  1179. staging_root: Path,
  1180. item: PackageItem,
  1181. staging_name: str,
  1182. ) -> dict[str, object]:
  1183. target = staging_root / "CPLD" / staging_name
  1184. target.parent.mkdir(parents=True, exist_ok=True)
  1185. if item.scan_archive:
  1186. try:
  1187. with target.open("wb") as destination:
  1188. return handoff.stream_candidate(item.candidate, target=destination)
  1189. except OSError as exc:
  1190. raise PackagingError(f"unable to stage {item.candidate.relative}: {exc}") from exc
  1191. digest = hashlib.sha256()
  1192. total = 0
  1193. secret_tail = b""
  1194. try:
  1195. with handoff.open_candidate(item.candidate) as source, target.open("wb") as destination:
  1196. for chunk in iter(lambda: source.read(1024 * 1024), b""):
  1197. secret_tail = handoff.scan_secret_markers(
  1198. chunk,
  1199. secret_tail,
  1200. item.candidate.relative,
  1201. )
  1202. destination.write(chunk)
  1203. digest.update(chunk)
  1204. total += len(chunk)
  1205. except OSError as exc:
  1206. raise PackagingError(f"unable to stage {item.candidate.relative}: {exc}") from exc
  1207. if total != item.candidate.size:
  1208. raise PackagingError(f"source size changed during staging: {item.candidate.relative}")
  1209. return {"path": item.candidate.relative, "size": total, "sha256": digest.hexdigest()}
  1210. def _volume_manifest(
  1211. *,
  1212. run_id: str,
  1213. package_name: str,
  1214. number: int,
  1215. count: int,
  1216. items: list[PackageItem],
  1217. inventory_by_path: dict[str, dict[str, object]],
  1218. ) -> dict[str, object]:
  1219. categories = sorted({item.category for item in items})
  1220. entries = [inventory_by_path[item.candidate.relative] for item in items]
  1221. return {
  1222. "schema": "cpld-agent-analysis-volume-v1",
  1223. "run_id": run_id,
  1224. "package_name": package_name,
  1225. "volume_number": number,
  1226. "volume_count": count,
  1227. "categories": categories,
  1228. "file_count": len(entries),
  1229. "uncompressed_bytes": sum(int(entry["size"]) for entry in entries),
  1230. "files": entries,
  1231. }
  1232. def _write_volume(
  1233. path: Path,
  1234. *,
  1235. run_id: str,
  1236. package_name: str,
  1237. number: int,
  1238. count: int,
  1239. items: list[PackageItem],
  1240. inventory_by_path: dict[str, dict[str, object]],
  1241. ) -> dict[str, object]:
  1242. manifest = _volume_manifest(
  1243. run_id=run_id,
  1244. package_name=package_name,
  1245. number=number,
  1246. count=count,
  1247. items=items,
  1248. inventory_by_path=inventory_by_path,
  1249. )
  1250. manifest_name = "CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json"
  1251. manifest_payload = handoff.json_bytes(manifest)
  1252. written_inventory: list[dict[str, object]] = []
  1253. try:
  1254. with zipfile.ZipFile(
  1255. path, "w", compression=zipfile.ZIP_DEFLATED, allowZip64=True
  1256. ) as archive:
  1257. for item in sorted(items, key=_item_sort_key):
  1258. expected = inventory_by_path[item.candidate.relative]
  1259. if item.scan_archive:
  1260. actual = handoff.write_candidate(archive, item.candidate)
  1261. else:
  1262. actual = _write_unscanned_candidate(archive, item)
  1263. if (
  1264. actual["size"] != expected["size"]
  1265. or actual["sha256"] != expected["sha256"]
  1266. ):
  1267. raise PackagingError(
  1268. f"source changed while writing ZIP: {item.candidate.relative}"
  1269. )
  1270. written_inventory.append(actual)
  1271. with archive.open(
  1272. handoff.zip_info(manifest_name), "w", force_zip64=True
  1273. ) as target:
  1274. target.write(manifest_payload)
  1275. except (OSError, zipfile.BadZipFile) as exc:
  1276. raise PackagingError(f"unable to create ZIP volume: {exc}") from exc
  1277. expected_names = {f"CPLD/{item.candidate.relative}" for item in items}
  1278. expected_names.add(manifest_name)
  1279. handoff.verify_archive(
  1280. path,
  1281. expected_names=expected_names,
  1282. inventory=written_inventory,
  1283. expected_payloads={manifest_name: manifest_payload},
  1284. )
  1285. return {
  1286. "file": path.name,
  1287. "volume_number": number,
  1288. "volume_count": count,
  1289. "categories": manifest["categories"],
  1290. "file_count": len(items),
  1291. "uncompressed_bytes": manifest["uncompressed_bytes"],
  1292. "compressed_bytes": path.stat().st_size,
  1293. "sha256": handoff.sha256_file(path),
  1294. }
  1295. def _estimated_item_bytes(item: PackageItem) -> int:
  1296. return item.candidate.size + 512 + (len(item.candidate.relative.encode("utf-8")) * 2)
  1297. def _partition_items(
  1298. items: tuple[PackageItem, ...],
  1299. *,
  1300. target_zip_bytes: int,
  1301. ) -> list[list[PackageItem]]:
  1302. base_overhead = min(64_000, max(1_024, target_zip_bytes // 20))
  1303. groups: list[list[PackageItem]] = []
  1304. current: list[PackageItem] = []
  1305. current_category: str | None = None
  1306. estimated_bytes = base_overhead
  1307. for item in sorted(items, key=_item_sort_key):
  1308. item_estimate = _estimated_item_bytes(item)
  1309. if current and (
  1310. item.category != current_category
  1311. or estimated_bytes + item_estimate > target_zip_bytes
  1312. ):
  1313. groups.append(current)
  1314. current = []
  1315. estimated_bytes = base_overhead
  1316. if not current:
  1317. current_category = item.category
  1318. current.append(item)
  1319. estimated_bytes += item_estimate
  1320. if current:
  1321. groups.append(current)
  1322. return groups
  1323. def _split_oversized_groups(
  1324. staging: Path,
  1325. *,
  1326. run_id: str,
  1327. package_name: str,
  1328. groups: list[list[PackageItem]],
  1329. inventory_by_path: dict[str, dict[str, object]],
  1330. target_zip_bytes: int,
  1331. max_zip_bytes: int,
  1332. ) -> list[list[PackageItem]]:
  1333. pending = list(groups)
  1334. accepted: list[list[PackageItem]] = []
  1335. probe_number = 0
  1336. while pending:
  1337. group = pending.pop(0)
  1338. probe_number += 1
  1339. probe = staging / f".volume-probe-{probe_number:04d}.zip"
  1340. try:
  1341. _write_volume(
  1342. probe,
  1343. run_id=run_id,
  1344. package_name=package_name,
  1345. number=1,
  1346. count=1,
  1347. items=group,
  1348. inventory_by_path=inventory_by_path,
  1349. )
  1350. size = probe.stat().st_size
  1351. finally:
  1352. probe.unlink(missing_ok=True)
  1353. if size < max_zip_bytes and (size <= target_zip_bytes or len(group) == 1):
  1354. accepted.append(group)
  1355. continue
  1356. if len(group) == 1:
  1357. raise PackagingError(
  1358. f"single analysis file requires chunking before ZIP creation: {group[0].candidate.relative}"
  1359. )
  1360. middle = len(group) // 2
  1361. pending[0:0] = [group[:middle], group[middle:]]
  1362. return accepted
  1363. def _prepare_large_file_chunks(
  1364. staging: Path,
  1365. *,
  1366. run_id: str,
  1367. package_name: str,
  1368. items: tuple[PackageItem, ...],
  1369. inventory_by_path: dict[str, dict[str, object]],
  1370. target_zip_bytes: int,
  1371. max_zip_bytes: int,
  1372. ) -> tuple[tuple[PackageItem, ...], list[dict[str, object]], Path | None]:
  1373. packaged_items: list[PackageItem] = []
  1374. large_files: list[dict[str, object]] = []
  1375. chunk_root: Path | None = None
  1376. probe_number = 0
  1377. chunk_payload_bytes = max(1, (target_zip_bytes * 3) // 4)
  1378. for item in sorted(items, key=_item_sort_key):
  1379. must_probe = _estimated_item_bytes(item) > target_zip_bytes
  1380. if must_probe:
  1381. probe_number += 1
  1382. probe = staging / f".large-file-probe-{probe_number:04d}.zip"
  1383. try:
  1384. _write_volume(
  1385. probe,
  1386. run_id=run_id,
  1387. package_name=package_name,
  1388. number=1,
  1389. count=1,
  1390. items=[item],
  1391. inventory_by_path=inventory_by_path,
  1392. )
  1393. probe_size = probe.stat().st_size
  1394. finally:
  1395. probe.unlink(missing_ok=True)
  1396. if probe_size <= target_zip_bytes and probe_size < max_zip_bytes:
  1397. packaged_items.append(item)
  1398. continue
  1399. else:
  1400. packaged_items.append(item)
  1401. continue
  1402. if chunk_root is None:
  1403. chunk_root = staging / ".large-file-chunks"
  1404. chunk_root.mkdir()
  1405. original = inventory_by_path[item.candidate.relative]
  1406. file_id = hashlib.sha256(item.candidate.relative.encode("utf-8")).hexdigest()[:16]
  1407. file_chunk_root = chunk_root / file_id
  1408. file_chunk_root.mkdir()
  1409. file_name = Path(item.candidate.relative).name
  1410. chunks: list[dict[str, object]] = []
  1411. original_digest = hashlib.sha256()
  1412. original_bytes = 0
  1413. secret_tail = b""
  1414. with handoff.open_candidate(item.candidate) as source:
  1415. number = 0
  1416. while True:
  1417. payload = source.read(chunk_payload_bytes)
  1418. if not payload:
  1419. break
  1420. number += 1
  1421. secret_tail = handoff.scan_secret_markers(
  1422. payload,
  1423. secret_tail,
  1424. item.candidate.relative,
  1425. )
  1426. original_digest.update(payload)
  1427. original_bytes += len(payload)
  1428. chunk_name = f"{file_name}.part{number:04d}"
  1429. chunk_path = file_chunk_root / chunk_name
  1430. with chunk_path.open("xb") as handle:
  1431. handle.write(payload)
  1432. chunk_relative = f"HANDOFF-LARGE-FILES/{file_id}/{chunk_name}"
  1433. chunk_item = make_package_item(
  1434. chunk_path,
  1435. relative=chunk_relative,
  1436. category=item.category,
  1437. source_id=item.source_id,
  1438. scan_archive=False,
  1439. )
  1440. packaged_items.append(chunk_item)
  1441. chunks.append(
  1442. {
  1443. "number": number,
  1444. "path": chunk_relative,
  1445. "archive_path": f"CPLD/{chunk_relative}",
  1446. "size": len(payload),
  1447. "sha256": hashlib.sha256(payload).hexdigest(),
  1448. }
  1449. )
  1450. if original_bytes != original["size"] or original_digest.hexdigest() != original["sha256"]:
  1451. raise PackagingError(f"source changed while splitting large file: {item.candidate.relative}")
  1452. if len(chunks) < 2:
  1453. raise PackagingError(f"large file split did not produce multiple chunks: {item.candidate.relative}")
  1454. large_files.append(
  1455. {
  1456. "path": item.candidate.relative,
  1457. "category": item.category,
  1458. "source_id": item.source_id,
  1459. "original_path": item.original_path,
  1460. "size": original["size"],
  1461. "sha256": original["sha256"],
  1462. "chunks": chunks,
  1463. }
  1464. )
  1465. return tuple(packaged_items), large_files, chunk_root
  1466. def _assert_items_unchanged(
  1467. items: tuple[PackageItem, ...],
  1468. inventory_by_path: dict[str, dict[str, object]],
  1469. ) -> None:
  1470. for item in items:
  1471. current = handoff.hash_candidate(item.candidate)
  1472. expected = inventory_by_path[item.candidate.relative]
  1473. if current["size"] != expected["size"] or current["sha256"] != expected["sha256"]:
  1474. raise PackagingError(f"source changed during analysis packaging: {item.candidate.relative}")
  1475. def _assert_source_trees_unchanged(collection: AnalysisCollection) -> None:
  1476. for snapshot in collection.source_snapshots:
  1477. current = _source_snapshot(
  1478. snapshot.root,
  1479. source_id=snapshot.source_id,
  1480. extra_exclusions=snapshot.extra_exclusions,
  1481. )
  1482. if (
  1483. current.candidates != snapshot.candidates
  1484. or current.excluded != snapshot.excluded
  1485. ):
  1486. raise PackagingError("source tree changed during analysis packaging: retry from a stable workspace snapshot")
  1487. def _start_here_text(package_name: str, volume_count: int) -> str:
  1488. return (
  1489. f"# {package_name} 分析交付包\n\n"
  1490. f"本目录包含 {volume_count} 个互相独立的普通 ZIP。请先核对 `SHA256SUMS.txt`,"
  1491. "再把所有 ZIP 解压到同一个目录。\n\n"
  1492. "`HANDOFF-INDEX.json` 记录每个原始文件的来源、目标卷、大小和 SHA-256。\n"
  1493. )
  1494. def _publish_directory_atomically(staging: Path, final: Path, *, force: bool) -> None:
  1495. backup: Path | None = None
  1496. backup_created = False
  1497. new_directory_published = False
  1498. if os.path.lexists(final):
  1499. if not force:
  1500. raise PackagingError(f"package output already exists: {final}")
  1501. file_stat = os.lstat(final)
  1502. if not stat.S_ISDIR(file_stat.st_mode) or handoff.stat_is_reparse_point(file_stat):
  1503. raise PackagingError(f"existing package output is not a regular directory: {final}")
  1504. backup = final.with_name(f".{final.name}.{uuid.uuid4().hex}.backup")
  1505. try:
  1506. if backup is not None:
  1507. os.replace(final, backup)
  1508. backup_created = True
  1509. os.replace(staging, final)
  1510. new_directory_published = True
  1511. except BaseException as exc:
  1512. if new_directory_published and os.path.lexists(final):
  1513. try:
  1514. shutil.rmtree(final)
  1515. except OSError:
  1516. pass
  1517. if backup_created and backup is not None and os.path.lexists(backup):
  1518. try:
  1519. os.replace(backup, final)
  1520. except OSError as rollback_exc:
  1521. raise PackagingError(
  1522. f"package publication failed and rollback was incomplete: {rollback_exc}"
  1523. ) from exc
  1524. if isinstance(exc, PackagingError):
  1525. raise
  1526. raise PackagingError(f"unable to publish package directory atomically: {exc}") from exc
  1527. if backup is not None:
  1528. shutil.rmtree(backup)
  1529. def create_analysis_package(
  1530. *,
  1531. collection: AnalysisCollection,
  1532. output_root: Path,
  1533. package_name: str,
  1534. max_zip_bytes: int,
  1535. target_zip_bytes: int,
  1536. force: bool,
  1537. ) -> dict[str, object]:
  1538. _validate_package_name(package_name)
  1539. if max_zip_bytes <= 0 or not 0 < target_zip_bytes < max_zip_bytes:
  1540. raise PackagingError("ZIP size limits are invalid")
  1541. if not collection.items:
  1542. raise PackagingError("analysis package has no included files")
  1543. output_root = output_root.expanduser().resolve(strict=False)
  1544. output_root.mkdir(parents=True, exist_ok=True)
  1545. final_dir = output_root / package_name
  1546. if os.path.lexists(final_dir) and not force:
  1547. raise PackagingError(f"package output already exists: {final_dir}")
  1548. run_id = uuid.uuid4().hex
  1549. staging = Path(tempfile.mkdtemp(prefix=f".{package_name}.{run_id}.", dir=output_root))
  1550. try:
  1551. inventory = _audit_package_items(collection.items)
  1552. inventory_by_path = {str(item["path"]): item for item in inventory}
  1553. package_items = collection.items
  1554. package_inventory = inventory
  1555. package_inventory_by_path = inventory_by_path
  1556. large_files: list[dict[str, object]] = []
  1557. chunk_root: Path | None = None
  1558. single_path = staging / f"{package_name}.zip"
  1559. single_info = _write_volume(
  1560. single_path,
  1561. run_id=run_id,
  1562. package_name=package_name,
  1563. number=1,
  1564. count=1,
  1565. items=list(sorted(collection.items, key=_item_sort_key)),
  1566. inventory_by_path=inventory_by_path,
  1567. )
  1568. if single_path.stat().st_size < max_zip_bytes:
  1569. volume_infos = [single_info]
  1570. groups = [list(sorted(collection.items, key=_item_sort_key))]
  1571. else:
  1572. single_path.unlink()
  1573. package_items, large_files, chunk_root = _prepare_large_file_chunks(
  1574. staging,
  1575. run_id=run_id,
  1576. package_name=package_name,
  1577. items=collection.items,
  1578. inventory_by_path=inventory_by_path,
  1579. target_zip_bytes=target_zip_bytes,
  1580. max_zip_bytes=max_zip_bytes,
  1581. )
  1582. package_inventory = _audit_package_items(package_items)
  1583. package_inventory_by_path = {
  1584. str(item["path"]): item for item in package_inventory
  1585. }
  1586. initial_groups = _partition_items(
  1587. package_items,
  1588. target_zip_bytes=target_zip_bytes,
  1589. )
  1590. groups = _split_oversized_groups(
  1591. staging,
  1592. run_id=run_id,
  1593. package_name=package_name,
  1594. groups=initial_groups,
  1595. inventory_by_path=package_inventory_by_path,
  1596. target_zip_bytes=target_zip_bytes,
  1597. max_zip_bytes=max_zip_bytes,
  1598. )
  1599. volume_infos = []
  1600. count = len(groups)
  1601. for number, group in enumerate(groups, start=1):
  1602. category = group[0].category if len({item.category for item in group}) == 1 else "mixed"
  1603. safe_category = re.sub(r"[^a-z0-9]+", "-", category.casefold()).strip("-") or "data"
  1604. volume_path = staging / f"{package_name}.part{number:03d}-{safe_category}.zip"
  1605. volume_info = _write_volume(
  1606. volume_path,
  1607. run_id=run_id,
  1608. package_name=package_name,
  1609. number=number,
  1610. count=count,
  1611. items=group,
  1612. inventory_by_path=package_inventory_by_path,
  1613. )
  1614. if volume_path.stat().st_size >= max_zip_bytes:
  1615. raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
  1616. volume_infos.append(volume_info)
  1617. volume_by_path: dict[str, str] = {}
  1618. for volume_info, group in zip(volume_infos, groups, strict=True):
  1619. for item in group:
  1620. volume_by_path[item.candidate.relative] = str(volume_info["file"])
  1621. large_paths = {str(item["path"]) for item in large_files}
  1622. indexed_files = [
  1623. {**item, "volume": volume_by_path[str(item["path"])]}
  1624. for item in inventory
  1625. if str(item["path"]) not in large_paths
  1626. ]
  1627. for large_file in large_files:
  1628. for chunk in large_file["chunks"]:
  1629. chunk["volume"] = volume_by_path[str(chunk["path"])]
  1630. index = {
  1631. "schema": "cpld-agent-analysis-index-v1",
  1632. "run_id": run_id,
  1633. "created_at_utc": _utc_now(),
  1634. "package_name": package_name,
  1635. "status": collection.status,
  1636. "max_zip_bytes": max_zip_bytes,
  1637. "target_zip_bytes": target_zip_bytes,
  1638. "sources": list(collection.sources),
  1639. "git": list(collection.git),
  1640. "warnings": list(collection.warnings),
  1641. "excluded": list(collection.excluded),
  1642. "volumes": volume_infos,
  1643. "files": indexed_files,
  1644. "large_files": large_files,
  1645. }
  1646. if large_files:
  1647. (staging / "reassemble_large_files.py").write_text(
  1648. REASSEMBLER_SCRIPT,
  1649. encoding="utf-8",
  1650. newline="\n",
  1651. )
  1652. (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
  1653. (staging / "START-HERE.zh-CN.md").write_text(
  1654. _start_here_text(package_name, len(volume_infos)),
  1655. encoding="utf-8",
  1656. newline="\n",
  1657. )
  1658. checksum_lines = [f"{info['sha256']} {info['file']}" for info in volume_infos]
  1659. (staging / "SHA256SUMS.txt").write_text(
  1660. "\n".join(checksum_lines) + "\n",
  1661. encoding="ascii",
  1662. newline="\n",
  1663. )
  1664. for info in volume_infos:
  1665. volume_path = staging / str(info["file"])
  1666. if volume_path.stat().st_size >= max_zip_bytes:
  1667. raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
  1668. if handoff.sha256_file(volume_path) != info["sha256"]:
  1669. raise PackagingError(f"ZIP volume hash changed after verification: {volume_path.name}")
  1670. _assert_items_unchanged(collection.items, inventory_by_path)
  1671. _assert_source_trees_unchanged(collection)
  1672. if chunk_root is not None:
  1673. shutil.rmtree(chunk_root)
  1674. _publish_directory_atomically(staging, final_dir, force=force)
  1675. except BaseException:
  1676. if os.path.lexists(staging):
  1677. shutil.rmtree(staging, ignore_errors=True)
  1678. raise
  1679. return {
  1680. "status": collection.status,
  1681. "mode": "package",
  1682. "run_id": run_id,
  1683. "output_dir": str(final_dir),
  1684. "volumes": volume_infos,
  1685. "included_file_count": len(inventory),
  1686. "included_bytes": sum(int(item["size"]) for item in inventory),
  1687. "excluded_entry_count": len(collection.excluded),
  1688. "warning_count": len(collection.warnings),
  1689. }
  1690. def _reference_fingerprint(inventory: list[dict[str, object]]) -> str:
  1691. digest = hashlib.sha256()
  1692. for item in sorted(inventory, key=lambda row: str(row["path"])):
  1693. path = str(item["path"])
  1694. size = str(item["size"])
  1695. sha = str(item["sha256"])
  1696. digest.update(f"{path}|{size}|{sha}\n".encode("utf-8"))
  1697. return digest.hexdigest()
  1698. def _create_reference_package_with_cache(
  1699. *,
  1700. collection: AnalysisCollection,
  1701. output_root: Path,
  1702. package_name: str,
  1703. max_zip_bytes: int,
  1704. target_zip_bytes: int,
  1705. force: bool,
  1706. ) -> dict[str, object]:
  1707. reference_package_name = f"{package_name}-reference"
  1708. reference_dir = output_root / reference_package_name
  1709. fingerprint_path = reference_dir / "REFERENCE-FINGERPRINT"
  1710. inventory = _audit_package_items(collection.items)
  1711. fingerprint = _reference_fingerprint(inventory)
  1712. if not force and fingerprint_path.exists():
  1713. previous = fingerprint_path.read_text(encoding="ascii").strip()
  1714. if previous == fingerprint:
  1715. index_path = reference_dir / "HANDOFF-INDEX.json"
  1716. if index_path.exists():
  1717. index = json.loads(index_path.read_text(encoding="utf-8"))
  1718. return {
  1719. "status": collection.status,
  1720. "mode": "reference_cached",
  1721. "package_name": reference_package_name,
  1722. "output_dir": str(reference_dir),
  1723. "volumes": index.get("volumes", []),
  1724. "included_file_count": len(inventory),
  1725. "included_bytes": sum(int(item["size"]) for item in inventory),
  1726. "fingerprint": fingerprint,
  1727. "skipped": True,
  1728. }
  1729. payload = create_analysis_package(
  1730. collection=collection,
  1731. output_root=output_root,
  1732. package_name=reference_package_name,
  1733. max_zip_bytes=max_zip_bytes,
  1734. target_zip_bytes=target_zip_bytes,
  1735. force=force,
  1736. )
  1737. reference_dir = Path(payload["output_dir"])
  1738. fingerprint_path = reference_dir / "REFERENCE-FINGERPRINT"
  1739. fingerprint_path.write_text(fingerprint + "\n", encoding="ascii")
  1740. payload["fingerprint"] = fingerprint
  1741. payload["skipped"] = False
  1742. return payload
  1743. def merge_archive_preparation(
  1744. collection: AnalysisCollection,
  1745. preparation: ArchivePreparation,
  1746. ) -> AnalysisCollection:
  1747. warnings = (*collection.warnings, *preparation.warnings)
  1748. excluded = sorted(
  1749. (*collection.excluded, *preparation.excluded),
  1750. key=lambda item: handoff.windows_collision_key(item["path"]),
  1751. )
  1752. return AnalysisCollection(
  1753. status="pass_with_warnings" if warnings else "pass",
  1754. items=preparation.items,
  1755. excluded=tuple(excluded),
  1756. warnings=tuple(warnings),
  1757. sources=collection.sources,
  1758. git=collection.git,
  1759. source_snapshots=collection.source_snapshots,
  1760. )
  1761. def explain_analysis_path(
  1762. path: Path,
  1763. *,
  1764. repo_root: Path,
  1765. config: HandoffConfig,
  1766. ) -> dict[str, object]:
  1767. root = repo_root.resolve(strict=True)
  1768. requested = path if path.is_absolute() else root / path
  1769. target = requested.expanduser().resolve(strict=False)
  1770. resolved_sources, warnings = resolve_external_sources(config.external_sources)
  1771. source_roots: list[tuple[str, str, Path, Path | None]] = [
  1772. ("workspace-current", "core", root, None)
  1773. ]
  1774. for source in resolved_sources:
  1775. if source.kind == "file":
  1776. source_roots.append((source.id, source.category, source.path.parent, source.path))
  1777. else:
  1778. source_roots.append((source.id, source.category, source.path, None))
  1779. matches: list[tuple[int, str, str, Path, Path | None]] = []
  1780. for source_id, category, source_root, exact_file in source_roots:
  1781. if exact_file is not None and target != exact_file:
  1782. continue
  1783. try:
  1784. target.relative_to(source_root)
  1785. except ValueError:
  1786. continue
  1787. matches.append((len(source_root.parts), source_id, category, source_root, exact_file))
  1788. if not matches:
  1789. raise PackagingError("path is outside the current repository and configured external sources")
  1790. _, source_id, category, source_root, exact_file = max(matches, key=lambda item: item[0])
  1791. relative = exact_file.name if exact_file is not None else target.relative_to(source_root).as_posix()
  1792. if not relative:
  1793. relative = "."
  1794. is_dir = target.is_dir()
  1795. context = handoff.load_scan_context(source_root)
  1796. reason = analysis_exclusion_reason(
  1797. relative,
  1798. is_dir=is_dir,
  1799. context=context,
  1800. extra_exclusions=config.extra_exclusions,
  1801. )
  1802. archive_relative = (
  1803. f"workspace-current/{relative}"
  1804. if source_id == "workspace-current"
  1805. else f"external/{source_id}/{relative}"
  1806. )
  1807. return {
  1808. "status": "pass_with_warnings" if warnings else "pass",
  1809. "mode": "explain",
  1810. "path": str(target),
  1811. "exists": target.exists(),
  1812. "source_id": source_id,
  1813. "category": category,
  1814. "source_relative_path": relative,
  1815. "archive_path": f"CPLD/{archive_relative}",
  1816. "decision": "exclude" if reason else "include",
  1817. "reason": reason,
  1818. "content_scan": "not_run",
  1819. "warnings": warnings,
  1820. }
  1821. def audit_analysis_collection(collection: AnalysisCollection) -> dict[str, object]:
  1822. inventory = _audit_package_items(collection.items)
  1823. inventory_by_path = {str(item["path"]): item for item in inventory}
  1824. _assert_items_unchanged(collection.items, inventory_by_path)
  1825. return {
  1826. "status": collection.status,
  1827. "mode": "audit_only",
  1828. "included_file_count": len(inventory),
  1829. "included_bytes": sum(int(item["size"]) for item in inventory),
  1830. "excluded_entry_count": len(collection.excluded),
  1831. "warning_count": len(collection.warnings),
  1832. "warnings": list(collection.warnings),
  1833. "sources": list(collection.sources),
  1834. "git": list(collection.git),
  1835. }
  1836. def _validate_output_root(
  1837. output_root: Path,
  1838. *,
  1839. repo_root: Path,
  1840. config: HandoffConfig,
  1841. ) -> Path:
  1842. output = output_root.expanduser().resolve(strict=False)
  1843. source_paths = [repo_root.resolve(strict=True)]
  1844. resolved_sources, _ = resolve_external_sources(config.external_sources)
  1845. source_paths.extend(source.path if source.kind != "file" else source.path.parent for source in resolved_sources)
  1846. for source_path in source_paths:
  1847. try:
  1848. output.relative_to(source_path)
  1849. except ValueError:
  1850. continue
  1851. raise PackagingError(f"output directory must be outside every packaged source root: {source_path}")
  1852. return output
  1853. def build_parser() -> argparse.ArgumentParser:
  1854. parser = argparse.ArgumentParser(description=__doc__)
  1855. parser.add_argument("--audit-only", action="store_true", help="scan and verify inputs without creating ZIP files")
  1856. parser.add_argument("--explain", type=Path, metavar="PATH", help="explain whether one path is included or excluded")
  1857. parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG, help="source and exclusion configuration JSON")
  1858. parser.add_argument("--source-root", type=Path, default=ROOT, help="root directory to package as the primary source")
  1859. parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR, help="parent directory for the package directory")
  1860. parser.add_argument("--package-name", help="portable package directory and ZIP base name")
  1861. parser.add_argument("--force-overwrite", action="store_true", help="atomically replace an existing package directory")
  1862. parser.add_argument("--no-git-bundle", action="store_true", help="omit the git history bundle from the package")
  1863. return parser
  1864. def main(argv: list[str] | None = None) -> int:
  1865. args = build_parser().parse_args(argv)
  1866. package_name = args.package_name or datetime.now(timezone.utc).strftime(
  1867. "cpld-agent-analysis-%Y%m%dT%H%M%SZ"
  1868. )
  1869. source_root = args.source_root.expanduser().resolve(strict=True)
  1870. try:
  1871. config = load_config(args.config, repo_root=source_root)
  1872. if args.explain is not None:
  1873. payload = explain_analysis_path(args.explain, repo_root=source_root, config=config)
  1874. else:
  1875. seven_zip = find_7z()
  1876. _validate_package_name(package_name)
  1877. output_root = _validate_output_root(args.output_dir, repo_root=source_root, config=config)
  1878. with tempfile.TemporaryDirectory(prefix="ca-") as temporary:
  1879. temp_root = Path(temporary)
  1880. collection = collect_analysis_inputs(
  1881. repo_root=source_root,
  1882. config=config,
  1883. temp_root=temp_root / "inputs",
  1884. include_git_bundle=not args.no_git_bundle,
  1885. )
  1886. preparation = prepare_unsupported_archives(
  1887. collection.items,
  1888. temp_root=temp_root / "archives",
  1889. seven_zip=seven_zip,
  1890. extra_exclusions=config.extra_exclusions,
  1891. )
  1892. prepared_collection = merge_archive_preparation(collection, preparation)
  1893. if args.audit_only:
  1894. payload = audit_analysis_collection(prepared_collection)
  1895. else:
  1896. core_collection, reference_collection = _split_collection_by_reference(
  1897. prepared_collection
  1898. )
  1899. if not core_collection.items and not reference_collection.items:
  1900. raise PackagingError("analysis package has no included files")
  1901. payload: dict[str, object] = {}
  1902. if core_collection.items:
  1903. payload["core"] = create_analysis_package(
  1904. collection=core_collection,
  1905. output_root=output_root,
  1906. package_name=package_name,
  1907. max_zip_bytes=config.max_zip_bytes,
  1908. target_zip_bytes=config.target_zip_bytes,
  1909. force=args.force_overwrite,
  1910. )
  1911. if reference_collection.items:
  1912. payload["reference"] = _create_reference_package_with_cache(
  1913. collection=reference_collection,
  1914. output_root=output_root,
  1915. package_name=package_name,
  1916. max_zip_bytes=config.max_zip_bytes,
  1917. target_zip_bytes=config.target_zip_bytes,
  1918. force=args.force_overwrite,
  1919. )
  1920. except (PackagingError, OSError, ValueError) as exc:
  1921. print(f"error: {exc}", file=sys.stderr)
  1922. return 1
  1923. print(json.dumps(payload, ensure_ascii=False, indent=2))
  1924. return 0
  1925. if __name__ == "__main__":
  1926. raise SystemExit(main())