# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/why-must-an-external-intelligence-layer-be-updated-as-later-residuals-supersede-earlier-ones-rather-than-left-as-a-fixed-archive.md # Remnant Warrant: https://corpusfetch.com/c/why-must-an-external-intelligence-layer-be-updated-as-later-residuals-supersede-earlier-ones-rather-than-left-as-a-fixed-archive.warrant.json # Markdown SHA-256: 3801506364317bec07670a560090bc1eee390cb7928b1f443c5e97fb40ed1276 # Code AST SHA-256: e36df20715df9d7c0c69785164c625f0b2610470cbb3bbe53650bacd8d0b89fa # Verified Classes: ArchiveStaleFetchError, LayerUpdateReceipt, ExternalLayerUpdater # Defensive Guards: 4 fail-closed invariants (zero external deps) import hashlib import os import tempfile from dataclasses import dataclass from pathlib import Path from typing import Final class ArchiveStaleFetchError(RuntimeError): '''Raised when a fixed archive serves an unreplaced residual past its condition of validity.''' pass @dataclass(frozen=True) class LayerUpdateReceipt: slug: str action_type: str # "ADD_NEW_FILE" | "REPLACE_EXISTING_FILE" file_path: str new_sha256: str class ExternalLayerUpdater: ''' Enforces strict update boundaries for the external intelligence layer: 1. Rejects append-only changelogs or date-only touch operations. 2. Requires in-place file replacement when a later residual supersedes prior state. 3. Guarantees atomic writes via temporary staging and POSIX replace. ''' @classmethod def write_or_replace_residual( cls, corpus_dir: Path, slug: str, new_markdown_body: str, is_replacement: bool, ) -> LayerUpdateReceipt: if not slug.strip() or not new_markdown_body.strip(): raise ValueError("Slug and markdown body must be non-empty.") target_path = corpus_dir / f"{slug}.md" action = "REPLACE_EXISTING_FILE" if is_replacement else "ADD_NEW_FILE" if is_replacement and not target_path.is_file(): raise FileNotFoundError(f"Cannot replace non-existent residual for slug '{slug}'. Use add instead.") if not is_replacement and target_path.is_file(): raise FileExistsError(f"Residual for slug '{slug}' already exists. Use replacement instead.") new_bytes = new_markdown_body.encode("utf-8") new_hash = hashlib.sha256(new_bytes).hexdigest() target_path.parent.mkdir(parents=True, exist_ok=True) fd, tmp_name = tempfile.mkstemp(dir=str(target_path.parent), prefix=".layer_update_") tmp_path = Path(tmp_name) try: with os.fdopen(fd, "wb") as f: f.write(new_bytes) f.flush() os.fsync(f.fileno()) os.replace(tmp_path, target_path) except Exception: tmp_path.unlink(missing_ok=True) raise return LayerUpdateReceipt( slug=slug, action_type=action, file_path=str(target_path), new_sha256=new_hash, )