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
43 changes: 43 additions & 0 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,49 @@ Live milestone + debt tracker. Suite: **611 passing + 7 xfail** (known-gap pins)
> defining GO readiness. This tracker records work; it does not define preconditions for GO-1.
> Where the two appear to disagree, the checklist governs.

### M7 — §C / C2 parked items (surfaced 2026-08-16 during C2 preparation)

Three items surfaced while extracting the request/auth seam for the live captcha path
(commit `203c016`). None was acted on in that commit. They are recorded here so each
deferral is a decision on the record rather than something a later reviewer reconstructs
from a commit body — deliberately NOT filed under post-GO debt below, because GO-1 is
already granted and the first item may bear on GO-2.

- [ ] **Redirect posture on the live verify path — open, and deliberately not classified as
post-GO.** `_real_request` / `request_fn` follow redirects via urllib's default opener.
Verified on CPython 3.12.10: on POST it redirects for 301/302/303 only and rebuilds the
`Request` WITHOUT `data`, so a captcha answer body is never resubmitted and **C1 §5 is not
violated**; 307/308 raise `HTTPError` and fall to C1 §4 residual, which is correct. Two
concerns remain. (a) **Classification fidelity:** a followed redirect means the status
reaching the classifier may not be `/verify`'s own — a 303 landing on a 404 would classify
as C1-4 `CONFIRMED_FAILURE`, a C1 §9 stop condition, from a response `/verify` never gave.
C1 §3.2 makes HTTP status authoritative for the enumerated non-2xx rows, so this is
load-bearing, not cosmetic. (b) **Credential safety:** `docs/moltbook_api_spec.md` §1
documents that a bare-domain request triggers a redirect that STRIPS the `Authorization`
header. The transport hardcodes the `www` base URL, so no known path reaches that case
today, but it establishes that redirect behaviour here has a credential dimension and not
only a classification one. **Whether this must be settled before GO-2 is not decided here.**
Parked by operator direction 2026-08-16 during the §10(b) ruling, explicitly to keep the
§10(b) work from absorbing an unrelated change to shared request behaviour.

- [ ] **`moltbook/client.py:144` duplicates the Authorization-header derivation, and its comment
is stale.** `client.py`'s `_auth_header()` and `transport.py`'s former `_auth_headers()`
both spelled `f"Bearer {api_key}"` independently; `client.py:143` still describes itself as
"the ONLY place the key is touched", which `transport.py` has made inaccurate. C2's DRY
helper (`auth_headers()`) is deliberately **transport-scoped** and does not consolidate the
cross-module pair: doing so would reach outside C2's authorized boundary and would ripple
into `tests/test_moltbook_credential_integrity.py:196`, which asserts on
`client._auth_header()`. Parked by operator direction 2026-08-16. Note this duplication is
the same drift class the transport-scoped helper exists to prevent, observed one layer up.

- [ ] **Test-count sync deferred to the C2-complete commit.** `CLAUDE.md`, `TODO.md` and
`README.md` state a suite count that active C2 work has since moved. Deferred by operator
decision 2026-08-16 to be synced **once**, at the C2-complete count, rather than resynced
at each intermediate commit — each restatement being another opportunity to record a wrong
number. Unlike PR #69's situation, this is an intermediate count inside active work, not a
completed state the docs failed to follow. Recorded here so the mismatch reads as a
decision rather than as neglect, which is what #69 had to reconstruct.

### M7 — post-GO governance milestones (NOT prerequisites for GO-1)

- [ ] **IdentityIntegrity v1.1 — cross-session identity change detection.** Ruled post-GO by
Expand Down
88 changes: 68 additions & 20 deletions moltbook/transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -1050,6 +1050,65 @@ def trace(self) -> tuple[DryRunOutcome, ...]:
return tuple(self._trace)


# ────────── Instance-free building blocks for the request/auth path ─────────────
#
# Both functions below are deliberately module-level and deliberately WITHOUT a
# leading underscore: unlike this module's private helpers (_collapse_letter_runs,
# _normalize_captcha_prompt, _word_number_value), they exist precisely to be called
# from OUTSIDE the class. The live captcha wiring must build `submit_captcha_fn`
# BEFORE MoltbookHTTPTransport exists — the constructor's Note E fail-closed check
# requires it as a constructor argument — so it cannot reach a bound method. An
# underscore here would signal "internal, do not import", which is the opposite of
# why these were extracted.
#
# One HTTP path, not two: the transport's default request_fn and the live captcha
# submission both build on real_request(), so retry/redirect/timeout posture cannot
# diverge between the write path and the verify path (C1 §5's concern).

def real_request(
base_url: str, method: str, path: str, body: dict | None, headers: dict,
) -> HTTPResponse:
"""
The default `request_fn` implementation, minus the instance. Extracted verbatim
from MoltbookHTTPTransport._real_request — same urllib call, same JSON encoding,
same timeout, same HTTPError capture, no behavioural change of any kind.

NOTE: this is not itself a `request_fn`. The seam's signature is
(method, path, json_body, headers) -> HTTPResponse; this takes a leading
`base_url`, so callers partially apply it (functools.partial / a lambda).

Implementation Note D: headers are captured identically on BOTH paths —
a 429 arrives via HTTPError, so capturing only on the success path would
silently fail on the exact case header capture exists for.
"""
url = f"{base_url}{path}"
data = json.dumps(body).encode("utf-8") if body is not None else None
req = urllib.request.Request(
url, data=data, headers={**headers, "Content-Type": "application/json"}, method=method,
)
try:
with urllib.request.urlopen(req, timeout=10) as resp:
raw = resp.read().decode("utf-8")
return HTTPResponse(
resp.status, (json.loads(raw) if raw else {}), dict(resp.headers),
)
except urllib.error.HTTPError as exc:
raw = exc.read().decode("utf-8")
return HTTPResponse(
exc.code, (json.loads(raw) if raw else {}), dict(exc.headers),
)


