couple of issues. 1) adding a recovery key in the wallet is failing with "couldn't reach the server". 2) the account reaper in staging is failing on foreign key constraints
Assistant
The error string exists in several screens but none obviously the recovery-key flow. Let me find the add-recovery-key flow specifically, and look at the reaper.
Assistant· <synthetic>
API Error: Unable to connect to API (ENOTFOUND)
User
couple of issues. 1) adding a recovery key in the wallet is failing with "couldn't reach the server". 2) the account reaper in staging is failing on foreign key constraints
Assistant· <synthetic>
API Error: Unable to connect to API (ConnectionRefused)
User
try again
Assistant
Last verification for the reaper analysis — whether consumed email_tokens rows are deleted or linger:
Assistant
Root-cause investigation complete on both. Findings:
Bug 2 — account reaper FK failures (root cause certain)
purge_account's DELETE_BY_DID list has drifted behind the schema. I applied all 53 migrations to a scratch SQLite DB and diffed the real FK graph against the delete list. FK enforcement is on (.foreign_keys(true)), there are no account-keyed cascades, so any missed table makes DELETE FROM accounts fail with FOREIGN KEY constraint failed — and the reaper retries every pass, forever. Four gaps:
email_tokens (V036) is missing entirely. Worse, its rows are never reclaimed — consume_email_token only stamps used_at, and no sweep deletes them. So any account that ever ran an email-confirm/update flow is permanently un-purgeable. This alone explains an hourly-failing staging reaper.
agent_identities.parent_did (V047). Purging a parent leaves its children's registrations (did = child, parent_did = parent) dangling. The V047 CHECK (child ⇒ parent_did NOT NULL) means you can't just null it, either.
agent_child_provisionings.parent_did. Same parent-purge gap — the list deletes only WHERE child_did = ? (MM-400's design doc explicitly called that "never parent_did" for the tombstone table, but the provisioning table has FKs on both columns).
agent_audit_events.did — deleted only via the purged account's own registrations; an event carrying this DID on another account's registration would survive and dangle (edge case, but same failure mode).
Timing fits: MM-400 child deletion landed 2026-07-17 and HV-2's demo child on staging was its motivating case — if you scheduled the child (or cleaned up the test parent) after that deploy, the reaper started hitting these on the next pass. A child-only purge is actually covered and tested; the parent-purge and email_tokens paths are not.
Proposed fix: add DELETE FROM email_tokens WHERE did = ?, resolve the parent-purge semantics (below), and — the durable part — add a schema-driven completeness test: run the migrations, walk PRAGMA foreign_key_list for every table, and assert each FK-to-accounts column is covered by DELETE_BY_DID/the block-blob machinery or sits on an explicit documented allowlist. That makes this whole bug class impossible to reintroduce silently (this is the third time a new migration outran the delete list).
User
Take care of the issues please, cascade-schedule the children
Assistant
Now setting up: fresh branch from origin/main for the PDS fix, and a look at the changelog-fragment mechanism (CI-gated per the recent commit).
Assistant
Now let me look at the V036 schema and the firehose emit_account signature, then write the failing tests.
Assistant
All five new tests fail with exactly the staging failure mode — root cause reproduced locally. Now the fix:
Assistant
All 15 tests green. Let me update the module-map doc row for account_delete.rs, run the neighboring test modules that exercise purge, and mark progress:
Assistant
All other call sites use catch-all closures (they'll compile unchanged and inherit better messages). Let me view map_discovery_error precisely, then make the edits:
Assistant
Now the edits. First pds_client.rs — classify plc.directory non-2xx responses through the existing status classifier:
Assistant
Now rekey.rs — new error variants, a shared PLC-fetch error mapper, and the exhaustive session mapping:
Assistant
Now the TypeScript union and the screen copy:
Assistant
Now the tests. Let me check the existing httpmock test pattern for plc.directory fetches:
Assistant
Now unit tests for the two mappers — in rekey.rs and session_provider.rs test mods:
Assistant
Now build and test the wallet crate, plus format:
Assistant
Frontend checks pass (0 errors, 139 tests). While clippy runs, verify whether the docs IPC reference needs regenerating for the new error codes:
Assistant
The background clippy job will notify on completion. Meanwhile run the static checks:
Assistant
Both PRs are up. One follow-up worth flagging as a separate task — the same session-error flattening exists in the sibling flows:
email_tokens rows are now purged with the account (they were never in the delete list, and consumption only stamps used_at, so any account with email-flow history was permanently un-purgeable — this is what was failing the staging reaper hourly).
Parent purge cascade-schedules children, per your call: each sovereign child is deactivated with delete_after = now + child_deletion_grace_secs inside the same transaction, its registration/provisioning rows go with the parent, and a best-effort #account deactivated frame fires after commit so relays stop serving its repo immediately. The reaper then purges the child normally — and a follow-up test proves that later child purge is clean.
Stray audit events carrying the purged DID on another account's registration are unlinked (did = NULL) rather than deleted — they're the other account's trail.
A schema-walking tripwire test now runs PRAGMA foreign_key_list over the fully-migrated schema and fails if any FK to accounts isn't reached by the purge. This is the third time a migration silently outran the delete list; that drift class now fails CI instead of the production reaper.
TDD throughout: all four behavioral tests reproduced the exact staging failure before the fix; 15/15 green after. Full just ci-pds passed.
★ Insight ─────────────────────────────────────
The tripwire test is the real fix here. The delete-list pattern requires every future migration author to remember a file they aren't touching — a human invariant. Deriving the obligation from the schema itself (PRAGMA foreign_key_list at test time) turns "remember to update the list" into "the build breaks until you do," which is the only kind of invariant that survives a codebase this active.
─────────────────────────────────────────────────
PR #351 — wallet "Couldn't reach the server" (re-key)
PdsClient's plc.directory reads (fetch_audit_log, fetch_plc_data_document, discover_pds) now classify non-2xx by status through the existing classify_xrpc_response: a 429 becomes RATE_LIMITED with its Retry-After, an outage carries its status; 404 keeps . surfaces throttles too, while keeping the "rejected operation" shape for real rejections.
User
#350 has changes requested
Assistant
Three CodeRabbit threads plus a real CI failure (rustfmt diff on the grace line). Let me switch to the branch, fix formatting, and triage:
Assistant
Now the changelog wording, then re-verify and push:
Assistant
Now reply to and resolve the three threads:
Assistant
All three threads are resolved and the fix commit is pushed. Since local fmt and CI disagreed once already, let me watch the PR checks to confirm green:
Assistant
Review batch on #350 handled — here's the disposition:
Thread
Verdict
Action
CI rustfmt failure (grace binding)
Real
Reformatted; cargo fmt --all --check now passes locally
Changelog overstates "every row purged"
Valid nit
Accepted CodeRabbit's wording — "purged or safely unlinked"
"Persist a durable tombstone for cascade-scheduled children"
Declined with evidence
The agent_child_deletions tombstone exists for the parent's audit view, and V049 doctrine reclaims it when the parent is deleted — this very transaction's pre-existing parent-keyed delete would remove any tombstone written here, with no surviving reader. Added an operator-visible tracing::info! (parent, child, delete_after) per scheduled child instead.
"Don't make child deactivation frames best-effort; use an outbox"
Declined with evidence
The drift is bounded: the child's terminal #account deleted frame at reap is transactionally staged, lifecycle endpoints serve the deactivated state immediately, and a post-commit emit failure implies the just-committed DB is broken — which the reaper's next pass surfaces anyway. Worst case is relays serving cached data until delete_after, the staleness class durable-log replay already heals. Encoded that rationale in the code comment.
Everything is pushed as one commit (972dca82), all three threads are resolved with a disposition comment explaining the two declines, and the purge tests still pass 15/15. I've got a background watch on the PR's CI checks and will report when they finish — expect one more CodeRabbit pass on the new commit, which I'd triage the same way if it raises anything.
User
#351 is failing checks
Assistant
Found and fixed — the failure was the ticket-ref-check gate, not the code: I'd written "(the MM-290 lesson)" in a rekey.rs doc comment, and the repo bans Linear ticket references in Rust source (traceability lives in docs/, and comments must state the why in system terms). This exact gate has bitten before, which is why it runs early in the pipeline.
The fix is pushed (b63efe2a): the comment now states the invariant directly — flattened errors make the real cause undiagnosable from the screen — with no ticket number. Verified locally before pushing this time: just ticket-ref-check ✓, cargo fmt --all --check ✓, rekey tests 19/19 ✓. The rest of #351's checks were already green (both iOS compile jobs, both frontend checks), so only the PDS gate needed the re-run.
I have background watches on both PRs' checks now and will report when they land. I also updated my project memory so this gate gets run before the first push of any branch touching .rs files, not just PDS-crate ones — this was its second bite.
Assistant
#350 is now fully green — PDS gate passed, and CodeRabbit's re-review came back clean, so the review-fix commit and the two declined threads stand. It's ready to merge whenever you are (merging to main deploys staging, where the reaper backlog should then clear on its next hourly pass).
Still watching #351's re-run — I'll report when it lands.
Assistant
While that runs, let me capture the flake with enough context for a deflake task chip:
Assistant
The verdict on #351's second failure: not my change — the pds test local_parent_mints_lists_and_revokes_sovereign_child flaked in CI (502 from the mocked plc.directory leg during child mint, under runner load). Evidence: this branch's crates/pds is byte-identical to green main, and the test passes 3/3 locally on the branch. I've rerun the failed job and I'm watching it; I also flagged a deflake task chip with the diagnosis, since an infra-flaky test in the PDS gate will keep taxing unrelated PRs. Will report when the rerun lands.
Assistant
#351 is now fully green — the rerun confirmed the 502 was the flake, and every check passes.
Final state of both fixes:
#350 (reaper FK gaps + child cascade + schema tripwire) — green, review threads resolved, ready to merge. Merging deploys staging, where the reaper should clear its failing backlog on the next hourly pass — the new "parent purge: cascade-scheduled child deletion" and "account reaper pass complete" log lines will confirm it.
#351 (wallet plc.directory/session error classification) — green, ready to merge. Once it rides a main push into TestFlight, "Add a recovery key" will either just work or name its real blocker (throttle vs. directory problem vs. genuine connectivity) instead of the misleading connection message.
Two task chips are pending if you want them: extending the same error-classification fix to the sibling wallet flows (handle change, repo-key rotation, app passwords), and deflaking the agent_child mint test whose mocked plc leg 502'd this run.
One design decision is yours: what should purging a parent with living children mean? Deleting the child registrations kills the children's only credential (they become exactly the orphaned-hosting problem MM-400 was created to solve); refusing the purge makes the reaper loop; cascading a scheduled deletion onto the children is doctrine-consistent with the ADR-0023 custody ladder ("recovery authority belongs to the parent") but is a bigger transaction. My lean is cascade-schedule the children, but that's a product call, not a bug fix.
Bug 1 — wallet "Couldn't reach the server" on Add recovery key
What I verified: the "Add a recovery key" strip is the MM-411 re-key flow; both prod and staging are on 0.6.0 and every server endpoint it touches is live and healthy (PUT /v1/recovery/escrow-share, POST /v1/sessions/sovereign, refreshSession all respond correctly). So it's not a missing/broken server route.
The message maps only from RekeyError::NETWORK_ERROR, and that code is a dumping ground — the MM-290 defect class, resurfaced in the paths MM-290's fix never reached:
fetch_audit_log (what the review screen calls on mount) maps any non-2xx from plc.directory — including a 429 rate-limit or 5xx — to NetworkError. Same for discover_pds, post_plc_operation, fetch_plc_data_document.
map_session_error's catch-all flattens ServerFailure{status}, UnsupportedHost, and InvalidResponse into NetworkError too.
So "Couldn't reach the server. Check your connection." currently means any of: plc.directory throttling you (likely, given the 15-min PLC monitor plus per-identity home-surface checks all hitting plc.directory), a plc.directory 5xx, a PDS 5xx during session refresh, or a genuine transport failure — and the wallet discards the distinguishing information before it reaches the screen. The most probable live trigger is plc.directory returning 429/5xx on the audit-log fetch, but I can't confirm which without the real status (that's the point — nobody can).
Proposed fix: classify PLC-directory HTTP failures by status in PdsClient (429 → RATE_LIMITED with retry-after, 5xx → a distinct "the directory had a problem" surface) exactly as MM-290 did for the XRPC helpers, and remove map_session_error's catch-all so server verdicts stop masquerading as connectivity. That either fixes the symptom outright (if it's throttling, the user gets the honest "wait a moment" message) or names the real failure on the next occurrence.
Want me to implement these? The reaper fix + completeness test and the wallet classification fix are both uncontroversial; I'd hold the parent-purge cascade until you pick a semantic.
DidNotFound
post_plc_operation
Session discovery passes throttles/HTTP verdicts through as RateLimited/ServerFailure instead of Offline, and the re-key flow's map_session_error is now exhaustive — no catch-all.
The review screen gains honest copy: a throttle says "wait a moment," a directory problem says "the identity directory had a problem," and only genuine transport failures say "check your connection." The precise cause rides the error payload into the console log, so the next occurrence names itself.
★ Insight ─────────────────────────────────────
This was the MM-290 defect class resurfacing in paths that fix never reached — the XRPC helpers got status classification, but the plc.directory client kept blanket NetworkError. When one error variant is the "easy" mapping target, it accretes meanings until the message stops carrying information; the cure is making the honest variant equally cheap to reach (one shared classifier).
─────────────────────────────────────────────────
Two notes: the same map_session_error catch-all still exists in the handle-change, repo-key-rotation, and app-passwords flows — I've flagged that as a task chip you can spin off. And once #350 merges to staging, the reaper should clear its backlog on its next hourly pass; worth glancing at the staging logs afterward to confirm the "account reaper pass complete" line reports deletions instead of errors.