"""Record verified upload content and successful App registration for safe cleanup.""" from __future__ import annotations import ast from pathlib import Path import stat import sys MARKER = "# FMODE_VERIFIED_DELIVERABLE_ACK_V1" RESULT = 'res.append({"path": p, "ok": same, "url": url, "did": did, "bytes": len(data), "detail": detail})' ACK = ' "src_mtime": int(_mtime_or_0(r["path"])), "gc": False,' HASHED_RESULT = RESULT.replace('"detail": detail', '"sha256": hashlib.sha256(data).hexdigest(), "detail": detail') VERIFIED_ACK = ACK + ''' "uploadedAt": int(time.time() * 1000), "cloudAck": True, "hubRegistered": isinstance(r.get("hub"), dict) and r["hub"].get("ok") is True, "sha256": r.get("sha256"), # FMODE_VERIFIED_DELIVERABLE_ACK_V1''' def patch_text(source: str) -> str: ast.parse(source) if MARKER in source: if HASHED_RESULT not in source or VERIFIED_ACK not in source: raise ValueError("Incomplete verified-deliverable acknowledgment patch") return source if source.count(RESULT) != 1 or source.count(ACK) != 1: raise ValueError("Deliverable hook differs from the verified upload baseline") tree = ast.parse(source) if not any(isinstance(node, ast.Import) and any(a.name == "hashlib" for a in node.names) for node in tree.body): raise ValueError("Deliverable hook is missing its verified hashlib import") updated = source.replace(RESULT, HASHED_RESULT, 1).replace(ACK, VERIFIED_ACK, 1) ast.parse(updated) return updated def main() -> None: if len(sys.argv) != 2: raise ValueError("Provide one copied App-container deliverable hook path") target = Path(sys.argv[1]).resolve(strict=True) root = Path("/opt/fmode-containers").resolve(strict=True) rel = target.relative_to(root) if (not rel.parts[0].startswith("agent-node-app-") or rel.parts[1:] != ("data", "scripts", "fmode-deliverable-hook.py")): raise ValueError("Only a copied App-container deliverable hook can be patched") original = target.read_text(encoding="utf-8") updated = patch_text(original) if updated != original: mode = stat.S_IMODE(target.stat().st_mode) backup = target.with_name(target.name + ".before-verified-ack") if not backup.exists(): backup.write_text(original, encoding="utf-8") backup.chmod(mode) temp = target.with_name(target.name + ".verified-ack.tmp") temp.write_text(updated, encoding="utf-8") temp.chmod(mode) temp.replace(target) print("Verified deliverable acknowledgments:", rel.parts[0]) if __name__ == "__main__": main()