#!/usr/bin/env python3 """Compact generated continuation documents when their context budgets overflow.""" from __future__ import annotations import json import re from pathlib import Path ROOT = Path(__file__).resolve().parents[1] BUDGET = ROOT / "docs/current/FREECAD_WEB_CONTEXT_BUDGET.json" HANDOFF = ROOT / "docs/current/FREECAD_WEB_HANDOFF.md" TASKS = ROOT / "docs/tasks/p6/full-parity" def fit(text: str, limit: int) -> str: raw = text.encode("utf-8") if len(raw) <= limit: return text return raw[: max(0, limit - 40)].decode("utf-8", "ignore").rstrip() + "\n" def compact_handoff(limit: int) -> bool: if HANDOFF.stat().st_size <= limit: return False text = HANDOFF.read_text(encoding="utf-8", errors="replace") marker = "## 本回合检查点" prefix = text.split(marker, 1)[0].rstrip() checkpoint = text.split(marker, 1)[1] if marker in text else "" bullets = [line.strip() for line in checkpoint.splitlines() if line.strip().startswith("-")] # Keep only the latest checkpoint facts; table fields and the automatic # continuation entry remain authoritative and are preserved in prefix. latest = bullets[-5:] compact = prefix + "\n\n## 本回合检查点(压缩)\n" + "\n".join(latest) + "\n" HANDOFF.write_text(fit(compact, limit), encoding="utf-8") return True def compact_card(path: Path, limit: int) -> bool: if path.stat().st_size <= limit: return False text = path.read_text(encoding="utf-8", errors="replace") sections = re.split(r"(?m)(?=^## )", text) header = sections[0].rstrip() result = [section for section in sections[1:] if section.startswith("## 结果") or section.startswith("## 当前结果")] recovery = [section for section in sections[1:] if section.startswith("## 首错")] continuation = [section for section in sections[1:] if section.startswith("## 自动续接状态")] keep = [header] if result: keep.append(result[-1].rstrip()) if recovery: keep.append(recovery[-1].rstrip()) if continuation: keep.append(continuation[-1].rstrip()) compact = "\n\n".join(keep) + "\n" path.write_text(fit(compact, limit), encoding="utf-8") return True def main() -> int: limits = json.loads(BUDGET.read_text(encoding="utf-8"))["limits"] changed = [] if compact_handoff(int(limits["handoff_bytes"])): changed.append(str(HANDOFF.relative_to(ROOT))) for path in sorted(TASKS.glob("FW-*.md")): if compact_card(path, int(limits["task_card_bytes"])): changed.append(str(path.relative_to(ROOT))) if changed: print("CONTINUATION_DOCS_COMPACTED: " + ", ".join(changed)) else: print("CONTINUATION_DOCS_WITHIN_BUDGET") return 0 if __name__ == "__main__": raise SystemExit(main())