def auth_headers(api_key: str) -> dict:
"""
The single derivation of the Authorization header for this module. Exists so the
class method and the live captcha wiring cannot drift into two spellings of
`f"Bearer {api_key}"` — the drift that already happened between this module and
moltbook/client.py:144 (parked, not fixed here).
"""
return {"Authorization": f"Bearer {api_key}"}


# ───────────────── §12 MVP slice: the real Moltbook HTTP transport ──────────────

class MoltbookHTTPTransport:
Expand Down Expand Up @@ -1109,28 +1168,17 @@ def live_config_version(self) -> str:
return self._live_config_version

def _auth_headers(self) -> dict:
return {"Authorization": f"Bearer {self._api_key}"}
# Pure delegation — instance-specific behavior does not belong here;
# extend auth_headers() instead, so the class and the live captcha wiring
# keep deriving the header from one place.
return auth_headers(self._api_key)

def _real_request(self, method: str, path: str, body: dict | None, headers: dict) -> HTTPResponse:
url = f"{self._base_url}{path}"
data = json.dumps(body).encode("utf-8") if body is not None else None
req = urllib.request.Request(
url, data=data, headers={**headers, "Content-Type": "application/json"}, method=method,
)
# Implementation Note D: headers are captured identically on BOTH paths —
# a 429 arrives via HTTPError, so capturing only on the success path would
# silently fail on the exact case header capture exists for.
try:
with urllib.request.urlopen(req, timeout=10) as resp:
raw = resp.read().decode("utf-8")
return HTTPResponse(
resp.status, (json.loads(raw) if raw else {}), dict(resp.headers),
)
except urllib.error.HTTPError as exc:
raw = exc.read().decode("utf-8")
return HTTPResponse(
exc.code, (json.loads(raw) if raw else {}), dict(exc.headers),
)
# Pure delegation — instance-specific behavior does not belong here;
# extend real_request() instead. This wrapper exists only to bind
# self._base_url, so that the write path and the live captcha verify path
# cannot drift apart in retry/redirect/timeout posture.
return real_request(self._base_url, method, path, body, headers)

# ── Safe reads (§8) ──────────────────────────────────────────────────────────
def health_check(self) -> TransportResult:
Expand Down
45 changes: 45 additions & 0 deletions tests/test_moltbook_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,12 @@
TransportResult,
VerificationStatus,
as_client_transport,
auth_headers,
canonical_payload_hash,
describe_retry_category,
make_dry_run_action_id,
parse_verification_block,
real_request,
reconcile,
resolve_ambiguous_write,
solve_captcha_deterministic,
Expand Down Expand Up @@ -471,6 +473,49 @@ def _raise(req, timeout):
assert response.rate_limit.retry_after_delay_seconds == 60
assert response.rate_limit.remaining == 0

def test_real_request_module_level_needs_no_transport_instance(self, monkeypatch):
"""C2 request-seam extraction: real_request() is callable with NO transport in
existence. This is the whole point of the extraction — the live captcha wiring
must build submit_captcha_fn BEFORE MoltbookHTTPTransport is constructed (the
Note E fail-closed check takes it as a constructor argument), so it can never
reach a bound method.

The two _real_request tests above would still pass if an instance dependency
were reintroduced, because they hold an instance. This one would not — it is
the mechanical guard behind the 'pure delegation' comment on the wrapper."""
import io
import urllib.request as _ur

class _FakeResp(io.BytesIO):
status = 200
headers = {"X-RateLimit-Remaining": "7"}

seen: dict = {}

def _urlopen(req, timeout):
seen["url"] = req.full_url
seen["method"] = req.get_method()
return _FakeResp(b'{"id": "p9"}')

monkeypatch.setattr(_ur, "urlopen", _urlopen)
response = real_request(
"https://example.invalid", "POST", "/posts", {"content": "x"}, {},
)
assert response.status_code == 200
assert response.body == {"id": "p9"}
assert response.headers["x-ratelimit-remaining"] == "7"
assert seen["url"] == "https://example.invalid/posts" # base_url joined as before
assert seen["method"] == "POST"

def test_auth_headers_wrapper_matches_module_helper(self):
"""C2 auth extraction: the class method and the module-level helper derive the
same header from one place. transport.py and moltbook/client.py:144 already
drifted into two spellings of f"Bearer {api_key}" (parked, not fixed here);
this pins the new pair mechanically instead of trusting the comment."""
transport = MoltbookHTTPTransport("key", live_config_version=CONFIG_V1)
assert transport._auth_headers() == auth_headers("key")
assert auth_headers("key") == {"Authorization": "Bearer key"}

def test_missing_retry_after_parses_to_none(self):
info = HTTPResponse(429, {}, self.RL_HEADERS).rate_limit # no Retry-After at all
assert info.retry_after_delay_seconds is None
Expand Down
Loading