Repository navigation
fix(registry): key agents by AdCP URL canonicalization - #8249
Conversation
The registry keyed agents by `lower(trim(agent_url))` with every trailing slash stripped. AdCP URL canonicalization lowercases only the scheme and host; path case and a non-root trailing slash are significant. The old key therefore merged agents the spec says are distinct — `/tenants/Acme/mcp` and `/tenants/acme/mcp` shared one key, so an authorization, a compliance badge or an ownership claim could attach to the wrong agent — and failed to merge agents the spec says are the same (`:443`, dot segments, `%7E`, IDN hosts). After #7829 it is also an active matching regression: an agent served at `/mcp/` stops matching in find_agents_for_property. registryAgentUrlKey (server/src/db/registry-agent-url-key.ts) is now the one implementation, delegating to canonicalTargetUri from @adcp/sdk/signing with one registry-local rule: a root-served agent with no query loses its `/`, so those keys stay byte-identical across the migration. canonicalizeAgentUrl is a re-export, so every call site moves together, and the read-only audit from #7968 imports the same function instead of carrying a copy. SQL no longer canonicalizes agent URLs anywhere — the spec algorithm needs IDN A-labels, dot-segment resolution and selective percent-decoding. Seven queries in federated-index-db.ts take an app-computed key parameter; four were restructured, including moving signing_keys_pinned out of the manifest JSONB walk and giving reconcileAdagentsAuthorizations a FOR UPDATE transaction in place of its single-statement form. Migration 625 relaxes both CHECK constraints (NOT VALID, so a legacy key the new shape rejects cannot fail the deploy), adds the key columns to caa_emit_event's modified-event detection so a rewrite reaches change-feed consumers, and folds both sides of the suppress join for bad_actor overrides — exact equality would let a publisher lift a ban by editing one character of path case. The data rewrite is migrate-registry-agent-url-keys.ts: dry-run by default, refusing to write while any store has a merge, a chain, an unkeyable row, an unmodelled unique index, or a stranded suppression. Tables are discovered from information_schema and must appear in REWRITE_STORES or REPORT_ONLY_STORES, so a new store can be neither silently rewritten nor silently left on the old key. Three deliberate divergences from the comparer rules in docs/reference/url-canonicalization, all because this is a producer-side key rather than a signature comparison: userinfo is rejected rather than stripped, a U-label host is converted rather than rejected, and query percent-encoding is normalized where the SDK's 3.2 profile preserves raw bytes for signature fidelity. Refs #7830 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
There was a problem hiding this comment.
Ladon verdict: Approve
Approve — registry-key canonicalization change (#7830) is thorough and well-guarded.
The reviewer verified the core of this change in depth: the registryAgentUrlKey helper with rejection/idempotence tests, migration 625 (both CHECKs NOT VALID, caa_emit_event modified-detection, bad_actor suppress fold, view column list matching migration 570 so CREATE OR REPLACE VIEW is safe), all 13 SQL canonicalization sites in federated-index-db.ts converted to app-computed key params with no orphaned readers, CHECK-regex↔CANONICAL_AUTHORITY parity via fuzz test, and the migration script's merge/chain/unkeyable/stranded-suppression gating, one-transaction rewrite, FOR UPDATE races, and VALIDATE-vs-tombstone handling. Operational concerns (deploy-then-rewrite window, keysRejectedByConstraint) are documented in the PR runbook. No changeset is required — this is not protocol surface (no static/schemas/source or docs/reference changes).
Medium findings
- server/src/db/federated-index-db.ts:466 — bulkGetFirstAuthForAgents: null key from unkeyable input can collapse rows via DISTINCT ON NULL. Latent, no production caller today.
Decision: One medium finding, no critical/high. Although high_risk is true (migration 625 added; registry-api.ts modified), the migration file is (added) scaffolding and row 5 requires a medium finding on a (modified) high-risk file — the single medium is in federated-index-db.ts, which is not a high-risk path. The medium is category edge-case, not data-loss/schema/infra, so row 4 does not fire. gated_paths is false, no team gate, no prior decision. Only 1 medium → falls through to row 9 (approve). Worth a human eye on the DISTINCT ON NULL note before any caller is added.
Medium findings
- server/src/db/federated-index-db.ts:466 — bulkGetFirstAuthForAgents: null key from unkeyable input collapses rows via DISTINCT ON NULL
Five integration tests asserted the pre-#7830 key: that a path-case or trailing-slash variant collapses onto the same agent. Under AdCP URL canonicalization it does not, so they now vary only what the key still folds — scheme and host case, a default port, surrounding whitespace — and member-agents-api gains a case proving `/mcp`, `/MCP` and `/mcp/` register as three separate agents rather than upserting onto each other. Regenerates static/openapi/registry.yaml for the agent_url parameter description. Refs #7830 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
There was a problem hiding this comment.
Ladon verdict: Approve
Approve — subsequent review, clean.
The current reviewer run surfaces no Critical, High, or Medium findings. The delta encodes the #7830 URL canonicalization behavior (scheme/host case folding, default-port normalization, whitespace trimming; path case and non-root trailing slash remain significant) and the reviewer verified the new test pins (member-agents-api.test.ts:48-51, the /mcp vs /MCP vs /mcp/ three-agent case at :79-95, admin/refresh tests, and OpenAPI registry.yaml:185/188) match registryAgentUrlKey in server/src/db/registry-agent-url-key.ts.
Prior decision was approve with one medium (federated-index-db.ts:466); that file is absent from the current delta and the finding is out of scope — no carry-forward.
High-risk flag is true only via a new migration file (625_...sql, added) and a modified registry-api.ts route, but the reviewer found no medium-or-higher concern on the modified file, so row 5 does not fire and the added migration is normal scaffolding (not escalation-worthy on the flag alone).
Decision-table walk: no critical/high (row 1 no); gated_paths false (row 2 no); no (deleted) reasons (row 3 no); no medium findings at all (rows 4, 5, 8 no); prior decision was approve, not escalate (row 6 no); no no-auto-approve team match (row 7 no). Falls through to row 9 → approve.
Verification on the final head
|
Maintainer decision on #7830: /mcp and /mcp/ are the same agent for registry identity. The production collision listing bears it out — every one of the 47 key collisions is a trailing-slash pair, root or non-root, and there is not a single case-only, port, http/https or fragment variant among them. registryAgentUrlKey now strips trailing slashes from the path, on top of canonicalTargetUri's scheme/host case, default port, dot segments and percent-encoding. The one exception is a root path carrying a query, where the slash stays so the query still reads as a query. This diverges from docs/reference/url-canonicalization deliberately, and only for identity. AUTHORIZATION MATCHING IS UNCHANGED. AgentValidator and everything that decides whether an adagents.json entry authorizes an agent keep comparing spec-exactly, with the trailing slash significant (#7829). The seam is AgentConfig.declared_url: set only where the key folded something away, and read through declaredAgentUrl() by find_agents_for_property and properties.ts. registry-identity-vs-authorization.test.ts pins both halves — a manifest listing /mcp/ authorizes /mcp/ and not /mcp, while the two key identically. Every store and code path the key touches is classified as identity, authorization or raw-matched in the helper's header. Collisions are now resolved rather than blocked. registry-key-stores.ts declares a per-table merge policy: which row survives and how each column composes. Compliance status follows the freshest check; registry metadata takes the conservative value for every gate it holds; a badge keeps the active one over a revoked one; a ban can never be downgraded to a correction; an authorization merge unions validity but never the grant. No value is dropped silently — every merge lists the surviving row, the rows that do not, and every field whose value the merged row does not carry. agent_contexts and member_profiles.agents still have no policy and still block, because a wrong merge there hands over credentials or ownership. The production gate is exact now. registry-agent-url-key-sql.ts is a SQL twin of the key, held to the TypeScript helper by a corpus test, and audit-registry-key-collisions.ts groups by it per table per unique index. The old coarse gate rtrimmed every trailing slash and so reported path-case variants as merge risks; this one reports exactly the groups Postgres would reject, labelled by whether the migration rewrites that store. Migration 625's CHECK follows the key: no trailing slash on the path anywhere, with the root-plus-query exception. `declared_url` is member-supplied and reaches the validator, so the visibility gate only accepts it when it keys back to the same agent. Otherwise a member could claim their own agent's identity and a well-authorized agent's declared URL, and the directory would report theirs as authorized wherever that one is. Refs #7830 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Updated for the 2026-10-17 maintainer decision: trailing slashes foldHead is now 1. The gate is exact. The coarse I verified it on a seeded database: the root-slash pair and the non-root pair each report as one 2. Trailing slashes fold, root and non-root. 3. Authorization matching is unchanged, and that needed work. Folding Every store and path the key touches is classified identity / authorization / raw-matched in the PR description and in the helper's header. 4. Merge policy, all 9 tables. Declared per table in Not merging. Please re-run Step 1 and Step 2 from the description. Expected: |
There was a problem hiding this comment.
Ladon verdict: Request changes
Request changes — 1 blocking finding.
Blocking findings
- server/src/scripts/migrate-registry-agent-url-keys.ts:447 —
planMerges/applyMergesdrop the partial-index predicate (deleted_at IS NULL/superseded_at IS NULL) for derived-key stores. The siblingaudit-registry-key-collisions.tscorrectly applies it; here tombstoned/superseded rows sharing a canonical+scope can be ranked as winner and the live losers DELETEd — dropping an authorization or lifting a ban. This is a reproducible data-loss/authorization bug on a production migration path.
Context
This is a subsequent pass on the #7830 trailing-slash-folding delta; the prior run was clean (approve). The reviewer confirms the identity/authorization split (declared_url/declaredAgentUrl) is fail-closed, migration 625's check constraint matches the TS key, and agent_contexts/member_profiles correctly have no merge policy. The merge-policy test only seeds active rows, so this predicate gap is not caught by tests. Per decision table row 1 (a high finding present), the outcome is request-changes.
Medium findings
None.
Blocking findings
- server/src/scripts/migrate-registry-agent-url-keys.ts:447 — planMerges/applyMerges drop the partial-index predicate (deleted_at IS NULL/superseded_at IS NULL) for derived-key stores; tombstoned/superseded rows can be ranked as merge winner and live rows DELETEd, dropping an authorization or lifting a ban
The merge re-read in planMerges fetched rows by key and scope columns but dropped the unique index's partial predicate. idx_caa_unique_active and idx_aao_unique_active only constrain live rows, so the plan counted the collision from active rows alone while the re-read pulled in every tombstoned and superseded row sharing the same key and scope. rankRows would then happily crown a dead row — a superseded bad_actor override outranks a live correction, a soft-deleted authorization with a fresh updated_at outranks the live grant — and applyMerges deleted the live rows as losers. That drops an authorization or lifts a ban. The DELETE and UPDATE omitted the predicate too, so they could reach rows the plan never looked at. MergeAction now carries the predicate and all three statements apply it, so the group the plan describes and the group the apply touches are the same set by construction. The regression test seeds two live catalog_agent_authorizations rows plus a tombstone on the same key and scope holding the freshest updated_at of the three — the exact ranking trap. Reverting the fix makes it fail with both live rows in loserKeys. Found by the PR reviewer. Refs #7830 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Superseded by a later Ladon review that rechecked and resolved its blocking findings.
There was a problem hiding this comment.
Ladon verdict: Approve
Approve — subsequent pass on PR #8249 (trailing-slash key folding, #7830).
The prior high-severity blocker is resolved: migrate-registry-agent-url-keys.ts planMerges/applyMerges no longer drop the partial-index predicate (deleted_at IS NULL / superseded_at IS NULL) for derived-key stores. MergeAction.predicate now carries the predicate, the planMerges re-read applies it (L2313), and applyMerges applies it to both the loser DELETE and the winner UPDATE (L2382), consistent with the readTable detection pass and the sibling audit script. Parameter numbering is correct and the predicate is server-rendered SQL, not operator input. A new regression test seeds a freshest-updated tombstone and asserts only the two live rows fold while the tombstone survives untouched.
No current findings. high_risk is true only from (added) migration scaffolding and (modified) route files, but with zero medium-or-higher findings on those modified files, no escalation trigger applies (rows 3-5 do not fire). Prior decision was request-changes, not escalate, so row 6 is irrelevant. No gated paths, no no-auto-approve team match. Falls through to row 9.
Maintainer decision on the open item in #8249. catalog_agent_authorizations keeps keying by identity — the indexes stay on agent_url_canonical and the folded key does the lookup work — but every per-agent read that answers "is this agent authorized" now restricts to the raw agent_url values that are spec-exactly the same agent. A publisher that authorized https://a.example/mcp/ has not authorized https://a.example/mcp, and the directory can no longer say otherwise in either direction. specExactAgentUrls(agentUrl) resolves it: one indexed read of the distinct raw spellings under the key, filtered through isSpecExactAgentMatch, passed to the query as AND v.agent_url = ANY($n::text[]). A single agent has a handful of spellings, so this is one small indexed read whatever the registry's size, and an empty result correctly matches nothing. Nine read sites carry it: getDomainsForAgent, getPublishersForAgentDetail, bulkGetFirstAuthForAgents, getPropertiesForAgent, getPropertiesForAgentDomain, getPublisherDomainsForAgent, getAuthorizationSource, isPropertyAuthorizedForAgent, and AuthorizationSnapshotDatabase.getNarrow. validator.ts's normalizeUrl now calls through to the same specExactAgentUrl the directory uses, so the two implementations cannot drift — which is the actual guarantee being asked for. getAllAgentDomainPairs is deliberately not filtered: it is the crawler's bulk snapshot for diffing agent.discovered / agent.removed, an identity enumeration rather than a per-agent authorization answer. registry-directory-spec-exact.test.ts covers one case per read site plus a cross-check that the directory and the AgentValidator agree. Neutering the filter makes all ten fail. The snapshot endpoint resolves against whichever relation its include mode reads: an include=effective pull surfaces phantom rows from the override layer that have no base row at all, so resolving against the base table would filter every one of them out. The existing sync-endpoint test caught exactly that. Read-side only: no key, migration, merge policy or stored value changes, so the collision gate and dry-run outputs are unaffected. Refs #7830 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Directory now answers spec-exactly — head
|
There was a problem hiding this comment.
Ladon verdict: Approve
Approve — clean pass, no blocking or medium findings.
This PR adds spec-exact agent-URL filtering (#7829/#7830) to per-agent authorization reads in the federated-index layer. The reviewer confirmed all 9 per-agent read sites in federated-index-db.ts are covered, the bulk getAllAgentDomainPairs snapshot correctly stays folded, param alignment is correct across every query (including authorization-snapshot-db.getNarrow $3), and validator.ts now routes through the shared specExactAgentUrl so directory and AgentValidator cannot drift — pinned by a new agreement test. Comprehensive integration coverage spans every read site.
High-risk flag is true, but only due to (added) migration scaffolding and (modified) route files with no medium-or-higher findings. Per the arbiter rules, a new migration file and modified routes with a clean review do not warrant escalation. The sole residual (two trailing-slash variants collapsing on dedup_canonical in a single bulk batch) is documented pre-existing behavior on a non-occurring input, not introduced here.
Delta touches server query logic only — no schema/dist/changeset surface, so changeset-scope and schema↔docs coherence gates do not apply. gated_paths is false; no no-auto-approve team match. Prior decision was also approve.
Decision table: no critical/high (row 1 n/a); gated_paths false (row 2 n/a); no (deleted) high-risk entries (row 3 n/a); no medium findings (rows 4, 5, 8 n/a); prior was approve not escalate (row 6 n/a); no team gate (row 7 n/a). Falls through to row 9 → approve.
…istry-key-canonicalization
Merged
|
| Scanned for | Found |
|---|---|
| New migrations | none — server/src/db/ is untouched on main since the merge base |
New tables / columns keyed by agent_url |
none |
New readers of agent_url_canonical |
none |
New canonicalizeAgentUrl / registryAgentUrlKey / canonicalTargetUri call sites |
none |
New SQL canonicalization (LOWER/RTRIM/BTRIM on a URL) |
none |
Only two agent_url additions in the delta fall outside dist/, and neither is a registry site: a local test variable in hosted-compliance-echoed-release.test.ts holding a loopback URL passed to comply(), and a target_format_id.agent_url in a storyboard lint fixture — the protocol's format-id.agent_url field, not the registry identity key. Everything else is released dist/schemas / dist/compliance artifacts. So there is nothing new to classify as identity vs authorization.
Migration 625 is still the next number. Main tops at 624 and added no migrations; npm run test:migrations passes (no duplicates).
One thing the merge did change that touches this PR: main bumped @adcp/sdk 15.9.2 → 15.9.5, and both registryAgentUrlKey and specExactAgentUrl delegate to its canonicalTargetUri. I re-ran all 84 assertions across the key, SQL-twin, identity-vs-authorization, merge-policy and migration suites on 15.9.5 — all unchanged, so the canonicalization both halves rely on behaves identically.
Local suites on the merged tree: server unit green, 759 files / 12,690 tests (up from 756 / 12,649 — main's new tests). Integration green apart from the known sandbox artifacts: 5 suites that fail to load for environment reasons and also fail on origin/main, plus registry-feed, which passes in isolation and in all four CI shards.
Gate and dry run: no re-run needed on account of the merge. Nothing in it touches the key, the stored values, migration 625 or the merge policies, so your d17127dc artifacts still describe this head's write behaviour. (Re-running before --apply is still worth it for a different reason — writes that land during the deploy window can create collisions that were not there at review time.)
HARD STOP stands. Not merging.
There was a problem hiding this comment.
Ladon verdict: Approve
Approve — clean pass, no blocking findings.
Reviewed all 44 delta files (= full PR), including the two largest changed files in full (federated-index-db.ts and the 958-line migrate-registry-agent-url-keys.ts). The #7830 identity/authorization key split is implemented consistently across every registry read site: identity keys fold trailing slash while authorization matching stays spec-exact via declared_url/specExactAgentUrl. Migration 625's CHECK authority class matches the app's CANONICAL_AUTHORITY verbatim; the migration script is dry-run by default and fail-closed (blocks on chains, unkeyable rows, unresolved merges, stranded suppressions). agent-visibility-gate.ts accepts declared_url only when it keys back to the same agent — fail-closed against authorization borrowing. Tests cover each read site plus validator agreement; docs/OpenAPI coherent. No changeset required (no protocol-surface changes).
Decision-rule walkthrough:
- Row 1 (critical/high): no such findings.
- Row 2 (gated paths): gated_paths is false; review_decision is APPROVED regardless.
- Row 3 (deleted high-risk): no deletions — migration 625 and all route files are added/modified only.
- Rows 4/5 (medium + schema/infra or modified high-risk): no medium findings at all.
- Row 6 (sticky escalate): prior decision was approve, not escalate.
- Row 7 (no-auto-approve team): no team match.
- Row 8 (≥3 medium): zero medium findings.
- Row 9: approve.
high_risk is true only via normal added migration scaffolding and modified route files with no medium-or-higher concern, so the flag alone does not warrant escalation. Consistent with the prior approve on the preceding head.
#8249 folded the non-root trailing slash into the registry identity key, so `https://x.example/mcp/` and `https://x.example/mcp` are one agent stored under the slashless key. The writers and the DB readers moved; the HTTP per-agent routes did not — they still looked the requested URL up raw. After the production rewrite, `GET /api/registry/agents/{…%2Fmcp%2F}/compliance` returned `status: unknown` with no data while the slashless spelling returned the merged agent (`degraded`, 3.1.29). Same for `interchange.io/` and `sell.nofluffadvisory.com/`: every badge embed or bookmark holding the slashed spelling went blank. Every route that takes `:encodedUrl` and resolves it to registry identity now keys the requested URL before the lookup, so either spelling resolves to the folded agent and the response echoes the canonical `agent_url` (19 routes: compliance, compliance/history, compliance/diagnostics, verification, the four badge routes, storyboard-status, the monitoring routes, lifecycle, grading-profile and the three storyboard POSTs). `?? rawAgentUrl` keeps the existing 404/empty behavior for inputs the key rejects. `GET /registry/lookup/agent/:agentUrl/domains` is deliberately NOT keyed and is now annotated as such: "which publishers authorize this agent" is an authorization answer, decided spec-exactly with the trailing slash significant (#7829). Keying it would make `/mcp/` inherit `/mcp`'s authorizations. Also records in the migration script runbook that `flyctl deploy --process-groups worker` recreated the worker group with 2 HA machines even though it had been scaled to 0, so pausing the workers does not survive a deploy. Refs #7830. Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Closes #7830
Problem
The registry keyed agents by
lower(trim(agent_url))with every trailing slash stripped (canonicalizeAgentUrl,server/src/db/publisher-db.ts). AdCP URL canonicalization lowercases only the scheme and host; path case and a non-root trailing slash are significant. The registry therefore merged agents the spec says are distinct —/tenants/Acme/mcpand/tenants/acme/mcpshared one key, so an authorization, a compliance badge or an ownership claim could attach to the wrong one — and failed to merge agents the spec says are the same (:443, dot segments,%7E, IDN hosts).chk_caa_agent_url_canonical(migration 440) andchk_aao_agent_url_canonical(432) froze the old shape into the schema.After #7829 it is also an active matching regression:
find_agents_for_propertypasses registry keys into a spec-conformant validator, so an agent served at/mcp/and listed as/mcp/stops matching.What changed
One shared helper.
server/src/db/registry-agent-url-key.tsexportsregistryAgentUrlKey, delegating tocanonicalTargetUrifrom@adcp/sdk/signing(profile3.2).canonicalizeAgentUrlis now a re-export, so all ~75 call sites move together, and the read-only audit from #7968 imports the same function instead of carrying its own copy.One registry-local rule, which diverges from the spec on purpose: the path never ends in a slash.
https://agent.example/andhttps://agent.example/mcp/key ashttps://agent.exampleandhttps://agent.example/mcp. The one exception is a root path carrying a query (https://agent.example/?t=1), where the slash is kept so the query still reads as a query.RFC 3986 treats
/mcpand/mcp/as different resources and authorization matching still does — see "Identity vs authorization" below. For identity they are one agent, which is the maintainer's call and matches the data: every single registry-key collision in production is a trailing-slash pair. The keys that change are path case, trailing slash, default port, dot segments, percent-encoding, IDN host, fragment, and the bare-?case from adcp-client#3084.Identity vs authorization
The key folds a trailing slash. The spec-exact check does not. Both are true at once, and the seam is
declaredAgentUrl().catalog_agent_authorizations.agent_url_canonicaland the override mirror,agent_registry_metadata,agent_compliance_status,agent_verification_badges,agent_storyboard_status, the capability / health / inventory snapshots,agent_contexts,discovered_agents,member_profiles.agents[].urlAgentValidator.validateand its callers —find_agents_for_property(mcp-tools.ts),properties.ts— which compare against a publisher's liveadagents.jsonagent_publisher_authorizations,agent_property_authorizations; their readers compareagent_urlto the caller's input directly (#3177 dual-read)member_profiles.agents[].urlis the store that mixes both: it is the identity key and the URL handed to the validator. Folding it alone would re-introduce the #7829 regression — a publisher that lists/mcp/would stop authorizing an agent registered as/mcp/. SoAgentConfiggainsdeclared_url, set only when the key folded something away, and every authorization path readsdeclaredAgentUrl(agent). The member and admin write paths set it; the migration backfills it for every profile entry it folds;mcp_endpointuses it too, so the endpoint actually called is the one that was registered.server/tests/unit/registry-identity-vs-authorization.test.tspins this: a manifest listinghttps://a.example/mcp/authorizes/mcp/and not/mcp, while the two key identically. If that test ever goes green withagent.urlin thevalidate()call, everyadagents.jsonin the registry has been silently widened.declared_urlis member-supplied and feeds the authorization path, sogateAgentVisibilityForCalleronly accepts it whenregistryAgentUrlKey(declared_url) === url— i.e. when it really is another spelling of the same agent. Without that check a member could claimurlof their own agent anddeclared_urlof a well-authorized one, and the directory would report theirs as authorized wherever that one is.The directory answers spec-exactly too (maintainer decision, 2026-10-18).
catalog_agent_authorizationsstill KEYS by identity — the indexes stay onagent_url_canonicaland the folded key does the lookup work — but every per-agent read that answers "is this agent authorized" then restricts to the rawagent_urlvalues that are spec-exactly the same agent. The directory therefore cannot disagree with the #7829 validator in either direction.The mechanism is
specExactAgentUrls(agentUrl): one indexed read of the distinct raw spellings under the key, filtered in the app throughisSpecExactAgentMatch, passed to the query asAND v.agent_url = ANY($n::text[]). A single agent has a handful of spellings, so this is one small indexed read regardless of registry size, and[]correctly matches nothing.Nine read sites carry it:
getDomainsForAgentgetPublishersForAgentDetailGET /v1/agents/{url}/publishers)bulkGetFirstAuthForAgentsgetPropertiesForAgentgetPropertiesForAgentDomaingetPublisherDomainsForAgentgetAuthorizationSourceisPropertyAuthorizedForAgentAuthorizationSnapshotDatabase.getNarrow/registry/authorizationsper-agent pullvalidator.ts'snormalizeUrlnow calls straight through to the samespecExactAgentUrlthe directory uses, so the two implementations cannot drift apart.Deliberately NOT filtered:
getAllAgentDomainPairs, which is the crawler's bulk snapshot for diffingagent.discovered/agent.removedevents. It is an identity-level enumeration, not a per-agent authorization answer.No more SQL-side canonicalization. The spec algorithm needs IDN A-labels, dot-segment resolution and selective percent-decoding, none of which are practical in SQL. All 15 SQL expressions in
federated-index-db.tsare gone: seven queries take an app-computed key parameter, and four were restructured (bulkGetFirstAuthForAgentsjoins anunnest($raw, $keys)mapping,getAllAgentDomainPairsleaves the cross-arm fold to its one caller,reconcileAdagentsAuthorizationskeys both sides in the app inside oneFOR UPDATEtransaction, andsigning_keys_pinnedmoved out of the manifest JSONB walk intosigningKeysPinnedByPublisher).Migration 625 does three things:
NOT VALIDon purpose — they govern every write from here on, including the rewrite's own, but do not scan rows the rewrite has not reached, so a legacy key the new shape rejects cannot fail the deploy.agent_url/agent_url_canonicaltocaa_emit_event's modified-event detection. Without it a key rewrite emits nothing and every delta consumer of/api/registry/feedkeeps the old key forever, with nothing on the feed to say otherwise.v_effective_agent_authorizationsforbad_actoroverrides only, folding both sides the way the old key did. See "Design decisions" below — this one is a security fix, not a refactor.The data rewrite is a separate script,
migrate-registry-agent-url-keys.ts: dry-run by default,--applyto write,--only=<store>for staged remediation of a single blocked store. Tables are discovered frominformation_schemaand matched against two hand-maintained lists —REWRITE_STORES(identity stores, where a stale key makes the row unreachable) andREPORT_ONLY_STORES(append-only history, and tables whose readers match a raw URL). A table with anagent_urlcolumn in neither list makes the script refuse to run, so a new store can be neither silently rewritten nor silently left behind.Merge policy
A trailing-slash collision is resolved automatically, under a declared per-table policy in
server/src/scripts/registry-key-stores.ts. Each policy says which row survives and how each column is composed; everything not named comes from the winner, so a merged row is one coherent observation rather than a splice.agent_compliance_statuslast_checked_atagent_registry_metadatacompliance_opt_outandmonitoring_pausedany-true,check_interval_hoursmin,badge_requalification_generationmax + 1,created_atmin; the heartbeat lease is cleared so the survivor can be re-claimedagent_verification_badgesverified_atcreated_atmin,token_expires_atmaxagent_storyboard_statusrun_id, step counts and the first-failure detail move together from the winning runcatalog_agent_authorizationsexpires_atmax anddisputedany-true — a union of validity, not of grant:signing_keys,collectionsandauthorized_forcome from the winner alone, because unioning them would widen what the agent may doadagents_authorization_overridesbad_actor>correction>file_broken, then newestcreated_atmin — a merge can never downgrade a ban to a correction that later auto-expiresdiscovered_agentsdiscovered_at, furthestexpires_at, lowestprobe_failure_countNothing is dropped silently. Every merge lists the surviving row, the rows that do not survive, and every single field whose value the merged row does not carry. That list is printed in the dry run and again on apply.
There is still no policy — and therefore a block — for
agent_contexts(per-org OAuth tokens) andmember_profiles.agents(ownership), where a wrong merge hands an agent someone else's credentials or someone else's owner. Production has no collisions in either.It also refuses to write on a chain (one row's new key is another moving row's current key — collision-free in the end state, but Postgres checks a unique index per row, so the UPDATE aborts halfway), an unkeyable row, a unique index whose scope cannot be modelled, or a stranded suppression. Splits and lossy rows are reported without blocking. All table rewrites run in one transaction — per-store commits would be the wrong granularity, because
compliance-db.tsjoinsagent_registry_metadata→agent_compliance_status→agent_verification_badgesonagent_url.reconcile-agent-url-canonicalization.tsis deleted: it encoded the old algorithm in SQL alongsidecanonicalizeAgentUrlin TypeScript, so after this change its two halves would disagree. The new script subsumes it.Design decisions a maintainer should weigh
user:pass@. A registry key must never be derived from a URL carrying credentials — the raw URL is stored next to the key and surfaces in registry API responses. The writer logs and skips the row, so this fails closed.https://bücher.exampleandhttps://xn--bcher-kva.exampleget one registry row. Conversion is WHATWG's UTS-46 profile rather than the spec'sUseSTD3ASCIIRules=truepin, which lets", backtick,{and}through; the helper narrows the authority to the same character class the CHECK enforces, and an integration test fuzzes the printable range to keep the two in step. Full STD3 would additionally reject_and the sub-delims, which existing registry hosts rely on — deliberately not done.canonicalTargetUri's 3.2 profile appends the query byte for byte so an RFC 9421 signature base stays faithful to what was sent. A registry key cannot afford that:?x=%7e,?x=%7Eand?x=~are one URL under url-canonicalization step 6, and three keys would be three agents — and three ways to evade a suppression. The helper applies the decode-unreserved + uppercase-hex pass the SDK leaves out. This changes one assertion in the fix(registry): bind OAuth issuers and adopt SDK 15 #7968 audit test.bad_actorsuppressions keep matching on a case-folded key. Exact key equality means a banned agent walks free the moment the publisher edits one character of path case — a different key, so the suppression stops matching, with the override row still showing as active in the audit trail. (The trailing-slash half of this is now handled by the identity fold itself.) Migration 432's own comment says the constraint exists so "a compromised moderator cannot silently un-ban a bad actor"; exact matching would hand that power to the publisher instead.correctionandfile_brokensuppressions stay exact, because there the moderator is fixing one specific entry and hiding a genuinely different agent would be wrong./mcp≠/mcp/, which is what this PR did before the maintainer's 2026-10-17 decision. That version needed no merges at all (every production collision disappears) but leftfind_agents_for_propertymatching correctly only when the member and the publisher spelled the URL identically. The fold trades a one-time, reviewed merge of ~22 agents for one row per agent forever. Reverting to the spec-exact option means dropping the trailing-slash strip inregistryAgentUrlKey, the matching clause in migration 625's CHECK, and the merge policies; thedeclared_urlmachinery becomes unnecessary but harmless.= ANY(ARRAY[newKey, legacyKey]). I did not do it, and I think it would be wrong: a lookup for/Mcpwould also match a row keyed/mcp, which is the P0 bug this PR fixes, reintroduced in the fail-open direction for the duration. Unreachable-and-retried beats silently-authorized-against-the-wrong-agent. The cost is that the window is real; see the operational sequence below./mcpand/MCPas separate agents and each gets its own badge and compliance record.member_profiles.agentshas no cross-org uniqueness, so this was already unenforced for exact matches; the change widens it from one spelling to many. The fix is a claim check atmember-agents.tsregistration and is a product decision, not part of this issue.HARD STOP — do not merge before the production audit
This rewrites production registry keys. Everything below is read-only.
Step 1 — the exact collision gate
The earlier Step 2 gate grouped by a coarse key that rtrims every trailing slash, so it reported every
/mcpvs/mcp/pair as a merge risk whether or not the real key folded it. It is replaced by a checked-in script that groups by the registry key itself:The SQL it groups by lives in
server/src/db/registry-agent-url-key-sql.tsand is held to the TypeScript helper byserver/tests/integration/registry-agent-url-key-sql.test.ts— a corpus runs through both and the test fails on any disagreement outside the subset the twin declares it cannot compute (percent-encoding, dot segments, non-ASCII bytes; production has none of those, which is why the earlier run reported noBLIND-SPOT).Every group is labelled
rewrittenorreport-only, so a collision inagent_publisher_authorizations— which the migration does not touch — can no longer be mistaken for one the migration has to resolve.Expected output now: groups in the rewritten stores for the ~22 trailing-slash agents, each of which the migration folds under a declared policy, and nothing else. Specifically:
UNKEYABLElines → must be none. The earlier run had none.MERGElines → the trailing-slash pairs, which are now expected and handled. Cross-check the count against the dry run'smergeCountper store; they must match.report-onlylines → informational;agent_property_authorizationsandagent_publisher_authorizationskeep their raw values.NOT EXACT→ must be absent. If it appears, the twin cannot key those rows and the dry run is the only exact answer for them.Step 2 — the dry run
DATABASE_URL=… npx tsx server/src/scripts/migrate-registry-agent-url-keys.ts \ | tee /tmp/7830-dryrun.jsonSafe to proceed when
"blocked": false,unresolvedMergesis[],strandedSuppressionsis[], and every store'smerges[]reads the way you expect — each entry naming the surviving row, the rows that do not survive, and every value the merged row does not carry. That list is the review artifact; attach it to #7830.Step 3 — sizing
Step 4 — the deploy and the rewrite are one operation
fly.tomlruns migrations asrelease_command, then deploys web bluegreen and worker afterwards, rolling. The worker is the crawler and the compliance runner, so there is a window in which old machines write legacy keys and new machines write new keys to the same tables — and a live writer that cannot find a row does not just fail, it inserts a new one under the new key, converting a row the rewrite could have folded into a collision. So:If the dry run's
keysRejectedByConstraintis non-zero, step 1 is not optional: those rows carry a legacy key the relaxed CHECK rejects, and aNOT VALIDconstraint is still enforced on UPDATE, so any write touching one fails until the rewrite fixes it.Note what
VALIDATEat the end does and does not prove: it proves no row carries a shape the key can never take. It does not prove the rewrite is complete — an old key likehttps://x.example/mcpsatisfies the new predicate perfectly. Completeness is the dry run reporting zero rewrites and zero merges.Rollback
Migration 625 alone needs no undo — it only widens two CHECKs, extends an event condition, and widens a suppression join. Re-adding the old constraints will fail once any new-form key has been written, so the rollback for the code is a Fly release rollback, and it has to happen before such a key is written.
The rewrite is not reversible from the rewritten data alone for self-keyed stores, so take the artifact first:
Plus a Fly Postgres volume snapshot as the coarse net.
Also for the runbook
Migrations 441, 488, 541 and 570 contain one-shot backfills that compute keys with the old rule. They are already applied in production and released migrations are immutable, so a database rebuilt from scratch (staging, DR) replays them and lands old-form keys that nothing corrects — the rewrite is a script, not a migration. Migration 625's header says so; the bootstrap runbook should too.
Rebase scan (merge of
origin/main, 2026-10-18)The branch was 61 commits behind.
origin/mainis merged in at48a6908dd— clean, no conflicts — and I re-scanned the whole delta for anything this change has to classify.New
agent_urlreaders, writers, stores or canonicalization: none. Specifically, across68c90b62e..origin/main:server/src/db/is untouched on main since the merge base, so 625 is still the next number (main tops at 624)agent_urlagent_url_canonicalcanonicalizeAgentUrl/registryAgentUrlKey/canonicalTargetUricall sitesLOWER/RTRIM/BTRIMon a URL)Two
agent_urladditions appear in the delta outsidedist/, and neither is a registry site: a local test variable inhosted-compliance-echoed-release.test.tsholding a loopback URL passed tocomply(), and atarget_format_id.agent_urlin a storyboard lint fixture — that is the protocol'sformat-id.agent_urlfield, not the registry identity key. Everything else is releaseddist/schemasanddist/complianceartifacts.One thing the merge did change that matters here: main bumped
@adcp/sdk15.9.2 → 15.9.5, and bothregistryAgentUrlKeyandspecExactAgentUrldelegate to itscanonicalTargetUri. All 84 assertions across the key, SQL-twin, identity-vs-authorization, merge-policy and migration suites still pass unchanged on 15.9.5, so the canonicalization behaviour both halves rely on is the same.The gate and dry-run outputs are unaffected by the merge — nothing in it touches the key, the stored values, the migration or the merge policies.
Noticed, not touched
FederatedIndexDatabase.deleteExpiredcomparesagent_publisher_authorizations.agent_urlagainstdiscovered_agents.agent_urlandmember_profiles.agents[].url— a rewritten store against a report-only one, which would be a silent deletion path after the rewrite. It is dead code:federatedIndex.cleanupExpired()has no callers, and the third statement has thrownoperator does not exist: text = jsonbsince it was written, so it has never deleted anything. Making it work would create that deletion path, so it is left alone.Tests
server/tests/unit/registry-agent-url-key.test.ts— every canonicalization class and every rejection, plus idempotence and the frozen legacy algorithm.server/tests/unit/registry-agent-url-key-rewrite-plan.test.ts— one test per collision class: rewrite, merge, chain, split, unkeyable, lossy, multi-scope, and the no-uniqueness case.server/tests/unit/registry-identity-vs-authorization.test.ts— the seam:/mcpand/mcp/key identically, a manifest listing/mcp/authorizes/mcp/and not/mcp, and the registered spelling is what reaches the validator.server/tests/integration/registry-agent-url-key-sql.test.ts— the SQL twin the production gate runs on, checked against the helper over a corpus.server/tests/integration/registry-directory-spec-exact.test.ts— one case per read site, nine of them plus a cross-check: an authorization declared ashttps://a.example/mcp/is reported for that spelling and NOT forhttps://a.example/mcp, and the directory and theAgentValidatoragree on which is which. Neutering the filter makes all ten fail.server/tests/integration/registry-key-merge-policy.test.ts— each merge policy, seeded with the production collision shapes (root-slash and non-root pairs) across compliance status, registry metadata, badges, storyboard status, discovered agents: the right row survives, the composed values are the conservative ones, every dropped value is in the report, and a second run finds nothing left to fold.server/tests/integration/registry-agent-url-key-migration.test.ts— against a real Postgres: the relaxed constraints accept every key the helper can emit for any printable host byte and reject the forbidden shapes; the dry run reports without writing;--applyrefuses while blocked; the rewrite produces exactlyregistryAgentUrlKey(raw)for every changed class including tombstoned rows; a row whose raw URL moved under the plan is skipped rather than mis-keyed; an unclassifiedagent_urltable stops the run; abad_actorban still suppresses a path-case variant while acorrectionsuppression does not.Each fails if the fix is reverted.
Review
Reviewed by the
code-reviewer,security-revieweranddata-analystsubagents before opening. Everything they raised is either fixed above or called out in "Design decisions" — the STD3 host characters, the query percent-encoding, the Cf/bidi characters, the suppression lift, the apply-time race on a moved raw URL, the scope-ordinal bug, the chain collisions, theVALIDATE-vs-tombstones gap, the unmodelled-index blind spot, the blind rewriting of append-only tables, the per-store transaction granularity, the change-feed silence, and thereconcileAdagentsAuthorizationsatomicity.🤖 Generated with Claude Code