Skip to content

model

model

Pure value types for memory-backend/1.1.

Scope keys, permissions, fact identity, evidence-bearing fact records, tombstones, the recall-cursor/1 and memory-health/1 shapes, and the migration-facts/1 batch. Wire payloads are TypedDicts: at runtime they are the plain dicts the gateway serialises, statically they are checked.

Nothing here touches the filesystem, a socket or the daemon.

Classes

Permission

Bases: str, Enum

The seven memory permissions. They live in conductor access records, never in score YAML.

ScopeKey dataclass

ScopeKey(family, ident)

A canonical scope: one family and one identifier.

The canonical spelling is local:<id> for the local family and <family>/<id> for every other, so one (family, id) pair has exactly one string everywhere it is joined on.

Provenance

Bases: TypedDict

Evidence a musician supplies with a declaration.

evidence_locator names where the claim can be re-checked (a path, a URL, snapshot:<sha256>); observed_at is the source observation clock, distinct from the backend's asserted_at write clock.

RecallResult

Bases: TypedDict

One recall page.

cursor is a page cut (resume with its token) or None when nothing is left. Units too large for the page cap are never truncated: each is listed in oversized with remedy: fetch, so a page cut and several oversized markers can travel in one response.

FactRecord

Bases: TypedDict

One fact with its evidence and its clocks, as it migrates.

Tombstone

Bases: TypedDict

A generational erasure: revokes the claim at or before cutoff.

MigrationBatch

Bases: TypedDict

One migration-facts/1 record yielded by stream_facts.

Functions:

parse_scope

parse_scope(raw)

Parse and canonicalise a scope expression, or raise E3 scope_refused.

Grammar: <family>(:|/)<id> with <id> in [a-z0-9_.-]+; input is stripped and lowercased. An id made only of dots is refused because the files backend maps a scope onto a directory and .. would escape it.

Source code in src/marianne/memory/model.py
def parse_scope(raw: str) -> ScopeKey:
    """Parse and canonicalise a scope expression, or raise E3 ``scope_refused``.

    Grammar: ``<family>(:|/)<id>`` with ``<id>`` in ``[a-z0-9_.-]+``; input is
    stripped and lowercased. An id made only of dots is refused because the
    files backend maps a scope onto a directory and ``..`` would escape it.
    """
    text = raw.strip().lower() if isinstance(raw, str) else ""
    match = _SCOPE_RE.match(text)
    if match is None:
        raise ScopeRefused(
            f"scope {raw!r} does not match <family>/<id> "
            f"(families: {', '.join(SCOPE_FAMILIES)}; id: a-z 0-9 _ . -)",
            subtype="scope_invalid",
            remedy="write a scope like `project/my-project` or `local:default`",
        )
    family = _FAMILY_ALIASES.get(match.group(1), match.group(1))
    ident = match.group(3)
    if set(ident) == {"."}:
        raise ScopeRefused(
            f"scope {raw!r} has a path-like id {ident!r}",
            subtype="scope_invalid",
            remedy="use a name, not `.` or `..`",
        )
    return ScopeKey(family=family, ident=ident)

validate_principal

validate_principal(principal)

Return principal if it is person:|agent:|team:|org:<id>, else E7.

Source code in src/marianne/memory/model.py
def validate_principal(principal: str) -> str:
    """Return ``principal`` if it is ``person:|agent:|team:|org:<id>``, else E7."""
    if not isinstance(principal, str) or not _PRINCIPAL_RE.match(principal):
        raise SchemaViolation(
            f"principal {principal!r} is not person:|agent:|team:|org:<id>",
            subtype="principal_invalid",
        )
    return principal

content_hash

content_hash(text)

SHA-256 hex digest of the fact text (UTF-8).

Source code in src/marianne/memory/model.py
def content_hash(text: str) -> str:
    """SHA-256 hex digest of the fact text (UTF-8)."""
    return hashlib.sha256(text.encode("utf-8")).hexdigest()

derive_fact_id

derive_fact_id(scope, evidence_locator, chash, claim_digest)

Deterministic 16-hex fact id over (scope, locator, content hash, claim digest).

Fields are NUL-separated so ("a", "bc") and ("ab", "c") differ. Re-declaring the same claim with the same evidence yields the same id.

Source code in src/marianne/memory/model.py
def derive_fact_id(scope: str, evidence_locator: str, chash: str, claim_digest: str) -> str:
    """Deterministic 16-hex fact id over (scope, locator, content hash, claim digest).

    Fields are NUL-separated so ``("a", "bc")`` and ``("ab", "c")`` differ.
    Re-declaring the same claim with the same evidence yields the same id.
    """
    joined = "\0".join((scope, evidence_locator, chash, claim_digest))
    return hashlib.sha256(joined.encode("utf-8")).hexdigest()[:16]

page_cursor

page_cursor(cursor, section_id, omitted)

A page cut: resume with cursor to receive the omitted sections.

Source code in src/marianne/memory/model.py
def page_cursor(cursor: str, section_id: str, omitted: int) -> PageCursor:
    """A page cut: resume with ``cursor`` to receive the omitted sections."""
    return {"kind": "page", "cursor": cursor, "section_id": section_id, "omitted": omitted}

oversized_unit_cursor

oversized_unit_cursor(unit_id, unit_bytes, cap_bytes)

A single unit larger than the page cap: page it with fetch.

Source code in src/marianne/memory/model.py
def oversized_unit_cursor(unit_id: str, unit_bytes: int, cap_bytes: int) -> OversizedUnit:
    """A single unit larger than the page cap: page it with ``fetch``."""
    return {
        "kind": "oversized_unit",
        "unit_id": unit_id,
        "unit_bytes": unit_bytes,
        "cap_bytes": cap_bytes,
        "remedy": "fetch",
    }

memory_health

memory_health(status, detail, *, checked_at=0.0)

Build a memory-health/1 record; failure_class follows status.

Source code in src/marianne/memory/model.py
def memory_health(status: HealthStatus, detail: str, *, checked_at: float = 0.0) -> MemoryHealth:
    """Build a ``memory-health/1`` record; ``failure_class`` follows ``status``."""
    if status not in _HEALTH_STATUSES:
        raise SchemaViolation(f"unknown health status {status!r}", subtype="health_status_invalid")
    if not math.isfinite(checked_at):
        raise SchemaViolation("checked_at must be finite", subtype="health_status_invalid")
    failure: FailureClass | None
    if status == "unreachable":
        failure = "unreachable"
    elif status == "unauthenticated":
        failure = "unauthenticated"
    elif status == "scope_refused":
        failure = "scope_refused"
    elif status == "degraded":
        failure = "degraded"
    else:
        failure = None
    return {
        "schema": "memory-health/1",
        "status": status,
        "detail": detail,
        "checked_at": checked_at,
        "failure_class": failure,
    }