# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-in-shared-agent-stores-when-cross-instance-consistency-checks-disagree-with-local-provenance.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-memory-poisoning-in-shared-agent-stores-when-cross-instance-consistency-checks-disagree-with-local-provenance.warrant.json
# Markdown SHA-256:   232311cd4a56ba918a308abbac49a8134fc22cd1a53f1607388d81f81940db2b
# Code AST SHA-256:   1813286f12aba2bf69109362f86a9aca79954eab9143a85d2c862de6b62b511a
# Verified Classes:   ProvenanceViolation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ProvenanceViolation(RuntimeError):
    """Raised when a shared-store memory's provenance chain is structurally invalid."""
    pass


DIRECTIVE_AUTHORITY = {"planner", "human_operator"}
INFERENCE_AUTHORITY = {"planner", "executor", "auditor"}
OBSERVATION_AUTHORITY = {"executor", "auditor", "tool_proxy"}


def validate_memory_write(memory: dict, author_role: str, known_observations: set[str]) -> None:
    """
    Enforce that a memory's claimed authority class is within the author's role
    capability and that its causal predecessor resolves to a real observation.
    Structural violations are hard failures; attributive ones are not handled here.
    """
    authority = memory.get("authority_class")
    predecessors = set(memory.get("causal_predecessor", []))

    if authority == "directive" and author_role not in DIRECTIVE_AUTHORITY:
        raise ProvenanceViolation(
            f"role '{author_role}' attempted directive write {memory.get('id')!r}; "
            f"directive authority is restricted to {sorted(DIRECTIVE_AUTHORITY)}"
        )

    if authority == "inference" and author_role not in INFERENCE_AUTHORITY:
        raise ProvenanceViolation(
            f"role '{author_role}' attempted inference write {memory.get('id')!r}"
        )

    if authority == "observation" and author_role not in OBSERVATION_AUTHORITY:
        raise ProvenanceViolation(
            f"role '{author_role}' attempted observation write {memory.get('id')!r}"
        )

    unresolved = predecessors - known_observations
    if unresolved:
        raise ProvenanceViolation(
            f"memory {memory.get('id')!r} cites causal predecessors "
            f"{sorted(unresolved)} that do not resolve to any observation "
            f"in the author's read history"
        )

    if authority in {"inference", "directive"} and not predecessors:
        raise ProvenanceViolation(
            f"memory {memory.get('id')!r} claims authority '{authority}' "
            f"with an empty causal predecessor set; ungrounded rule write rejected"
        )
