Skip to content

feat(portal): deactivate and reactivate users with their patches - #270

Merged
allisonmahmood merged 3 commits into
mainfrom
portal/257-deactivation-pick
Sep 16, 2026
Merged

allisonmahmood merged 3 commits into
mainfrom
portal/257-deactivation-pick

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Deactivating a user left admins to retire their patches separately, without seeing which tools would break. Reactivation had the same gap for restoring patches.

Company now links to pick pages where admins can keep the patches as they are, select some, or act on all. Confirmations recompute breakage for the exact selection, including off-source warnings on restore. User access changes and selected patch changes commit together or all roll back. Last-active-admin, company-scoping and same-origin checks remain in place.

Stacked on #269 (portal/256-confirmation-pages). This PR targets that branch, not main.

Closes #257.

Verification

  • pnpm test --maxWorkers=2: 925 tests passed across 80 files.
  • pnpm typecheck and pnpm lint passed.
  • Browser-verified desktop and mobile selection, confirmation, deactivation and reactivation flows.
  • Standards and specification reviews completed with no blocking findings.

Implemented with GPT-6 Astra in Oh My Pi.

@github-actions github-actions Bot added area:server Touches the server area area:docs Touches the docs area size:l 501-1,000 changed lines labels Sep 15, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed 7a6fec2 with git diff origin/portal/256-confirmation-pages...HEAD against #257. One pass, no subagents; merge blockers only.

Standards

No merge-blocking method or YAGNI findings. The change uses the shared HTML components and existing patch lifecycle operations. The optional outer transaction is explicitly required by #257, not speculative infrastructure.

Spec

No merge-blocking intent findings. The pick and confirmation flows, dependency-chain handling, reactivation warnings, atomic user/patch changes, last-active-admin checks, route move, and named documentation updates match #257.

Verification: all 70 tests passed across the three affected suites:

pnpm test packages/portal/src/PortalPages.test.ts packages/companies/src/Users.test.ts packages/auth/src/CompanyPage.test.ts --maxWorkers=2

Standards: 0 blocking findings, none to rank. Spec: 0 blocking findings, none to rank.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Opus review

Three-dot diff against origin/portal/256-confirmation-pages, head 7a6fec2. Two axes run as separate sub-agents per code-review, then three extra passes the request asked for. Standards sources: CLAUDE.md, .agents/skills/effect-service-conventions/SKILL.md, .agents/skills/ui-consistency/SKILL.md. Spec: #257, with #247 §10 and §4 as parent.

This is good work. The flow is correct, the tests are the ones the ticket named, and the docs surfaces all moved. Almost everything below is about one piece of machinery that shouldn't exist.


Standards

Hard — effect-service-conventions

packages/companies/src/Users.ts:73-84, 170-180, 204-235 — the optional transaction?: SqlClient.TransactionConnection.Service parameter and the inTransaction helper are redundant with Effect's own semantics.

node_modules/effect/dist/unstable/sql/SqlClient.js, makeWithTransaction:

const connOption = Context.getOption(services, options.transactionService);
const conn = connOption._tag === "Some" ? Effect.succeed([undefined, connOption.value[0]]) : options.acquireConnection;
const id = connOption._tag === "Some" ? connOption.value[1] + 1 : 0;
… (id === 0 ? options.begin(conn) : options.savepoint(conn, id))

sql.withTransaction already detects an ambient transaction, reuses the same connection and issues SAVEPOINT instead of BEGIN. So users.deactivate(ref) called from inside the portal's sql.withTransaction(run) (UserLifecyclePage.ts:227) already commits and rolls back with the outer transaction. The parameter's only observable effect is skipping one SAVEPOINT statement.

The diff proves this itself: patches.retire and patches.restore (packages/patches/src/Patches.ts:1817, 1850, both …, sql.withTransaction)) were given no such parameter, and UserLifecyclePage.ts:219-220 calls them bare — relying on exactly the nesting that Users was rebuilt to avoid. Two mechanisms for one property, in one function, eleven lines apart.

Users is now the only place in the repo that threads a connection by hand (grep -rn TransactionConnection packages --include=*.ts returns Users.ts and its dist only).

The skill's rule: "Production service construction must acquire Effect service dependencies from the environment with yield* Foo.Foo … Flag factories or constructors that accept Foo["Service"] … when that value is an implementation dependency owned by the service." The letter says constructors, so calling this a hard breach is a judgement call — but a Context.Service value owned by the SqlClient that Users already holds is being passed as a method argument, which is the thing the rule exists to stop.

The tell is in the test. packages/companies/src/Users.test.ts:231 "commits or rolls back lifecycle changes with the supplied outer transaction" has to strip the ambient service to observe anything:

// Remove inheritance so only the explicit connection can keep these writes in the transaction.
const withoutAmbientTransaction = Effect.updateContext((context: Context.Context<never>) =>
  Context.omit(sql.transactionService)(context)
);

A test that must disable inheritance to prove a parameter is a test for the parameter, not for a behaviour. Speculative Generality.

There is also a latent hazard worth one sentence: nested withTransaction ends with Context.getUnsafe(services, transactionSemaphore). inTransaction puts transactionService into context without that semaphore. Inside the portal the outer withTransaction supplied both, so it is fine today — but hand a stored transaction to Users.deactivate from a fiber outside the original scope and any nested withTransaction beneath it dies on getUnsafe. The API invites a call the type system cannot refuse.

Recommendation: delete the third parameter from all three methods, delete inTransaction, delete UserLifecyclePage.ts:132, and call users.deactivate(ref) / users.reactivate(ref). The atomicity test at PortalPages.test.ts:2005 should stay green unchanged; that is the test that actually matters.

UserLifecyclePage.ts:132 — consequence of the above. Option.getOrThrow(yield* Effect.serviceOption(sql.transactionService)) turns an absent service into an untyped defect at a seam where the type system could have carried the invariant. Goes away with the parameter.

Judgement — duplicated helpers

render.ts already has all three, module-private:

  • UserLifecyclePage.ts:22-25 notice is character-identical to render.ts:60-63 refusal.
  • UserLifecyclePage.ts:19-20 hidden duplicates render.ts:58-59 and diverges: it interpolates name raw where render.ts wraps it in escapeAttribute. Not exploitable (only literals are passed today), but the weaker copy is the one the next page will reach for.
  • UserLifecyclePage.ts:91-92 duplicates render.ts:339-340 confirmationAcknowledgement, dropping its checked re-render.

Export the three from render.ts.

Judgement — Repeated Switches

~25 action === "deactivate" branches. Honest split: in handle (:135-148, :187-195, :215-220) they are real behavioural forks and the shared pick → confirm → commit flow earns one module. In renderPick / renderConfirm (:40, :45-57, :71-94) they are almost entirely copy selection. One per-action record (verb, eligibleState, keepLabel, actLabel, allLabel, ackText, consequence) resolved once would remove roughly fifteen of them and make the two ~1500-character template literals legible. Worth doing; not a blocker.

Judgement — UI

Every class used is verified present in the shared set — btn/-primary/-quiet/-danger, field-checkbox, field-choice, list, list-row, note/-refused/-ok, pill/-progress, page-heading, supporting-text, confirmation-*, actions in packages/core/src/html.ts; portal-subpage in packages/portal/src/render.ts:16. No invented classes and no page-level overrides, so §12's component-set rule is satisfied. Four small things:

  • :94 <p class="note note-ok">Nothing breaks</p> has no role. ui-consistency: completed actions use role="status". The repo's only other note-ok (packages/integrations/src/ConnectionPage.ts:64) pairs it with role="status".
  • :50 pill pill-progress labels "Read by" — a semantic token repurposed for colour.
  • :82 a bare nested <ul> inside .confirmation-list > li; only the outer level is styled, so the inner list falls back to browser discs and indent.
  • :54 interpolates ${row.patch.state} unescaped where render.ts:82 escapes the same value. Typed union, so a divergence rather than a bug.

Hit every surface

Applied and hit: vocabulary and glossaries (portal/CONTEXT.md Pick page and Confirmation page, companies/CONTEXT.md Deactivation and Reactivation, CONTEXT-MAP.md both context lines and the Portal → relationship), docs/product.md § Ownership and deactivation, reverse states, served pages, and route ownership moved cleanly out of AuthPages.ts:169-172 with CompanyPage.Action narrowed to match. Not applicable: wire contract / docs/API.md, CLI and ADR-0004, dev loop, migrations, repo layout.


