Skip to content

Commit 0fdbf88

Browse files
GodSpeed313claude
andauthored
C2 seam extraction — instance-free request/auth path for the live captcha wiring (#71)
* Extract the request/auth seam to module level for the C2 live captcha path C1 decided what things mean; C2 is making the transport structurally capable of carrying that decision, not making any new decisions. This commit is the structural half only — no classification logic, no C1 semantics. The live captcha wiring must build `submit_captcha_fn` BEFORE MoltbookHTTPTransport exists, because the Note E fail-closed presence check takes it as a constructor argument. It therefore cannot reach a bound method, and `_real_request` was trapped behind an instance it does not yet have. The factory shape was never the problem; the trapped default was. Extraction only: - `real_request(base_url, method, path, body, headers)` at module level, containing `_real_request`'s prior body with ONLY the Note D comment relocated into the docstring. No logic, HTTP semantics, redirect posture, error handling, or timeout change. - Deliberately no leading underscore. This module uses underscore at module level to mean "internal, do not import" (`_collapse_letter_runs`, `_normalize_captcha_prompt`, `_word_number_value`); one here would signal the opposite of why it was extracted. - `real_request` is NOT itself a `request_fn` — the seam signature is (method, path, json_body, headers); callers partially apply the base_url. - `auth_headers(api_key)` at module level, transport-scoped. - `_real_request()` / `_auth_headers()` reduced to one-line delegations, each carrying a guard comment stating that instance-specific behavior does not belong in the wrapper. One HTTP path, not two: the write path and the live verify path now build on the same function, so retry/redirect/timeout posture cannot diverge between them (C1 §5's concern). Tests: 613 passed, 7 xfailed. Two added. The existing two `_real_request` tests are deliberately untouched — they now cover the delegation, which is the regression evidence that extraction changed no behaviour. The new module-level test pins the one property they cannot: callable with no transport instance in existence. Those two would still pass if an instance dependency were reintroduced, because they hold an instance; this one would not, which makes the "pure delegation" guard mechanical rather than a comment asking the next editor to remember. DELIBERATE DEFERRALS — recorded as policy, not omissions: 1. Redirect posture. `_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 the 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. The open concern is classification fidelity — a followed redirect means the status reaching the classifier may not be `/verify`'s own (a 303 landing on 404 would classify as C1-4 CONFIRMED_FAILURE, a C1 §9 stop condition, from a response `/verify` never gave). Also note `docs/moltbook_api_spec.md` §1: a bare-domain request triggers a redirect that STRIPS the Authorization header, so redirect behaviour here carries a documented credential-safety dimension too. PARKED, unresolved, not touched in this commit. 2. `moltbook/client.py:144` `_auth_header()` duplicates `f"Bearer {api_key}"`, and its comment calls itself "the ONLY place the key is touched", which `transport.py` has made inaccurate. The DRY helper here is deliberately transport-scoped and does NOT consolidate it; fixing it would reach outside C2 and ripple into tests/test_moltbook_credential_integrity.py:196. PARKED alongside (1). 3. Test-count sync. CLAUDE.md, TODO.md and README.md all still read 611. 613 is an intermediate count inside active C2 work, not a completed state the docs failed to follow — unlike PR #69's situation. Syncing now would only be resynced when the classification tests land. DEFERRED by decision to the C2-complete commit, to be synced once. Structurally scoped throughout: no C1 decision introduced, no `submit_captcha_fn` policy beyond making the live path authenticable, no `TransportResult.rate_limit` change, no Note E constructor invariant touched, no write-path behaviour changed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * Track the three C2 parked items as recorded decisions, not omissions The redirect finding and the client.py auth duplication were tracked nowhere — they existed only in the review conversation and in 203c016's commit body. That is the state where a later reviewer has to reconstruct a deferral by noticing a mismatch, which is what PR #69 had to do for the test counts. Adds a new "M7 — §C / C2 parked items" subsection. Deliberately NOT filed under "post-GO engineering debt (NOT prerequisites for GO-1)": GO-1 is already granted, so that heading's qualifier is spent, and the redirect item may bear on GO-2. Classifying it as post-GO would assert a readiness decision that belongs to the operator and to docs/m7_operator_go_checklist.md, not to this tracker — which its own readiness-authority note at the top already says. Three items: 1. Redirect posture — filed as open, with the verified facts separated from the unresolved ones: C1 §5 is provably not violated (POST redirects drop `data` on 301/302/303; 307/308 raise and fall to §4 residual), while classification fidelity and a documented credential dimension (moltbook_api_spec §1: bare-domain redirect strips Authorization) remain open. Whether it gates GO-2 is explicitly not decided here. 2. client.py:144's duplicate `f"Bearer {api_key}"` and its stale "the ONLY place the key is touched" comment — recorded with why C2's helper is transport-scoped rather than consolidating it. 3. Test-count sync — recorded as deferred to the C2-complete commit by decision, with the reason it differs from #69's case. Contains no test count. Item 3 states that the documented count has moved without restating a number, so this commit cannot itself become a stale count needing a later correction. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
1 parent 88d92b7 commit 0fdbf88

3 files changed

Lines changed: 156 additions & 20 deletions

File tree

‎TODO.md‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,49 @@ Live milestone + debt tracker. Suite: **611 passing + 7 xfail** (known-gap pins)
2424
> defining GO readiness. This tracker records work; it does not define preconditions for GO-1.
2525
> Where the two appear to disagree, the checklist governs.
2626
27+
### M7 — §C / C2 parked items (surfaced 2026-08-16 during C2 preparation)
28+
29+
Three items surfaced while extracting the request/auth seam for the live captcha path
30+
(commit `203c016`). None was acted on in that commit. They are recorded here so each
31+
deferral is a decision on the record rather than something a later reviewer reconstructs
32+
from a commit body — deliberately NOT filed under post-GO debt below, because GO-1 is
33+
already granted and the first item may bear on GO-2.
34+
35+
- [ ] **Redirect posture on the live verify path — open, and deliberately not classified as
36+
post-GO.** `_real_request` / `request_fn` follow redirects via urllib's default opener.
37+
Verified on CPython 3.12.10: on POST it redirects for 301/302/303 only and rebuilds the
38+
`Request` WITHOUT `data`, so a captcha answer body is never resubmitted and **C1 §5 is not
39+
violated**; 307/308 raise `HTTPError` and fall to C1 §4 residual, which is correct. Two
40+
concerns remain. (a) **Classification fidelity:** a followed redirect means the status
41+
reaching the classifier may not be `/verify`'s own — a 303 landing on a 404 would classify
42+
as C1-4 `CONFIRMED_FAILURE`, a C1 §9 stop condition, from a response `/verify` never gave.
43+
C1 §3.2 makes HTTP status authoritative for the enumerated non-2xx rows, so this is
44+
load-bearing, not cosmetic. (b) **Credential safety:** `docs/moltbook_api_spec.md` §1
45+
documents that a bare-domain request triggers a redirect that STRIPS the `Authorization`
46+
header. The transport hardcodes the `www` base URL, so no known path reaches that case
47+
today, but it establishes that redirect behaviour here has a credential dimension and not
48+
only a classification one. **Whether this must be settled before GO-2 is not decided here.**
49+
Parked by operator direction 2026-08-16 during the §10(b) ruling, explicitly to keep the
50+
§10(b) work from absorbing an unrelated change to shared request behaviour.
51+
52+
- [ ] **`moltbook/client.py:144` duplicates the Authorization-header derivation, and its comment
53+
is stale.** `client.py`'s `_auth_header()` and `transport.py`'s former `_auth_headers()`
54+
both spelled `f"Bearer {api_key}"` independently; `client.py:143` still describes itself as
55+
"the ONLY place the key is touched", which `transport.py` has made inaccurate. C2's DRY
56+
helper (`auth_headers()`) is deliberately **transport-scoped** and does not consolidate the
57+
cross-module pair: doing so would reach outside C2's authorized boundary and would ripple
58+
into `tests/test_moltbook_credential_integrity.py:196`, which asserts on
59+
`client._auth_header()`. Parked by operator direction 2026-08-16. Note this duplication is
60+
the same drift class the transport-scoped helper exists to prevent, observed one layer up.
61+
62+
- [ ] **Test-count sync deferred to the C2-complete commit.** `CLAUDE.md`, `TODO.md` and
63+
`README.md` state a suite count that active C2 work has since moved. Deferred by operator
64+
decision 2026-08-16 to be synced **once**, at the C2-complete count, rather than resynced
65+
at each intermediate commit — each restatement being another opportunity to record a wrong
66+
number. Unlike PR #69's situation, this is an intermediate count inside active work, not a
67+
completed state the docs failed to follow. Recorded here so the mismatch reads as a
68+
decision rather than as neglect, which is what #69 had to reconstruct.
69+
2770
### M7 — post-GO governance milestones (NOT prerequisites for GO-1)
2871

2972
- [ ] **IdentityIntegrity v1.1 — cross-session identity change detection.** Ruled post-GO by

‎moltbook/transport.py‎

Lines changed: 68 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1050,6 +1050,65 @@ def trace(self) -> tuple[DryRunOutcome, ...]:
10501050
return tuple(self._trace)
10511051

10521052

1053+
# ────────── Instance-free building blocks for the request/auth path ─────────────
1054+
#
1055+
# Both functions below are deliberately module-level and deliberately WITHOUT a
1056+
# leading underscore: unlike this module's private helpers (_collapse_letter_runs,
1057+
# _normalize_captcha_prompt, _word_number_value), they exist precisely to be called
1058+
# from OUTSIDE the class. The live captcha wiring must build `submit_captcha_fn`
1059+
# BEFORE MoltbookHTTPTransport exists — the constructor's Note E fail-closed check
1060+
# requires it as a constructor argument — so it cannot reach a bound method. An
1061+
# underscore here would signal "internal, do not import", which is the opposite of
1062+
# why these were extracted.
1063+
#
1064+
# One HTTP path, not two: the transport's default request_fn and the live captcha
1065+
# submission both build on real_request(), so retry/redirect/timeout posture cannot
1066+
# diverge between the write path and the verify path (C1 §5's concern).
1067+
1068+
def real_request(
1069+
base_url: str, method: str, path: str, body: dict | None, headers: dict,
1070+
) -> HTTPResponse:
1071+
"""
1072+
The default `request_fn` implementation, minus the instance. Extracted verbatim
1073+
from MoltbookHTTPTransport._real_request — same urllib call, same JSON encoding,
1074+
same timeout, same HTTPError capture, no behavioural change of any kind.
1075+
1076+
NOTE: this is not itself a `request_fn`. The seam's signature is
1077+
(method, path, json_body, headers) -> HTTPResponse; this takes a leading
1078+
`base_url`, so callers partially apply it (functools.partial / a lambda).
1079+
1080+
Implementation Note D: headers are captured identically on BOTH paths —
1081+
a 429 arrives via HTTPError, so capturing only on the success path would
1082+
silently fail on the exact case header capture exists for.
1083+
"""
1084+
url = f"{base_url}{path}"
1085+
data = json.dumps(body).encode("utf-8") if body is not None else None
1086+
req = urllib.request.Request(
1087+
url, data=data, headers={**headers, "Content-Type": "application/json"}, method=method,
1088+
)
1089+
try:
1090+
with urllib.request.urlopen(req, timeout=10) as resp:
1091+
raw = resp.read().decode("utf-8")
1092+
return HTTPResponse(
1093+
resp.status, (json.loads(raw) if raw else {}), dict(resp.headers),
1094+
)
1095+
except urllib.error.HTTPError as exc:
1096+
raw = exc.read().decode("utf-8")
1097+
return HTTPResponse(
1098+
exc.code, (json.loads(raw) if raw else {}), dict(exc.headers),
1099+
)
1100+
1101+
1102+
def auth_headers(api_key: str) -> dict:
1103+
"""
1104+
The single derivation of the Authorization header for this module. Exists so the
1105+
class method and the live captcha wiring cannot drift into two spellings of
1106+
`f"Bearer {api_key}"` — the drift that already happened between this module and
1107+
moltbook/client.py:144 (parked, not fixed here).
1108+
"""
1109+
return {"Authorization": f"Bearer {api_key}"}
1110+
1111+
10531112
# ───────────────── §12 MVP slice: the real Moltbook HTTP transport ──────────────
10541113

10551114
class MoltbookHTTPTransport:
@@ -1109,28 +1168,17 @@ def live_config_version(self) -> str:
11091168
return self._live_config_version
11101169

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

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

11351183
# ── Safe reads (§8) ──────────────────────────────────────────────────────────
11361184
def health_check(self) -> TransportResult:

‎tests/test_moltbook_transport.py‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,10 +76,12 @@
7676
TransportResult,
7777
VerificationStatus,
7878
as_client_transport,
79+
auth_headers,
7980
canonical_payload_hash,
8081
describe_retry_category,
8182
make_dry_run_action_id,
8283
parse_verification_block,
84+
real_request,
8385
reconcile,
8486
resolve_ambiguous_write,
8587
solve_captcha_deterministic,
@@ -471,6 +473,49 @@ def _raise(req, timeout):
471473
assert response.rate_limit.retry_after_delay_seconds == 60
472474
assert response.rate_limit.remaining == 0
473475

476+
def test_real_request_module_level_needs_no_transport_instance(self, monkeypatch):
477+
"""C2 request-seam extraction: real_request() is callable with NO transport in
478+
existence. This is the whole point of the extraction — the live captcha wiring
479+
must build submit_captcha_fn BEFORE MoltbookHTTPTransport is constructed (the
480+
Note E fail-closed check takes it as a constructor argument), so it can never
481+
reach a bound method.
482+
483+
The two _real_request tests above would still pass if an instance dependency
484+
were reintroduced, because they hold an instance. This one would not — it is
485+
the mechanical guard behind the 'pure delegation' comment on the wrapper."""
486+
import io
487+
import urllib.request as _ur
488+
489+
class _FakeResp(io.BytesIO):
490+
status = 200
491+
headers = {"X-RateLimit-Remaining": "7"}
492+
493+
seen: dict = {}
494+
495+
def _urlopen(req, timeout):
496+
seen["url"] = req.full_url
497+
seen["method"] = req.get_method()
498+
return _FakeResp(b'{"id": "p9"}')
499+
500+
monkeypatch.setattr(_ur, "urlopen", _urlopen)
501+
response = real_request(
502+
"https://example.invalid", "POST", "/posts", {"content": "x"}, {},
503+
)
504+
assert response.status_code == 200
505+
assert response.body == {"id": "p9"}
506+
assert response.headers["x-ratelimit-remaining"] == "7"
507+
assert seen["url"] == "https://example.invalid/posts" # base_url joined as before
508+
assert seen["method"] == "POST"
509+
510+
def test_auth_headers_wrapper_matches_module_helper(self):
511+
"""C2 auth extraction: the class method and the module-level helper derive the
512+
same header from one place. transport.py and moltbook/client.py:144 already
513+
drifted into two spellings of f"Bearer {api_key}" (parked, not fixed here);
514+
this pins the new pair mechanically instead of trusting the comment."""
515+
transport = MoltbookHTTPTransport("key", live_config_version=CONFIG_V1)
516+
assert transport._auth_headers() == auth_headers("key")
517+
assert auth_headers("key") == {"Authorization": "Bearer key"}
518+
474519
def test_missing_retry_after_parses_to_none(self):
475520
info = HTTPResponse(429, {}, self.RL_HEADERS).rate_limit # no Retry-After at all
476521
assert info.retry_after_delay_seconds is None

0 commit comments

Comments
 (0)