Skip to content

Phase 4: identity uniqueness - #1264

Merged
neuromechanist merged 18 commits into
feature/issue-1250-epic-account-tiersfrom
feature/issue-1254-phase4-identity-uniqueness
Sep 6, 2026
Merged

neuromechanist merged 18 commits into
feature/issue-1250-epic-account-tiersfrom
feature/issue-1254-phase4-identity-uniqueness

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1254
Part of #1250

Summary

One person, one account. An ORCID iD, an email address (case-insensitively) or a GitHub handle now backs at most one live NEMAR account. The database enforces it, the application refuses it first with a typed error that says what to do, and every write normalises the identifier so all three rules compare the same strings.

Production is the reason: rows 42 and 43 both carry ORCID 0000-0002-1974-1293 with orcid_verified=1. The oauth_identities row left 42 (an unlink, or an identity insert whose rollback did not run) while users.orcid stayed behind on it, so the second sign-up saw an unclaimed iD and made a second account.

Migration 0077 — flag, then partial-index

A plain CREATE UNIQUE INDEX ON users(orcid) fails on 42/43 and takes the deploy with it, and making it buildable would mean deleting or merging someone's real account inside a migration. So 0077 adds users.identity_conflict, flags every non-canonical duplicate, and creates the unique indexes as partial ones that exclude a flagged row.

  • ORCID canonical = the row holding the oauth_identities row, lowest id only if none does. In the 42/43 case the lowest id is the orphan, so "lowest id wins" would have crowned the row that cannot sign in.
  • Email canonical = lowest live id, compared COLLATE NOCASE.
  • Nothing is deleted, nothing is merged, and the migration is buildable on any catalog whatever it contains.
  • A flagged row still signs in, still owns its datasets, still reads normally; it loses only its claim on the identifier.
  • Statement (2) also canonicalises a legacy lowercase x check digit, narrowly (a GLOB matching only a bare iD), so a case variant cannot slip past an index that compares exactly.

Typed error codes (the website renders these)

Declared once in shared/contract/identity.ts with their messages, so the CLI, the website and the JSON message read the same wording:

code where
orcid_in_use ORCID finalize, link/relink callback, CLI signup
orcid_already_linked ORCID finalize (pre-existing; kept so the website is not broken)
orcid_linked_other link/relink callback (pre-existing)
email_in_use ORCID finalize, /auth/email/change/{request,verify}, CLI signup
github_in_use CLI signup
identity_conflict_remains POST /admin/users/:id/clear-identity-conflict

error deliberately carries different things on the two families of route, because different things read it and both are already right: browser-facing routes put the CODE there (the website reads it there, and email_in_use predates this phase), CLI signup keeps its short human label there because that is the field the CLI prints. code and message are purely additive on both.

Refusals and normalisation

  • ORCID finalize now refuses an iD held through users.orcid OR oauth_identities (it only checked the identity table), and refuses a case-variant email.
  • Link / relink consult findOrcidHolder before writing, so relink cannot take an iD off another account.
  • Unlink now clears users.orcid as well as orcid_verified. The citation value is re-derivable (a re-link refills it, and so does DOI enrichment); the false claim on an identifier is not worth keeping, and it is exactly the shape row 42 is in.
  • CLI signup refuses a duplicate ORCID (nothing checked this before) and a case-variant email, and its pre-checks run before the GitHub API call.
  • Email change compares case-insensitively at both request and verify.
  • Normalisation lives in one module (backend/src/services/identity.ts): email trimmed+lowercased, ORCID reduced to a bare iD with an uppercase check digit, GitHub handle trimmed with a leading @ stripped. PATCH /auth/profile now imports the GitHub rule instead of spelling it out again, and five hand-rolled copies of the email field schema collapse into one — which also fixes a latent bug: they ran .email() before their own trim, so a pasted " ada@lab.org " 400'd.