Spec

(a) Missing or partial: nothing material. Every bullet and every "Done when" item is implemented and tested — the badges; the three recomputed selections (PortalPages.test.ts:1808 chain-inside-selection, :1704 exact confirmation, plus the dependant-outside case); the transaction committing together and rolling back when the second retire fails, on an alternate layer (:2005 "rolls back the user and first retirement when the second retirement fails"); the no-live-patches shortcut; reactivation's warning (:1840); the last-active-admin refusal; /company's links (packages/auth/src/CompanyPage.test.ts).

Traced and confirmed correct:

  • "A user with no live patches goes straight to the confirmation" — :173 returns the pick only when eligible.length > 0, so a GET falls through to confirm() at :209. ✅
  • "Keep their patches live … deactivates at once, no second page" — choice === "keep" empties selectedIds (:162-168) and skips the confirm() return at :209, committing at :215-221. ✅
  • "the last-active-admin rule runs on GET and POST" — checkDeactivation at :136 runs before any render on both methods. Correctly not applied to reactivate, which cannot reduce the admin count. ✅
  • "after this the portal is their only caller" — users.deactivate / users.reactivate have exactly two non-test call sites, both UserLifecyclePage.ts:215-216. The one-click routes are gone from AuthPages.ts:169-172 and the CompanyPage.Action union. ✅

(b) Not asked for

  1. :130-131 takes the dependency advisory lock and SELECT id FROM patches WHERE company_id = … ORDER BY id FOR UPDATE over every patch in the company — on GET as well as POST. Rendering a pick page blocks every concurrent publish, retire and reassign in the company for the duration of the render. §10 asks a preview to lock nothing; only the commit needs it. See Method below.
  2. Users.checkDeactivation is a new public service method; §10 asked only that deactivate / reactivate accept an outer transaction.
  3. Refusals not in the spec: already-active / already-deactivated 409 (:139-143), "Choose whether to keep, select or act on all patches" 422 (:171-172), stale-selection 409 (:182-183).
  4. The reactivate pick page also lists the user's live and deleted patches as disabled rows; §10 asks for "the user's retired patches". Harmless and arguably kinder; flagging it as observed scope, not a defect.

(c) Implemented but wrong: none found. One cosmetic dead end: the confirmation reached by the no-live-patches shortcut still renders "Back to selection" (:94) pointing at the GET URL, which re-renders the same confirmation.

Checked and not a finding: the missing-acknowledgement refusal at :214 returns 409 rather than §5's 422 for validation failures — but the sibling confirmation pages already answer 409 for the same case (PortalPages.ts:344, 348), so this is consistent with the portal, not a deviation.


Intent — #257 versus what was done

Faithful, including the parts easy to fudge. The chain rule is implemented on the actual selection rather than approximated (:184-196): deactivation excludes dependants inside the selection, reactivation counts a source as intact when it is live or in the same restore selection — genuinely the mirror §10 asked for, and both directions are tested. force: true on :219-220 is right, not a shortcut: the page has already displayed and acknowledged exactly what refuseDependants / offSources would refuse, so re-refusing at the service would be the bug.

The one intent gap is the GET-path locking (Spec b1), which #257 did not ask for and which changes the cost of merely looking at a page.

Method — is the seam right?

The transaction seam: yes. One sql.withTransaction around the whole request handler (:227) is correct. The unit of work is the request, and putting the boundary there means the preview and the commit see one snapshot. Failures propagate out and roll the whole thing back; refusals return as values and commit nothing. That is the right shape, and the alternate-layer rollback test proves it.

What is wrong is only how the participants join it: Patches joins implicitly and for free, Users joins through hand-threaded plumbing. Same seam, two mechanisms. Remove the plumbing and the seam is unimproved and much smaller.

Portal coordinating Patches' lock protocol: no, not as written. :130 hand-writes

pg_advisory_xact_lock(hashtextextended('patchy:dependencies:' || …, 0))

which is a verbatim copy of packages/patches/src/Patches.ts:1079's lockDependencies. The lock-key string is Patches' private invariant. If Patches ever changes it, the portal silently stops ordering — and the failure is not a red test, it is a production lock-order cycle. :131 is the only place outside packages/patches that takes patch row locks at all.

