Validate one of the agent’s own linked accounts by probing the provider with
the stored keychain secret. Ownership is verified (the account must be linked
to agent_id) before the secret is read.
Step 2/4: (re)point the agent’s provider link at this account.
agent_identity_link’s own ON CONFLICT(agent_id, provider) DO UPDATE already overwrites whatever account_id was linked
before, so no separate unlink is needed for the success path:
an unlink that succeeds followed by a link that fails would permanently drop
the agent’s existing provider link with no compensation (the
failure branch below only cleans up for is_new accounts).
Ownership check: the supplied account_id must already be
linked to the calling agent, so callers can’t overwrite
another agent’s credentials by guessing a UUID.
Step 3 (upsert DB). Compensate on failure for new accounts.
identity_upsert_with_mirror, not plain identity_upsert:
without the mirror write, an account created/updated after the fix shipped still had
no fallback entry and reproduced the reported bug on its own next channel switch.