New surfaces

  • GET /admin/users/duplicates — groups live accounts sharing an identifier, marks the canonical row, and carries id / username / email / created_at / has_oauth_identity / dataset_count / identity_conflict per row.
  • POST /admin/users/:id/clear-identity-conflict — clears the flag only when no collision remains; 409 with the colliding rows otherwise.
  • nemar admin duplicates [--json] [--clear <id>] — a new top-level admin command (not a flag on admin users). Exits non-zero when a duplicate exists.
  • nemar auth profile — every identifier with its verification state, the access tier, and a "where to change each" footer. Always fetched, never cached: it is the command someone runs before changing an identifier.
  • GET /users/me gains status, email_verified, orcid_verified, given_name, family_name (all .optional() in the contract — absence renders as "unknown", never as "no").

ADR 0043

one person, one account: the flag-and-partial-index strategy and why (deploy safety, no deletion), self-service remediation first, manual merge last.

Testing

bun run lint, bun run typecheck clean. Offline (pure) tier: 4295 pass, 20 skip, 1 fail — the single failure is ADR index > ADR numbers are unique and gapless from 0001, by construction: 0042 belongs to phase 3 (#1253), which is landing in parallel. Same situation ADR 0041 documented, and it goes green at rebase. If 0042 lands first this ADR renumbers with it.

New tests, all real-engine (bun:sqlite behind realD1, real Hono dispatch, real bcrypt/HMAC/session issuance; the only external boundaries are local Bun.serve() stand-ins for ORCID and GitHub reached through the bindings production already uses to point at a mirror):

  • backend/test/identity-uniqueness-migration.test.ts (11) — the migration over a fixture carrying the 42/43 shape, a three-row case-variant email group, a pair colliding on both identifiers, a legacy lowercase check digit, clean rows and a tombstone. Asserts the whole-catalog property (every live group ends with exactly one unflagged row), both indexes and their DDL, that a later duplicate INSERT is refused, that a flagged duplicate can still be inserted, and that a flagged row stays readable.
  • backend/test/identity-refusals-route.test.ts (24) — every refusal at every entry point, plus normalisation and the unlink release.
  • backend/test/user-duplicates-route.test.ts (16) — the report and the clear endpoint. The canonical mark is asserted against the flags migration 0077 itself wrote, not against a second copy of the rule.
  • backend/test/users-me-profile-fields.test.ts (3) — the source of the new /users/me fields.
  • test/auth-profile-cli.test.ts (7), test/admin-duplicates-cli.test.ts (8) — real subprocess CLI runs against a local server. Classified into tier 2 by CI's TEST_API_URL|runCli\( grep (same as auth-status-upload-access.test.ts), but self-contained: verified passing with TEST_API_URL/TEST_ADMIN_API_KEY/TEST_USER_API_KEY unset. No live-backend file is touched by this phase.

Every new assertion was mutation-checked, one perturbation at a time, reverting between each (20 mutations; each failed the expected test and only that test). Two survivors were found and fixed rather than explained away:

  1. Reverting signup's email pre-check to exact case changed nothing observable, because 0077's index then rejects the INSERT and the catch returns the same 409 body. The pre-checks run before validateGitHubUsername, so the tests now also assert no GitHub API call was spent — which is the real reason for that ordering (a duplicate must not cost a rate-limited request against a shared token).
  2. Dropping email_verified from /users/me left every CLI test green, because the CLI test serves its own payload. backend/test/users-me-profile-fields.test.ts was added to pin the source.

Two pre-existing things the work turned up and fixed:

  • GET /admin/users/duplicates initially 404'd: Hono runs every matching handler in registration order, and GET /users/:username matches /users/duplicates. registerUserDuplicateRoutes now runs first, with the reason recorded at the call site. Caught by driving the HTTP route rather than the handler.
  • backend/test/web-email-verification.test.ts's seedWebUser reused one ORCID iD for every row, so it was manufacturing exactly the duplicate this phase forbids. Each seeded row now gets its own iD.

Rollout note

Row 42 was soft-deleted in production on 2026-09-05, after this branch was written. Consequences for the deploy:

  • 0077's ORCID pass will find no duplicate there. Its flagging predicate is deleted_at IS NULL, so the tombstoned row is not a candidate and row 43 keeps 0000-0002-1974-1293 unflagged. The migration is still correct for that catalog — it flags nothing where there is now nothing to flag — and the fixtures keep the 42/43 shape because it is the shape the RULES have to handle, not a claim about today's rows.
  • The email pass and the check-digit pass are unchanged; whatever case-variant email pairs exist are still flagged.
  • The deploy is not newly risky. The CREATE UNIQUE INDEX statements were the part that could have failed on live data, and the deletion only removes candidates.
  • One leftover, forward-fixed only. That delete ran through the tombstone as it was, which nulled users.orcid but left orcid_verified = 1 — the same half-state that produced 42/43 in the first place. user-tombstone.ts now clears both, so no future tombstone can do it, but row 42 keeps the stale flag until someone repairs it. It is inert (every reader gates on deleted_at IS NULL), so I have not added a repair statement to a migration that is already proven against real D1. One line if it is wanted:
    UPDATE users SET orcid_verified = 0 WHERE deleted_at IS NOT NULL AND orcid IS NULL AND orcid_verified = 1;

Notes for the reviewer

  • Migration 0077's statement (3b) reads identity_conflict while writing it. That is safe because it only ever flags non-minimum rows, so the minimum it computes stays unflagged and is order-independent; the reasoning is written on the statement and pinned by the "colliding on BOTH identifiers" fixture.
  • The ORCID index compares exactly (per the issue), not COLLATE NOCASE. Statement (2) plus normalisation at every write is what makes that complete rather than a gap.
  • normalizeOrcid in ORCID finalize is unreachable as a repair (verifyPending already rejects a non-canonical iD) and is kept as a guarantee about what gets stored. Commented as such.
  • Rebased onto Phase 3 (9176d311). 0076/0042 are theirs, 0077/0043 are mine, and the ADR index's gapless check is green. Both phases' behaviour is kept everywhere they overlapped; the github_in_use refusals now run behind Phase 3's tri-state validateGitHubUsername, so a GitHub outage is a 503 rather than a duplicate-identity 409.
  • bun run migrations:d1-check is new and is a release check, not per-PR CI (~1 min). It exists because migration 0077 shipped a 79-character GLOB that bun:sqlite runs and D1 rejects at 50 — every test green, deploy aborted mid-file. AGENTS.md's release section names it.
  • Every users-by-email lookup is now COLLATE NOCASE. Normalising the request is not sufficient on its own: it only fixes rows this phase creates, and the ~600 rows already in the catalog are stored exactly as typed. The one deliberate exception is the non-production seed-web-user test fixture, which stays exact-case so a fixture cannot silently adopt a pre-existing legacy row; it already fails loudly if its own INSERT/UPDATE disagree.

@github-actions

github-actions Bot commented Sep 6, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR1264

Version: 0.9.16-PR1264.29fcda5
Commit: 29fcda5


🤖 Updated on each push.

@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review round 1 — all 16 items addressed

Every item fixed on this branch; nothing declined as a false positive. Six commits, a65196e5..f2db9d4c.

Offline tier 4336 pass, 20 skip, 1 fail (the expected ADR index > gapless from 0001, 0042 is phase 3's). bun run lint, bun run typecheck, and bun run migrations:d1-check clean. The two CLI files verified again with TEST_API_URL/TEST_ADMIN_API_KEY/TEST_USER_API_KEY unset: 17 pass.


A. Deploy blocker

1. The 79-char GLOB. Confirmed exactly as reported, and worse than a lint issue — statement 1 (the ALTER) lands first, so the deploy aborts with the column added and nothing flagged.

I probed the limit rather than guessing: D1 accepts a 50-character LIKE/GLOB pattern and rejects a 51-character one. Replaced with a pattern-free shape plus one 8-character GLOB:

 WHERE LENGTH(orcid) = 19
   AND SUBSTR(orcid, 19, 1) = 'x'          -- BINARY collation: 'X' must NOT match
   AND SUBSTR(orcid, 5, 1) = '-'
   AND SUBSTR(orcid, 10, 1) = '-'
   AND SUBSTR(orcid, 15, 1) = '-'
   AND REPLACE(SUBSTR(orcid, 1, 18), '-', '') NOT GLOB '*[^0-9]*';

Validated per-value on real D1 (0000-...-353x matches; the uppercase form, an all-digit iD, a URI, a garbage prefix, a non-digit body and a misplaced hyphen all do not).

Two proof runs, both recorded in the migration header:

  1. bun run migrations:d1-check — fresh local D1, all 78 migrations replayed, catalogue matches bun:sqlite (84 objects, 22 tables).
  2. 0001–0075 applied, then the 42/43 ORCID pair + a case-variant email pair + a lowercase-x iD seeded, then 0077. Result: orphan flagged, identity-backed row kept, higher-id case variant flagged, check digit canonicalised, and a later duplicate INSERT refused with UNIQUE constraint failed: users.orcid / users.email — the COLUMN name, which independently confirms isUniqueViolationOn's matching works against real D1 and not just bun:sqlite.

The recurrence guard is scripts/d1-migration-check.ts (bun run migrations:d1-check, ~1 min, added to AGENTS.md's release section, not per-PR CI). It replays each migration through wrangler d1 execute --local one file at a time, then diffs the object inventory and every table's PRAGMA table_info against bun:sqlite. Verified it catches the original bug: restoring the 79-char GLOB gives FAILED on 0077_identity_uniqueness.sql / LIKE or GLOB pattern too complex.

One thing worth flagging: wrangler d1 migrations apply cannot do this replay, for a pre-existing reason. Wrangler text-scans a file for BEGIN TRANSACTION/COMMIT and refuses it as "several transactions" even when the words appear only in a -- comment — true of 0021, 0031, 0063, 0064, 0071, 0075 and 0077. The script strips whole-line comments before handing the SQL over; the catalogue diff is what proves the strip changed nothing. Also found: D1 caps compound SELECT terms (a 7-branch UNION ALL fails).

B. Everyday regression

2. Fixed. All three schemas use emailFieldSchema; all three lookups are COLLATE NOCASE.

Worth recording why the obvious test does not work. My first version signed up mixed-case and retrieved with another case — and it passed with the exact-case lookup restored, because once the request is normalised, an exact-case lookup still matches every row this phase creates. The regression only exists for the ~600 rows already in the catalog, stored as typed. The tests therefore seed a legacy row directly (John.Smith@Example.ORG + a real hashPassword) and never go through signup. Mutation-checked: reverting the lookups now fails 3 tests.

Also fixed the same latent bug the reviewer flagged in 10 — the signup inline schema now imports emailFieldSchema too.

C. Races and typed errors

3. Finalize's INSERT is wrapped; users.email → 409 email_in_use, users.orcid → 409 orcid_in_use, anything else rethrows.

4. clear-identity-conflict's UPDATE is wrapped; a UNIQUE hit re-reads the candidates so the 409 names who it actually collided with, rather than echoing the stale (empty) pre-check list.

5. Both linkIdentity and relinkIdentity call sites map a lost race to fail("orcid_in_use"). The helper claimedByAnother accepts both spellings — users.orcid (0077) and oauth_identities.provider_subject (0050) — because which one fires depends only on which statement of the batch got there first, so handling one and not the other would return a typed refusal or a 500 at random. Fixed the false comment at linkIdentity.

6. Only isOrcidIdentityUniqueViolation produces orcid_already_linked. The users row is still deleted either way (it has committed, and an account with an email and no ORCID login is a dead end the user cannot fix), but a non-uniqueness failure now returns 500 with a distinct log line instead of telling someone to go unlink an iD from an account that does not exist.

7. All three PATCH /auth/profile sites use identityRefusal("github_in_use") / isUniqueViolationOn.

All four are tested with real fault injection (CREATE TRIGGER ... RAISE(ABORT, '<exact SQLite text>'), the pattern phase 2 used), plus a paired negative in each case: an unrelated 'disk I/O error' must still be a 500 / the generic orcid_error redirect, so the catch cannot be widened into "every failure is a collision".

D. Correctness

8. normalizeOrcid now anchors both ends and accepts exactly two shapes — a bare iD, or an orcid.org/sandbox.orcid.org URI. garbage0000-0002-1825-0097 is rejected at signup (400, no row).

9. Real bug, fixed. canonicalIdOf now prefers an unflagged row for every identifier, falling back to the migration's rule only when a group has none. A flagged row is invisible to the partial indexes, so it holds nothing however low its id is. New compound fixture (one pair colliding on both iD and email, identity row on the higher id) asserts every group marks the unflagged row canonical.

10. Both done — the admin fixture route and the signup inline schema use emailFieldSchema.

11. Used rather than deleted: signup's two hand-rolled GitHub queries now go through findGithubHolder. Its deleted_at IS NULL makes no difference for GitHub (the tombstone NULLs the handle, so no tombstone can hold one) — the note comment in signup was rewritten to say that precisely, rather than leaving the reader to reconcile it with the username check that still must see tombstones.

E. Tests

All added:

  • Migration re-run idempotency (statements 2 onward replayed onto their own output; identical rows, both indexes present, no error) — with a guard so a reshaped file cannot make the slice silently replay nothing.
  • backend/test/identity-conflict-still-usable.test.ts — a row flagged by the real migration signs in through POST /auth/login and reads GET /users/me behind the real authMiddleware, keeps its iD and its upload grant. Row 42 is a real person's account; if the flag locked people out the migration would be a silent mass revocation.
  • backend/test/identity-unique-violation.unit.test.ts (12 tests) — including the exact hazard you named. msg.includes("users.email") was true for users.email_verified; the helper now parses the column list out of the message. Both engines' spellings are covered, including D1's : SQLITE_CONSTRAINT (extended: ...) suffix.
  • dataset_count excludes sandbox datasets; clear-identity-conflict 403 for a non-admin.
  • CLI: a malformed report and one missing flagged_count both fail loudly rather than printing "No duplicate accounts." — the one output that must never appear by accident.
  • Registration-order assertion in the inventory test. Reversing the order in admin/index.ts now fails 11 tests; previously the route just quietly stopped existing.

Every new assertion mutation-checked, one perturbation at a time with a revert between each. All caught, each by the expected test.

F. Comments and docs

13. Replaced with your wording. Confirmed the claim was false — RegExpRouter throws UnsupportedPathError for this path set and the fallback router matches in registration order.

14. orcid_already_linked is marked DEPRECATED ALIAS with "do not add new emitters", referencing nemarOrg/website#305, which I opened with the full code list and the removal condition. Also noted in ADR 0043.

15. All three. The "re-derivable by the DOI enrichment pass" claim was false — grep confirms only finalize, linkIdentity and relinkIdentity write users.orcid. The ADR now says the way back is a manual re-link, and says so is the smaller cost; it also records that an earlier draft claimed otherwise. 0041 cross-reference made precise. Migration header carries the "statements 2 through the trailing lookup index" wording and the 0076-is-phase-3 numbering note.

16. profile added to the nemar auth row, duplicates to nemar admin, ADR 0043 to the load-bearing list, and a release-checks paragraph for migrations:d1-check explaining the bun:sqlite/D1 divergence that motivates it.


Ready for the phase-3 rebase; 0076/0042 are theirs and my numbers stand.

@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review round 2 — items 17-19

All three fixed in 01b718ea. Offline tier 4339 pass, 20 skip, 1 fail (the expected ADR gapless check). bun run lint, bun run typecheck, bun run migrations:d1-check, and the two CLI files with all TEST_* vars unset (17 pass) are clean. Each fix mutation-checked; all three reverts caught.


17. /auth/code/request and /auth/code/verify

Confirmed and fixed. Both users lookups are now email = ? COLLATE NOCASE AND deleted_at IS NULL.

This one was the worst of the set to leave in: /code/request answers an unmatched address with the masked 200 and sends nothing (the deliberate #595 no-enumeration behaviour), so a legacy user gets a page saying "if your email is on file you'll get a code shortly" and then silence — indistinguishable from a typo, and unreportable. It is also the flow most of the production population actually uses.

Test seeds a legacy Legacy.User@Nemar.test row directly and drives the real round trip with legacy.user@nemar.test:

  • request returns a real dev_code and not dev_skip: "unregistered" (that field is the exact symptom, so it is asserted by name);
  • verify then signs that row in, asserted by returned user id;
  • an address matching no account still gets dev_skip: "unregistered" and no code — the guard against fixing this by making the lookup so loose it stops distinguishing anything, and against losing Gate /auth/code/request: don't send codes to unregistered emails #595's property while doing it.

Reverting either lookup fails these (2 and 1 respectively).

Email-change path checked as instructed: already correct. /email/change/{request,verify} both go through findEmailHolder (NOCASE) from round 1, and the write is UPDATE users SET email = ? WHERE id = ? — keyed by id, not by address.

I swept the whole backend rather than just those two. Every FROM users ... WHERE email = ? is now NOCASE except one deliberate hold-out: the non-production seed-web-user test fixture (admin/users.ts). It stays exact-case so a fixture cannot silently adopt a pre-existing legacy row, and it already fails loudly with an explicit 500 if its own INSERT and UPDATE disagree. Called out in the PR body so it is not read as an oversight. The auth_codes lookups stay exact too — that table's email is an internal key always written from the normalised value in the same request, not an identity.

18. stripFullLineComments invariant

Added verbatim, plus the reason the catalogue diff cannot cover it (it compares schema, not the data a migration writes).

19. Tombstone leaving orcid_verified = 1

Fixed in USER_TOMBSTONE_MASK_SQL, with the comment naming why it matters: orcid = NULL with orcid_verified = 1 is a row asserting it proved an iD it no longer has — the same half-state that made 42 and 43 two accounts for one person, reached here by a second route. Every writer of one now writes the other (this statement, unlink, linkIdentity/relinkIdentity).

test/user-soft-delete.unit.test.ts gains the column, seeds it as 1 (a column left at its default would pass even if the mask typo'd the name — the file's own stated rule), and asserts 0. Test renamed to "zeroes both verified flags". Removing the line from the mask fails it.

Rollout note

Added to the PR body. Summary: row 42's soft delete means 0077's ORCID pass now finds no duplicate in production — its predicate is deleted_at IS NULL, so the tombstone is not a candidate and row 43 keeps the iD unflagged. The email and check-digit passes are unaffected, and the deploy is not newly risky (the CREATE UNIQUE INDEX statements were the only part that could fail on live data, and the deletion only removes candidates).

The fixtures deliberately keep the 42/43 shape: it is the shape the rules have to handle, not a claim about today's rows.

One leftover I did not action, deliberately. That delete ran through the old tombstone, so row 42 still carries orcid_verified = 1 with orcid = NULL. It is inert — every reader gates on deleted_at IS NULL — and repairing it means adding SQL to a migration already proven against real D1, so I would rather you decide than have me quietly re-open that. One line if wanted:

UPDATE users SET orcid_verified = 0 WHERE deleted_at IS NOT NULL AND orcid IS NULL AND orcid_verified = 1;

Nothing further from me. Waiting on Phase 3 (#1265) to merge, then I rebase — 0076/0042 are theirs, my 0077/0043 stand, and the ADR gapless check goes green with it.

@neuromechanist
neuromechanist force-pushed the feature/issue-1254-phase4-identity-uniqueness branch from 01b718e to 29fcda5 Compare September 6, 2026 02:54
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Rebased onto Phase 3 (9176d311)

Force-pushed with --force-with-lease: 01b718ea → 29fcda55, 18 commits replayed. Base is feature/issue-1250-epic-account-tiers, GitHub reports MERGEABLE.

Offline tier 4449 pass, 20 skip, 0 fail — test/adr-index.unit.test.ts is green. bun run lint, bun run typecheck, and bun run migrations:d1-check (now 79 migrations, catalogue matches bun:sqlite) all clean. Both phases' CLI files with all TEST_* unset: 38 pass.

Conflicts, and how each was resolved

File Conflict Resolution
backend/src/services/profile.ts Both sides added an import to the same line Kept both — normalizeGithubHandle from ./identity and Phase 3's validateUsernameFormat from ./username
src/lib/api/admin.ts Both added type imports; both appended a trailing block sharing one );\n} closer Kept both import groups; split the shared closer so Phase 3's backfillUsernames and my getUserDuplicates/clearIdentityConflict each close properly, and restored my section's // ==== header
test/admin-route-inventory.unit.test.ts Both added rows to EXPECTED_ENTRIES Kept both. Rewrote my comment: it claimed "RegExpRouter matches the static segment first", which round 1 established is false — it now says the route is reachable only because registerUserDuplicateRoutes runs first
src/commands/admin.ts Both appended a new command block Took Phase 3's file, re-appended my duplicates block verbatim, re-added my three imports (clearIdentityConflict, getUserDuplicates, DuplicateGroup)
src/commands/auth.ts Both appended a new command block, interleaved badly by git Same approach: Phase 3's file plus my profile block verbatim, plus errorDetail on the errors import
.context/decisions/README.md Both added an index line Kept both, 0042 then 0043
backend/src/routes/auth-web.ts /code/verify's user SELECT — Phase 3 added three columns, I added COLLATE NOCASE Kept both: the three columns and the NOCASE equality

The tri-state, as instructed

validateGitHubUsername now returns found / not_found / unavailable, and every github_in_use refusal runs behind it:

  • CLI signup (auth.ts) — Phase 3's unavailable → 503 and not_found → 400 guards come first, then const githubUser = githubLookup.user, then my findGithubHolder(db, githubUser.login) + identityRefusal("github_in_use").
  • PATCH /auth/profile (auth-web.ts) — same order, with my identityRefusal on both the pre-check and the canonical-login re-check, and isUniqueViolationOn(err, "github_username") in the catch (Phase 3's username UNIQUE handling sits right after it).

A GitHub outage is now a 503 "try again in a few minutes", never a duplicate-identity 409 — the two failures can no longer be confused in either direction.

Two things the rebase turned up

1. backend/test/profile-username-route.test.ts failed (4 tests). Phase 3's seedUser defaults every row to one shared ORCID_ID, so any test seeding two rows died on UNIQUE constraint failed: users.orcid. The fixture was manufacturing exactly the duplicate 0077 exists to prevent — the same thing I found in web-email-verification.test.ts in round 1, in a file written in parallel. Each seeded row now gets a distinct iD from a counter reset per test; callers passing an explicit orcid are untouched. All 28 pass. This is the constraint working, not a regression — worth knowing that any future fixture reusing an iD across live rows will now fail loudly at the seed.

2. AGENTS.md rows were incomplete. Phase 3 updated the user-flow paragraph (kept intact) but not the CLI tables or the load-bearing ADR list. Since I was editing those exact lines I completed them rather than leaving them wrong: added request-upload-access to the nemar auth row, backfill-usernames to nemar admin, and ADR 0042 to the load-bearing list alongside 0040 and 0043. Flagging it because it is Phase 3 content I touched, not mine.

Verified after the auto-merges

Git auto-merged several files it did not flag, so I checked the result rather than trusting it. No Phase 3 content was lost anywhere — git diff origin/...HEAD shows deletions only on the four lines I deliberately edited. Confirmed present: all five signup identity checks, all three NOCASE lookups in auth.ts (the only exact-case users-by-email lookup left in the backend is the deliberate seed-web-user fixture), the claimedByAnother race mapping in auth-orcid.ts, my five /users/me fields alongside Phase 3's, and my optional contract fields alongside theirs.

Housekeeping

Migration 0077's header and ADR 0043's numbering note both said "until phase 3 is rebased in, the gapless check fails by construction". That is now past tense and wrong, so both were rewritten to record that 0076/0042 and 0077/0043 coexist and touch disjoint columns. Route-total pin updated 100 → 102 (Phase 3's two entries plus mine).

Nothing outstanding from my side.

@neuromechanist
neuromechanist merged commit fa82400 into feature/issue-1250-epic-account-tiers Sep 6, 2026
12 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-1254-phase4-identity-uniqueness branch September 6, 2026 02:58

This branch was previously deployed

1 inactive deployment
npm — 29fcda55 Deployed Sep 6, 2026 by neuromechanist via publish #2320
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant