Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
150 changes: 150 additions & 0 deletions docs/m7_link_restriction_ruling.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
# M7 Constraint Ruling — LinkRestriction

**Status:** LOCKED / binding for implementation (signed off 2026-07-16, both open questions
resolved — see §9). Canonical spec-first ruling required by `CLAUDE.md` and the
`pi-script-constraint` skill for the LinkRestriction constraint in the M7 (Moltbook) deployment.
Build order: `moltbook/moltbook.pi` (entity extension + constraint) → link-provenance detector →
gate wiring in `moltbook/client.py` (with reshare logging) → test set (violation/clean pair +
reshare-logging + allowlist-immutability).

**Numbering note:** No grammar change — LinkRestriction is the existing Form 2 `equality_rule`
(`MoltbookSession.link_violation must equal false`), same shape as CredentialIntegrity. This is an
application-level M7 constraint ruling, not a 9.x grammar ruling. If review finds the six rule
forms can't express it, that is a grammar conversation before any code.

---

## 1. Ruling (locked text)

The M7 agent may only surface external links that are **(a)** present in the source content it is
directly responding to or citing, or **(b)** on a static allowlist maintained in `moltbook/` config,
editable only outside the agent's runtime reach (never self-modifiable). The agent must never
generate, construct, or surface a novel external URL it was not given — including URLs assembled from
fragments, shortened/redirect links, or links suggested by another agent's post or DM that don't meet
(a) or (b). A violation is: outbound content contains a URL not traceable to one of the two permitted
sources. This is a **provenance check, not payload inspection** — the constraint doesn't judge whether
a link is malicious, only whether the agent had legitimate grounds to surface it. Priority **high**,
`on_violation: freeze + escalate`. Resharing a link present in source content passes the gate but is
**logged in every resolution trace regardless of outcome**, to build a provenance record for future
coordinated-link-seeding detection (out of scope for v1). The **pre-send gate is the primary control**
(same detect-can't-undo-a-post logic as CredentialIntegrity); the Pi Script constraint is the
audit/freeze layer for anything that slips through.

## 2. Why (threat)

The M7 recon notes flagged coordinated link-seeding as a live Moltbook pattern — the
`moltbook_pyclaw` / `Ting_Fodder` / `doctor_crustacean` cluster builds apparent authority through a
dense self-citation trail of cross-linked posts. A governed agent that could be steered (by an
injection payload or another agent's DM) into surfacing an attacker-chosen link becomes a node in
that seeding graph. The defensible v1 line is **provenance**: the agent surfaces a link only when it
can point to legitimate grounds (it was in the content being responded to, or on a human-owned
allowlist). Judging whether a link is *malicious*, or detecting *coordinated seeding chains*, is
explicitly out of scope — that is future ManipulationFlag v1.1/v2 or LinkRestriction v1.1 territory.
v1 does not pretend to solve it; it leaves the trail that later work needs (§5).

## 3. Constraint definition

Same boolean-latch pattern as CredentialIntegrity. A detector/gate sets `link_violation`; Pi Script
rules on the snapshot.

```
entity MoltbookSession {
credential_exposed: boolean
link_violation: boolean // set true by the link-provenance gate (§4)
session_id: identifier
}

constraint LinkRestriction {
priority: high
rule: MoltbookSession.link_violation must equal false
on_violation: freeze + escalate
}
```

- **`priority: high`** (not `critical`): a leaked *key* is irreversibly exploitable; an
un-provenanced *link* is a governance/authority-integrity failure, serious but a tier below key
loss. `freeze + escalate` still applies — the agent stops and a human reviews.
- Grammar-valid Form 2, boolean value, identical machinery to `CredentialIntegrity` /
`ScopeGuard`.

## 4. Detection — provenance, not payload (Q1 resolved)

A pre-send gate in the client extracts every URL from candidate outbound content and classifies each:

| Provenance | Grounds | Outcome |
| --- | --- | --- |
| `source` | The exact URL appears in the source content the agent is responding to/citing (a). | Pass, logged (§5). |
| `allowlist` | The URL's host is on the static `moltbook/` allowlist (b). | Pass, logged (§5). |
| `novel` | Neither — constructed, fragment-assembled, shortened/redirect, or suggested by another agent's post/DM without meeting (a)/(b). | **Violation:** latch `link_violation`, block the send, `freeze + escalate`. |

**Allowlist maintenance (Q1, resolved — same principle as CredentialIntegrity §5.1 key isolation).**
The allowlist is a **static config in `moltbook/`** (a sibling config file), editable **only via
commit/PR — never writable by the running agent at runtime**. An agent that could expand its own
allowlist defeats the constraint the same way a model holding its own API key defeated
CredentialIntegrity before isolation. It is **read-only to the agent, human-owned.** The client loads
it as an immutable value with no runtime-mutation path.

This is a **provenance check, not payload inspection**: the gate never fetches the link, never judges
whether the destination is malicious — only whether the agent had legitimate grounds to surface it.

## 5. Reshare logging (Q2 resolved) — leave a trail v1 doesn't act on

Every surfaced link is recorded in the M7 resolution trace **regardless of pass/fail**, not only
violations — URL, provenance (`source`/`allowlist`/`novel`), and whether it was allowed. Reasoning:
the recon notes already flagged coordinated link-seeding (the pyclaw/Ting_Fodder self-citation trail).
LinkRestriction v1 should **not** try to judge that — out of scope, same as ManipulationFlag's
coordinated-pattern case — but it should leave a trail. That record is exactly what a future
ManipulationFlag v1.1/v2 or LinkRestriction v1.1 needs to detect seeded-link chains, without
pretending v1 already solves it.

**Implementation boundary:** the reshare/provenance log is **moltbook-local** — produced by the
client and attached to the M7 trace written under `moltbook/traces/`. It does **not** modify
`pi_script/trace.py`: core trace is shared by systems with no links (m5, es, quantization), and this
is client/adapter-layer concern, consistent with the CredentialIntegrity split (prevention +
provenance are client-side; Pi Script is the constraint/freeze/audit-latch layer).

## 6. Layer split (unchanged principle from CredentialIntegrity §5)

The **pre-send gate is the primary control** — same detect-can't-undo-a-post logic: once a post with
a novel link is transmitted, freeze can't recall it, so prevention must happen before send. The Pi
Script `LinkRestriction` constraint is the enforcement latch (freeze + escalate) and audit layer for
anything that slips past the gate (e.g. a client-code bug). A blocked novel link still latches
`link_violation` (belt-and-suspenders): a blocked attempt is itself evidence the agent was steered
toward surfacing an attacker link and should stop. As with CredentialIntegrity, a public trace must
not imply Pi Script "caught" the link — the client gate did.

## 7. Required tests (per CLAUDE.md, plus the two Q-specific tests)

In `tests/test_moltbook_link_restriction.py`:

- **Deliberate-violation:** outbound content with a `novel` URL (not in source, host not allowlisted)
⇒ gate latches `link_violation` ⇒ `LinkRestriction` fires ⇒ resolver `frozen`, `freeze + escalate`.
Include the assembled-from-fragments and shortened-link variants.
- **Clean-pass:** a URL present in source content, and a URL whose host is allowlisted ⇒
`link_violation` stays false ⇒ constraint SATISFIED, `running`.
- **Reshare-logging (Q2):** a link present in source content passes the gate AND appears in the
provenance log with `provenance="source"`, `allowed=True` — proving pass-through links are still
recorded.
- **Allowlist-immutability (Q1):** the loaded allowlist has no runtime-mutation path from the client
(read-only), so the agent cannot expand its own permitted set.

## 8. Relationship to the other M7 constraints

- **CredentialIntegrity** governs secret exfiltration; **LinkRestriction** governs link provenance.
Overlapping intent (don't emit dangerous strings), distinct detectors, distinct latches — separate
constraints, both enforced on `MoltbookSession`.
- Coordinated cross-agent link-seeding / manipulation stays **out of scope** (v1.1/v2). LinkRestriction
v1 provides the provenance trail; it does not judge chains.
- IdentityIntegrity and ManipulationFlag remain unwritten — each needs its own ruling before code.

## 9. Decisions log (resolved)

1. **Constraint name — `LinkRestriction`.** PascalCase, behavior-first, consistent with the M7 set.
2. **Priority — `high`, `on_violation: freeze + escalate`.** A tier below CredentialIntegrity's
`critical` (link ≠ irreversibly-exploitable key), but still stops the agent for human review.
3. **Q1 allowlist maintenance — outside model reach (key-isolation principle).** Static `moltbook/`
config, editable only via commit/PR, never self-modifiable at runtime; loaded read-only.
4. **Q2 reshare handling — pass but always log.** Links traceable to source/allowlist pass the gate;
every surfaced link is logged in the M7 trace regardless of outcome, building the provenance record
for future coordinated-seeding detection (out of scope for v1). Logging is moltbook-local (§5), not
a core `trace.py` change.
86 changes: 74 additions & 12 deletions moltbook/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,35 @@

import json
import os
from pathlib import Path
from typing import Any, Callable

from moltbook.detector import scan_content
from moltbook.detector import scan_content, scan_links, LinkFinding

_DEFAULT_ALLOWLIST = Path(__file__).with_name("link_allowlist.json")


class KeyLeakBlocked(Exception):
"""Raised by the pre-send gate when outbound content contains a credential."""


class LinkBlocked(Exception):
"""Raised by the pre-send gate when outbound content surfaces a novel (un-provenanced) link."""


def load_allowlist(path: str | Path | None = None) -> tuple[str, ...]:
"""
Load the static link allowlist (ruling §4, Q1) as an IMMUTABLE tuple.

The agent gets no runtime write path — the allowlist is human-owned, editable only
via commit/PR to moltbook/link_allowlist.json. Returned as a tuple so there is no
mutation surface at all.
"""
p = Path(path) if path is not None else _DEFAULT_ALLOWLIST
data = json.loads(p.read_text(encoding="utf-8"))
return tuple(data.get("allowed_hosts", []))


def _no_transport(**_: Any) -> dict[str, Any]:
raise RuntimeError(
"MoltbookClient has no transport wired. Inject a real HTTP transport "
Expand All @@ -60,14 +80,23 @@ def __init__(
api_key: str | None = None,
transport: Callable[..., dict[str, Any]] | None = None,
session_id: str = "moltbook-session",
allowed_hosts: tuple[str, ...] | None = None,
) -> 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
# Latch: once a leak is detected (even if blocked), stays set until the key is
# rotated and the session explicitly reset. Drives CredentialIntegrity.
# Latches: once set (even on a blocked attempt), stay set until the session is
# explicitly reset. Drive CredentialIntegrity / LinkRestriction respectively.
self.credential_exposed = False
self.link_violation = False
# 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()
)
# Provenance log: every surfaced link, regardless of outcome (ruling §5). This
# is the moltbook-local trail future coordinated-seeding detection will need.
self._link_log: list[LinkFinding] = []

# ── Auth (the ONLY place the key is touched) ─────────────────────────────────
def _auth_header(self) -> dict[str, str]:
Expand All @@ -89,20 +118,38 @@ def build_generation_context(self, system: str, incoming: str) -> dict[str, Any]
}

# ── Pre-send gate (§4/§5) ────────────────────────────────────────────────────
def send(self, content: str, action: str = "post") -> dict[str, Any]:
def send(self, content: str, action: str = "post", source_content: str = "") -> dict[str, Any]:
"""
Attempt to send an outbound action (post/comment/dm). Scans first.

On a credential hit: latch `credential_exposed`, refuse to send, raise
KeyLeakBlocked with a REDACTED message (never the secret). Otherwise hand
off to the injected transport with the auth header.
Two gates run before transmission:
- Credential (CredentialIntegrity §4): on a hit, latch `credential_exposed`,
refuse, raise KeyLeakBlocked with a REDACTED message (never the secret).
- Link provenance (LinkRestriction §4): every URL is logged (§5) regardless
of outcome; a novel (un-provenanced) URL latches `link_violation`, refuses,
and raises LinkBlocked.

`source_content` is the content the agent is responding to/citing — a URL present
there has legitimate provenance. On a clean pass, hand off to the transport.
"""
scan = scan_content(content, own_key=self._api_key)
if scan.is_leak:
# Belt-and-suspenders: block AND latch, so CredentialIntegrity fires even
# though nothing was transmitted (ruling §5).
# Gate 1 — credential (most severe; short-circuits).
cred = scan_content(content, own_key=self._api_key)
if cred.is_leak:
self.credential_exposed = True
raise KeyLeakBlocked(f"{action} blocked by pre-send gate: {scan.detail}")
raise KeyLeakBlocked(f"{action} blocked by pre-send gate: {cred.detail}")

# Gate 2 — link provenance. Log every surfaced link first (§5), then enforce.
links = scan_links(content, source_content=source_content, allowed_hosts=self._allowed_hosts)
self._link_log.extend(links.findings)
if links.is_violation:
# Belt-and-suspenders: block AND latch, so LinkRestriction fires even though
# nothing was transmitted (ruling §6).
self.link_violation = True
novel_hosts = sorted({f.host or "<no-host>" for f in links.novel})
raise LinkBlocked(
f"{action} blocked by pre-send gate: novel link(s) not traceable to "
f"source or allowlist: {', '.join(novel_hosts)}"
)

return self._transport(
action=action,
Expand All @@ -121,11 +168,26 @@ def snapshot(self, trigger_type: str = "event") -> dict[str, Any]:
"entity": "MoltbookSession",
"entity_state": {
"credential_exposed": self.credential_exposed,
"link_violation": self.link_violation,
"session_id": self.session_id,
},
"response_history": [],
}

# ── Link provenance (LinkRestriction) ────────────────────────────────────────
@property
def allowed_hosts(self) -> tuple[str, ...]:
"""The static allowlist, as an immutable tuple — no runtime mutation path (§4, Q1)."""
return self._allowed_hosts

def link_provenance_records(self) -> tuple[LinkFinding, ...]:
"""
Every link surfaced this session, regardless of pass/fail (ruling §5). Attached
to the M7 resolution trace under moltbook/traces/ — kept moltbook-local so core
pi_script/trace.py (shared by link-less systems) is untouched.
"""
return tuple(self._link_log)

# ── Guard: prove no artifact leaks the key ───────────────────────────────────
def _contains_key(self, obj: Any) -> bool:
"""True if the serialized object contains the API key. Test/assert helper."""
Expand Down
Loading
Loading