Skip to content

feat(workspace): add permanent workspace deletion - #246

Merged
imshashank merged 21 commits into
mainfrom
codex/feat-workspace-deletion
Aug 8, 2026
Merged

imshashank merged 21 commits into
mainfrom
codex/feat-workspace-deletion

Conversation

@imshashank

@imshashank imshashank commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • add an administrator-only danger zone for permanently deleting the active workspace
  • show a fresh, server-computed deletion inventory and require the exact case-sensitive workspace name
  • lock normal workspace access as soon as deletion is confirmed, safely drain outstanding upload capabilities, and expose a durable retry flow
  • remove the complete workspace database graph and exact object-storage prefix while preserving shared users and data in other workspaces
  • disconnect realtime clients and recover each client into a surviving workspace or workspace creation

Safety and authorization

  • the API always targets the authenticated session's current workspace and accepts no caller-supplied workspace id, slug, or storage prefix
  • shared server policy grants org:delete only to workspace administrators
  • marker, readiness, and final database phases lock the organization and current member rows, then recheck the current role and confirmation inside each transaction
  • the first phase commits organization.deletion_requested_at, which blocks normal web, realtime, MCP, upload, invite, public-doc, and public-attachment access
  • final cleanup waits for the later of every recorded upload expiration plus completion grace and the deletion marker plus one full URL lifetime and completion grace
  • the marker-based 30-minute drain covers a presigned target whose attachment insert or transaction commit failed
  • the retry endpoint remains available to administrators, and pending workspaces remain discoverable only for an administrator retry

Data and storage cleanup

  • the dialog counts members, teams, projects, issues, documents, stored files and versions, integrations, and webhooks
  • it identifies nested comments, attachments, activity, notifications, automations, saved views, cycles, labels, workflow states, credentials, and other cascade-owned records
  • a schema regression requires every direct organization_id foreign key to cascade from organization.id
  • active workspace pointers are cleared, while user, account, passkey, avatar, session, and other-workspace records are preserved
  • exact-prefix storage cleanup runs without an open database transaction, followed by a short cascaded-delete transaction; storage, statement, or commit failure leaves the durable retry marker intact
  • S3-compatible cleanup uses the exact <organizationId>/ prefix, bounded batches, current objects, historical versions, and delete markers
  • partial responses and malformed pagination fail closed, while providers that explicitly lack the version API use current-object cleanup

Migration and deployment

  • preserve the latest main migration as 0001 and add this feature as migration 0002
  • add nullable attachment.upload_expires_at with a conservative rolling-deploy default and backfill
  • add nullable organization.deletion_requested_at for durable, fail-closed retries
  • versioned AWS buckets require s3:ListBucketVersions and s3:DeleteObjectVersion in addition to existing list and delete permissions

Verification

  • ORBIT_TEST_LANE=workspace_deletion_final10 bun run verify
  • all package test suites passed, including 237 shared tests, 538 services tests, 757 core tests, 161 database tests, and 1,689 web tests
  • all nine package typechecks passed
  • lint, comment policy, source-byte policy, runtime import policy, and dependency checks passed
  • the complete migration chain applied successfully to an empty disposable database and produced all three expected migrations
  • focused regressions cover failed upload registration after URL issuance, exact protection boundaries, transaction failures, idempotent storage retries, access lockout, tenant isolation, and UI retry behavior

Notes

This PR adds the deletion capability only. It does not invoke deletion against any deployed workspace, and it does not modify the protected noveum.ai organization.

@imshashank
imshashank requested a review from pulkitxm as a code owner August 8, 2026 17:25
@vercel

vercel Bot commented Aug 8, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
orbit Ready Ready Preview Aug 8, 2026 8:57pm

Request Review

@coderabbitai

coderabbitai Bot commented Aug 8, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds administrator-only permanent workspace deletion with exact-name confirmation, upload draining, transactional database cleanup, S3 object and version deletion, access blocking, realtime invalidation, client recovery, API routes, and settings UI.

Changes

Workspace deletion

