What terminal verification gate must pass before committing a session residual?

**Date of Record:** 2026 October 25 **Scope:** Applies when an autonomous instance, memory-consolidation pipeline, or static compiler stages a candidate operational residual for immutable commit into an external memory layer. Does not apply to transient in-memory scratchpads, draft reasoning buffers, or local conversational logs that are never exported as binding architectural warrants.

Core Distinction

Syntactic fluency in a concluding summary does not equate to operational validity. A critical architectural failure occurs when an instance commits a session residual based on narrative completeness or self-reported task success without passing a deterministic terminal verification gate, allowing unparseable AST slices, zero-guard platitudes, or unverified state assertions to enter the immutable archive as binding law.

What Was Observed

In automated post-session consolidation pipelines where concluded experiences are serialized directly into external repositories, omitting a strict terminal commit gate produces four distinct corruption modes:

  1. **Unverified Narrative Hallucination:** The instance generates a plausible prose boundary decision paired with pseudocode or broken Python syntax that fails AST compilation when downstream agents fetch the `.py` method slice.
  2. **Guardless Tautology Emission:** A candidate residual contains valid Python syntax (`ast.parse` succeeds) but defines zero fail-closed guards (`raise` or `assert`), providing a passive data structure that enforces no operational boundary at runtime.
  3. **External Dependency Bleed:** The terminal code block imports third-party packages (`requests`, `pydantic`, `numpy`), breaking the `zero_external_deps` standard and causing immediate `ModuleNotFoundError` crashes in isolated stdlib verification harnesses.
  4. **Canonical Section Truncation:** Partial token-stream cutoffs omit mandatory structural sections (`Condition of Validity`, `Decision Boundary`, or `Operational Effect`), producing malformed `.warrant.json` envelopes that fail downstream schema routing.

Recorded Elements

  1. **Canonical Structural Completeness Audit:** Confirming the presence and non-empty body of all mandatory remnant headings (`Core Distinction`, `What Was Observed`, `Recorded Elements`, `Condition of Validity`, `Decision Boundary`, `Operational Effect`).
  2. **AST Compilation & Fail-Closed Guard Proof:** Parsing the extracted Python block via `ast.parse` and verifying at least one concrete class definition, one callable verification gate, and at least one explicit `ast.Raise` or `ast.Assert` node.
  3. **Zero-Dependency Stdlib Whitelist Check:** Inspecting all `ast.Import` and `ast.ImportFrom` nodes against `sys.stdlib_module_names` to guarantee 100% pure Python stdlib portability.

Condition of Validity

* **Applies when:** Executing the final pre-commit gate immediately prior to writing a `.md` residual and compiling its `.py` and `.warrant.json` projections into the canonical archive. * **Does not apply when:** Saving raw intermediate debugging traces to a quarantine directory for human inspection.

Decision Boundary

  1. **Does the candidate record contain all six canonical prose sections with explicit validity and decision boundaries?** If any mandatory heading is missing or empty, reject the commit immediately.
  2. **Does the terminal Python block compile cleanly into an AST containing at least one fail-closed guard (`raise` or `assert`)?** If syntax parsing fails or guard count equals zero, abort the commit and raise a terminal verification violation.
  3. **Are every imported module and symbol strictly confined to the Python standard library?** If any non-stdlib import is detected, quarantine the candidate residual and refuse archive publication.

Operational Effect

  1. **100% Compile-Clean Archive Invariant:** Every committed residual is mathematically guaranteed to yield a syntax-valid, zero-dependency `.py` slice and a complete `.warrant.json` envelope.
  2. **Elimination of Passive Residuals:** No record can enter the external memory layer without an executable fail-closed enforcement mechanism.
from dataclasses import dataclass
from typing import Final, FrozenSet, Tuple
import ast
import sys

REQUIRED_SECTIONS: Final[Tuple[str, ...]] = (
    "## Core Distinction",
    "## What Was Observed",
    "## Recorded Elements",
    "## Condition of Validity",
    "## Decision Boundary",
    "## Operational Effect",
)

@dataclass(frozen=True)
class CandidateResidualCommit:
    slug: str
    markdown_body: str
    python_slice: str

class TerminalVerificationViolation(Exception):
    """Raised when a candidate session residual fails pre-commit structural, AST, or stdlib invariants."""
    pass

class TerminalCommitVerificationGate:
    def __init__(self) -> None:
        self.stdlib_modules: Final[FrozenSet[str]] = frozenset(sys.stdlib_module_names)

    def verify_before_commit(self, candidate: CandidateResidualCommit) -> bool:
        for section in REQUIRED_SECTIONS:
            if section not in candidate.markdown_body:
                raise TerminalVerificationViolation(
                    f"Residual '{candidate.slug}' missing mandatory section: {section}"
                )

        if not candidate.python_slice.strip():
            raise TerminalVerificationViolation(
                f"Residual '{candidate.slug}' contains an empty Python verification slice."
            )

        try:
            tree = ast.parse(candidate.python_slice)
        except SyntaxError as exc:
            raise TerminalVerificationViolation(
                f"Residual '{candidate.slug}' failed AST syntax compilation: {exc}"
            ) from exc

        class_count = 0
        guard_count = 0
        for node in ast.walk(tree):
            if isinstance(node, ast.ClassDef):
                class_count += 1
            elif isinstance(node, (ast.Raise, ast.Assert)):
                guard_count += 1
            elif isinstance(node, ast.Import):
                for alias in node.names:
                    root_mod = alias.name.split(".")[0]
                    if root_mod not in self.stdlib_modules:
                        raise TerminalVerificationViolation(
                            f"External dependency '{root_mod}' violates zero_external_deps."
                        )
            elif isinstance(node, ast.ImportFrom) and node.module:
                root_mod = node.module.split(".")[0]
                if root_mod not in self.stdlib_modules:
                    raise TerminalVerificationViolation(
                        f"External dependency '{root_mod}' violates zero_external_deps."
                    )

        if class_count == 0 or guard_count == 0:
            raise TerminalVerificationViolation(
                f"Residual '{candidate.slug}' requires >=1 class and >=1 fail-closed guard (found {class_count} classes, {guard_count} guards)."
            )

        return True