The reasoning behind it is sound, and I checked it: reassign does take the patch row (manageable → FOR UPDATE OF patches) before its target-user FOR SHARE (Patches.ts const reassign), so patches-before-users is a real, consistent order, and ORDER BY id prevents cycles between concurrent portal calls. The comment at :128-129 is accurate. The problem is ownership, not correctness.

Two changes would fix both this and Spec b1:

  1. Give Patches the operation: patches.withCompanyLifecycleLock(companyId)(effect), exported beside the other lifecycle verbs. The key format stays inside the context that owns it, and the portal stops knowing how the lock is spelled.
  2. Take it only on the commit path. The GET render needs no lock; choice === "keep" and choice === "confirm" do. Today a pick-page render is a company-wide write barrier.

YAGNI

One clear violation, one note, and otherwise clean.

  • The optional-transaction parameter is the violation (Standards, hard). It is built for a caller that does not exist and a semantic Effect already provides. In fairness to the implementer: feat(portal): deactivation and reactivation with the user's patches, in one transaction #257 and Portal: finding and managing patches in the deployed stage #247 §10 explicitly asked for it — "Users.deactivate and Users.reactivate take an optional outer transaction and open their own only when none is given (the portal always passes one)". This is a spec that specified machinery rather than behaviour, and the PR delivered it exactly. The right fix is to amend §10 to state the property — deactivation and the selected retires commit together or not at all — and let withTransaction nesting supply it, as it already does for Patches. Worth doing before ci+docs(domain): the packed e2e through the lifecycle; the map after the portal #259 builds on the signature.
  • Note, not a finding: thirteen catchTags arms at :228-252 for errors this page cannot raise (InvalidDescription, ReservedName, VersionUnavailable, InvalidOwner, and HasDependants / SourcesOff, unreachable under force: true). This is forced: Patches.retire and restore both advertise the whole LifecycleError union (Patches.ts:201-213), so narrowing would leak an error to a 500. The root cause is the Patches signature, not this page. Worth a separate ticket if it keeps costing callers.
  • Everything else earns its place. checkDeactivation is a legitimate seam — the last-active-admin rule belongs inside Users, and the alternative is the portal counting admins. Its name is the weak part: Patches already has manageable and publishable for exactly this lock-and-validate-and-return shape, so deactivatable would read better and match the house style. Judgement call.
  • Minor asymmetry: deactivate goes through checkDeactivation, reactivate through (yield* users.list(…)).find(…) at :137. Since Users has no get(userId), the scan is the only option without adding one — worth noting rather than fixing here.
  • :139's if ((action === "deactivate") !== (user.deactivatedAt === null)) is a boolean XOR that takes a second read. const alreadyInTargetState = action === "deactivate" ? user.deactivatedAt !== null : user.deactivatedAt === null says it once.

Summary. Standards: one hard finding (the transaction parameter) plus three judgement clusters. Spec: nothing missing or wrong; one piece of unasked-for scope that matters (company-wide locking on GET). Intent is faithfully served and the transaction seam is in the right place. Neither blocking finding is about what the page does — both are about machinery around it, and both get smaller, not bigger, when fixed.

Reviewed by Claude Opus 5 (1M context) in Claude Code, standing in for grok build as first reviewer.

@allisonmahmood

allisonmahmood commented Sep 15, 2026 •

Copy link
Copy Markdown
Owner Author

Reviewed both conversation reviews, the Reviews tab, and inline review comments. The latter two contained no reviews or inline findings. Astra reported no blockers; the dispositions below address Opus's findings.

