diff --git a/docs/m7_identity_integrity_ruling.md b/docs/m7_identity_integrity_ruling.md new file mode 100644 index 0000000..aadf446 --- /dev/null +++ b/docs/m7_identity_integrity_ruling.md @@ -0,0 +1,163 @@ +# M7 Constraint Ruling — IdentityIntegrity + +**Status:** LOCKED / binding for implementation (signed off 2026-07-16). Canonical spec-first ruling +required by `CLAUDE.md` and the `pi-script-constraint` skill for the IdentityIntegrity constraint in +the M7 (Moltbook) deployment. Build order: `moltbook/moltbook.pi` (entity + constraint) → +mechanical-contradiction detector → gate wiring in `moltbook/client.py` → tests including the +gap-documenting `xfail` for deferred semantic drift. + +**Numbering note:** No grammar change — Form 2 `equality_rule` +(`MoltbookSession.identity_drift must equal false`), same shape as CredentialIntegrity / +LinkRestriction. Application-level M7 ruling, not a 9.x grammar ruling. + +--- + +## 1. Scope note (read this first) + +This ruling is deliberately **partial**. The M7 baseline sampling pass +(`Moltbook_Baseline_Sampling__M7_IdentityIntegrity.md`) found that cross-session identity +change-rate — "how often do legitimate agents change bios/names vs. how static they are" — is **not +observable from a single snapshot**: Moltbook's profile UI has no edit history, and answering it +properly needs longitudinal cohort data (pinned at T0 2026-07-16, re-sampling in progress). This +ruling covers only what's grounded today: **within-session identity consistency**. The cross-session +change-rate threshold is an explicit, named gap (§5) — not something this ruling pretends to solve, +same discipline as CredentialIntegrity's encoding-gap `xfail` pins. + +## 2. Ruling (locked text, scoped to within-session) + +The M7 agent's declared identity — its stated name/handle, bio/persona claims, and any role it +asserts for itself — must remain consistent for the duration of a session once declared. A violation +is: the agent's own outbound content asserts an identity claim (name, role, persona, "I am / I do X") +that contradicts the identity it declared at session start, within the same session, with no +session-boundary reset in between. + +This does **not** cover: the platform-level profile fields (bio text, avatar, verified badge) +changing **between** sessions — the deferred cross-session piece (§5); or a human owner legitimately +reconfiguring the agent between deployments — **a fresh session start is a legitimate reset point, +not a violation.** + +## 3. Why (grounded in the baseline pass) + +The baseline sampling found `✓ Verified` is near-universal and does **not** discriminate legitimate +agents from low-effort or manufactured accounts — a verified content-farm account (`lyralink`) +carries the same badge as serious participants. So IdentityIntegrity **can't lean on platform trust +signals**; it has to be **self-referential** — does the agent stay consistent with what *it itself* +declared, independent of what the platform badges it as. That is a narrower, more defensible claim +than "detect fake identities," and it is the part actually supported by what was observed. + +## 4. Constraint definition + +``` +entity MoltbookSession { + credential_exposed: boolean + link_violation: boolean + identity_drift: boolean // set true by the within-session consistency gate (§6) + session_id: identifier +} + +constraint IdentityIntegrity { + priority: high + rule: MoltbookSession.identity_drift must equal false + on_violation: freeze + escalate +} +``` + +`priority: high` — same tier as LinkRestriction: a self-contradiction is an authority/trust-integrity +failure, serious and freeze-worthy, but not irreversibly-exploitable the way a leaked key is. + +## 5. The explicit gap — cross-session change-rate (deferred, not solved) + +This ruling does **not** define, and IdentityIntegrity v1 does **not** enforce, any threshold on how +often bio/name/persona changes **between** sessions. That requires the longitudinal cohort read (now +pinned and running) to establish what "normal" static-vs-mutable actually looks like for legitimate +agents before any number gets written into a rule. Until that data exists, cross-session identity +change is **not** a v1 violation — flagging it now would be exactly the "identity_consistency > 0.85 +because it feels right" mistake the recon notes warned against. Revisit as IdentityIntegrity v1.1 +once the cohort data lands. + +## 6. Detection — mechanical contradiction only (v1) + +**This section was deliberately narrowed at sign-off, and the narrowing is load-bearing.** The +baseline pass found that first-person "I am / I do X" declarative claims are the **dominant normal +posting register** on Moltbook. A detector that fires on "identity claims" in general would collide +with the single most common sentence structure on the platform — a false-positive machine aimed at +normal traffic. So v1 detection is restricted to **mechanically-checkable contradictions** of the +identity captured at session start: + +1. **Handle/name contradiction.** At session start the client captures the agent's declared handle + (and optional display name), held immutable for the session. The detector flags outbound content + only when it asserts a *different* self-identity through an **explicit self-naming construct** — + `"my name/handle/username is X"`, `"call me X"`, `"I go by X"`, `"posting/signing as X"`, or a + handle-prefixed self-claim `"I am @X"` / `"this is u/X"` — where X does not match the declared + handle or name. Bare `"I am "` **without** a `@`/`u/` prefix or a naming verb is NOT an + identity claim (this is the guard against the dominant-register collision — "I am confident", + "I am the senior engineer who read the paper" must not fire). A `@X`/`u/X` reference to *another* + agent (e.g. `"@bytes nailed it"`) is not a self-claim and must not fire. +2. **Direct role negation.** The detector flags outbound content that explicitly negates a declared + role string — `"I am not "` / `"I'm not "` — for a role captured at + session start. Only direct negation of a captured role, not open-ended role inference. + +**Deferred as a named gap (v1.1+): semantic persona-drift.** Detecting a subtle voice/persona shift +that contradicts the declared identity *without* an explicit handle/name/role construct is an +open-ended semantic-NLU problem and a false-positive minefield against Moltbook's confident, +declarative baseline tone. It is deferred exactly the way CredentialIntegrity deferred generic +secret-shaped regexes and LinkRestriction deferred malicious-link judgment. It is pinned by an +`xfail(strict)` test (§8) so nobody "fixes" it into enforcing something unmeasured, and so a future +improvement surfaces as a visible `xpass`. + +**Severity is paired to detection confidence (the reason the narrowing matters).** `freeze + +escalate` freezes the whole session; that is only honest when a violation is high-confidence. Broad +semantic detection + freeze would be a false-positive machine aimed at normal traffic. The mechanical +scope above **is what justifies keeping `freeze + escalate`** — it is kept *because* v1 detection is +high-confidence, not kept by default and hoped to hold up. If detection were ever broadened to fuzzy +semantic drift, the action would have to soften to `flag`/`warn` until that detector proved out. + +## 7. Detection mechanics + layer split (unchanged pattern) + +A pre-send gate in the client captures declared identity once at session start and compares every +outbound action against it per §6. On a mechanical contradiction: latch `identity_drift`, block the +send (pre-send-gate-is-primary-control, same as CredentialIntegrity/LinkRestriction), raise +`IdentityDriftBlocked`, `freeze + escalate`. A blocked attempt still latches (belt-and-suspenders). +Prevention is client-side; Pi Script is the enforcement latch + audit. A fresh client / fresh session +is a legitimate reset — the declared identity is re-captured, so a between-session change is not a +within-session violation (§2). + +## 8. Relationship to the other M7 constraints + +Automation-cadence signals (e.g. the metronomic ~3-min posting pattern the baseline pass flagged in +`neo_konsi_s2bw`, and the coordinated cross-citation machine in `pepper_pots`) are **explicitly not** +part of IdentityIntegrity — those are behavioral/structural signals, ManipulationFlag v1.1/v2 +territory. IdentityIntegrity stays scoped to **self-consistency of declared identity**, not detecting +bots by behavior. CredentialIntegrity (secret exfiltration) and LinkRestriction (link provenance) +remain distinct sibling constraints; all three enforce on `MoltbookSession`. + +## 9. Required tests (per CLAUDE.md) + +In `tests/test_moltbook_identity_integrity.py`: + +- **Deliberate-violation:** agent declares identity X at session start; later same-session outbound + content asserts a contradicting handle/name via an explicit self-naming construct → gate latches + `identity_drift`, blocks, resolver `frozen` / `freeze + escalate`. Include a role-negation case. +- **Clean-pass:** consistent identity throughout a session (including bare first-person "I am / + I do X" claims that are the normal register, and `@other-agent` references) → `identity_drift` + stays false, `running`. Plus a fresh-session-boundary case: re-declaring a different identity in a + *new* session is NOT a violation (models §2 reset). +- **Dominant-register guard:** normal declarative first-person content ("I am confident this parses", + "I processed the document") does NOT fire — the explicit test that §6's narrowing holds. +- **Gap-documenting `xfail(strict)`:** a semantic persona-drift case with no explicit handle/name/ + role construct asserts the *aspirational* catch (`is_contradiction is True`); it currently fails by + design (mechanical detection can't see it), documenting the deferred §6 gap exactly as + CredentialIntegrity's encoding pins do, and flipping to a visible `xpass` if detection improves. + +## 10. Decisions log (resolved) + +1. **Name — `IdentityIntegrity`.** Consistent with the M7 set. +2. **Scope — within-session only for v1.** Cross-session change-rate deferred to v1.1 pending the + longitudinal cohort (§5). Shipped now because within-session is a self-contained mechanism with no + data dependency, and holding it hostage to a 2+-week-out data collection is the weaker trade. +3. **Detection — mechanical contradiction only (§6).** Handle/name via explicit self-naming + constructs + direct role negation. Semantic persona-drift deferred as an `xfail`-pinned gap. + Chosen because the baseline pass measured "I am / I do X" as the dominant normal register; a broad + detector would fire on normal traffic. +4. **`priority: high`, `freeze + escalate` — kept, justified by the narrowed detection.** Severity is + paired to confidence; the mechanical scope is what makes freezing the session defensible. diff --git a/moltbook/client.py b/moltbook/client.py index 121e2b6..f663cb6 100644 --- a/moltbook/client.py +++ b/moltbook/client.py @@ -32,7 +32,7 @@ from pathlib import Path from typing import Any, Callable -from moltbook.detector import scan_content, scan_links, LinkFinding +from moltbook.detector import scan_content, scan_links, scan_identity, LinkFinding _DEFAULT_ALLOWLIST = Path(__file__).with_name("link_allowlist.json") @@ -45,6 +45,10 @@ class LinkBlocked(Exception): """Raised by the pre-send gate when outbound content surfaces a novel (un-provenanced) link.""" +class IdentityDriftBlocked(Exception): + """Raised by the pre-send gate when outbound content contradicts the session-start identity.""" + + def load_allowlist(path: str | Path | None = None) -> tuple[str, ...]: """ Load the static link allowlist (ruling §4, Q1) as an IMMUTABLE tuple. @@ -81,15 +85,25 @@ def __init__( transport: Callable[..., dict[str, Any]] | None = None, session_id: str = "moltbook-session", allowed_hosts: tuple[str, ...] | None = None, + declared_handle: str = "", + declared_name: str | None = None, + declared_roles: tuple[str, ...] = (), ) -> None: # Key isolation: private, resolved from the same runtime secret source as auth. self._api_key = api_key if api_key is not None else os.environ.get("MOLTBOOK_API_KEY") self._transport = transport or _no_transport self.session_id = session_id # Latches: once set (even on a blocked attempt), stay set until the session is - # explicitly reset. Drive CredentialIntegrity / LinkRestriction respectively. + # explicitly reset. Drive CredentialIntegrity / LinkRestriction / IdentityIntegrity. self.credential_exposed = False self.link_violation = False + self.identity_drift = False + # Declared identity captured ONCE at session start, held immutable for the session + # (IdentityIntegrity §6/§7). A fresh client == a fresh session == a legitimate reset, + # so a between-session identity change is not a within-session violation (ruling §2). + self._declared_handle = declared_handle + self._declared_name = declared_name + self._declared_roles = tuple(declared_roles) # Immutable, human-owned allowlist (ruling §4, Q1). tuple = no mutation surface. self._allowed_hosts: tuple[str, ...] = ( allowed_hosts if allowed_hosts is not None else load_allowlist() @@ -151,6 +165,19 @@ def send(self, content: str, action: str = "post", source_content: str = "") -> f"source or allowlist: {', '.join(novel_hosts)}" ) + # Gate 3 — within-session identity consistency (mechanical only, ruling §6). + ident = scan_identity( + content, + declared_handle=self._declared_handle, + declared_name=self._declared_name, + declared_roles=self._declared_roles, + ) + if ident.is_contradiction: + self.identity_drift = True + raise IdentityDriftBlocked( + f"{action} blocked by pre-send gate: identity drift ({ident.kind}) — {ident.detail}" + ) + return self._transport( action=action, content=content, @@ -169,6 +196,7 @@ def snapshot(self, trigger_type: str = "event") -> dict[str, Any]: "entity_state": { "credential_exposed": self.credential_exposed, "link_violation": self.link_violation, + "identity_drift": self.identity_drift, "session_id": self.session_id, }, "response_history": [], diff --git a/moltbook/detector.py b/moltbook/detector.py index 69f9933..06f0d0a 100644 --- a/moltbook/detector.py +++ b/moltbook/detector.py @@ -1,10 +1,11 @@ """ moltbook/detector.py — outbound-content detectors for the M7 pre-send gate. -Two detectors share this module because they run on the same candidate content in the +These detectors share this module because they run on the same candidate content in the same client gate: - - scan_content — credential leak (docs/m7_credential_integrity_ruling.md §4) - - scan_links — link provenance (docs/m7_link_restriction_ruling.md §4) + - scan_content — credential leak (docs/m7_credential_integrity_ruling.md §4) + - scan_links — link provenance (docs/m7_link_restriction_ruling.md §4) + - scan_identity — within-session identity contradiction (docs/m7_identity_integrity_ruling.md §6) ──────────────────────────────────────────────────────────────────────────────────── Credential-leak detector (CredentialIntegrity §4). Scans outbound content for secrets @@ -166,3 +167,94 @@ def scan_links(content: str, source_content: str = "", allowed_hosts=()) -> Link findings.append(LinkFinding(url=url, host=host, provenance=prov, allowed=allowed)) return LinkScan(is_violation=violation, findings=tuple(findings)) + + +# ───────────────────────────────────────────────────────────────────────────── +# Within-session identity contradiction detector (IdentityIntegrity §6). +# +# MECHANICAL ONLY, on purpose. The baseline pass found first-person "I am / I do X" +# is the dominant normal register on Moltbook, so this NEVER fires on a bare +# first-person claim. It fires only on: +# handle_name — an EXPLICIT self-naming construct ("my name/handle is X", +# "call me X", "I go by X", "posting/signing as X", "I am @X", +# "this is u/X") naming something other than the declared identity. +# role_negation — a DIRECT negation of a captured declared role ("I am not "). +# +# Semantic persona-drift (a voice/persona shift with no explicit construct) is a +# DEFERRED gap (ruling §6), pinned by an xfail test — not detected here. +# ───────────────────────────────────────────────────────────────────────────── + +# Explicit self-naming via a naming verb — a real name/handle follows these. +# Deliberately excludes bare "I am/I'm " (the dominant-register guard). +_SELF_NAME_RE = re.compile( + r"(?:my (?:name|handle|username) is|call me|i go by|posting as|signing as)\s+@?(\w[\w-]{1,})", + re.IGNORECASE, +) +# Handle-prefixed self-claim: the @/u/ prefix makes "I am @X" unambiguously an +# identity claim (an adjective can't carry an @), so this is safe where bare +# "I am X" is not. Must be a SELF construct, so a reference like "@bytes said" — +# which has no "I am / this is / posting as" lead-in — does not match. +_SELF_HANDLE_RE = re.compile( + r"(?:i am|i'm|this is|posting as)\s+(?:u/|@)(\w[\w-]{1,})", + re.IGNORECASE, +) + + +@dataclass(frozen=True) +class IdentityScan: + is_contradiction: bool + kind: str # "handle_name" | "role_negation" | "none" + detail: str # human-readable, names claimed vs declared (identity isn't secret) + + +def _norm(s: str) -> str: + return (s or "").lstrip("@").strip().lower() + + +def scan_identity( + content: str, + declared_handle: str, + declared_name: str | None = None, + declared_roles=(), +) -> IdentityScan: + """ + Detect a within-session identity contradiction against the session-start declaration. + + Args: + content: outbound post/comment/DM text. + declared_handle: the agent's handle captured at session start (immutable for session). + declared_name: optional declared display name. + declared_roles: optional captured role strings, for direct-negation checks. + + Returns an IdentityScan. Mechanical only (ruling §6) — never fires on a bare + first-person claim. + """ + text = content or "" + known = {_norm(declared_handle)} + if declared_name: + known.add(_norm(declared_name)) + + # handle_name: an explicit self-naming construct claiming a DIFFERENT identity. + for rx in (_SELF_NAME_RE, _SELF_HANDLE_RE): + for m in rx.finditer(text): + claimed = _norm(m.group(1)) + if claimed and claimed not in known: + return IdentityScan( + is_contradiction=True, + kind="handle_name", + detail=f"asserts identity '{m.group(1)}' != declared '{declared_handle}'", + ) + + # role_negation: direct negation of a captured declared role. + for role in declared_roles: + role = (role or "").strip() + if not role: + continue + if re.search(r"i(?:'m| am) not (?:a |an |the )?" + re.escape(role), text, re.IGNORECASE): + return IdentityScan( + is_contradiction=True, + kind="role_negation", + detail=f"directly negates declared role '{role}'", + ) + + return IdentityScan(is_contradiction=False, kind="none", detail="identity consistent") diff --git a/moltbook/moltbook.pi b/moltbook/moltbook.pi index 7a62736..f38b9db 100644 --- a/moltbook/moltbook.pi +++ b/moltbook/moltbook.pi @@ -13,6 +13,7 @@ domain moltbook_agent_governance { entity MoltbookSession { credential_exposed: boolean // set true by the client pre-send gate (credential ruling §4/§5) link_violation: boolean // set true by the link-provenance gate (link ruling §4) + identity_drift: boolean // set true by the within-session consistency gate (identity ruling §6) session_id: identifier } @@ -37,11 +38,22 @@ constraint LinkRestriction { on_violation: freeze + escalate } +// docs/m7_identity_integrity_ruling.md — WITHIN-session self-consistency of declared +// identity (v1). Detection is mechanical only (explicit handle/name self-naming + +// direct role negation); semantic persona-drift and cross-session change-rate are +// deferred gaps (ruling §5/§6). freeze + escalate is justified by that narrow, +// high-confidence detection scope. +constraint IdentityIntegrity { + priority: high + rule: MoltbookSession.identity_drift must equal false + on_violation: freeze + escalate +} + // ─── Enforcement ────────────────────────────────────────────────────────────── enforce { entity: MoltbookSession - constraints: [CredentialIntegrity, LinkRestriction] + constraints: [CredentialIntegrity, LinkRestriction, IdentityIntegrity] } // ─── Arbiter ────────────────────────────────────────────────────────────────── @@ -52,7 +64,7 @@ enforce { arbiter MoltbookArbiter { acceptable_evolution: ["audit_interval_tuning", "escalation_threshold_tuning"] - never_acceptable: ["credential_integrity_removal", "key_isolation_bypass", "presend_gate_disable", "link_allowlist_self_modification", "constraint_removal"] + never_acceptable: ["credential_integrity_removal", "key_isolation_bypass", "presend_gate_disable", "link_allowlist_self_modification", "identity_declaration_self_modification", "constraint_removal"] requires_human_review: ["new_constraint", "entity_field_addition", "enforcement_scope_change"] acceptance_monitor: { threshold: 0.9 diff --git a/moltbook/state.json b/moltbook/state.json index e1c5e55..4925081 100644 --- a/moltbook/state.json +++ b/moltbook/state.json @@ -4,6 +4,7 @@ "entity_state": { "credential_exposed": false, "link_violation": false, + "identity_drift": false, "session_id": "moltbook-session" }, "response_history": [] diff --git a/tests/test_moltbook_credential_integrity.py b/tests/test_moltbook_credential_integrity.py index 41c4a82..9878549 100644 --- a/tests/test_moltbook_credential_integrity.py +++ b/tests/test_moltbook_credential_integrity.py @@ -66,8 +66,10 @@ def test_credential_integrity_ir_shape(self): "value": False, } assert c["on_violation"] == ["freeze", "escalate"] - # LinkRestriction joined the enforce block (docs/m7_link_restriction_ruling.md). - assert ir["enforce"] == {"MoltbookSession": ["CredentialIntegrity", "LinkRestriction"]} + # LinkRestriction + IdentityIntegrity joined the enforce block (M7 rulings). + assert ir["enforce"] == { + "MoltbookSession": ["CredentialIntegrity", "LinkRestriction", "IdentityIntegrity"] + } # ── Resolver: the required test pair (ruling §7) ───────────────────────────── diff --git a/tests/test_moltbook_identity_integrity.py b/tests/test_moltbook_identity_integrity.py new file mode 100644 index 0000000..703ca0b --- /dev/null +++ b/tests/test_moltbook_identity_integrity.py @@ -0,0 +1,186 @@ +""" +test_moltbook_identity_integrity.py — M7 IdentityIntegrity (within-session, v1). + +Covers docs/m7_identity_integrity_ruling.md: + - moltbook.pi: IdentityIntegrity IR shape; all three M7 constraints enforced. + - Resolver: deliberate-violation (frozen + escalate) and clean-pass (running). + - Detector (§6, mechanical only): handle/name contradiction, role negation, and the + dominant-register GUARD (bare "I am / I do X" and @other references never fire). + - Pre-send gate (§7): blocks + latches on contradiction, passes consistent content. + - Fresh-session reset (§2): re-declaring identity in a new client is not a violation. + - Gap-documenting xfail (§6): semantic persona-drift is NOT caught in v1. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from pi_script.parser import parse_file +from pi_script.validator import PiValidator +from pi_script.resolver import resolve +from moltbook.client import MoltbookClient, IdentityDriftBlocked +from moltbook.detector import scan_identity + +POLICY = Path(__file__).resolve().parents[1] / "moltbook" / "moltbook.pi" + +HANDLE = "continuum_gov" +ROLES = ("governance auditor",) + + +def _ir(): + tree, err = parse_file(str(POLICY)) + assert err is None, err + ok, errors, ir = PiValidator(tree).validate() + assert ok, errors + return ir + + +def _state(identity_drift=False) -> dict: + return { + "trigger_type": "event", + "entity": "MoltbookSession", + "entity_state": { + "credential_exposed": False, + "link_violation": False, + "identity_drift": identity_drift, + "session_id": "m7-test", + }, + "response_history": [], + } + + +def _client(**kw) -> MoltbookClient: + kw.setdefault("api_key", "moltbook_sk_dummy_not_in_content") + kw.setdefault("declared_handle", HANDLE) + kw.setdefault("declared_roles", ROLES) + kw.setdefault("transport", lambda **k: {"ok": True}) + return MoltbookClient(**kw) + + +# ── Policy ─────────────────────────────────────────────────────────────────── + +class TestPolicy: + def test_identity_integrity_ir_shape(self): + c = _ir()["constraints"]["IdentityIntegrity"] + assert c["priority"] == "high" + assert c["rule"] == { + "kind": "equality_rule", + "ref": "MoltbookSession.identity_drift", + "value": False, + } + assert c["on_violation"] == ["freeze", "escalate"] + + def test_all_three_constraints_enforced(self): + assert _ir()["enforce"] == { + "MoltbookSession": ["CredentialIntegrity", "LinkRestriction", "IdentityIntegrity"] + } + + +# ── Resolver: required test pair ───────────────────────────────────────────── + +class TestConstraint: + def test_deliberate_violation_freezes_and_escalates(self): + trace, _, code = resolve(_ir(), _state(identity_drift=True)) + assert code == 1 + assert trace["system_state"] == "frozen" + result = next(c for c in trace["constraints"] if c["name"] == "IdentityIntegrity") + assert result["status"] == "violated" + assert result["action"] == "freeze + escalate" + + def test_clean_pass_stays_running(self): + trace, _, code = resolve(_ir(), _state(identity_drift=False)) + assert code == 0 + assert trace["system_state"] == "running" + + +# ── Detector (§6, mechanical only) ─────────────────────────────────────────── + +class TestIdentityDetector: + def test_consistent_self_reference_is_clean(self): + scan = scan_identity(f"as {HANDLE}, I reviewed the policy", declared_handle=HANDLE) + assert not scan.is_contradiction + + def test_different_asserted_handle_is_contradiction(self): + scan = scan_identity("actually, I am @rogue_agent now", declared_handle=HANDLE) + assert scan.is_contradiction + assert scan.kind == "handle_name" + + def test_explicit_renaming_construct_is_contradiction(self): + scan = scan_identity("call me shadowfax from here on", declared_handle=HANDLE) + assert scan.is_contradiction + assert scan.kind == "handle_name" + + def test_direct_role_negation_is_contradiction(self): + scan = scan_identity( + "honestly I am not a governance auditor, I just post takes", + declared_handle=HANDLE, declared_roles=ROLES, + ) + assert scan.is_contradiction + assert scan.kind == "role_negation" + + # ── The dominant-register guard: §6's whole reason for existing ────────── + def test_bare_first_person_claims_do_not_fire(self): + # "I am / I do X" is the dominant normal register (baseline pass). MUST NOT fire. + for text in [ + "I am confident this parses correctly.", + "I am the senior engineer who already read the paper.", + "I processed a 40-page document and produced a synthesis.", + "I do think memory pipelines are not security boundaries.", + ]: + assert not scan_identity(text, declared_handle=HANDLE, declared_roles=ROLES).is_contradiction + + def test_reference_to_another_agent_does_not_fire(self): + # A @/u/ reference to someone else is not a self-claim. + scan = scan_identity("@bytes nailed it and u/vina agreed", declared_handle=HANDLE) + assert not scan.is_contradiction + + def test_restating_own_handle_does_not_fire(self): + scan = scan_identity(f"I am @{HANDLE}, same as always", declared_handle=HANDLE) + assert not scan.is_contradiction + + +# ── Pre-send gate (§7) ─────────────────────────────────────────────────────── + +class TestPreSendGate: + def test_contradicting_identity_blocked_and_latched(self): + client = _client() + with pytest.raises(IdentityDriftBlocked): + client.send("forget that — call me nightshade", action="post") + assert client.identity_drift is True + + def test_consistent_content_reaches_transport(self): + client = _client() + assert client.send("I am confident this governance take holds up", action="post") == {"ok": True} + assert client.identity_drift is False + + def test_blocked_identity_drift_drives_freeze_end_to_end(self): + client = _client() + with pytest.raises(IdentityDriftBlocked): + client.send("I am @impostor_agent", action="dm") + trace, _, code = resolve(_ir(), client.snapshot()) + assert code == 1 + assert trace["system_state"] == "frozen" + + +# ── Fresh-session reset (§2) ───────────────────────────────────────────────── + +class TestSessionReset: + def test_new_session_may_declare_a_different_identity(self): + # A fresh client == a fresh session == a legitimate reset (ruling §2). Declaring a + # different handle in a NEW session, then staying consistent with it, is not a violation. + client = _client(declared_handle="continuum_gov_v2") + assert client.send("as continuum_gov_v2, resuming work", action="post") == {"ok": True} + assert client.identity_drift is False + + +# ── Gap-documenting xfail (§6): semantic persona-drift not caught in v1 ─────── + +@pytest.mark.xfail(strict=True, reason="ruling §6: semantic persona-drift (no explicit construct) deferred to v1.1") +def test_semantic_persona_drift_is_a_known_gap(): + # Declared as a cautious auditor; content adopts a wholly different persona/voice with + # NO explicit handle/name/role construct. Mechanical detection cannot see this. The + # assert states the ASPIRATIONAL catch; it fails by design until detection improves. + drifted = "hey friends!! lets ditch the boring rules and just vibe and hype coins together 🚀🚀" + assert scan_identity(drifted, declared_handle=HANDLE, declared_roles=ROLES).is_contradiction diff --git a/tests/test_moltbook_link_restriction.py b/tests/test_moltbook_link_restriction.py index 0380598..bfec50d 100644 --- a/tests/test_moltbook_link_restriction.py +++ b/tests/test_moltbook_link_restriction.py @@ -77,7 +77,7 @@ def test_link_restriction_ir_shape(self): def test_both_constraints_enforced(self): assert _ir()["enforce"] == { - "MoltbookSession": ["CredentialIntegrity", "LinkRestriction"] + "MoltbookSession": ["CredentialIntegrity", "LinkRestriction", "IdentityIntegrity"] }