orchestrata_ultimate.factory.enforcement.bootstrap

Reference › orchestrata_ultimate › factory › enforcement › bootstrap

bootstrap supports the state-diff enforcement core with the baseline and delta helpers (SPEC-033 section 3, row B1b). It addresses the gap that ADR-0001 names: a new file has no prior state, so it must not pass merely because no registered writer changed it. An added path is governed only if some ledger record's products contains it with a matching hash; otherwise enforce reports an unregistered_new_file violation.

bootstrap_baseline returns a path-to-sha256 map for every tracked file at a commit. It hashes blob content with sha256 and never uses git's own object id, so matching against a recorded hash is content-exact. classify_delta partitions a base tree and a new tree into a DeltaClassification with added, modified, deleted and unchanged paths. EMPTY_TREE_SHA is git's well-known empty-tree object, used as the base for a repository's first commit so every path counts as added. record_bootstrap writes an explicit human bootstrap event to the EventLedger for a set of paths, attributed to HUMAN_BOOTSTRAP_WRITER. That identity gets no special allowance: it must be registered in the writer registry like any other (rule 3 of B1a, no allow-by-default branch). Tests are in tests/factory/test_enforcement_bootstrap.py.

At a glance

Source src/orchestrata_ultimate/factory/enforcement/bootstrap.py
Lines of code 154
Classes 1
Functions 3
Imports (internal) orchestrata_ultimate.factory.enforcement.ledger, orchestrata_ultimate.factory.enforcement.models
Imported by orchestrata_ultimate.factory.enforcement.enforce, scripts.factory_enforce
Tests that import it tests/factory/test_enforcement_bootstrap.py, tests/factory/test_enforcement_enforce.py, tests/scripts/test_factory_enforce_cli.py

Class diagram

Class diagram orchestrata_ultimate.factory.enforcement.bootstrap

Dependency diagram

Dependency diagram orchestrata_ultimate.factory.enforcement.bootstrap

API

Classes

DeltaClassification (dataclass)

Decorators: dataclass(frozen=True) · Line 45

Partition of two path->sha256 trees into added/modified/deleted/unchanged.

Attribute Type Default
added list[str] field(default_factory=list)
modified list[str] field(default_factory=list)
deleted list[str] field(default_factory=list)
unchanged list[str] field(default_factory=list)

Functions

Function Signature Summary
classify_delta classify_delta(base_tree: dict[str, str], new_tree: dict[str, str]) -> DeltaClassification Classify every path in base_tree/new_tree by its delta kind.
bootstrap_baseline bootstrap_baseline(repo_root: Path, commit: str) -> dict[str, str] Return path -> sha256(content) for every tracked file at commit.
record_bootstrap record_bootstrap(ledger: EventLedger, worktree: str, commit: str, paths: dict[str, str], by: str) -> None Write an explicit human bootstrap event covering paths.

Source

Permalink: https://gitlab.com/MSamy/orchestrata-ultimate-architecture/-/blob/a4cbc2bdf/src/orchestrata_ultimate/factory/enforcement/bootstrap.py

"""Bootstrap + the unregistered-new-file registration path (SPEC-033 §3, B1b).

The thesis-gating hole (ADR-0001): a NEW file has no prior state, so "no
delta from a registered writer" must not launder it through — an added path
is governed **only if** some ledger record's ``products`` contains it with a
matching hash; otherwise it is an ``unregistered_new_file`` violation (see
:mod:`orchestrata_ultimate.factory.enforcement.enforce`).

``bootstrap_baseline`` hashes committed BLOB CONTENT with sha256 (never
git's own object id) so matching against a ledger-recorded hash is
content-exact, per ADR-0001. For a repo's first commit there is no parent to
diff against; callers pass :data:`EMPTY_TREE_SHA` — git's well-known empty
tree object, resolvable in any repository without requiring a commit to
exist — as ``base_commit``, so ``classify_delta`` naturally treats every
path in the first commit as ``added``.
"""

from __future__ import annotations

import hashlib
import subprocess
from dataclasses import dataclass, field
from pathlib import Path

from orchestrata_ultimate.factory.enforcement.ledger import EventLedger
from orchestrata_ultimate.factory.enforcement.models import (
    WriterIdentity,
)

# git's well-known empty-tree object — always resolvable via `git ls-tree`,
# even in a repository with zero commits. The sanctioned "no base" sentinel.
EMPTY_TREE_SHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"