Layer / File(s) Summary
Deletion contracts and persistence
packages/shared/*, packages/db/*, packages/services/src/storage/types.ts, packages/services/src/storage/key.ts
Adds deletion permissions, confirmation validation, control-message variants, deletion timestamps, upload expiry fields, and safe organization storage prefixes.
Storage inventory and cleanup
packages/services/src/storage/s3.ts, packages/services/tests/storage/*, docs/configuration.md, docs/self-hosting.md
Adds paginated object and version summaries, batched prefix deletion, provider fallbacks, and required S3 permissions.
Core deletion and write protection
packages/core/src/org/*, packages/core/src/content/*, packages/core/tests/org/*, packages/core/tests/content/*
Adds transactional deletion, row locking, upload-drain checks, tenant cleanup, retry behavior, and blocking of writes and invitations during deletion.
Access blocking and realtime invalidation
packages/realtime-server/*, packages/core/src/realtime/publisher.ts, apps/web/src/lib/auth/principal.ts, apps/web/src/lib/api/handler.ts, apps/web/src/lib/realtime/provider.tsx
Rejects pending-deletion memberships, publishes organization deletion events, closes affected connections, and recovers clients to another workspace or workspace creation.
Deletion API and settings flow
apps/web/src/app/api/organizations/current/deletion/route.ts, apps/web/src/features/settings/workspace-danger-zone.tsx, apps/web/src/app/(app)/settings/general/page.tsx, apps/web/src/app/(app)/layout.tsx
Adds summary and deletion endpoints, administrator-only danger-zone controls, exact-name confirmation, pending-state handling, and post-deletion navigation.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

  • Noveum/orbit#4: Extends organization, membership, invite, and realtime behavior introduced there.
  • Noveum/orbit#5: Extends shared storage APIs and S3 driver behavior.
  • Noveum/orbit#115: Overlaps in realtime authentication and control-message handling.

Suggested reviewers: pulkitxm

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely identifies the main change: adding permanent workspace deletion.
Description check ✅ Passed The description directly explains the workspace deletion feature, its safeguards, cleanup behavior, migration changes, and verification.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/feat-workspace-deletion

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot added documentation Docs, the README, or anything that explains Orbit tests Test coverage and test infrastructure area: web The Next.js app and its UI area: realtime The socket, the hub, scopes and fan-out area: database Schema, migrations, queries, seed area: policy Roles, permissions and authorization labels Aug 8, 2026
Comment thread apps/web/src/lib/realtime/provider.tsx Resolved
@imshashank

Copy link
Copy Markdown
Contributor Author

Review loop 1

Reviewed all 39 changed files from main, including authorization, transaction and lock ordering, the complete organization foreign-key graph, storage pagination and version cleanup, API behavior, realtime invalidation, dialog state and accessibility, migration rollout, generated metadata, and regression coverage.

Confirmed problems and fixes

  1. High: stale administrator authority could survive into deletion. The service checked org:delete before opening the transaction but did not re-read or lock the caller's membership. A principal resolved immediately before a demotion or removal could retain stale authority. Fixed by locking the current member row and reapplying shared policy inside the organization-locked deletion transaction before storage is touched. Added a stale-principal regression.
  2. High: exact URL expiry left a late upload race. S3 authenticates a presigned request when it begins, so a PUT started before expiration can finish after expiration and potentially after prefix cleanup. Fixed by adding a 15-minute upload-completion grace after the last target expires, returning the protected boundary through availableAt, enforcing it again inside the transaction, and explaining the window in the dialog. Added raw-expiry and exact-grace-boundary regressions.
  3. Medium: server confirmation was not truly exact. The shared validator trimmed the supplied workspace name, so direct API callers could include surrounding spaces despite the exact-name contract. Fixed by rejecting surrounding whitespace and preserving the comparison bytes. Added validator coverage.
  4. Medium: version pagination did not require both S3 markers. A truncated ListObjectVersions response without NextVersionIdMarker could repeat or incompletely summarize a key's history. Fixed by failing closed unless both AWS continuation markers are present. Added separate missing-key-marker and missing-version-marker regressions.
  5. Documentation: two PR-body claims were inaccurate. The body named the prefix as org/{organizationId}/ and described nested categories as individually counted. Corrected it to <organizationId>/ and distinguished counted categories from explicitly identified cascade-owned categories.

No other confirmed problems remained after this loop.

Verification

  • ORBIT_TEST_LANE=workspace_deletion bun run verify
  • 529 service tests passed
  • 746 core tests passed
  • 1,626 web tests passed
  • all other package tests, typechecks, lint, comment policy, source-byte policy, runtime import policy, and dependency checks passed

@imshashank
imshashank force-pushed the codex/feat-workspace-deletion branch from 9eef112 to fcc5db8 Compare August 8, 2026 18:45
@github-actions github-actions Bot added area: mcp The MCP server, its tools and its OAuth area: auth Sign-in, sessions, passkeys, OAuth labels Aug 8, 2026
@imshashank
imshashank force-pushed the codex/feat-workspace-deletion branch from fcc5db8 to 7ad4c20 Compare August 8, 2026 19:02
@imshashank

Copy link
Copy Markdown
Contributor Author

Review loop 2

Reviewed all 64 changed files again after loop 1, including every deletion phase, cross-system failure boundary, pending-workspace ingress, public and authenticated read path, upload capability lifetime, migration, UI retry state, documentation, and the complete rebased diff against the latest main.

Confirmed problems and fixes

  1. Critical: irreversible storage cleanup was not atomic with the database commit. A final commit failure could leave the database workspace alive after its files were deleted. Fixed with a durable two-phase deletion marker. All fallible database mutations now run before exact-prefix cleanup, storage deletion is the last transaction operation, and a storage or commit failure leaves a fail-closed retry state. Added storage-failure, database-failure, and idempotent-retry regressions.
  2. Critical: a failed cleanup could return the workspace to normal use. That allowed new records or files to recreate data between retries. Fixed by preserving organization.deletion_requested_at independently of final cleanup and rejecting ordinary access while it exists.
  3. High: pending deletion was not enforced at every ingress. Closed gaps in web API and page contexts, layout prefetching, realtime tickets and membership revalidation, MCP token resolution, upload registration, inline uploads, organization writes, and invite acceptance. Added explicit package-level regressions.
  4. High: public content could remain reachable during a failed retry. Published docs, sitemap entries, and public attachment resolution now join through a non-deleting organization and fail closed while cleanup is pending.
  5. High: a presigned upload URL could outlive its guard row. registerUpload issues the external capability before its attachment transaction commits. If the insert or commit failed, deletion had no row from which to learn the URL expiry. Fixed by immediately locking the workspace on the first confirmed deletion, then waiting one complete 15-minute URL lifetime plus the 15-minute completion grace before storage cleanup. The final boundary is the later of this drain and every recorded target guard. Added an integration regression that injects a PostgreSQL failure after URL issuance, proves no attachment row exists, proves early cleanup is blocked, and proves cleanup succeeds at the exact boundary.
  6. Medium: administrators could become stranded from a durable retry. Normal organization lists now hide pending workspaces, while an explicit administrator retry listing keeps them discoverable after a sign-out or workspace switch. Non-administrators still cannot see them.
  7. Medium: the initial dialog blocked before it could quiesce the workspace. A tracked upload made the first confirmation unavailable while new uploads could continue. The first exact-name confirmation can now commit the deletion marker; only pending retries are disabled until availableAt.
  8. Low: the implementation plan described the obsolete one-phase upload guard. Updated the design, implementation plan, deployment details, and PR description to document the durable marker, 30-minute untracked-capability drain, pending access lock, retry behavior, and exact storage ordering.
  9. Test infrastructure: the catchup suite teardown could hang after successful assertions. The test forced a five-second connection shutdown timeout that could leave the hook unresolved. Replaced it with a clean awaited connection close. The isolated database suite and the full repository suite both terminate normally.

Investigated review concern

The organization-forbidden realtime close intentionally enters workspace recovery. Every producer of that terminal close means the active workspace is no longer usable, whether from deletion, membership removal, or fail-closed revalidation. The client never reconnects to that tenant; it activates a surviving accessible workspace or opens workspace creation. No change was needed.

Verification

  • rebased cleanly onto main at e7a67c10736bb56f14d69b758f888c66e656f2cf
  • ORBIT_TEST_LANE=workspace_deletion_final5 bun run verify
  • 3,611 tests passed across all packages
  • all nine package typechecks passed
  • lint, comment policy, source-byte policy, runtime import policy, and dependency checks passed

No confirmed problem remains from this loop. The branch is now waiting on the fresh GitHub checks for commit 7ad4c205c578d19df1d0790ae0575404724c1b4a.

@imshashank

Copy link
Copy Markdown
Contributor Author

Final review and rebase audit

This is the third complete review pass after the two documented adversarial loops.

Problems found and fixed:

  1. Upload attachment authorization was happening after storage configuration was initialized. A guest could receive a storage configuration error instead of the required authorization failure. Storage construction now happens only after the parent and workspace authorization checks.
  2. Concurrent changes on main claimed migration number 0001, while this branch also carried a migration numbered 0001. The branch is now rebased on the latest main, main's snapshot and journal are preserved exactly, and this feature is migration 0002.
  3. The rebased feature snapshot briefly placed the deletion marker in main's immutable snapshot rather than the feature snapshot. The marker now exists only in 0002; a structural comparison confirms 0002 differs from 0001 only by attachment.upload_expires_at and organization.deletion_requested_at.

Verification after the fixes:

  • ORBIT_TEST_LANE=workspace_deletion_final10 bun run verify passed
  • all package tests passed, including 235 shared, 161 database, and 1,676 web tests
  • all nine package typechecks passed
  • lint, comment policy, source-byte policy, runtime import policy, and dependency checks passed
  • migrations 0000, 0001, and 0002 applied successfully to an empty disposable database
  • the fresh database contained main's web_vital table, the deletion marker, and the 15-minute upload expiry default

No unresolved review findings remain. This PR changes code only and has not deleted or modified any deployed workspace.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (10)
apps/web/tests/features/settings/workspace-danger-zone.test.tsx (1)

98-102: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a surrounding-whitespace case to the confirmation test.

This test pins case sensitivity only. The deletion flow also rejects a name with surrounding whitespace. If someone adds a .trim() to the component input, no test in this file fails, and the exact-match guarantee degrades silently.

💚 Proposed additional assertion
     await user.type(screen.getByLabelText('Type Nova to confirm'), 'nova');
     expect(confirm).toBeDisabled();
     await user.clear(screen.getByLabelText('Type Nova to confirm'));
+    await user.type(screen.getByLabelText('Type Nova to confirm'), ' Nova ');
+    expect(confirm).toBeDisabled();
+    await user.clear(screen.getByLabelText('Type Nova to confirm'));
     await user.type(screen.getByLabelText('Type Nova to confirm'), 'Nova');
     expect(confirm).toBeEnabled();

As per coding guidelines: "A feature is incomplete until it has tests that would fail if the feature broke."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/tests/features/settings/workspace-danger-zone.test.tsx` around lines
98 - 102, Add a surrounding-whitespace assertion to the confirmation test near
the existing case-sensitivity checks: verify that values such as “ Nova ” remain
disabled, preserving the exact-match requirement and ensuring trimming the
component input would fail the test.

Source: Coding guidelines

packages/services/tests/storage/storage-prefix.test.ts (1)

11-16: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Import the prefix helpers directly instead of casting the module namespace.

The cast at Lines 11-14 asserts that assertSafePrefix and storagePrefixFor exist on the storage index. If the index stops re-exporting them, the type checker stays silent and the test fails at runtime with an unclear error. Import the helpers from the module that defines them, or from the index as plain named imports so the type checker enforces the contract.

♻️ Proposed import
-import * as storage from '../../src/storage/index.ts';
-
-const expectedStorage = storage as typeof storage & {
-  readonly assertSafePrefix: (prefix: string) => string;
-  readonly storagePrefixFor: (organizationId: string) => string;
-};
-const { assertSafePrefix, storagePrefixFor } = expectedStorage;
-const { S3StorageDriver } = storage;
+import { assertSafePrefix, storagePrefixFor } from '../../src/storage/key.ts';
+import { S3StorageDriver } from '../../src/storage/s3.ts';

As per coding guidelines: "Use strict types: do not use any or non-null assertions".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/services/tests/storage/storage-prefix.test.ts` around lines 11 - 16,
Remove the expectedStorage cast and import assertSafePrefix and storagePrefixFor
as direct named imports from their defining module or the storage index. Update
their usage to reference the named imports while retaining the S3StorageDriver
import, so TypeScript verifies that both helpers are actually exported.

Source: Coding guidelines

packages/services/src/storage/s3.ts (1)

252-304: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Bound the delete-and-relist loops.

Both loops re-list the prefix after every delete batch and rely on the listing becoming empty. If a provider reports a successful batch but keeps returning the same keys, or if new objects keep arriving under the prefix, the loop never exits and the deletion request never returns. Add a maximum iteration count and fail with a storage error when it is reached.

♻️ Proposed guard
 async function deleteCurrentObjects(
   client: S3Client,
   bucket: string,
   prefix: string,
 ): Promise<void> {
-  while (true) {
+  for (let pass = 0; pass < MAX_DELETE_PASSES; pass += 1) {
     const page = await client.send(
       new ListObjectsV2Command({ Bucket: bucket, Prefix: prefix, MaxKeys: MAX_DELETE_OBJECTS }),
     );
     const listed = listedObjects(page.Contents ?? [], prefix);
     if (listed.length > 0) {
       await deleteObjects(
         client,
         bucket,
         listed.map((entry) => ({ Key: entry.key })),
         'Object storage could not delete every workspace file.',
       );
       continue;
     }
     if (page.IsTruncated === true) {
       throw internal('Object storage returned an incomplete workspace file listing.');
     }
     return;
   }
+  throw internal('Object storage could not delete every workspace file.');
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/services/src/storage/s3.ts` around lines 252 - 304, Bound the retry
loops in deleteCurrentObjects and deleteVersionedObjects with a maximum
iteration count. Increment the count for each list/delete cycle, and when the
limit is reached, throw the established internal storage error instead of
continuing to relist indefinitely; preserve the existing successful completion
and truncated-listing behavior.
packages/db/tests/schema/organization-cascade.test.ts (1)

33-36: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Make the failure message identify the offending tables.

toEqual([]) prints the whole row objects on failure, but the count assertion toBeGreaterThan(30) gives no context when a new table is added without the cascade. Consider asserting on a mapped list of table names so a failure names the table directly.

♻️ Proposed clearer assertion
-    expect(rows.length).toBeGreaterThan(30);
-    expect(
-      rows.filter((row) => row.referencedTable !== 'organization' || row.deleteAction !== 'c'),
-    ).toEqual([]);
+    expect(rows.length).toBeGreaterThan(30);
+    expect(
+      rows
+        .filter((row) => row.referencedTable !== 'organization' || row.deleteAction !== 'c')
+        .map((row) => row.tableName),
+    ).toEqual([]);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/db/tests/schema/organization-cascade.test.ts` around lines 33 - 36,
Update the cascade validation assertion around the rows filtering in the
organization cascade test to map offending rows to their table-name field before
asserting emptiness, so failures identify the tables lacking the expected
cascade. Keep the existing row filter and count assertion behavior unchanged.
apps/web/tests/lib/realtime/provider.test.ts (1)

156-164: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

The fixed microtask tick count makes this test brittle.

handleTerminalClose starts recovery without returning the promise, so the test drains it with three await Promise.resolve() calls. The count matches the current number of awaits inside recoverWorkspaceAfterForbidden. If an await is added or removed in the implementation, this test fails without a behavior change, or asserts before recovery completes.

Let the gate signal completion instead of counting ticks.

♻️ Proposed refactor
-    handleTerminalClose(ORGANIZATION_FORBIDDEN_CLOSE_CODE, session.gate, workspace.gate);
-    await Promise.resolve();
-    await Promise.resolve();
-    await Promise.resolve();
+    const activated = new Promise<void>((resolve) => {
+      settle = resolve;
+    });
+    handleTerminalClose(ORGANIZATION_FORBIDDEN_CLOSE_CODE, session.gate, workspace.gate);
+    await activated;

workspaceGateReturning can call settle at the end of setActive.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/tests/lib/realtime/provider.test.ts` around lines 156 - 164, Replace
the three fixed Promise.resolve microtask waits in the terminal-close test with
completion signaling through workspaceGateReturning: have its setActive
implementation invoke settle after recovery-related updates finish, then await
that gate before asserting workspace.calls, location.href, and session.calls.
apps/web/src/lib/realtime/provider.tsx (1)

40-40: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use z.looseObject() instead of .passthrough().

This repo uses Zod 4.4.3, where .passthrough() is legacy; replace it with the top-level constructor so the same change later avoids a deprecation warning.

♻️ Proposed refactor
-const activationSchema = z.object({ error: z.unknown().optional() }).passthrough();
+const activationSchema = z.looseObject({ error: z.unknown().optional() });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/src/lib/realtime/provider.tsx` at line 40, Update the
activationSchema declaration to use Zod’s z.looseObject() constructor instead of
chaining .passthrough(), preserving the existing error field and acceptance of
unknown properties.
packages/core/tests/content/attachment-service.test.ts (1)

86-100: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Scope the lock probe to the organization row to avoid a false positive.

waitForDatabaseLock counts every backend in the current database that waits on any lock. Bun runs test files concurrently, so an unrelated concurrent test that waits on a lock satisfies the probe. The assertion expect(first).toBe('lock') at Line 354 then passes even when registerUpload did not wait for the organization row. Filter by the blocked relation, or by the pid that this connection blocks, so the probe proves the intended wait.

♻️ Proposed narrowing with `pg_blocking_pids`
-async function waitForDatabaseLock(client: ReturnType<typeof postgres>): Promise<void> {
-  const deadline = Date.now() + 5_000;
-  while (Date.now() < deadline) {
-    const rows = await client<{ waiting: number }[]>`
-      select count(*)::int as waiting
-      from pg_stat_activity
-      where datname = current_database()
-        and pid <> pg_backend_pid()
-        and wait_event_type = 'Lock'
-    `;
-    if ((rows[0]?.waiting ?? 0) > 0) return;
-    await pause(10);
-  }
-  throw new Error('The upload did not wait for the organization row lock.');
-}
+async function waitForDatabaseLock(client: ReturnType<typeof postgres>): Promise<void> {
+  const deadline = Date.now() + 5_000;
+  while (Date.now() < deadline) {
+    const rows = await client<{ waiting: number }[]>`
+      select count(*)::int as waiting
+      from pg_stat_activity
+      where datname = current_database()
+        and pid <> pg_backend_pid()
+        and wait_event_type = 'Lock'
+        and pg_backend_pid() = any(pg_blocking_pids(pid))
+    `;
+    if ((rows[0]?.waiting ?? 0) > 0) return;
+    await pause(10);
+  }
+  throw new Error('The upload did not wait for the organization row lock.');
+}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/tests/content/attachment-service.test.ts` around lines 86 -
100, Update waitForDatabaseLock to detect only lock waits caused by the
organization-row lock, rather than counting all locks in the current database.
Narrow the pg_stat_activity query using the relevant blocked relation or
pg_blocking_pids for the connection holding that organization lock, while
preserving the existing timeout and success behavior used by the assertion
around registerUpload.
packages/core/tests/org/organization-deletion-service.test.ts (2)

25-61: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Import the deletion service directly instead of casting the module namespace.

Lines 48-61 assert a structure onto core and Lines 25-46 re-declare DeletionSummary and DeletionResult locally. The cast makes the test compile even if deleteOrganization or getOrganizationDeletionSummary is removed, renamed, or given a different signature; the break then surfaces as a runtime failure rather than a typecheck failure. The service is already re-exported from packages/core/src/index.ts, and every other test in this file imports its subject directly (registerUpload, createDoc, createIssue). Import the two functions and their result types from the service module so the compiler checks the contract.

♻️ Proposed direct import
-import * as core from '../../src/index.ts';
+import {
+  deleteOrganization,
+  getOrganizationDeletionSummary,
+} from '../../src/org/organization-deletion-service.ts';
-const expectedCore = core as typeof core & {
-  readonly getOrganizationDeletionSummary: (
-    principal: Principal,
-    driver: StorageDriver,
-    now?: Date,
-  ) => Promise<DeletionSummary>;
-  readonly deleteOrganization: (
-    principal: Principal,
-    input: unknown,
-    driver: StorageDriver,
-    now?: Date,
-  ) => Promise<DeletionResult>;
-};
-const { deleteOrganization, getOrganizationDeletionSummary } = expectedCore;
 const deletionDrainMilliseconds = (UPLOAD_URL_TTL_SECONDS + UPLOAD_COMPLETION_GRACE_SECONDS) * 1000;

Remove the local DeletionSummary and DeletionResult interfaces and use the types the service exports. The Principal import then becomes unused.

As per coding guidelines: "Use strict TypeScript; avoid any and non-null assertions".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/tests/org/organization-deletion-service.test.ts` around lines
25 - 61, Replace the `expectedCore` namespace cast and local
`DeletionSummary`/`DeletionResult` interfaces with direct imports of
`deleteOrganization`, `getOrganizationDeletionSummary`, and their exported
result types from the deletion service module (via the existing public export).
Update the test references to use those imports directly and remove the
now-unused `Principal` import, preserving strict type checking without `any` or
non-null assertions.

Source: Coding guidelines


144-170: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the shared database-lock test helpers. Both files define identical databaseUrl, pause, and waitForDatagbaseLock helpers; only the thrown message differs. The shared root cause is a missing test-support helper for lock-wait probing, so a future fix to the probe query must be applied twice.

  • packages/core/tests/org/organization-deletion-service.test.ts#L144-L170: move databaseUrl, pause, and waitForDatabaseLock into the shared test-support module and accept the failure message as a parameter, then import them here.
  • packages/core/tests/content/attachment-service.test.ts#L74-L100: delete the local copies and import the shared helpers, passing the upload-specific failure message.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/tests/org/organization-deletion-service.test.ts` around lines
144 - 170, Extract the duplicate databaseUrl, pause, and waitForDatabaseLock
helpers from
packages/core/tests/org/organization-deletion-service.test.ts#L144-L170 and
packages/core/tests/content/attachment-service.test.ts#L74-L100 into the shared
test-support module, adding a failure-message parameter to waitForDatabaseLock.
Remove both local helper copies, import the shared helpers in each test, and
pass the organization-deletion and upload-specific failure messages
respectively.
packages/core/tests/org/organization-service.test.ts (1)

116-121: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Generate the member id with newId().

Line 117 hardcodes 'member_pending_workspace'. Every other record in this suite uses the generated-id convention. Use newId() so the insert cannot collide if the row survives a reset or if the case is duplicated.

♻️ Proposed fix
     await db.insert(schema.member).values({
-      id: 'member_pending_workspace',
+      id: newId(),
       organizationId: deleting.organization.id,
       userId: member.id,
       role: 'member',
     });

Based on learnings: "Within packages/core, use the established newId() convention for generating IDs for newly added records."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/tests/org/organization-service.test.ts` around lines 116 - 121,
Replace the hardcoded id in the member insert with a generated id from newId(),
following the existing convention in this test suite and preserving the rest of
the member record unchanged.

Source: Learnings

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/web/src/features/settings/workspace-danger-zone.tsx`:
- Around line 19-44: Move deletionSummarySchema, summaryResponseSchema, and
deletionResponseSchema into `@orbit/shared`, exporting their inferred types
alongside the schemas. Remove the client-local definitions and import the shared
schemas and types in this component and the corresponding deletion route
handler, ensuring both continue parsing the same API payloads.

In `@docs/superpowers/plans/2026-08-08-workspace-deletion.md`:
- Line 31: Update the migration references in the workspace deletion plan’s Task
2 to use the checked-in 0002_glossy_mister_sinister migration and matching
journal entry instead of the 0001_*.sql placeholder, ensuring the plan does not
instruct creation of a duplicate or out-of-order migration.
- Around line 360-368: The deletion flow currently performs storage cleanup
inside the database transaction. Update
docs/superpowers/plans/2026-08-08-workspace-deletion.md:360-368 and
docs/superpowers/specs/2026-08-08-workspace-deletion-design.md:75-81 so the
durable deletion marker is committed first, paginated or bounded
driver.deletePrefix cleanup runs outside the transaction, and a short final
transaction removes the organization and related database state.
- Line 3: Remove the agentic workflow instruction line from the plan document,
including its references to “agentic workers” and superpowers skills. Leave the
remaining implementation plan and task-tracking steps unchanged.

In `@packages/core/src/org/organization-deletion-service.ts`:
- Around line 229-250: The organization storage cleanup currently runs inside
the transaction; restructure the deletion flow around the transaction callback
so the database deletion commits before invoking driver.deletePrefix. Preserve
the persisted deletionRequestedAt state and use it to make storage cleanup
retryable after commit, including when cleanup or commit fails, while keeping
the existing organization-selection and session-update behavior in the
transaction.

In `@packages/core/tests/org/member-service.test.ts`:
- Around line 51-59: Ensure the shared workspace organization’s
deletionRequestedAt state is isolated for both pending-deletion tests: in
packages/core/tests/org/member-service.test.ts:51-59 and
packages/core/tests/content/doc-service.test.ts:297-309, confirm the workspace
is reseeded per test through resetDatabase or clear deletionRequestedAt to null
after the test; apply the appropriate cleanup at both sites so later tests using
resolvePrincipal, getPublishedDoc, or listPublicDocs retain access.

In `@packages/services/src/storage/s3.ts`:
- Around line 160-168: Update both inventory loops to reject empty continuation
markers as well as undefined values when the response is truncated. In the S3
object listing flow, validate NextContinuationToken before assigning
continuationToken; apply equivalent non-empty validation to NextKeyMarker and
NextVersionIdMarker in the versioned listing flow, preserving the existing
incomplete-listing error behavior.

---

Nitpick comments:
In `@apps/web/src/lib/realtime/provider.tsx`:
- Line 40: Update the activationSchema declaration to use Zod’s z.looseObject()
constructor instead of chaining .passthrough(), preserving the existing error
field and acceptance of unknown properties.

In `@apps/web/tests/features/settings/workspace-danger-zone.test.tsx`:
- Around line 98-102: Add a surrounding-whitespace assertion to the confirmation
test near the existing case-sensitivity checks: verify that values such as “
Nova ” remain disabled, preserving the exact-match requirement and ensuring
trimming the component input would fail the test.

In `@apps/web/tests/lib/realtime/provider.test.ts`:
- Around line 156-164: Replace the three fixed Promise.resolve microtask waits
in the terminal-close test with completion signaling through
workspaceGateReturning: have its setActive implementation invoke settle after
recovery-related updates finish, then await that gate before asserting
workspace.calls, location.href, and session.calls.

In `@packages/core/tests/content/attachment-service.test.ts`:
- Around line 86-100: Update waitForDatabaseLock to detect only lock waits
caused by the organization-row lock, rather than counting all locks in the
current database. Narrow the pg_stat_activity query using the relevant blocked
relation or pg_blocking_pids for the connection holding that organization lock,
while preserving the existing timeout and success behavior used by the assertion
around registerUpload.

In `@packages/core/tests/org/organization-deletion-service.test.ts`:
- Around line 25-61: Replace the `expectedCore` namespace cast and local
`DeletionSummary`/`DeletionResult` interfaces with direct imports of
`deleteOrganization`, `getOrganizationDeletionSummary`, and their exported
result types from the deletion service module (via the existing public export).
Update the test references to use those imports directly and remove the
now-unused `Principal` import, preserving strict type checking without `any` or
non-null assertions.
- Around line 144-170: Extract the duplicate databaseUrl, pause, and
waitForDatabaseLock helpers from
packages/core/tests/org/organization-deletion-service.test.ts#L144-L170 and
packages/core/tests/content/attachment-service.test.ts#L74-L100 into the shared
test-support module, adding a failure-message parameter to waitForDatabaseLock.
Remove both local helper copies, import the shared helpers in each test, and
pass the organization-deletion and upload-specific failure messages
respectively.

In `@packages/core/tests/org/organization-service.test.ts`:
- Around line 116-121: Replace the hardcoded id in the member insert with a
generated id from newId(), following the existing convention in this test suite
and preserving the rest of the member record unchanged.

In `@packages/db/tests/schema/organization-cascade.test.ts`:
- Around line 33-36: Update the cascade validation assertion around the rows
filtering in the organization cascade test to map offending rows to their
table-name field before asserting emptiness, so failures identify the tables
lacking the expected cascade. Keep the existing row filter and count assertion
behavior unchanged.

In `@packages/services/src/storage/s3.ts`:
- Around line 252-304: Bound the retry loops in deleteCurrentObjects and
deleteVersionedObjects with a maximum iteration count. Increment the count for
each list/delete cycle, and when the limit is reached, throw the established
internal storage error instead of continuing to relist indefinitely; preserve
the existing successful completion and truncated-listing behavior.

In `@packages/services/tests/storage/storage-prefix.test.ts`:
- Around line 11-16: Remove the expectedStorage cast and import assertSafePrefix
and storagePrefixFor as direct named imports from their defining module or the
storage index. Update their usage to reference the named imports while retaining
the S3StorageDriver import, so TypeScript verifies that both helpers are
actually exported.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 2bdc3189-e68e-4d9d-981a-99bbd3327eaf

📥 Commits

Reviewing files that changed from the base of the PR and between b276ebe and eb76ef7.

📒 Files selected for processing (64)
  • apps/web/src/app/(app)/layout.tsx
  • apps/web/src/app/(app)/settings/general/page.tsx
  • apps/web/src/app/api/organizations/current/deletion/route.ts
  • apps/web/src/app/invite/[token]/page.tsx
  • apps/web/src/features/settings/workspace-danger-zone.tsx
  • apps/web/src/lib/api/handler.ts
  • apps/web/src/lib/auth/principal.ts
  • apps/web/src/lib/realtime/provider.tsx
  • apps/web/tests-support-issue-routes.ts
  • apps/web/tests/app/(app)/layout.test.tsx
  • apps/web/tests/app/api/docs/duplicate.test.ts
  • apps/web/tests/app/api/docs/home.test.ts
  • apps/web/tests/app/api/issues/delete-issue.test.ts
  • apps/web/tests/app/api/organizations/current/deletion/route.test.ts
  • apps/web/tests/app/settings/general/page.test.tsx
  • apps/web/tests/features/settings/workspace-danger-zone.test.tsx
  • apps/web/tests/lib/auth/principal.test.ts
  • apps/web/tests/lib/realtime/provider.test.ts
  • docs/configuration.md
  • docs/self-hosting.md
  • docs/superpowers/plans/2026-08-08-workspace-deletion.md
  • docs/superpowers/specs/2026-08-08-workspace-deletion-design.md
  • packages/core/src/content/attachment-service.ts
  • packages/core/src/content/doc-service.ts
  • packages/core/src/index.ts
  • packages/core/src/org/invite-service.ts
  • packages/core/src/org/member-service.ts
  • packages/core/src/org/organization-deletion-service.ts
  • packages/core/src/org/organization-lock.ts
  • packages/core/src/org/organization-service.ts
  • packages/core/src/realtime/publisher.ts
  • packages/core/tests/content/attachment-service.test.ts
  • packages/core/tests/content/doc-service.test.ts
  • packages/core/tests/org/invite-service.test.ts
  • packages/core/tests/org/member-service.test.ts
  • packages/core/tests/org/organization-deletion-service.test.ts
  • packages/core/tests/org/organization-service.test.ts
  • packages/core/tests/realtime/publisher.test.ts
  • packages/db/drizzle/0002_glossy_mister_sinister.sql
  • packages/db/drizzle/meta/0002_snapshot.json
  • packages/db/drizzle/meta/_journal.json
  • packages/db/src/schema/content.ts
  • packages/db/src/schema/org.ts
  • packages/db/tests/apply-catchup.test.ts
  • packages/db/tests/schema/index.test.ts
  • packages/db/tests/schema/organization-cascade.test.ts
  • packages/mcp-server/tests/auth.test.ts
  • packages/realtime-server/src/auth.ts
  • packages/realtime-server/src/hub.ts
  • packages/realtime-server/tests/auth/authorize-scope.test.ts
  • packages/realtime-server/tests/hub.test.ts
  • packages/services/src/storage/index.ts
  • packages/services/src/storage/key.ts
  • packages/services/src/storage/parent.ts
  • packages/services/src/storage/s3.ts
  • packages/services/src/storage/types.ts
  • packages/services/tests/storage/parent.test.ts
  • packages/services/tests/storage/storage-prefix.test.ts
  • packages/shared/src/events/control.ts
  • packages/shared/src/policy/index.ts
  • packages/shared/src/validators/organization.ts
  • packages/shared/tests/events/control.test.ts
  • packages/shared/tests/policy/policy.test.ts
  • packages/shared/tests/validators/organization.test.ts

Comment thread packages/services/src/storage/s3.ts Resolved
@imshashank

Copy link
Copy Markdown
Contributor Author

Review loop 3

I reviewed the complete PR again after the prior two review and fix loops. Seven findings were evaluated:

  1. Deletion response contracts were duplicated in the client. Fixed by moving the strict schemas and types to @orbit/shared, validating route responses, and importing the same contracts in the UI.
  2. The implementation plan contained worker-specific execution instructions. Fixed by removing them from repository documentation.
  3. The implementation plan referenced placeholder 0001 migration files. Fixed to reference the actual 0002 migration and snapshot.
  4. The design document described storage cleanup inside a database transaction. Fixed to document the staged marker, readiness, storage, and final transaction sequence.
  5. The service held a database transaction open during object-storage cleanup. Fixed by performing exact-prefix cleanup outside a transaction, then revalidating authorization, confirmation, and readiness in a short final transaction. New regression coverage proves a competing organization lock is available while cleanup is blocked and that statement or commit failure remains retryable.
  6. A concern suggested deletion state could leak between two tests. No code change was required because both cited suites call resetDatabase() and create a fresh workspace in beforeEach. The complete suites pass.
  7. Empty object-storage pagination markers could be reused. Fixed by rejecting empty continuation, key, and version markers, with tests proving malformed truncated responses fail closed without another request.

Fresh verification after all fixes:

  • ORBIT_TEST_LANE=workspace_deletion_final10 bun run verify
  • 237 shared, 538 services, 757 core, 161 database, and 1,689 web tests passed
  • all nine package typechecks passed
  • lint and every repository policy check passed
  • git diff --check passed

All seven threads have been answered and resolved. No deployed workspace was deleted or modified by this PR.

@imshashank
imshashank merged commit 9dbf7f9 into main Aug 8, 2026
13 checks passed
@imshashank
imshashank deleted the codex/feat-workspace-deletion branch August 8, 2026 21:03

This branch was successfully deployed

1 active deployment
Preview — 937a0903 Deployed Aug 8, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: auth Sign-in, sessions, passkeys, OAuth area: database Schema, migrations, queries, seed area: mcp The MCP server, its tools and its OAuth area: policy Roles, permissions and authorization area: realtime The socket, the hub, scopes and fan-out area: web The Next.js app and its UI documentation Docs, the README, or anything that explains Orbit tests Test coverage and test infrastructure

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant