package_for_agent_analysis.py 78 KB

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