package_for_agent_analysis.py 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584
  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 os
  8. import re
  9. import shutil
  10. import stat
  11. import subprocess
  12. import sys
  13. import tempfile
  14. import uuid
  15. import zipfile
  16. from datetime import datetime, timezone
  17. from pathlib import Path
  18. from typing import NamedTuple
  19. ROOT = Path(__file__).resolve().parent
  20. TOOLS = ROOT / "tools"
  21. if str(TOOLS) not in sys.path:
  22. sys.path.insert(0, str(TOOLS))
  23. import package_agent_handoff as handoff # noqa: E402
  24. PackagingError = handoff.PackagingError
  25. CONFIG_SCHEMA = "cpld-agent-analysis-sources-v1"
  26. DEFAULT_CONFIG = ROOT / "config" / "agent_analysis_handoff_sources.json"
  27. DEFAULT_OUTPUT_DIR = Path.home() / "Downloads" / "CPLD-agent-analysis"
  28. CATEGORY_ORDER = {
  29. "core": 0,
  30. "hardware": 1,
  31. "td-docs": 2,
  32. "evidence": 3,
  33. }
  34. REASSEMBLER_SCRIPT = '''#!/usr/bin/env python3
  35. """Reassemble files that were split across analysis ZIP volumes."""
  36. from __future__ import annotations
  37. import argparse
  38. import hashlib
  39. import json
  40. import shutil
  41. import sys
  42. import zipfile
  43. from pathlib import Path, PurePosixPath
  44. def safe_output_path(root: Path, relative: str) -> Path:
  45. portable = PurePosixPath(relative)
  46. if portable.is_absolute() or not portable.parts or any(part in {"", ".", ".."} for part in portable.parts):
  47. raise RuntimeError(f"unsafe output path: {relative}")
  48. target = (root / Path(*portable.parts)).resolve(strict=False)
  49. try:
  50. target.relative_to(root.resolve(strict=False))
  51. except ValueError as exc:
  52. raise RuntimeError(f"output path escapes target directory: {relative}") from exc
  53. return target
  54. def sha256_path(path: Path) -> str:
  55. digest = hashlib.sha256()
  56. with path.open("rb") as handle:
  57. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  58. digest.update(chunk)
  59. return digest.hexdigest()
  60. def main() -> int:
  61. parser = argparse.ArgumentParser(description=__doc__)
  62. parser.add_argument("--package-dir", type=Path, default=Path(__file__).resolve().parent)
  63. parser.add_argument("--output-dir", type=Path, default=Path("reassembled"))
  64. args = parser.parse_args()
  65. package_dir = args.package_dir.resolve(strict=True)
  66. output_dir = args.output_dir.resolve(strict=False)
  67. index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
  68. output_dir.mkdir(parents=True, exist_ok=True)
  69. for item in index.get("large_files", []):
  70. target = safe_output_path(output_dir, item["path"])
  71. target.parent.mkdir(parents=True, exist_ok=True)
  72. temporary = target.with_name(target.name + ".partial")
  73. temporary.unlink(missing_ok=True)
  74. total = 0
  75. with temporary.open("xb") as destination:
  76. for chunk in sorted(item["chunks"], key=lambda value: value["number"]):
  77. volume = package_dir / chunk["volume"]
  78. with zipfile.ZipFile(volume, "r") as archive:
  79. with archive.open(chunk["archive_path"], "r") as source:
  80. digest = hashlib.sha256()
  81. chunk_bytes = 0
  82. while True:
  83. payload = source.read(1024 * 1024)
  84. if not payload:
  85. break
  86. destination.write(payload)
  87. digest.update(payload)
  88. chunk_bytes += len(payload)
  89. if chunk_bytes != chunk["size"] or digest.hexdigest() != chunk["sha256"]:
  90. raise RuntimeError(f"chunk verification failed: {chunk['archive_path']}")
  91. total += chunk_bytes
  92. if total != item["size"] or sha256_path(temporary) != item["sha256"]:
  93. temporary.unlink(missing_ok=True)
  94. raise RuntimeError(f"reassembled file verification failed: {item['path']}")
  95. temporary.replace(target)
  96. print(f"reassembled: {target}")
  97. return 0
  98. if __name__ == "__main__":
  99. try:
  100. raise SystemExit(main())
  101. except (OSError, RuntimeError, KeyError, ValueError, json.JSONDecodeError, zipfile.BadZipFile) as exc:
  102. print(f"error: {exc}", file=sys.stderr)
  103. raise SystemExit(1)
  104. '''
  105. class ExternalSource(NamedTuple):
  106. id: str
  107. category: str
  108. kind: str
  109. path_candidates: tuple[Path, ...]
  110. archive_policy: str
  111. class HandoffConfig(NamedTuple):
  112. max_zip_bytes: int
  113. target_zip_bytes: int
  114. external_sources: tuple[ExternalSource, ...]
  115. extra_exclusions: tuple[dict[str, str], ...]
  116. class ResolvedSource(NamedTuple):
  117. id: str
  118. category: str
  119. kind: str
  120. path: Path
  121. archive_policy: str
  122. class PackageItem(NamedTuple):
  123. candidate: handoff.Candidate
  124. category: str
  125. source_id: str
  126. original_path: str
  127. scan_archive: bool
  128. class AnalysisCollection(NamedTuple):
  129. status: str
  130. items: tuple[PackageItem, ...]
  131. excluded: tuple[dict[str, str], ...]
  132. warnings: tuple[dict[str, str], ...]
  133. sources: tuple[dict[str, object], ...]
  134. git: tuple[dict[str, object], ...]
  135. class ArchivePreparation(NamedTuple):
  136. items: tuple[PackageItem, ...]
  137. excluded: tuple[dict[str, str], ...]
  138. warnings: tuple[dict[str, str], ...]
  139. def _require_keys(payload: dict[str, object], allowed: set[str], label: str) -> None:
  140. unknown = sorted(set(payload) - allowed)
  141. if unknown:
  142. if any("include" in item.casefold() for item in unknown):
  143. raise PackagingError(f"positive include rules are forbidden in {label}: {unknown}")
  144. raise PackagingError(f"unsupported fields in {label}: {unknown}")
  145. def _expand_path(value: str, *, repo_root: Path, user_profile: Path) -> Path:
  146. tokens = {
  147. "repo_root": str(repo_root),
  148. "user_profile": str(user_profile),
  149. "codex_temp": str(user_profile / "CodexTemp"),
  150. }
  151. try:
  152. expanded = value.format_map(tokens)
  153. except (KeyError, ValueError) as exc:
  154. raise PackagingError(f"unsupported path token in external source: {value}") from exc
  155. return Path(expanded).expanduser()
  156. def load_config(
  157. path: Path,
  158. *,
  159. repo_root: Path = ROOT,
  160. user_profile: Path | None = None,
  161. ) -> HandoffConfig:
  162. try:
  163. payload = json.loads(path.read_text(encoding="utf-8-sig"))
  164. except (OSError, UnicodeError, json.JSONDecodeError) as exc:
  165. raise PackagingError(f"unable to read analysis source config: {path}") from exc
  166. if not isinstance(payload, dict):
  167. raise PackagingError("analysis source config must be a JSON object")
  168. _require_keys(
  169. payload,
  170. {
  171. "schema",
  172. "max_zip_bytes",
  173. "target_zip_bytes",
  174. "external_sources",
  175. "extra_exclusions",
  176. },
  177. "config",
  178. )
  179. if payload.get("schema") != CONFIG_SCHEMA:
  180. raise PackagingError(f"unsupported analysis source config schema: {payload.get('schema')}")
  181. max_zip_bytes = payload.get("max_zip_bytes")
  182. target_zip_bytes = payload.get("target_zip_bytes")
  183. if not isinstance(max_zip_bytes, int) or max_zip_bytes <= 0:
  184. raise PackagingError("max_zip_bytes must be a positive integer")
  185. if not isinstance(target_zip_bytes, int) or not 0 < target_zip_bytes < max_zip_bytes:
  186. raise PackagingError("target_zip_bytes must be positive and smaller than max_zip_bytes")
  187. raw_sources = payload.get("external_sources")
  188. if not isinstance(raw_sources, list):
  189. raise PackagingError("external_sources must be an array")
  190. profile = user_profile or Path.home()
  191. sources: list[ExternalSource] = []
  192. seen_ids: set[str] = set()
  193. for index, raw_source in enumerate(raw_sources):
  194. if not isinstance(raw_source, dict):
  195. raise PackagingError(f"external_sources[{index}] must be an object")
  196. _require_keys(
  197. raw_source,
  198. {"id", "category", "kind", "path_candidates", "archive_policy"},
  199. f"external_sources[{index}]",
  200. )
  201. source_id = raw_source.get("id")
  202. category = raw_source.get("category")
  203. kind = raw_source.get("kind")
  204. archive_policy = raw_source.get("archive_policy")
  205. raw_paths = raw_source.get("path_candidates")
  206. if not isinstance(source_id, str) or not source_id or source_id in seen_ids:
  207. raise PackagingError(f"external source id is missing or duplicated: {source_id}")
  208. if not isinstance(category, str) or not category:
  209. raise PackagingError(f"external source category is invalid: {source_id}")
  210. if kind not in {"directory", "file", "git_worktree"}:
  211. raise PackagingError(f"external source kind is invalid: {source_id}")
  212. if archive_policy not in {"inspect", "copy"}:
  213. raise PackagingError(f"external archive policy is invalid: {source_id}")
  214. if not isinstance(raw_paths, list) or not raw_paths or not all(isinstance(item, str) for item in raw_paths):
  215. raise PackagingError(f"external source path_candidates are invalid: {source_id}")
  216. seen_ids.add(source_id)
  217. sources.append(
  218. ExternalSource(
  219. id=source_id,
  220. category=category,
  221. kind=kind,
  222. path_candidates=tuple(
  223. _expand_path(item, repo_root=repo_root, user_profile=profile)
  224. for item in raw_paths
  225. ),
  226. archive_policy=archive_policy,
  227. )
  228. )
  229. raw_exclusions = payload.get("extra_exclusions")
  230. if not isinstance(raw_exclusions, list) or not all(isinstance(item, dict) for item in raw_exclusions):
  231. raise PackagingError("extra_exclusions must be an array of objects")
  232. exclusions: list[dict[str, str]] = []
  233. for index, raw_exclusion in enumerate(raw_exclusions):
  234. _require_keys(raw_exclusion, {"path", "reason"}, f"extra_exclusions[{index}]")
  235. exclusion_path = raw_exclusion.get("path")
  236. reason = raw_exclusion.get("reason")
  237. if not isinstance(exclusion_path, str) or not exclusion_path or "\\" in exclusion_path:
  238. raise PackagingError(f"extra exclusion path is invalid: {index}")
  239. if not isinstance(reason, str) or not reason.strip():
  240. raise PackagingError(f"extra exclusion reason is invalid: {index}")
  241. normalized_path = handoff.normalize_relative(exclusion_path.strip("/").split("/"))
  242. exclusions.append({"path": normalized_path, "reason": reason.strip()})
  243. return HandoffConfig(
  244. max_zip_bytes=max_zip_bytes,
  245. target_zip_bytes=target_zip_bytes,
  246. external_sources=tuple(sources),
  247. extra_exclusions=tuple(exclusions),
  248. )
  249. def analysis_exclusion_reason(
  250. relative: str,
  251. *,
  252. is_dir: bool,
  253. context: handoff.ScanContext,
  254. extra_exclusions: tuple[dict[str, str], ...] = (),
  255. ) -> str | None:
  256. del context
  257. lower = relative.casefold()
  258. parts = lower.split("/")
  259. name = parts[-1]
  260. secret_reason = handoff.secret_path_reason(relative, is_dir=is_dir)
  261. if secret_reason:
  262. return secret_reason
  263. for item in extra_exclusions:
  264. prefix = str(item.get("path", "")).casefold().strip("/")
  265. if prefix and handoff.is_under(lower, prefix):
  266. return str(item.get("reason") or "configured_analysis_exclusion")
  267. if handoff.is_under(lower, ".git"):
  268. return "raw_git_metadata"
  269. if handoff.is_under(lower, ".omo"):
  270. return "agent_session_runtime"
  271. if lower == ".codex" or handoff.is_under(lower, ".codex/reports"):
  272. return None
  273. if handoff.is_under(lower, ".codex"):
  274. return "codex_session_runtime"
  275. if handoff.is_under(lower, "tmp") and len(parts) >= 2 and parts[1].startswith("sysinternals-handle-"):
  276. return "external_tool_cache"
  277. cache_components = {
  278. "__pycache__": "python_bytecode_cache",
  279. ".pytest_cache": "pytest_cache",
  280. ".hypothesis": "hypothesis_cache",
  281. ".mypy_cache": "mypy_cache",
  282. ".ruff_cache": "ruff_cache",
  283. ".tox": "tox_environment",
  284. ".nox": "nox_environment",
  285. ".venv": "virtual_environment",
  286. "venv": "virtual_environment",
  287. "htmlcov": "coverage_report",
  288. }
  289. for component in parts:
  290. if component in cache_components:
  291. return cache_components[component]
  292. if not is_dir:
  293. suffix = Path(name).suffix.casefold()
  294. if suffix in {".pyc", ".pyo"}:
  295. return "python_bytecode"
  296. if suffix in {".tmp", ".partial", ".part", ".swp", ".swo"} or name.endswith("~"):
  297. return "atomic_or_editor_temporary_file"
  298. if name in {".ds_store", "thumbs.db", "desktop.ini"}:
  299. return "os_metadata_cache"
  300. return None
  301. def scan_analysis_root(
  302. root: Path,
  303. *,
  304. extra_exclusions: tuple[dict[str, str], ...] = (),
  305. ) -> tuple[list[handoff.Candidate], list[dict[str, str]], handoff.ScanContext]:
  306. def resolve(relative: str, *, is_dir: bool, context: handoff.ScanContext) -> str | None:
  307. return analysis_exclusion_reason(
  308. relative,
  309. is_dir=is_dir,
  310. context=context,
  311. extra_exclusions=extra_exclusions,
  312. )
  313. return handoff.scan_tree(root, exclusion_resolver=resolve)
  314. def resolve_external_sources(
  315. sources: tuple[ExternalSource, ...],
  316. ) -> tuple[list[ResolvedSource], list[dict[str, str]]]:
  317. resolved: list[ResolvedSource] = []
  318. warnings: list[dict[str, str]] = []
  319. for source in sources:
  320. selected: Path | None = None
  321. for candidate in source.path_candidates:
  322. if source.kind == "file" and candidate.is_file():
  323. selected = candidate.resolve(strict=True)
  324. break
  325. if source.kind in {"directory", "git_worktree"} and candidate.is_dir():
  326. selected = candidate.resolve(strict=True)
  327. break
  328. if selected is None:
  329. warnings.append(
  330. {
  331. "code": "missing_external_source",
  332. "source_id": source.id,
  333. "message": "no configured path candidate is available",
  334. }
  335. )
  336. continue
  337. resolved.append(
  338. ResolvedSource(
  339. id=source.id,
  340. category=source.category,
  341. kind=source.kind,
  342. path=selected,
  343. archive_policy=source.archive_policy,
  344. )
  345. )
  346. return resolved, warnings
  347. def _candidate_from_path(path: Path, relative: str) -> handoff.Candidate:
  348. try:
  349. file_stat = os.lstat(path)
  350. except OSError as exc:
  351. raise PackagingError(f"unable to inspect generated analysis input: {relative}") from exc
  352. if not stat.S_ISREG(file_stat.st_mode) or handoff.stat_is_reparse_point(file_stat):
  353. raise PackagingError(f"analysis input is not a regular file: {relative}")
  354. return handoff.Candidate(
  355. absolute=path,
  356. relative=handoff.normalize_relative(relative.split("/")),
  357. size=file_stat.st_size,
  358. mtime_ns=file_stat.st_mtime_ns,
  359. device=int(file_stat.st_dev),
  360. inode=int(file_stat.st_ino),
  361. mode=int(file_stat.st_mode),
  362. )
  363. def make_package_item(
  364. path: Path,
  365. *,
  366. relative: str,
  367. category: str,
  368. source_id: str,
  369. scan_archive: bool = True,
  370. ) -> PackageItem:
  371. return PackageItem(
  372. candidate=_candidate_from_path(path, relative),
  373. category=category,
  374. source_id=source_id,
  375. original_path=path.name,
  376. scan_archive=scan_archive,
  377. )
  378. def _rebase_candidate(candidate: handoff.Candidate, prefix: str) -> handoff.Candidate:
  379. return handoff.Candidate(
  380. absolute=candidate.absolute,
  381. relative=handoff.normalize_relative([*prefix.split("/"), *candidate.relative.split("/")]),
  382. size=candidate.size,
  383. mtime_ns=candidate.mtime_ns,
  384. device=candidate.device,
  385. inode=candidate.inode,
  386. mode=candidate.mode,
  387. )
  388. def _rebase_exclusions(excluded: list[dict[str, str]], prefix: str) -> list[dict[str, str]]:
  389. return [
  390. {
  391. "path": handoff.normalize_relative([*prefix.split("/"), *item["path"].split("/")]),
  392. "rule": item["rule"],
  393. }
  394. for item in excluded
  395. ]
  396. def _collect_directory_items(
  397. *,
  398. root: Path,
  399. source_id: str,
  400. category: str,
  401. prefix: str,
  402. extra_exclusions: tuple[dict[str, str], ...],
  403. ) -> tuple[list[PackageItem], list[dict[str, str]]]:
  404. candidates, excluded, _ = scan_analysis_root(root, extra_exclusions=extra_exclusions)
  405. items = [
  406. PackageItem(
  407. candidate=_rebase_candidate(candidate, prefix),
  408. category=category,
  409. source_id=source_id,
  410. original_path=candidate.relative,
  411. scan_archive=True,
  412. )
  413. for candidate in candidates
  414. ]
  415. return items, _rebase_exclusions(excluded, prefix)
  416. def _run_git(command: list[str], *, cwd: Path, timeout: int = 300) -> str:
  417. try:
  418. completed = subprocess.run(
  419. command,
  420. cwd=cwd,
  421. stdout=subprocess.PIPE,
  422. stderr=subprocess.STDOUT,
  423. text=True,
  424. encoding="utf-8",
  425. errors="replace",
  426. timeout=timeout,
  427. check=False,
  428. )
  429. except (OSError, subprocess.TimeoutExpired) as exc:
  430. raise PackagingError(f"unable to run Git for {cwd.name}") from exc
  431. if completed.returncode != 0:
  432. detail = completed.stdout.strip().splitlines()
  433. suffix = f": {detail[-1]}" if detail else ""
  434. raise PackagingError(f"Git command failed for {cwd.name}{suffix}")
  435. return completed.stdout
  436. def _create_git_bundle(
  437. *,
  438. root: Path,
  439. source_id: str,
  440. temp_root: Path,
  441. ) -> tuple[PackageItem, dict[str, object]]:
  442. git = shutil.which("git")
  443. if not git:
  444. raise PackagingError("Git is required to create complete analysis history bundles")
  445. bundle_dir = temp_root / "git-bundles"
  446. bundle_dir.mkdir(parents=True, exist_ok=True)
  447. bundle_path = bundle_dir / f"{source_id}.bundle"
  448. _run_git([git, "bundle", "create", str(bundle_path), "--all"], cwd=root)
  449. verify_output = _run_git([git, "bundle", "verify", str(bundle_path)], cwd=root)
  450. head = _run_git([git, "rev-parse", "HEAD"], cwd=root).strip()
  451. branch = _run_git([git, "branch", "--show-current"], cwd=root).strip() or None
  452. status = _run_git(
  453. [
  454. git,
  455. "--no-optional-locks",
  456. "-c",
  457. "core.fsmonitor=false",
  458. "-c",
  459. "core.untrackedCache=false",
  460. "status",
  461. "--short",
  462. "--branch",
  463. "--untracked-files=all",
  464. ],
  465. cwd=root,
  466. )
  467. ref_lines = [line for line in verify_output.splitlines() if " refs/" in line or line.rstrip().endswith(" HEAD")]
  468. candidate = _candidate_from_path(bundle_path, f"git-history/{source_id}.bundle")
  469. item = PackageItem(
  470. candidate=candidate,
  471. category="core",
  472. source_id=source_id,
  473. original_path=".git",
  474. scan_archive=False,
  475. )
  476. metadata = {
  477. "source_id": source_id,
  478. "branch": branch,
  479. "head": head,
  480. "working_tree_clean": not any(
  481. line and not line.startswith("##") for line in status.splitlines()
  482. ),
  483. "status": "pass",
  484. "bundle_path": candidate.relative,
  485. "bundle_ref_count": len(ref_lines),
  486. "bundle_verify": "pass",
  487. }
  488. return item, metadata
  489. def collect_analysis_inputs(
  490. *,
  491. repo_root: Path,
  492. config: HandoffConfig,
  493. temp_root: Path,
  494. ) -> AnalysisCollection:
  495. root = repo_root.resolve(strict=True)
  496. temp_root.mkdir(parents=True, exist_ok=True)
  497. items: list[PackageItem] = []
  498. excluded: list[dict[str, str]] = []
  499. warnings: list[dict[str, str]] = []
  500. sources: list[dict[str, object]] = []
  501. git_metadata: list[dict[str, object]] = []
  502. root_items, root_excluded = _collect_directory_items(
  503. root=root,
  504. source_id="workspace-current",
  505. category="core",
  506. prefix="workspace-current",
  507. extra_exclusions=config.extra_exclusions,
  508. )
  509. items.extend(root_items)
  510. excluded.extend(root_excluded)
  511. sources.append(
  512. {
  513. "id": "workspace-current",
  514. "category": "core",
  515. "kind": "git_worktree",
  516. "path": str(root),
  517. "status": "pass",
  518. }
  519. )
  520. bundle_item, bundle_metadata = _create_git_bundle(
  521. root=root,
  522. source_id="workspace-current",
  523. temp_root=temp_root,
  524. )
  525. items.append(bundle_item)
  526. git_metadata.append(bundle_metadata)
  527. resolved_sources, source_warnings = resolve_external_sources(config.external_sources)
  528. warnings.extend(source_warnings)
  529. for source in resolved_sources:
  530. prefix = f"external/{source.id}"
  531. if source.kind == "file":
  532. candidate = _candidate_from_path(source.path, f"{prefix}/{source.path.name}")
  533. items.append(
  534. PackageItem(
  535. candidate=candidate,
  536. category=source.category,
  537. source_id=source.id,
  538. original_path=source.path.name,
  539. scan_archive=source.archive_policy == "inspect",
  540. )
  541. )
  542. else:
  543. source_items, source_excluded = _collect_directory_items(
  544. root=source.path,
  545. source_id=source.id,
  546. category=source.category,
  547. prefix=prefix,
  548. extra_exclusions=config.extra_exclusions,
  549. )
  550. items.extend(source_items)
  551. excluded.extend(source_excluded)
  552. sources.append(
  553. {
  554. "id": source.id,
  555. "category": source.category,
  556. "kind": source.kind,
  557. "path": str(source.path),
  558. "status": "pass",
  559. }
  560. )
  561. if source.kind == "git_worktree":
  562. external_bundle, external_git = _create_git_bundle(
  563. root=source.path,
  564. source_id=source.id,
  565. temp_root=temp_root,
  566. )
  567. items.append(external_bundle)
  568. git_metadata.append(external_git)
  569. items.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
  570. excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
  571. return AnalysisCollection(
  572. status="pass_with_warnings" if warnings else "pass",
  573. items=tuple(items),
  574. excluded=tuple(excluded),
  575. warnings=tuple(warnings),
  576. sources=tuple(sources),
  577. git=tuple(git_metadata),
  578. )
  579. def find_7z() -> Path | None:
  580. discovered = shutil.which("7z") or shutil.which("7zz")
  581. candidates = [
  582. Path(discovered) if discovered else None,
  583. Path(r"C:\Program Files\7-Zip\7z.exe"),
  584. Path(r"C:\Program Files (x86)\7-Zip\7z.exe"),
  585. ]
  586. for candidate in candidates:
  587. if candidate is not None and candidate.is_file():
  588. return candidate.resolve(strict=True)
  589. return None
  590. def _run_7z(seven_zip: Path, arguments: list[str], *, cwd: Path) -> str:
  591. try:
  592. completed = subprocess.run(
  593. [str(seven_zip), *arguments],
  594. cwd=cwd,
  595. stdout=subprocess.PIPE,
  596. stderr=subprocess.STDOUT,
  597. text=True,
  598. encoding="utf-8",
  599. errors="replace",
  600. timeout=300,
  601. check=False,
  602. )
  603. except (OSError, subprocess.TimeoutExpired) as exc:
  604. raise PackagingError("unable to run 7-Zip for archive inspection") from exc
  605. if completed.returncode != 0:
  606. detail = completed.stdout.strip().splitlines()
  607. suffix = f": {detail[-1]}" if detail else ""
  608. raise PackagingError(f"7-Zip archive inspection failed{suffix}")
  609. return completed.stdout
  610. def _parse_7z_members(payload: str, archive_label: str) -> list[dict[str, str]]:
  611. in_members = False
  612. current: dict[str, str] = {}
  613. members: list[dict[str, str]] = []
  614. for raw_line in payload.splitlines():
  615. line = raw_line.rstrip("\r\n")
  616. if line.strip() == "----------":
  617. in_members = True
  618. current = {}
  619. continue
  620. if not in_members:
  621. continue
  622. if not line.strip():
  623. if current:
  624. members.append(current)
  625. current = {}
  626. continue
  627. key, separator, value = line.partition(" = ")
  628. if separator:
  629. current[key.strip()] = value.strip()
  630. if current:
  631. members.append(current)
  632. for member in members:
  633. raw_path = member.get("Path", "")
  634. normalized = raw_path.replace("\\", "/")
  635. if not normalized or normalized.startswith("/") or re.match(r"^[A-Za-z]:", normalized):
  636. raise PackagingError(f"unsafe archive member path in {archive_label}")
  637. handoff.normalize_relative(normalized.split("/"))
  638. if member.get("Encrypted") not in {None, "", "-"}:
  639. raise PackagingError(f"encrypted archive member is unsupported in {archive_label}")
  640. if member.get("Symbolic Link") or member.get("Hard Link"):
  641. raise PackagingError(f"archive link member is unsupported in {archive_label}")
  642. if member.get("Alternate Stream") not in {None, "", "-"}:
  643. raise PackagingError(f"archive alternate stream is unsupported in {archive_label}")
  644. if member.get("Split Before") not in {None, "", "-"} or member.get("Split After") not in {
  645. None,
  646. "",
  647. "-",
  648. }:
  649. raise PackagingError(f"split archive member is unsupported in {archive_label}")
  650. return members
  651. def _inspect_and_extract_unsupported_archive(
  652. item: PackageItem,
  653. *,
  654. temp_root: Path,
  655. seven_zip: Path,
  656. extra_exclusions: tuple[dict[str, str], ...],
  657. ) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
  658. listing = _run_7z(
  659. seven_zip,
  660. ["l", "-slt", "-sccUTF-8", str(item.candidate.absolute)],
  661. cwd=item.candidate.absolute.parent,
  662. )
  663. members = _parse_7z_members(listing, item.candidate.relative)
  664. file_members = [
  665. member
  666. for member in members
  667. if member.get("Folder") != "+" and "D" not in member.get("Attributes", "")
  668. ]
  669. expected_bytes = sum(int(member.get("Size") or "0") for member in file_members)
  670. token = hashlib.sha256(item.candidate.relative.encode("utf-8")).hexdigest()[:16]
  671. extract_root = temp_root / "expanded-archives" / token
  672. extract_root.mkdir(parents=True, exist_ok=False)
  673. _run_7z(
  674. seven_zip,
  675. ["x", "-y", "-aoa", "-sccUTF-8", f"-o{extract_root}", str(item.candidate.absolute)],
  676. cwd=item.candidate.absolute.parent,
  677. )
  678. actual_files = [path for path in extract_root.rglob("*") if path.is_file()]
  679. actual_bytes = sum(path.stat().st_size for path in actual_files)
  680. if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
  681. raise PackagingError(
  682. f"archive extraction inventory mismatch: {item.candidate.relative} "
  683. f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
  684. )
  685. expanded_candidates, expanded_excluded, _ = scan_analysis_root(
  686. extract_root,
  687. extra_exclusions=extra_exclusions,
  688. )
  689. handoff.audit_candidates(expanded_candidates)
  690. expanded_prefix = f"{item.candidate.relative}.expanded"
  691. expanded_items = [
  692. PackageItem(
  693. candidate=_rebase_candidate(candidate, expanded_prefix),
  694. category=item.category,
  695. source_id=item.source_id,
  696. original_path=f"{item.original_path}!/{candidate.relative}",
  697. scan_archive=True,
  698. )
  699. for candidate in expanded_candidates
  700. ]
  701. rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
  702. sensitive_rules = {
  703. "credential_or_license_file",
  704. "credential_configuration_file",
  705. "private_key_file",
  706. "secret_environment_file",
  707. "cloud_credential_file",
  708. "container_registry_credential_file",
  709. }
  710. contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
  711. return expanded_items, rebased_excluded, contains_sensitive
  712. def prepare_unsupported_archives(
  713. items: tuple[PackageItem, ...],
  714. *,
  715. temp_root: Path,
  716. seven_zip: Path | None,
  717. extra_exclusions: tuple[dict[str, str], ...],
  718. ) -> ArchivePreparation:
  719. prepared: list[PackageItem] = []
  720. excluded: list[dict[str, str]] = []
  721. warnings: list[dict[str, str]] = []
  722. temp_root.mkdir(parents=True, exist_ok=True)
  723. for item in items:
  724. if handoff.archive_kind(item.candidate.relative) != "unsupported":
  725. prepared.append(item)
  726. continue
  727. if seven_zip is None:
  728. excluded.append(
  729. {
  730. "path": item.candidate.relative,
  731. "rule": "unsupported_archive_without_7zip",
  732. }
  733. )
  734. warnings.append(
  735. {
  736. "code": "missing_7zip",
  737. "source_id": item.source_id,
  738. "message": f"unsupported archive was skipped: {item.candidate.relative}",
  739. }
  740. )
  741. continue
  742. expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_unsupported_archive(
  743. item,
  744. temp_root=temp_root,
  745. seven_zip=seven_zip,
  746. extra_exclusions=extra_exclusions,
  747. )
  748. prepared.extend(expanded_items)
  749. excluded.extend(expanded_excluded)
  750. if contains_sensitive:
  751. excluded.append(
  752. {
  753. "path": item.candidate.relative,
  754. "rule": "unsupported_archive_contains_sensitive_content",
  755. }
  756. )
  757. else:
  758. prepared.append(item._replace(scan_archive=False))
  759. prepared.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 ArchivePreparation(
  762. items=tuple(prepared),
  763. excluded=tuple(excluded),
  764. warnings=tuple(warnings),
  765. )
  766. def _utc_now() -> str:
  767. return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
  768. def _validate_package_name(package_name: str) -> None:
  769. try:
  770. collision_key = handoff.windows_collision_key(package_name)
  771. except PackagingError as exc:
  772. raise PackagingError("package name is not a portable Windows file name") from exc
  773. if (
  774. not handoff.SAFE_PACKAGE_NAME.fullmatch(package_name)
  775. or package_name in {".", ".."}
  776. or not collision_key
  777. ):
  778. raise PackagingError("package name is not a portable Windows file name")
  779. def _item_sort_key(item: PackageItem) -> tuple[int, str, str]:
  780. return (
  781. CATEGORY_ORDER.get(item.category, len(CATEGORY_ORDER)),
  782. item.category.casefold(),
  783. handoff.windows_collision_key(item.candidate.relative),
  784. )
  785. def _audit_package_items(items: tuple[PackageItem, ...]) -> list[dict[str, object]]:
  786. inventory: list[dict[str, object]] = []
  787. collision_paths: dict[str, str] = {}
  788. for item in sorted(items, key=_item_sort_key):
  789. key = handoff.windows_collision_key(item.candidate.relative)
  790. previous = collision_paths.get(key)
  791. if previous is not None:
  792. raise PackagingError(
  793. f"analysis inputs contain a Windows path collision: {previous} and {item.candidate.relative}"
  794. )
  795. collision_paths[key] = item.candidate.relative
  796. if item.scan_archive:
  797. file_inventory = handoff.stream_candidate(item.candidate)
  798. else:
  799. file_inventory = handoff.hash_candidate(item.candidate)
  800. inventory.append(
  801. {
  802. **file_inventory,
  803. "archive_path": f"CPLD/{item.candidate.relative}",
  804. "category": item.category,
  805. "source_id": item.source_id,
  806. "original_path": item.original_path,
  807. }
  808. )
  809. return inventory
  810. def _write_unscanned_candidate(
  811. archive: zipfile.ZipFile,
  812. item: PackageItem,
  813. ) -> dict[str, object]:
  814. candidate = item.candidate
  815. digest = hashlib.sha256()
  816. total = 0
  817. secret_tail = b""
  818. entry_name = f"CPLD/{candidate.relative}"
  819. try:
  820. with archive.open(handoff.zip_info(entry_name, candidate.mode), "w", force_zip64=True) as target:
  821. with handoff.open_candidate(candidate) as source:
  822. for chunk in iter(lambda: source.read(1024 * 1024), b""):
  823. secret_tail = handoff.scan_secret_markers(
  824. chunk,
  825. secret_tail,
  826. candidate.relative,
  827. )
  828. target.write(chunk)
  829. digest.update(chunk)
  830. total += len(chunk)
  831. except OSError as exc:
  832. raise PackagingError(f"unable to package {candidate.relative}: {exc}") from exc
  833. if total != candidate.size:
  834. raise PackagingError(f"source size changed during packaging: {candidate.relative}")
  835. return {"path": candidate.relative, "size": total, "sha256": digest.hexdigest()}
  836. def _write_package_item(
  837. archive: zipfile.ZipFile,
  838. item: PackageItem,
  839. ) -> dict[str, object]:
  840. if item.scan_archive:
  841. return handoff.write_candidate(archive, item.candidate)
  842. return _write_unscanned_candidate(archive, item)
  843. def _volume_manifest(
  844. *,
  845. run_id: str,
  846. package_name: str,
  847. number: int,
  848. count: int,
  849. items: list[PackageItem],
  850. inventory_by_path: dict[str, dict[str, object]],
  851. ) -> dict[str, object]:
  852. categories = sorted({item.category for item in items})
  853. entries = [inventory_by_path[item.candidate.relative] for item in items]
  854. return {
  855. "schema": "cpld-agent-analysis-volume-v1",
  856. "run_id": run_id,
  857. "package_name": package_name,
  858. "volume_number": number,
  859. "volume_count": count,
  860. "categories": categories,
  861. "file_count": len(entries),
  862. "uncompressed_bytes": sum(int(entry["size"]) for entry in entries),
  863. "files": entries,
  864. }
  865. def _write_volume(
  866. path: Path,
  867. *,
  868. run_id: str,
  869. package_name: str,
  870. number: int,
  871. count: int,
  872. items: list[PackageItem],
  873. inventory_by_path: dict[str, dict[str, object]],
  874. ) -> dict[str, object]:
  875. manifest = _volume_manifest(
  876. run_id=run_id,
  877. package_name=package_name,
  878. number=number,
  879. count=count,
  880. items=items,
  881. inventory_by_path=inventory_by_path,
  882. )
  883. manifest_name = "CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json"
  884. manifest_payload = handoff.json_bytes(manifest)
  885. written_inventory: list[dict[str, object]] = []
  886. with zipfile.ZipFile(
  887. path,
  888. "x",
  889. compression=zipfile.ZIP_DEFLATED,
  890. compresslevel=6,
  891. allowZip64=True,
  892. strict_timestamps=False,
  893. ) as archive:
  894. for item in items:
  895. actual = _write_package_item(archive, item)
  896. expected = inventory_by_path[item.candidate.relative]
  897. if actual["size"] != expected["size"] or actual["sha256"] != expected["sha256"]:
  898. raise PackagingError(f"source changed while writing ZIP: {item.candidate.relative}")
  899. written_inventory.append(actual)
  900. handoff.write_bytes_entry(archive, manifest_name, manifest_payload)
  901. expected_names = {f"CPLD/{item.candidate.relative}" for item in items}
  902. expected_names.add(manifest_name)
  903. handoff.verify_archive(
  904. path,
  905. expected_names=expected_names,
  906. inventory=written_inventory,
  907. expected_payloads={manifest_name: manifest_payload},
  908. )
  909. return {
  910. "file": path.name,
  911. "volume_number": number,
  912. "volume_count": count,
  913. "categories": manifest["categories"],
  914. "file_count": len(items),
  915. "uncompressed_bytes": manifest["uncompressed_bytes"],
  916. "compressed_bytes": path.stat().st_size,
  917. "sha256": handoff.sha256_file(path),
  918. }
  919. def _estimated_item_bytes(item: PackageItem) -> int:
  920. return item.candidate.size + 512 + (len(item.candidate.relative.encode("utf-8")) * 2)
  921. def _partition_items(
  922. items: tuple[PackageItem, ...],
  923. *,
  924. target_zip_bytes: int,
  925. ) -> list[list[PackageItem]]:
  926. base_overhead = min(64_000, max(1_024, target_zip_bytes // 20))
  927. groups: list[list[PackageItem]] = []
  928. current: list[PackageItem] = []
  929. current_category: str | None = None
  930. estimated_bytes = base_overhead
  931. for item in sorted(items, key=_item_sort_key):
  932. item_estimate = _estimated_item_bytes(item)
  933. if current and (
  934. item.category != current_category
  935. or estimated_bytes + item_estimate > target_zip_bytes
  936. ):
  937. groups.append(current)
  938. current = []
  939. estimated_bytes = base_overhead
  940. if not current:
  941. current_category = item.category
  942. current.append(item)
  943. estimated_bytes += item_estimate
  944. if current:
  945. groups.append(current)
  946. return groups
  947. def _split_oversized_groups(
  948. staging: Path,
  949. *,
  950. run_id: str,
  951. package_name: str,
  952. groups: list[list[PackageItem]],
  953. inventory_by_path: dict[str, dict[str, object]],
  954. target_zip_bytes: int,
  955. max_zip_bytes: int,
  956. ) -> list[list[PackageItem]]:
  957. pending = list(groups)
  958. accepted: list[list[PackageItem]] = []
  959. probe_number = 0
  960. while pending:
  961. group = pending.pop(0)
  962. probe_number += 1
  963. probe = staging / f".volume-probe-{probe_number:04d}.zip"
  964. try:
  965. _write_volume(
  966. probe,
  967. run_id=run_id,
  968. package_name=package_name,
  969. number=1,
  970. count=1,
  971. items=group,
  972. inventory_by_path=inventory_by_path,
  973. )
  974. size = probe.stat().st_size
  975. finally:
  976. probe.unlink(missing_ok=True)
  977. if size < max_zip_bytes and (size <= target_zip_bytes or len(group) == 1):
  978. accepted.append(group)
  979. continue
  980. if len(group) == 1:
  981. raise PackagingError(
  982. f"single analysis file requires chunking before ZIP creation: {group[0].candidate.relative}"
  983. )
  984. middle = len(group) // 2
  985. pending[0:0] = [group[:middle], group[middle:]]
  986. return accepted
  987. def _prepare_large_file_chunks(
  988. staging: Path,
  989. *,
  990. run_id: str,
  991. package_name: str,
  992. items: tuple[PackageItem, ...],
  993. inventory_by_path: dict[str, dict[str, object]],
  994. target_zip_bytes: int,
  995. max_zip_bytes: int,
  996. ) -> tuple[tuple[PackageItem, ...], list[dict[str, object]], Path | None]:
  997. packaged_items: list[PackageItem] = []
  998. large_files: list[dict[str, object]] = []
  999. chunk_root: Path | None = None
  1000. probe_number = 0
  1001. chunk_payload_bytes = max(1, (target_zip_bytes * 3) // 4)
  1002. for item in sorted(items, key=_item_sort_key):
  1003. must_probe = _estimated_item_bytes(item) > target_zip_bytes
  1004. if must_probe:
  1005. probe_number += 1
  1006. probe = staging / f".large-file-probe-{probe_number:04d}.zip"
  1007. try:
  1008. _write_volume(
  1009. probe,
  1010. run_id=run_id,
  1011. package_name=package_name,
  1012. number=1,
  1013. count=1,
  1014. items=[item],
  1015. inventory_by_path=inventory_by_path,
  1016. )
  1017. probe_size = probe.stat().st_size
  1018. finally:
  1019. probe.unlink(missing_ok=True)
  1020. if probe_size <= target_zip_bytes and probe_size < max_zip_bytes:
  1021. packaged_items.append(item)
  1022. continue
  1023. else:
  1024. packaged_items.append(item)
  1025. continue
  1026. if chunk_root is None:
  1027. chunk_root = staging / ".large-file-chunks"
  1028. chunk_root.mkdir()
  1029. original = inventory_by_path[item.candidate.relative]
  1030. file_id = hashlib.sha256(item.candidate.relative.encode("utf-8")).hexdigest()[:16]
  1031. file_chunk_root = chunk_root / file_id
  1032. file_chunk_root.mkdir()
  1033. file_name = Path(item.candidate.relative).name
  1034. chunks: list[dict[str, object]] = []
  1035. original_digest = hashlib.sha256()
  1036. original_bytes = 0
  1037. secret_tail = b""
  1038. with handoff.open_candidate(item.candidate) as source:
  1039. number = 0
  1040. while True:
  1041. payload = source.read(chunk_payload_bytes)
  1042. if not payload:
  1043. break
  1044. number += 1
  1045. secret_tail = handoff.scan_secret_markers(
  1046. payload,
  1047. secret_tail,
  1048. item.candidate.relative,
  1049. )
  1050. original_digest.update(payload)
  1051. original_bytes += len(payload)
  1052. chunk_name = f"{file_name}.part{number:04d}"
  1053. chunk_path = file_chunk_root / chunk_name
  1054. with chunk_path.open("xb") as handle:
  1055. handle.write(payload)
  1056. chunk_relative = f"HANDOFF-LARGE-FILES/{file_id}/{chunk_name}"
  1057. chunk_item = make_package_item(
  1058. chunk_path,
  1059. relative=chunk_relative,
  1060. category=item.category,
  1061. source_id=item.source_id,
  1062. scan_archive=False,
  1063. )
  1064. packaged_items.append(chunk_item)
  1065. chunks.append(
  1066. {
  1067. "number": number,
  1068. "path": chunk_relative,
  1069. "archive_path": f"CPLD/{chunk_relative}",
  1070. "size": len(payload),
  1071. "sha256": hashlib.sha256(payload).hexdigest(),
  1072. }
  1073. )
  1074. if original_bytes != original["size"] or original_digest.hexdigest() != original["sha256"]:
  1075. raise PackagingError(f"source changed while splitting large file: {item.candidate.relative}")
  1076. if len(chunks) < 2:
  1077. raise PackagingError(f"large file split did not produce multiple chunks: {item.candidate.relative}")
  1078. large_files.append(
  1079. {
  1080. "path": item.candidate.relative,
  1081. "category": item.category,
  1082. "source_id": item.source_id,
  1083. "original_path": item.original_path,
  1084. "size": original["size"],
  1085. "sha256": original["sha256"],
  1086. "chunks": chunks,
  1087. }
  1088. )
  1089. return tuple(packaged_items), large_files, chunk_root
  1090. def _assert_items_unchanged(
  1091. items: tuple[PackageItem, ...],
  1092. inventory_by_path: dict[str, dict[str, object]],
  1093. ) -> None:
  1094. for item in items:
  1095. current = handoff.hash_candidate(item.candidate)
  1096. expected = inventory_by_path[item.candidate.relative]
  1097. if current["size"] != expected["size"] or current["sha256"] != expected["sha256"]:
  1098. raise PackagingError(f"source changed during analysis packaging: {item.candidate.relative}")
  1099. def _start_here_text(package_name: str, volume_count: int) -> str:
  1100. return (
  1101. f"# {package_name} 分析交付包\n\n"
  1102. f"本目录包含 {volume_count} 个互相独立的普通 ZIP。请先核对 `SHA256SUMS.txt`,"
  1103. "再把所有 ZIP 解压到同一个目录。\n\n"
  1104. "`HANDOFF-INDEX.json` 记录每个原始文件的来源、目标卷、大小和 SHA-256。\n"
  1105. )
  1106. def _publish_directory_atomically(staging: Path, final: Path, *, force: bool) -> None:
  1107. backup: Path | None = None
  1108. backup_created = False
  1109. new_directory_published = False
  1110. if os.path.lexists(final):
  1111. if not force:
  1112. raise PackagingError(f"package output already exists: {final}")
  1113. file_stat = os.lstat(final)
  1114. if not stat.S_ISDIR(file_stat.st_mode) or handoff.stat_is_reparse_point(file_stat):
  1115. raise PackagingError(f"existing package output is not a regular directory: {final}")
  1116. backup = final.with_name(f".{final.name}.{uuid.uuid4().hex}.backup")
  1117. try:
  1118. if backup is not None:
  1119. os.replace(final, backup)
  1120. backup_created = True
  1121. os.replace(staging, final)
  1122. new_directory_published = True
  1123. except BaseException as exc:
  1124. if new_directory_published and os.path.lexists(final):
  1125. try:
  1126. shutil.rmtree(final)
  1127. except OSError:
  1128. pass
  1129. if backup_created and backup is not None and os.path.lexists(backup):
  1130. try:
  1131. os.replace(backup, final)
  1132. except OSError as rollback_exc:
  1133. raise PackagingError(
  1134. f"package publication failed and rollback was incomplete: {rollback_exc}"
  1135. ) from exc
  1136. if isinstance(exc, PackagingError):
  1137. raise
  1138. raise PackagingError(f"unable to publish package directory atomically: {exc}") from exc
  1139. if backup is not None:
  1140. shutil.rmtree(backup)
  1141. def create_analysis_package(
  1142. *,
  1143. collection: AnalysisCollection,
  1144. output_root: Path,
  1145. package_name: str,
  1146. max_zip_bytes: int,
  1147. target_zip_bytes: int,
  1148. force: bool,
  1149. ) -> dict[str, object]:
  1150. _validate_package_name(package_name)
  1151. if max_zip_bytes <= 0 or not 0 < target_zip_bytes < max_zip_bytes:
  1152. raise PackagingError("ZIP size limits are invalid")
  1153. if not collection.items:
  1154. raise PackagingError("analysis package has no included files")
  1155. output_root = output_root.expanduser().resolve(strict=False)
  1156. output_root.mkdir(parents=True, exist_ok=True)
  1157. final_dir = output_root / package_name
  1158. if os.path.lexists(final_dir) and not force:
  1159. raise PackagingError(f"package output already exists: {final_dir}")
  1160. run_id = uuid.uuid4().hex
  1161. staging = Path(tempfile.mkdtemp(prefix=f".{package_name}.{run_id}.", dir=output_root))
  1162. try:
  1163. inventory = _audit_package_items(collection.items)
  1164. inventory_by_path = {str(item["path"]): item for item in inventory}
  1165. package_items = collection.items
  1166. package_inventory = inventory
  1167. package_inventory_by_path = inventory_by_path
  1168. large_files: list[dict[str, object]] = []
  1169. chunk_root: Path | None = None
  1170. single_path = staging / f"{package_name}.zip"
  1171. single_info = _write_volume(
  1172. single_path,
  1173. run_id=run_id,
  1174. package_name=package_name,
  1175. number=1,
  1176. count=1,
  1177. items=list(sorted(collection.items, key=_item_sort_key)),
  1178. inventory_by_path=inventory_by_path,
  1179. )
  1180. if single_path.stat().st_size < max_zip_bytes:
  1181. volume_infos = [single_info]
  1182. groups = [list(sorted(collection.items, key=_item_sort_key))]
  1183. else:
  1184. single_path.unlink()
  1185. package_items, large_files, chunk_root = _prepare_large_file_chunks(
  1186. staging,
  1187. run_id=run_id,
  1188. package_name=package_name,
  1189. items=collection.items,
  1190. inventory_by_path=inventory_by_path,
  1191. target_zip_bytes=target_zip_bytes,
  1192. max_zip_bytes=max_zip_bytes,
  1193. )
  1194. package_inventory = _audit_package_items(package_items)
  1195. package_inventory_by_path = {
  1196. str(item["path"]): item for item in package_inventory
  1197. }
  1198. initial_groups = _partition_items(
  1199. package_items,
  1200. target_zip_bytes=target_zip_bytes,
  1201. )
  1202. groups = _split_oversized_groups(
  1203. staging,
  1204. run_id=run_id,
  1205. package_name=package_name,
  1206. groups=initial_groups,
  1207. inventory_by_path=package_inventory_by_path,
  1208. target_zip_bytes=target_zip_bytes,
  1209. max_zip_bytes=max_zip_bytes,
  1210. )
  1211. volume_infos = []
  1212. count = len(groups)
  1213. for number, group in enumerate(groups, start=1):
  1214. category = group[0].category if len({item.category for item in group}) == 1 else "mixed"
  1215. safe_category = re.sub(r"[^a-z0-9]+", "-", category.casefold()).strip("-") or "data"
  1216. volume_path = staging / f"{package_name}.part{number:03d}-{safe_category}.zip"
  1217. volume_info = _write_volume(
  1218. volume_path,
  1219. run_id=run_id,
  1220. package_name=package_name,
  1221. number=number,
  1222. count=count,
  1223. items=group,
  1224. inventory_by_path=package_inventory_by_path,
  1225. )
  1226. if volume_path.stat().st_size >= max_zip_bytes:
  1227. raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
  1228. volume_infos.append(volume_info)
  1229. volume_by_path: dict[str, str] = {}
  1230. for volume_info, group in zip(volume_infos, groups, strict=True):
  1231. for item in group:
  1232. volume_by_path[item.candidate.relative] = str(volume_info["file"])
  1233. large_paths = {str(item["path"]) for item in large_files}
  1234. indexed_files = [
  1235. {**item, "volume": volume_by_path[str(item["path"])]}
  1236. for item in inventory
  1237. if str(item["path"]) not in large_paths
  1238. ]
  1239. for large_file in large_files:
  1240. for chunk in large_file["chunks"]:
  1241. chunk["volume"] = volume_by_path[str(chunk["path"])]
  1242. index = {
  1243. "schema": "cpld-agent-analysis-index-v1",
  1244. "run_id": run_id,
  1245. "created_at_utc": _utc_now(),
  1246. "package_name": package_name,
  1247. "status": collection.status,
  1248. "max_zip_bytes": max_zip_bytes,
  1249. "target_zip_bytes": target_zip_bytes,
  1250. "sources": list(collection.sources),
  1251. "git": list(collection.git),
  1252. "warnings": list(collection.warnings),
  1253. "excluded": list(collection.excluded),
  1254. "volumes": volume_infos,
  1255. "files": indexed_files,
  1256. "large_files": large_files,
  1257. }
  1258. if large_files:
  1259. (staging / "reassemble_large_files.py").write_text(
  1260. REASSEMBLER_SCRIPT,
  1261. encoding="utf-8",
  1262. newline="\n",
  1263. )
  1264. (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
  1265. (staging / "START-HERE.zh-CN.md").write_text(
  1266. _start_here_text(package_name, len(volume_infos)),
  1267. encoding="utf-8",
  1268. newline="\n",
  1269. )
  1270. checksum_lines = [f"{info['sha256']} {info['file']}" for info in volume_infos]
  1271. (staging / "SHA256SUMS.txt").write_text(
  1272. "\n".join(checksum_lines) + "\n",
  1273. encoding="ascii",
  1274. newline="\n",
  1275. )
  1276. for info in volume_infos:
  1277. volume_path = staging / str(info["file"])
  1278. if volume_path.stat().st_size >= max_zip_bytes:
  1279. raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
  1280. if handoff.sha256_file(volume_path) != info["sha256"]:
  1281. raise PackagingError(f"ZIP volume hash changed after verification: {volume_path.name}")
  1282. _assert_items_unchanged(collection.items, inventory_by_path)
  1283. if chunk_root is not None:
  1284. shutil.rmtree(chunk_root)
  1285. _publish_directory_atomically(staging, final_dir, force=force)
  1286. except BaseException:
  1287. if os.path.lexists(staging):
  1288. shutil.rmtree(staging, ignore_errors=True)
  1289. raise
  1290. return {
  1291. "status": collection.status,
  1292. "mode": "package",
  1293. "run_id": run_id,
  1294. "output_dir": str(final_dir),
  1295. "volumes": volume_infos,
  1296. "included_file_count": len(inventory),
  1297. "included_bytes": sum(int(item["size"]) for item in inventory),
  1298. "excluded_entry_count": len(collection.excluded),
  1299. "warning_count": len(collection.warnings),
  1300. }
  1301. def merge_archive_preparation(
  1302. collection: AnalysisCollection,
  1303. preparation: ArchivePreparation,
  1304. ) -> AnalysisCollection:
  1305. warnings = (*collection.warnings, *preparation.warnings)
  1306. excluded = sorted(
  1307. (*collection.excluded, *preparation.excluded),
  1308. key=lambda item: handoff.windows_collision_key(item["path"]),
  1309. )
  1310. return AnalysisCollection(
  1311. status="pass_with_warnings" if warnings else "pass",
  1312. items=preparation.items,
  1313. excluded=tuple(excluded),
  1314. warnings=tuple(warnings),
  1315. sources=collection.sources,
  1316. git=collection.git,
  1317. )
  1318. def explain_analysis_path(
  1319. path: Path,
  1320. *,
  1321. repo_root: Path,
  1322. config: HandoffConfig,
  1323. ) -> dict[str, object]:
  1324. root = repo_root.resolve(strict=True)
  1325. requested = path if path.is_absolute() else root / path
  1326. target = requested.expanduser().resolve(strict=False)
  1327. resolved_sources, warnings = resolve_external_sources(config.external_sources)
  1328. source_roots: list[tuple[str, str, Path, Path | None]] = [
  1329. ("workspace-current", "core", root, None)
  1330. ]
  1331. for source in resolved_sources:
  1332. if source.kind == "file":
  1333. source_roots.append((source.id, source.category, source.path.parent, source.path))
  1334. else:
  1335. source_roots.append((source.id, source.category, source.path, None))
  1336. matches: list[tuple[int, str, str, Path, Path | None]] = []
  1337. for source_id, category, source_root, exact_file in source_roots:
  1338. if exact_file is not None and target != exact_file:
  1339. continue
  1340. try:
  1341. target.relative_to(source_root)
  1342. except ValueError:
  1343. continue
  1344. matches.append((len(source_root.parts), source_id, category, source_root, exact_file))
  1345. if not matches:
  1346. raise PackagingError("path is outside the current repository and configured external sources")
  1347. _, source_id, category, source_root, exact_file = max(matches, key=lambda item: item[0])
  1348. relative = exact_file.name if exact_file is not None else target.relative_to(source_root).as_posix()
  1349. if not relative:
  1350. relative = "."
  1351. is_dir = target.is_dir()
  1352. context = handoff.load_scan_context(source_root)
  1353. reason = analysis_exclusion_reason(
  1354. relative,
  1355. is_dir=is_dir,
  1356. context=context,
  1357. extra_exclusions=config.extra_exclusions,
  1358. )
  1359. archive_relative = (
  1360. f"workspace-current/{relative}"
  1361. if source_id == "workspace-current"
  1362. else f"external/{source_id}/{relative}"
  1363. )
  1364. return {
  1365. "status": "pass_with_warnings" if warnings else "pass",
  1366. "mode": "explain",
  1367. "path": str(target),
  1368. "exists": target.exists(),
  1369. "source_id": source_id,
  1370. "category": category,
  1371. "source_relative_path": relative,
  1372. "archive_path": f"CPLD/{archive_relative}",
  1373. "decision": "exclude" if reason else "include",
  1374. "reason": reason,
  1375. "content_scan": "not_run",
  1376. "warnings": warnings,
  1377. }
  1378. def audit_analysis_collection(collection: AnalysisCollection) -> dict[str, object]:
  1379. inventory = _audit_package_items(collection.items)
  1380. inventory_by_path = {str(item["path"]): item for item in inventory}
  1381. _assert_items_unchanged(collection.items, inventory_by_path)
  1382. return {
  1383. "status": collection.status,
  1384. "mode": "audit_only",
  1385. "included_file_count": len(inventory),
  1386. "included_bytes": sum(int(item["size"]) for item in inventory),
  1387. "excluded_entry_count": len(collection.excluded),
  1388. "warning_count": len(collection.warnings),
  1389. "warnings": list(collection.warnings),
  1390. "sources": list(collection.sources),
  1391. "git": list(collection.git),
  1392. }
  1393. def _validate_output_root(
  1394. output_root: Path,
  1395. *,
  1396. repo_root: Path,
  1397. config: HandoffConfig,
  1398. ) -> Path:
  1399. output = output_root.expanduser().resolve(strict=False)
  1400. source_paths = [repo_root.resolve(strict=True)]
  1401. resolved_sources, _ = resolve_external_sources(config.external_sources)
  1402. source_paths.extend(source.path if source.kind != "file" else source.path.parent for source in resolved_sources)
  1403. for source_path in source_paths:
  1404. try:
  1405. output.relative_to(source_path)
  1406. except ValueError:
  1407. continue
  1408. raise PackagingError(f"output directory must be outside every packaged source root: {source_path}")
  1409. return output
  1410. def build_parser() -> argparse.ArgumentParser:
  1411. parser = argparse.ArgumentParser(description=__doc__)
  1412. parser.add_argument("--audit-only", action="store_true", help="scan and verify inputs without creating ZIP files")
  1413. parser.add_argument("--explain", type=Path, metavar="PATH", help="explain whether one path is included or excluded")
  1414. parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG, help="source and exclusion configuration JSON")
  1415. parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR, help="parent directory for the package directory")
  1416. parser.add_argument("--package-name", help="portable package directory and ZIP base name")
  1417. parser.add_argument("--force-overwrite", action="store_true", help="atomically replace an existing package directory")
  1418. return parser
  1419. def main(argv: list[str] | None = None) -> int:
  1420. args = build_parser().parse_args(argv)
  1421. package_name = args.package_name or datetime.now(timezone.utc).strftime(
  1422. "cpld-agent-analysis-%Y%m%dT%H%M%SZ"
  1423. )
  1424. try:
  1425. config = load_config(args.config, repo_root=ROOT)
  1426. if args.explain is not None:
  1427. payload = explain_analysis_path(args.explain, repo_root=ROOT, config=config)
  1428. else:
  1429. _validate_package_name(package_name)
  1430. output_root = _validate_output_root(args.output_dir, repo_root=ROOT, config=config)
  1431. with tempfile.TemporaryDirectory(prefix="ca-") as temporary:
  1432. temp_root = Path(temporary)
  1433. collection = collect_analysis_inputs(
  1434. repo_root=ROOT,
  1435. config=config,
  1436. temp_root=temp_root / "inputs",
  1437. )
  1438. preparation = prepare_unsupported_archives(
  1439. collection.items,
  1440. temp_root=temp_root / "archives",
  1441. seven_zip=find_7z(),
  1442. extra_exclusions=config.extra_exclusions,
  1443. )
  1444. prepared_collection = merge_archive_preparation(collection, preparation)
  1445. if args.audit_only:
  1446. payload = audit_analysis_collection(prepared_collection)
  1447. else:
  1448. payload = create_analysis_package(
  1449. collection=prepared_collection,
  1450. output_root=output_root,
  1451. package_name=package_name,
  1452. max_zip_bytes=config.max_zip_bytes,
  1453. target_zip_bytes=config.target_zip_bytes,
  1454. force=args.force_overwrite,
  1455. )
  1456. except (PackagingError, OSError, ValueError) as exc:
  1457. print(f"error: {exc}", file=sys.stderr)
  1458. return 1
  1459. print(json.dumps(payload, ensure_ascii=False, indent=2))
  1460. return 0
  1461. if __name__ == "__main__":
  1462. raise SystemExit(main())