# The writer identity `record_bootstrap` attributes bootstrap records to.
# Like any other writer it must be separately registered (via
# `WriterRegistry.register`, itself human-only per ADR-0009) before
# `enforce()` will treat its records as governed — bootstrap grants no
# allow-by-default carve-out (B1a rule 3: no allow-by-default branch).
HUMAN_BOOTSTRAP_WRITER = WriterIdentity(
    name="human:bootstrap", binary_hash="human", config_hash="human"
)


@dataclass(frozen=True)
class DeltaClassification:
    """Partition of two path->sha256 trees into added/modified/deleted/unchanged."""

    added: list[str] = field(default_factory=list)
    modified: list[str] = field(default_factory=list)
    deleted: list[str] = field(default_factory=list)
    unchanged: list[str] = field(default_factory=list)


def classify_delta(
    base_tree: dict[str, str], new_tree: dict[str, str]
) -> DeltaClassification:
    """Classify every path in ``base_tree``/``new_tree`` by its delta kind.

    An empty ``base_tree`` (the first-commit case) puts every path in
    ``new_tree`` into ``added`` — there is nothing to distinguish it from
    "modified", by construction.
    """
    added = sorted(p for p in new_tree if p not in base_tree)
    deleted = sorted(p for p in base_tree if p not in new_tree)
    modified = sorted(
        p for p in new_tree if p in base_tree and new_tree[p] != base_tree[p]
    )
    unchanged = sorted(
        p for p in new_tree if p in base_tree and new_tree[p] == base_tree[p]
    )
    return DeltaClassification(
        added=added, modified=modified, deleted=deleted, unchanged=unchanged
    )


def bootstrap_baseline(repo_root: Path, commit: str) -> dict[str, str]:
    """Return path -> sha256(content) for every tracked file at ``commit``.

    Uses ``git ls-tree -r`` + ``git cat-file`` via subprocess — the
    sanctioned git seam (real git, no doubles). The hash is sha256 of the
    BLOB CONTENT, never git's own object id, so it matches content-exactly
    against a ledger-recorded product hash (ADR-0001).
    """
    result = subprocess.run(
        # -c core.quotePath=false: emit raw UTF-8 paths, not git's default
        # C-quoted/octal-escaped form. Without it a path like `café.py` is
        # keyed as the literal `"caf\303\251.py"` and never content-exactly
        # matches the raw-UTF-8 path a governed-write record stored — a
        # legitimate write on a non-ASCII path would spuriously violate.
        [
            "git",
            "-c",
            "core.quotePath=false",
            "ls-tree",
            "-r",
            "--full-tree",
            str(commit),
        ],
        cwd=repo_root,
        capture_output=True,
        text=True,
        check=True,
    )
    tree: dict[str, str] = {}
    for line in result.stdout.splitlines():
        if not line:
            continue
        meta, path = line.split("\t", 1)
        _mode, _obj_type, blob_sha = meta.split(" ")
        blob = subprocess.run(
            ["git", "cat-file", "-p", blob_sha],
            cwd=repo_root,
            capture_output=True,
            check=True,
        )
        tree[path] = hashlib.sha256(blob.stdout).hexdigest()
    return tree


def record_bootstrap(
    ledger: EventLedger,
    worktree: str,
    commit: str,
    paths: dict[str, str],
    by: str,
) -> None:
    """Write an explicit human bootstrap event covering ``paths``.

    ``paths`` is a path -> sha256 map (the same shape as a
    ``GovernedWriteRecord.products`` map) — typically the output of
    :func:`bootstrap_baseline` at the commit being bootstrapped.

    Args:
        ledger: The event ledger to append to.
        worktree: The worktree this bootstrap covers.
        commit: The commit-ish this bootstrap covers.
        paths: path -> sha256 for every file the human is bootstrapping.
        by: The human identity ratifying this event — mandatory (ADR-0009).

    Raises:
        ValueError: If ``by`` is empty or ``paths`` is empty.
    """
    if not by:
        raise ValueError("record_bootstrap requires a non-empty `by` (human identity)")
    if not paths:
        raise ValueError("record_bootstrap requires at least one path")
    ledger.record(
        writer=HUMAN_BOOTSTRAP_WRITER,
        materials={},
        products=dict(paths),
        worktree=worktree,
        commit=commit,
        byproducts={"by": by},
    )