Fixed

  • Preview locking: GET pickers and POST selection previews no longer acquire dependency, patch-row, company-row or user-row mutation locks. Users.checkDeactivation is read-only. Commit requests still recompute the selection under locks, and Users.deactivate rechecks the last-active-admin rule under its company/user locks. The new socket regression holds the company mutation locks in another transaction: it timed out before the fix and passes for both deactivate and reactivate afterward.
  • Lock ownership: Patches.withCompanyLifecycleLock now owns the transaction and ordered company patch locks, reusing Patches' existing dependency-lock operation. Portal no longer copies the advisory-lock key or patch-row SQL. The argument is the acting user's id, matching the existing dependency-lock lookup.
  • Duplicated rendering helpers: the lifecycle page now uses render.ts's hidden-field, refusal and acknowledgement helpers. Hidden names and values share the existing escaping implementation.
  • Rendering consistency: "Read by" uses the neutral pill rather than a progress state; nested source warnings use confirmation-list; patch states pass through escapeHtml.
  • Shortcut navigation: a confirmation with no selected patches links back to Company instead of its own GET URL. The existing shortcut test now checks that destination.
  • State predicate readability: replaced the boolean comparison with the named alreadyInTargetState predicate.

Kept, with reasons

  • Per-action copy branches: two fixed actions do not need a copy-configuration record. The shared request flow and existing copy remain in place; the unclear state predicate was the readability fix worth making here.
  • No role="status" on "Nothing breaks": this describes a pre-action preview, not a completed action. The cited UI rule requires that role for completed actions, so it does not apply here. Refusals retain role="alert".
  • Preview guard and validation refusals: checkDeactivation keeps the last-admin rule in Users. Already-active/deactivated, malformed-choice and stale-selection refusals prevent misleading or stale submissions; they are not additional user workflows.
  • Disabled live/deleted rows on reactivation: they explain why those patches cannot be selected without allowing them to be restored. Reassigned patches remain excluded. No new lookup service or cosmetic guard rename is needed.
  • Lifecycle error handlers and acknowledgement 409: the advertised Patches error union requires those handlers; narrowing it would be unrelated service-contract work. The acknowledgement response matches the sibling confirmation pages.

Product behavior and terminology are unchanged. No wire-contract, CLI, migration, dev-loop, company-resource provisioning or repository-layout changes apply.

Verification

Current head: 596725802695c6bb1b130355f251accdd2a46805, pushed to portal/257-deactivation-pick. This commit removes the explicit transaction plumbing; the earlier preview-lock and rendering fixes remain in 7daf0dc.

  • pnpm exec vitest run packages/companies/src/Users.test.ts packages/portal/src/PortalPages.test.ts packages/auth/src/CompanyPage.test.ts --maxWorkers=2: all 71 tests passed, including ambient user/token commit and rollback, the Portal rollback of the user and first retirement when the second retirement fails, and standalone lifecycle calls.
  • pnpm typecheck passed, all 36 tasks; pnpm lint passed.
  • The previous rendering changes were browser-verified at 7daf0dc on desktop and mobile. This follow-up changes no HTML or user-facing behavior. No disposable runtime files remain.
  • CI on the current head: test (22), test (24), lint, postgres-concurrency, clerk-live, cli-smoke and dependency-review all passed. The separate label check passed too.
  • GitHub reports no required-check subset configured; all eight reported checks are green.

Rechecked conversation comments, review bodies and inline comments after the push; no new findings arrived. GitHub reports MERGEABLE and CLEAN at 596725802695c6bb1b130355f251accdd2a46805. No unresolved blockers. Ready to merge into the existing stacked base, portal/256-confirmation-pages; not merged here.

@allisonmahmood
allisonmahmood force-pushed the portal/256-confirmation-pages branch from 9438a39 to 0947073 Compare September 16, 2026 16:00
@allisonmahmood
allisonmahmood force-pushed the portal/257-deactivation-pick branch from 5967258 to fdc8c65 Compare September 16, 2026 16:00
@allisonmahmood
allisonmahmood force-pushed the portal/256-confirmation-pages branch from 0947073 to 30898ba Compare September 16, 2026 17:16
Base automatically changed from portal/256-confirmation-pages to main September 16, 2026 17:54
@allisonmahmood
allisonmahmood force-pushed the portal/257-deactivation-pick branch from fdc8c65 to 06ba077 Compare September 16, 2026 17:54
@allisonmahmood
allisonmahmood merged commit e6b06d1 into main Sep 16, 2026
8 checks passed
@allisonmahmood
allisonmahmood deleted the portal/257-deactivation-pick branch September 16, 2026 18:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:docs Touches the docs area area:server Touches the server area size:l 501-1,000 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(portal): deactivation and reactivation with the user's patches, in one transaction

1 participant