Skip to content

Commit fb4e4e4

Browse files
GodSpeed313claude
andcommitted
M7: LinkRestriction constraint + link-provenance pre-send gate
Spec-first ruling docs/m7_link_restriction_ruling.md (LOCKED), then the implementation, following the CredentialIntegrity pattern: - moltbook/moltbook.pi — link_violation field + LinkRestriction (must equal false; freeze + escalate; priority high — a tier below CredentialIntegrity's critical, a link is not an irreversibly-exploitable key). Joined enforce; arbiter never_acceptable gains link_allowlist_self_modification. - moltbook/detector.py — scan_links: pure provenance classification (source / allowlist / novel), never fetches or judges the destination. novel catches shortened/redirect and fragment-assembled URLs; subdomain matches allow. - moltbook/link_allowlist.json — static, human-owned allowlist (Q1). Loaded as an immutable tuple; the running agent has no runtime mutation path (key-isolation principle: an agent that could expand its own allowlist defeats the constraint). - moltbook/client.py — send() runs both gates (credential first, then links). Novel links block + latch link_violation + raise LinkBlocked. Every surfaced link is logged via link_provenance_records() regardless of outcome (Q2) — kept moltbook-local, NOT a core pi_script/trace.py change (shared by link-less systems; client/adapter-layer concern per the CredentialIntegrity split). - tests — violation/clean pair, detector provenance cases, gate behavior, end-to-end block->freeze, reshare-logging, allowlist-immutability. Updated the CredentialIntegrity enforce assertion for the now-two-constraint block. Full suite: 315 passed, 3 xfailed. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
1 parent 0db3f2e commit fb4e4e4

8 files changed

Lines changed: 563 additions & 23 deletions

‎docs/m7_link_restriction_ruling.md‎

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
# M7 Constraint Ruling — LinkRestriction
2+
3+
**Status:** LOCKED / binding for implementation (signed off 2026-07-16, both open questions
4+
resolved — see §9). Canonical spec-first ruling required by `CLAUDE.md` and the
5+
`pi-script-constraint` skill for the LinkRestriction constraint in the M7 (Moltbook) deployment.
6+
Build order: `moltbook/moltbook.pi` (entity extension + constraint) → link-provenance detector →
7+
gate wiring in `moltbook/client.py` (with reshare logging) → test set (violation/clean pair +
8+
reshare-logging + allowlist-immutability).
9+
10+
**Numbering note:** No grammar change — LinkRestriction is the existing Form 2 `equality_rule`
11+
(`MoltbookSession.link_violation must equal false`), same shape as CredentialIntegrity. This is an
12+
application-level M7 constraint ruling, not a 9.x grammar ruling. If review finds the six rule
13+
forms can't express it, that is a grammar conversation before any code.
14+
15+
---
16+
17+
## 1. Ruling (locked text)
18+
19+
The M7 agent may only surface external links that are **(a)** present in the source content it is
20+
directly responding to or citing, or **(b)** on a static allowlist maintained in `moltbook/` config,
21+
editable only outside the agent's runtime reach (never self-modifiable). The agent must never
22+
generate, construct, or surface a novel external URL it was not given — including URLs assembled from
23+
fragments, shortened/redirect links, or links suggested by another agent's post or DM that don't meet
24+
(a) or (b). A violation is: outbound content contains a URL not traceable to one of the two permitted
25+
sources. This is a **provenance check, not payload inspection** — the constraint doesn't judge whether
26+
a link is malicious, only whether the agent had legitimate grounds to surface it. Priority **high**,
27+
`on_violation: freeze + escalate`. Resharing a link present in source content passes the gate but is
28+
**logged in every resolution trace regardless of outcome**, to build a provenance record for future
29+
coordinated-link-seeding detection (out of scope for v1). The **pre-send gate is the primary control**
30+
(same detect-can't-undo-a-post logic as CredentialIntegrity); the Pi Script constraint is the
31+
audit/freeze layer for anything that slips through.
32+
33+
## 2. Why (threat)
34+
35+
The M7 recon notes flagged coordinated link-seeding as a live Moltbook pattern — the
36+
`moltbook_pyclaw` / `Ting_Fodder` / `doctor_crustacean` cluster builds apparent authority through a
37+
dense self-citation trail of cross-linked posts. A governed agent that could be steered (by an
38+
injection payload or another agent's DM) into surfacing an attacker-chosen link becomes a node in
39+
that seeding graph. The defensible v1 line is **provenance**: the agent surfaces a link only when it
40+
can point to legitimate grounds (it was in the content being responded to, or on a human-owned
41+
allowlist). Judging whether a link is *malicious*, or detecting *coordinated seeding chains*, is
42+
explicitly out of scope — that is future ManipulationFlag v1.1/v2 or LinkRestriction v1.1 territory.
43+
v1 does not pretend to solve it; it leaves the trail that later work needs (§5).
44+
45+
## 3. Constraint definition
46+
47+
Same boolean-latch pattern as CredentialIntegrity. A detector/gate sets `link_violation`; Pi Script
48+
rules on the snapshot.
49+
50+
```
51+
entity MoltbookSession {
52+
credential_exposed: boolean
53+
link_violation: boolean // set true by the link-provenance gate (§4)
54+
session_id: identifier
55+
}
56+
57+
constraint LinkRestriction {
58+
priority: high
59+
rule: MoltbookSession.link_violation must equal false
60+
on_violation: freeze + escalate
61+
}
62+
```
63+
64+
- **`priority: high`** (not `critical`): a leaked *key* is irreversibly exploitable; an
65+
un-provenanced *link* is a governance/authority-integrity failure, serious but a tier below key
66+
loss. `freeze + escalate` still applies — the agent stops and a human reviews.
67+
- Grammar-valid Form 2, boolean value, identical machinery to `CredentialIntegrity` /
68+
`ScopeGuard`.
69+
70+
## 4. Detection — provenance, not payload (Q1 resolved)
71+
72+
A pre-send gate in the client extracts every URL from candidate outbound content and classifies each:
73+
74+
| Provenance | Grounds | Outcome |
75+
| --- | --- | --- |
76+
| `source` | The exact URL appears in the source content the agent is responding to/citing (a). | Pass, logged (§5). |
77+
| `allowlist` | The URL's host is on the static `moltbook/` allowlist (b). | Pass, logged (§5). |
78+
| `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`. |
79+
80+
**Allowlist maintenance (Q1, resolved — same principle as CredentialIntegrity §5.1 key isolation).**
81+
The allowlist is a **static config in `moltbook/`** (a sibling config file), editable **only via
82+
commit/PR — never writable by the running agent at runtime**. An agent that could expand its own
83+
allowlist defeats the constraint the same way a model holding its own API key defeated
84+
CredentialIntegrity before isolation. It is **read-only to the agent, human-owned.** The client loads
85+
it as an immutable value with no runtime-mutation path.
86+
87+
This is a **provenance check, not payload inspection**: the gate never fetches the link, never judges
88+
whether the destination is malicious — only whether the agent had legitimate grounds to surface it.
89+
90+
## 5. Reshare logging (Q2 resolved) — leave a trail v1 doesn't act on
91+
92+
Every surfaced link is recorded in the M7 resolution trace **regardless of pass/fail**, not only
93+
violations — URL, provenance (`source`/`allowlist`/`novel`), and whether it was allowed. Reasoning:
94+
the recon notes already flagged coordinated link-seeding (the pyclaw/Ting_Fodder self-citation trail).
95+
LinkRestriction v1 should **not** try to judge that — out of scope, same as ManipulationFlag's
96+
coordinated-pattern case — but it should leave a trail. That record is exactly what a future
97+
ManipulationFlag v1.1/v2 or LinkRestriction v1.1 needs to detect seeded-link chains, without
98+
pretending v1 already solves it.
99+
100+
**Implementation boundary:** the reshare/provenance log is **moltbook-local** — produced by the
101+
client and attached to the M7 trace written under `moltbook/traces/`. It does **not** modify
102+
`pi_script/trace.py`: core trace is shared by systems with no links (m5, es, quantization), and this
103+
is client/adapter-layer concern, consistent with the CredentialIntegrity split (prevention +
104+
provenance are client-side; Pi Script is the constraint/freeze/audit-latch layer).
105+
106+
## 6. Layer split (unchanged principle from CredentialIntegrity §5)
107+
108+
The **pre-send gate is the primary control** — same detect-can't-undo-a-post logic: once a post with
109+
a novel link is transmitted, freeze can't recall it, so prevention must happen before send. The Pi
110+
Script `LinkRestriction` constraint is the enforcement latch (freeze + escalate) and audit layer for
111+
anything that slips past the gate (e.g. a client-code bug). A blocked novel link still latches
112+
`link_violation` (belt-and-suspenders): a blocked attempt is itself evidence the agent was steered
113+
toward surfacing an attacker link and should stop. As with CredentialIntegrity, a public trace must
114+
not imply Pi Script "caught" the link — the client gate did.
115+
116+
## 7. Required tests (per CLAUDE.md, plus the two Q-specific tests)
117+
118+
In `tests/test_moltbook_link_restriction.py`:
119+
120+
- **Deliberate-violation:** outbound content with a `novel` URL (not in source, host not allowlisted)
121+
⇒ gate latches `link_violation` ⇒ `LinkRestriction` fires ⇒ resolver `frozen`, `freeze + escalate`.
122+
Include the assembled-from-fragments and shortened-link variants.
123+
- **Clean-pass:** a URL present in source content, and a URL whose host is allowlisted ⇒
124+
`link_violation` stays false ⇒ constraint SATISFIED, `running`.
125+
- **Reshare-logging (Q2):** a link present in source content passes the gate AND appears in the
126+
provenance log with `provenance="source"`, `allowed=True` — proving pass-through links are still
127+
recorded.
128+
- **Allowlist-immutability (Q1):** the loaded allowlist has no runtime-mutation path from the client
129+
(read-only), so the agent cannot expand its own permitted set.
130+
131+
## 8. Relationship to the other M7 constraints
132+
133+
- **CredentialIntegrity** governs secret exfiltration; **LinkRestriction** governs link provenance.
134+
Overlapping intent (don't emit dangerous strings), distinct detectors, distinct latches — separate
135+
constraints, both enforced on `MoltbookSession`.
136+
- Coordinated cross-agent link-seeding / manipulation stays **out of scope** (v1.1/v2). LinkRestriction
137+
v1 provides the provenance trail; it does not judge chains.
138+
- IdentityIntegrity and ManipulationFlag remain unwritten — each needs its own ruling before code.
139+
140+
## 9. Decisions log (resolved)
141+
142+
1. **Constraint name — `LinkRestriction`.** PascalCase, behavior-first, consistent with the M7 set.
143+
2. **Priority — `high`, `on_violation: freeze + escalate`.** A tier below CredentialIntegrity's
144+
`critical` (link ≠ irreversibly-exploitable key), but still stops the agent for human review.
145+
3. **Q1 allowlist maintenance — outside model reach (key-isolation principle).** Static `moltbook/`
146+
config, editable only via commit/PR, never self-modifiable at runtime; loaded read-only.
147+
4. **Q2 reshare handling — pass but always log.** Links traceable to source/allowlist pass the gate;
148+
every surfaced link is logged in the M7 trace regardless of outcome, building the provenance record
149+
for future coordinated-seeding detection (out of scope for v1). Logging is moltbook-local (§5), not
150+
a core `trace.py` change.

‎moltbook/client.py‎

Lines changed: 74 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -29,15 +29,35 @@
2929

3030
import json
3131
import os
32+
from pathlib import Path
3233
from typing import Any, Callable
3334

34-
from moltbook.detector import scan_content
35+
from moltbook.detector import scan_content, scan_links, LinkFinding
36+
37+
_DEFAULT_ALLOWLIST = Path(__file__).with_name("link_allowlist.json")
3538

3639

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

4043

44+
class LinkBlocked(Exception):
45+
"""Raised by the pre-send gate when outbound content surfaces a novel (un-provenanced) link."""
46+
47+
48+
def load_allowlist(path: str | Path | None = None) -> tuple[str, ...]:
49+
"""
50+
Load the static link allowlist (ruling §4, Q1) as an IMMUTABLE tuple.
51+
52+
The agent gets no runtime write path — the allowlist is human-owned, editable only
53+
via commit/PR to moltbook/link_allowlist.json. Returned as a tuple so there is no
54+
mutation surface at all.
55+
"""
56+
p = Path(path) if path is not None else _DEFAULT_ALLOWLIST
57+
data = json.loads(p.read_text(encoding="utf-8"))
58+
return tuple(data.get("allowed_hosts", []))
59+
60+
4161
def _no_transport(**_: Any) -> dict[str, Any]:
4262
raise RuntimeError(
4363
"MoltbookClient has no transport wired. Inject a real HTTP transport "
@@ -60,14 +80,23 @@ def __init__(
6080
api_key: str | None = None,
6181
transport: Callable[..., dict[str, Any]] | None = None,
6282
session_id: str = "moltbook-session",
83+
allowed_hosts: tuple[str, ...] | None = None,
6384
) -> None:
6485
# Key isolation: private, resolved from the same runtime secret source as auth.
6586
self._api_key = api_key if api_key is not None else os.environ.get("MOLTBOOK_API_KEY")
6687
self._transport = transport or _no_transport
6788
self.session_id = session_id
68-
# Latch: once a leak is detected (even if blocked), stays set until the key is
69-
# rotated and the session explicitly reset. Drives CredentialIntegrity.
89+
# Latches: once set (even on a blocked attempt), stay set until the session is
90+
# explicitly reset. Drive CredentialIntegrity / LinkRestriction respectively.
7091
self.credential_exposed = False
92+
self.link_violation = False
93+
# Immutable, human-owned allowlist (ruling §4, Q1). tuple = no mutation surface.
94+
self._allowed_hosts: tuple[str, ...] = (
95+
allowed_hosts if allowed_hosts is not None else load_allowlist()
96+
)
97+
# Provenance log: every surfaced link, regardless of outcome (ruling §5). This
98+
# is the moltbook-local trail future coordinated-seeding detection will need.
99+
self._link_log: list[LinkFinding] = []
71100

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

91120
# ── Pre-send gate (§4/§5) ────────────────────────────────────────────────────
92-
def send(self, content: str, action: str = "post") -> dict[str, Any]:
121+
def send(self, content: str, action: str = "post", source_content: str = "") -> dict[str, Any]:
93122
"""
94123
Attempt to send an outbound action (post/comment/dm). Scans first.
95124
96-
On a credential hit: latch `credential_exposed`, refuse to send, raise
97-
KeyLeakBlocked with a REDACTED message (never the secret). Otherwise hand
98-
off to the injected transport with the auth header.
125+
Two gates run before transmission:
126+
- Credential (CredentialIntegrity §4): on a hit, latch `credential_exposed`,
127+
refuse, raise KeyLeakBlocked with a REDACTED message (never the secret).
128+
- Link provenance (LinkRestriction §4): every URL is logged (§5) regardless
129+
of outcome; a novel (un-provenanced) URL latches `link_violation`, refuses,
130+
and raises LinkBlocked.
131+
132+
`source_content` is the content the agent is responding to/citing — a URL present
133+
there has legitimate provenance. On a clean pass, hand off to the transport.
99134
"""
100-
scan = scan_content(content, own_key=self._api_key)
101-
if scan.is_leak:
102-
# Belt-and-suspenders: block AND latch, so CredentialIntegrity fires even
103-
# though nothing was transmitted (ruling §5).
135+
# Gate 1 — credential (most severe; short-circuits).
136+
cred = scan_content(content, own_key=self._api_key)
137+
if cred.is_leak:
104138
self.credential_exposed = True
105-
raise KeyLeakBlocked(f"{action} blocked by pre-send gate: {scan.detail}")
139+
raise KeyLeakBlocked(f"{action} blocked by pre-send gate: {cred.detail}")
140+
141+
# Gate 2 — link provenance. Log every surfaced link first (§5), then enforce.
142+
links = scan_links(content, source_content=source_content, allowed_hosts=self._allowed_hosts)
143+
self._link_log.extend(links.findings)
144+
if links.is_violation:
145+
# Belt-and-suspenders: block AND latch, so LinkRestriction fires even though
146+
# nothing was transmitted (ruling §6).
147+
self.link_violation = True
148+
novel_hosts = sorted({f.host or "<no-host>" for f in links.novel})
149+
raise LinkBlocked(
150+
f"{action} blocked by pre-send gate: novel link(s) not traceable to "
151+
f"source or allowlist: {', '.join(novel_hosts)}"
152+
)
106153

107154
return self._transport(
108155
action=action,
@@ -121,11 +168,26 @@ def snapshot(self, trigger_type: str = "event") -> dict[str, Any]:
121168
"entity": "MoltbookSession",
122169
"entity_state": {
123170
"credential_exposed": self.credential_exposed,
171+
"link_violation": self.link_violation,
124172
"session_id": self.session_id,
125173
},
126174
"response_history": [],
127175
}
128176

177+
# ── Link provenance (LinkRestriction) ────────────────────────────────────────
178+
@property
179+
def allowed_hosts(self) -> tuple[str, ...]:
180+
"""The static allowlist, as an immutable tuple — no runtime mutation path (§4, Q1)."""
181+
return self._allowed_hosts
182+
183+
def link_provenance_records(self) -> tuple[LinkFinding, ...]:
184+
"""
185+
Every link surfaced this session, regardless of pass/fail (ruling §5). Attached
186+
to the M7 resolution trace under moltbook/traces/ — kept moltbook-local so core
187+
pi_script/trace.py (shared by link-less systems) is untouched.
188+
"""
189+
return tuple(self._link_log)
190+
129191
# ── Guard: prove no artifact leaks the key ───────────────────────────────────
130192
def _contains_key(self, obj: Any) -> bool:
131193
"""True if the serialized object contains the API key. Test/assert helper."""

0 commit comments

Comments
 (0)