Skip to content

feat: run deployment builds in Cloudflare Containers (phase 3) - #2721

Merged
simple-agent-manager[bot] merged 34 commits into
mainfrom
sam/implement-phase-3-run-3xj273
Nov 16, 2026
Merged

simple-agent-manager[bot] merged 34 commits into
mainfrom
sam/implement-phase-3-run-3xj273

Conversation

@simple-agent-manager

@simple-agent-manager simple-agent-manager Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Instant build_and_publish uploads a verified portable Compose context and runs the build in a dedicated Cloudflare DinD microVM. VM sessions default to the node executor and can select Cloudflare in Admin Settings. The Go builder reuses internal/publish and existing publish callbacks; old agents fail explicitly rather than silently moving the build back to the source.

A conditional D1 UPDATE enforces two reservations per project and six platform-wide, clamped to class capacity. Cron drains eligible projects fairly; capacity errors back off. Reservation epochs fence late startup outcomes and retries. An independent durable deadline destroys the guest; terminal stop skips inactive guests and clears obsolete schedules and the native alarm. A durable quiescent marker suppresses SDK reconstruction renewal and stale alarm delivery until a fresh admission. A database trigger retains reservations through deletion cascades until confirmed shutdown or the bounded deadline-plus-grace escape.

Raphaël approved unrestricted build egress November15, superseding the initial host-allowlist proposal. Arbitrary root RUN code executes with host networking inside the microVM and receives only one job's callback/object authority. No platform credentials or runtime secrets are supplied. Bootstrap closes before build execution. Two exact Sonar HTTP findings are narrowly documented private-workerd-port false positives; this adds no public plaintext transport.

Merged and production verified. PR2721 merged08:11:32UTC as a96b6e847f557c5b4693a78efcb3e21b3298a3e2 after coordinator approval of exact head ab0d2363107ca12ac749a0f41db3a7cc9c3a29f3, PR Evidence green, ready CI success and a production-idle check. The merge used --match-head-commit; no main-only update or additional code change was needed. Staging cleanup and lease release were completed before merge.

Ready-state CI43823981787 attempt1 passed PR Evidence and all seven DO shards but API3 hit an unchanged capacity-pool-edit-query-plan.test.ts five-second timeout (idea01M7HNXQ1EE0W8NKV23PPHDA1M). Local focused2/2 passed; exactly one failed-jobs-only retry succeeded (attempt2). No approved-head changes.

Final coordinator correction

Diff from previously reviewed 7c17f185: merge main60e899730 via b741106 (only adjacent scheduled-handler imports conflicted; retained both and sorted), then bounded reservation retention. Applied0242 and guard0244 remain unchanged; no new migration or duplicate prefix, builder DOv23 remains after mainv22.

Cron now force-releases reservations after the immutable builder deadline plus deployments.builderReservationGraceMs (named default300000). The atomic update fences attempt, epoch, instance and deadline and changes unfinished jobs to unknown, revoking late callback authority. Existing terminal verdicts remain. A structured error and dedicated alert-level job event explicitly report unconfirmed physical shutdown; failed telemetry does not undo release or block later jobs. Temporary undercounting and occupied Cloudflare capacity are accepted instead of permanent admission/deletion failure.

Deletion audit: owner node DELETE preflights before provider destruction and again before D1 removal; a racing admission can retain the tombstone after provider deletion, with strict termination evidence supporting retry. Cron teardown and warm-pool handoff update/tombstone nodes, so do not fire the DELETE trigger. A small adjacent fix guards fallible per-node failure diagnosis so later nodes still progress (idea01M7HHXGHRBG8T97K1M357ESMN). Self-service account deletion is disabled in BetterAuth; direct user deletion remains atomically blocked by held reservations until confirmed/forced release.

Correction validation: 48 focused tests pass, including actual shipped SQLite/FKs proving inside-grace rejection, past-grace cascading deletion, preserved terminal verdicts, revoked late callbacks, stale reservation fences and per-item mutation/alert-failure isolation. API typecheck, package build/lint, affected API lint, docs build291pages, source-contract/runtime-tunable/migration-ordering/DO-safety checks pass. Independent security/correctness and config/docs/constitution reviews PASS. No Go executable changes. Current-head full CI43820100864 PASSED on the first attempt, including all seven Durable Object shards. Trusted incremental CodeRabbit43820106498 requested06:55:19; comment6909642429 at06:55:36 says Incremental review skipped, so wait ended immediately with no retrigger. The prior draft PR Evidence failure reflected the review-hold label; coordinator approval now authorizes removing it and rerunning the PR gate on this unchanged SHA.

Production verification — November16

  • Main CI43829277210 passed on the first attempt, exact mergeSHA, including all seven DO shards.
  • First containing Deploy Production43830871158 succeeded. D10242 and0244 applied08:29UTC; rollout gate passed08:41 and health08:42.
  • Live read-only Cloudflare metadata confirms migration tagv23 and COMPOSE_BUILDER / ComposeBuilderContainer namespace c6ac62e463504374bc7a8d049ad7c30f. Worker version 6e1809dd-88b7-4696-9dfd-0fa9fe77aca1 is at100%.
  • Sandbox appv1644 and node appv1165 both have completed rollout steps ending at100%. New builder app a03b08bd-8cfc-4a24-b259-c2c2a5b1d9e3 was directly created atv1; it has no gradual rollout. Builder image digest sha256:9cdeefd8ca4435b5bda7a3e7d4b1e147b686a12f6d40695772cb29b3127f4d63.
  • Independent live curl health returned200/healthy08:48. Verification used basic health and read-only Cloudflare state, with no production provisioning/fullE2E.
  • Completion audit found no blocking implementation gaps; its pending production criterion is now satisfied. Historical task-file status text remains bookkeeping history; this PR body and SAM task/idea hold the final state.
  • Diagnostics-first follow-up 01M7HDK9DV8G2JPBK1KTVNY6JN and deferred VM-proof 01M7H8GCR5FFDEXA70DNMEF8BW have both been posted UNBLOCKED. VM proof is still unproven and VM default remainsnode. No follow-up implementation or staging trial started here.

Validation

  • Previous reviewed head7c17: CI43813866700 SUCCESS on the first attempt, including all three Durable Object shards. git diff -U0 018a56f1..HEAD -- '*.go' filtered to changed lines finds two comment additions and zero executable changes. Only runner.go, the deployments guide and the active task differ; independent qualification review passed. Runtime CI43805600123 attempt2 SUCCESS.

  • API callback authentication/actual byte bounds, job/attempt/source handoff fencing and profile guard:126 focused tests passed during the correction unit; subsequent real-setting/legacy callback fixtures also passed.

  • Reservation epochs/fair drain/deadline:94 focused cases passed, including23 DO lifecycle cases. Controlled stale outcomes, capped backlog, deferred SDK startup, diagnostic blockage and inactive terminal wake cases failed before their fixes.

  • Deletion correction:89 related cases across8 files passed. Independent security reran22 deletion/route cases; actual shipped SQLite FK migrations prove direct/node/project/environment/user cascades, terminal-held versus released reservations and both delete/admission orderings. Workspace-only deletion retains the job because workspace_id has no FK.

  • Go builder/publish race suites and real daemon-free Compose5.7.1 path regression passed. Archive directory modes are restored after successful extraction; runtime placeholders remain separate from build interpolation.

  • Package build, API typecheck, affected lint, docs build and migration ordering/safety passed. Applied D10242 is unchanged; the new unapplied deletion guard is0244 after a fresh open-PR collision audit. DO migration remainsv23 (mainv22).

  • Prior candidate full manual CI: 43792773359 SUCCESS on83febdf0ac, including all three Durable Object shards. Prior76f3 run43791408547 exposed four stale fixture contracts; these are corrected in tests only, with48 related cases across6files, API typecheck/lint and source-contract check passing. Production code and e1ed binary inputs are unchanged. The superseded12372 run43790800522 (now canceled) found the source-contract checker rejecting a direct migration SQL read; the test now executes the same SQL via the existing applySqliteMigration helper, and13 migration cases plus the source-contract check pass locally. Historical c577 run43776771299 attempt2 passed after exactly one unchanged unrelated archive-shard retry; this is not final-head evidence. Known archive flake remains out of scope.

  • Native-alarm correction:33 focused cases across3files pass, including9 real installed-SDK/SQLite scenarios (original baseline6RED/1PASS). Removing only the production native-alarm deletion reproduces the explicit-stop failure; restored code is GREEN. API typecheck/lint/format pass; independent Cloudflare/lifecycle and security reviews pass. Delayed SDK sync and old-stop/readmission races are controlled. Current fullCI: 43805600123.

Staging Verification

Runtime was tested at 018a56f1acb78755a959ea053f18e5dad3338f64, with agent/builder e1ed097d8d345f241d1205dd47a4168cbfc1e5f4. Full CI 43805600123 attempt 2 passed after exactly one unchanged runtime-secret overlap-test retry (idea 01M7HB8YEFM9YTZWFH31PQ0DX0). Deployment 43807052699 and smoke passed. Worker served the exact commit at 100%; both actual Container rollouts completed 100% before trials; D1 0244 was applied.

  • Instant capability PASS: job 01M7HDZ456E5C8BJ91ZW4NDW07 succeeded at 05:43:39 UTC. Exact source instance was inactive at 05:42:23 while the job was still building at 05:42:34. No manual sleep or cancellation was needed.
  • Served release PASS: release 01M7HE3RQ41M15X3MC5870XKCC applied; unauthenticated GET at 05:49:32 returned 200 with the exact fixture marker and no redirects. The single target VM was cx23, 2 CPU/4 GB, and reported the deployed e1ed binary.
  • Success-terminal no-wake PASS: builder stayed inactive unchanged since 05:43:42 through its original 05:45:07.183 deadline plus two minutes (exact GET 05:47:15). Final telemetry read at 05:52:15 completed the exact window after 308 seconds ingestion wait: 4/4 native alarm events, explicit ABR 1, all sample intervals 1, and initial alarm/workload controls present. No alarm at the original deadline, no new placement, and no workload after the completion minute through deadline+2. No guest-boot or billing inference.
  • Failed-terminal no-wake PASS: the first job 01M7HCZC8WS4E7VJ88ST2FTA3Z failed in an invalid generated Python fixture (idea 01M7HDH4BFZ77B0XKREE33JNTT). Its builder likewise stayed inactive beyond its original deadline+2; final unsampled telemetry had 3/3 events after 309 seconds ingestion wait. This failed job does not count as served-release proof. The coordinator explicitly approved exactly one corrected replacement in the same lease.
  • Transfer receipts PASS: replacement context 1,049,708 bytes / SHA256 7f5276c169260cf0d917de67664497c8b01b0fb1a0adf054fdb656ff2ada9dde; image 22,585,856 bytes / SHA256 10481734d6bd0698c365775827c2970a1b00a9a8a13a30300acdac38795334d4. The earlier successful Instant trial on 83feb supplied the required >100 MiB proof: context 125,833,194 bytes / SHA256 d3053459ce85a46969333d4101d5b6601432a50022c8f0152eb4faf532fc4a9d; image 147,402,752 bytes / SHA256 c2164dbbbbb33b945137a3d29abb7b8ef768b71b91a1e5487c9fffacb9fd2644.

The previous 83feb trial exposed the stale native-alarm recurrence (idea 01M7GYR3VCTK0G72HBHJJ000G5); the real-SDK regression tests and the focused success/failed-terminal trials above validate its correction. Prior trial cleanup and lease release completed before this trial began.

VM Cloudflare capability remains unverified and explicitly deferred to idea 01M7H8GCR5FFDEXA70DNMEF8BW by the coordinator. No VM-source publish task/job was submitted. Baseline counters alone do not establish zero delta. VM sessions retain unconfigured deployments.buildExecutor=node; keep that default until the follow-up proves a served release and same-process zero source build/save delta.

Build diagnostics follow-up: Cloudflare currently discards Docker failure detail preserved by node builds. High-priority idea 01M7HDK9DV8G2JPBK1KTVNY6JN is the first follow-up after merge. The coordinator accepted this deferral with a code TODO and an explicit deployments-guide limitation. The final diff from runtime-tested 018a contains only Go comments, documentation and task evidence; executable Go is unchanged, although the comment rotates the release identity.

Cleanup: both tasks/workspaces, environment, profile and project deleted normally; all three owned node records are deleted with runtime termination confirmed (target VM at 05:51:19). Deadline setting restored to original absence at revision 86. Logout returned a null session and removed the private cache. Immediate audit at 05:52:59 is clear; late audit at 05:58:08 is clear. Normal release workflow43813679472 succeeded; authoritative PRIMARY lease record7816727391 is RELEASED at05:59:18.866. Exact source/builder instances are inactive; public DNS and release rows are gone. Exact R2 objects remain under the approved >=48-hour retention exception. Aggregate estimate USD 0.914512, reserve USD 0.95, below the USD 1 ceiling; this is not a billing assertion.

Specialist Review Evidence

Reviewer Status Outcome
go-specialist / go_review PASS Builder/archive/publish boundary, permission modes, Compose path interpolation and race suites reviewed.
security-auditor / security_design ADDRESSED Initial auth, artifact/release fences, bootstrap and arbitrary-root trust-boundary findings fixed.
security-auditor / merge_lease_review (final escape) PASS Independent deadline/grace, atomic unknown + release, callback revocation, reservation fences, alert-failure isolation and node-cleanup containment review.
security-auditor / security_final PASS Job-scoped authority/open egress/bootstrap lifetime; callback and final deletion correction independently reviewed.22 deletion tests rerun PASS.
cloudflare-specialist / merge_lease_review PASS Native-alarm quiescence correction and actual SDK/SQLite tests reviewed, including constructor renewal, stale SDK snapshots, capacity readmission and stop epoch races. Focused success and failed-terminal live no-wake proofs passed.
security-auditor / alarm_security_review PASS Native-alarm correction preserves destruction before D1, SDK terminal guards, late startup verdict delivery and epoch-fenced natural-stop writes.
cloudflare/constitution/env/doc validators / config_docs_review PASS Final grace-setting/default/bounds and forced-release documentation consistency independently reviewed; no remaining findings. Runtime body-cap registry, config/SDK reconstruction, applied0242 preservation,0244 collision audit and corrected docs reviewed.
API harness / harness_api_recovery PASS Exact sleep-only reconciliation preserves authoritative intent without fabricating HTTP success or claiming unmet capability.
security harness / harness_security_recovery PASS Final packet independently reviewed and archived; exact-instance GET-only helper reviewed before use, preserving instance identities through cascades.

CodeRabbit Review Evidence

Trusted main workflow43780966380 requested review November16 00:32UTC; CodeRabbit review5913874558 returned9 inline and1 outside finding. All9 inline findings are fixed, explained in replies and resolved. The valid outside deletion/accounting finding is fixed by0244 plus authorized preflights; the proposed permanent-R2-orphan issue does not apply because existing cleanup LISTs retained prefixes independently of job rows. One incremental trusted request43790805717 was made at02:13:14UTC after the production fixes; CodeRabbit check133049508279 ended neutral with Review rate limited (all analysis steps skipped). The wait ended immediately under policy; no retrigger. The subsequent76f3 change only routes the behavioral migration test through the shared helper; production code is unchanged. The new native-alarm unit received one trusted incremental request43805627532 at04:41UTC; check133096137886 ended neutral RATE LIMITED with all analysis skipped; wait ended immediately. No retrigger loop. Every arriving finding remains binding. Final bounded-reservation unit: trusted workflow43820106498 requested06:55:19UTC; CodeRabbit comment6909642429 at06:55:36 says Incremental review skipped. Wait ended immediately under policy; no retrigger.

Agent Preflight

  • Preflight completed before code changes

Classification

  • external-api-change
  • cross-component-change
  • business-logic-change
  • public-surface-change
  • docs-sync-change
  • security-sensitive-change
  • ui-change
  • infra-change

External References

Read the entire November 6 implementation section of idea 01KZ6V37D1QGDR3WN12PSDB0QD, linked phase-0 spike and PR #2605 contracts before implementation. Official documentation: outbound traffic, Container API, DinD guide. Installed Containers SDK 0.3.7 source/types checked. November 15 egress approval is recorded in knowledge CloudflareDeploymentBuilds.

Codebase Impact Analysis

Business logic remains in packages/app-deployment/, with thin adapters under apps/api/, schema in packages/worker-core/, source collector and Go builder in packages/vm-agent/, and image/deploy/cache wiring under scripts/deploy/. Existing deployment apply remains the target. Cron terminal cleanup and reserved-start recovery inspect at most classMax candidates; queue drain is bounded by builderDrainLimit.

Documentation & Specs

Deployments/Instant guides, security architecture, configuration reference, self-hosting note, API contracts and active task match the approved one-job microVM trust boundary and open egress.

Constitution & Risk Check

Operational budgets and sizing are configurable. Root DinD with host build networking is required by measured spike evidence. The microVM is the isolation boundary; arbitrary root code is assumed to possess one job's callback and short-lived object authority. No broad credentials are delivered. Cleanup and cross-project/attempt fences remain mandatory.

@simple-agent-manager simple-agent-manager Bot added the needs-human-review Agent could not complete all review gates — human must approve before merge label Nov 14, 2026
@coderabbitai

coderabbitai Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Explain Change →

Important

Review skipped

We couldn't safely recover the incremental review. No full review was started, and the last reviewed checkpoint was preserved. Retry later, or explicitly request a full review by commenting @coderabbitai full review.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
Walkthrough

This change adds a Cloudflare Container executor for deployment Compose builds. It adds build-context transfer, job-scoped callback authorization, capacity admission and recovery, a builder controller, and deployment configuration. VM builds remain available, and documentation describes executor selection and the build environment.

Changes: Cloudflare deployment build flow

Layer / File(s) Summary
Publish-job state and context identity
apps/api/src/db/migrations/*, packages/worker-core/src/schema.ts, packages/app-deployment/src/*, packages/vm-agent/internal/publish/contextcollect/*
Publish jobs gain executor reservation metadata and a Compose project name. Admission, recovery, reservation release, and progress transition rules are added. Context receipts now bind the project name, and a signed download URL can be created.
Publish requests and callback authorization
apps/api/src/routes/mcp/compose-publish-tools.ts, apps/api/src/routes/projects/*, apps/api/src/services/jwt.ts, apps/api/src/services/publish-job-token.ts, packages/vm-agent/internal/server/mcp_build_context.go
Publish requests select Node or Cloudflare execution. Publish-job tokens and a job-spec route bind requests to job identity and attempt. Callback routes validate job scope, environment, release identity, and artifact keys.
Admission, container lifecycle, and deployment wiring
packages/app-deployment/src/cloudflare-build-*, apps/api/src/durable-objects/compose-builder-container.ts, apps/api/src/app-deployment-ports/*, apps/api/wrangler.toml, scripts/deploy/*, .github/workflows/deploy-reusable.yml
Cloudflare jobs are admitted under platform and project limits, started in Compose Builder containers, and drained by scheduled work. Deployment configuration sets container capacity and instance type.
Builder execution and diagnostics
packages/vm-agent/cmd/sam-builder/*, packages/vm-agent/internal/builder/*, packages/vm-agent/internal/publish/*, packages/vm-agent/internal/server/system_info.go, packages/shared/src/types/workspace.ts
The builder accepts one launch, retrieves and validates its job specification and context, runs Compose builds, and reports progress. Source-node system information includes process-scoped build and save attempt counts.
Guides and API contract
apps/www/src/content/docs/docs/*, apps/api/src/routes/mcp/deployment-guide-tools.ts, specs/001-mvp/contracts/api.md, tasks/active/*
Documentation and the API contract describe executor selection, build context, callback scope, builder limits, and the execution environment.

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

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant PublishRequest
  participant BuildContextCallback
  participant D1PublishJobs
  participant ComposeBuilderContainer
  participant SamBuilder
  PublishRequest->>BuildContextCallback: collect and submit build context
  BuildContextCallback->>D1PublishJobs: complete context and request admission
  D1PublishJobs->>ComposeBuilderContainer: start reserved job
  ComposeBuilderContainer->>SamBuilder: send launch with scoped token
  SamBuilder->>D1PublishJobs: fetch job specification and report progress
Loading

Possibly related PRs

Suggested reviewers: raphaeltm

Merge Risk: High · previous review c5772

Cloudflare-executed deployment builds can be failed or stopped by late source callbacks, can fail at launch for jobs without an agent profile, and can be starved or outlive their deadline under load. The callback endpoints also accept unbounded request bodies. These should be fixed, and the staging trial and CI rerun, before merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: deployment builds moving to Cloudflare Containers. It matches the changeset (ComposeBuilderContainer, Cloudflare build executor, admission and drain logic). The '(phas…
Description check Passed The description follows the template's main sections: Summary, Validation, Staging Verification, End-to-End Verification, Post-Mortem, Specialist Review Evidence, CodeRabbit Review Evidence, and Agent…
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.
Full details: Title check

Explanation

The title names the main change: deployment builds moving to Cloudflare Containers. It matches the changeset (ComposeBuilderContainer, Cloudflare build executor, admission and drain logic). The '(phase 3)' suffix adds little for a reader scanning history, but it does not make the title misleading or vague.

Full details: Description check

Explanation

The description follows the template's main sections: Summary, Validation, Staging Verification, End-to-End Verification, Post-Mortem, Specialist Review Evidence, CodeRabbit Review Evidence, and Agent Preflight. It gives a clear problem and change, plus implementation notes. Several template items are unchecked or pending, which is expected for an unmerged draft. The UI screenshot section is not addressed, but the preflight marks ui-change as unchecked, so it is not required. The description is detailed, though some passages are dense and cite internal identifiers and SHAs that a reviewer must cross-check. Its staging evidence is clearly marked as incomplete.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

A rabbit checks the builder's queue,
Then tucks a project name in view.
The context hops, the job takes flight,
A token keeps its scope just right.
The bunny counts each build with care,
Then bounds through logs to fresh night air.

@codspeed

codspeed Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 5 untouched benchmarks
⏩ 1 skipped benchmark1


Comparing sam/implement-phase-3-run-3xj273 (ab0d236) with main (b3c04e1)2

Open in CodSpeed

Footnotes

  1. 1 benchmark was skipped, so the baseline result was used instead. If it was deleted from the codebase, click here and archive it to remove it from the performance reports. ↩

  2. No successful run was found on main (60e8997) during the generation of this report, so b3c04e1 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@github-actions
github-actions Bot requested a deployment to staging November 15, 2026 23:45 Abandoned
@raphaeltm

Copy link
Copy Markdown
Owner

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@github-actions
github-actions Bot requested a deployment to staging November 16, 2026 05:59 Abandoned
@raphaeltm

Copy link
Copy Markdown
Owner

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Action not completed

Incremental review skipped.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@sonarqubecloud

Copy link
Copy Markdown

simple-agent-manager Bot added a commit that referenced this pull request Nov 16, 2026
…2753) (#2772)

* Fix security finding acf_1c430965be49bdf046a1933ae3b533a0

* fix(api): race-safe first-superadmin election without demoting anyone

Corrects the bot election from #2753:

- Election (services/first-superadmin.ts): promote the signing-in user in one
  guarded UPDATE only while they are the ONLY real (status != 'system') account,
  are not suspended, and the election marker is absent; then record the oldest
  real superadmin as the marker in the same D1 batch. A later sign-up never wins
  against an existing account (suspended or non-admin), and two sign-ups whose
  rows both exist fail closed rather than electing by timing.
- Report installs with more than one superadmin via a structured
  first-superadmin.multiple_superadmins warning on sign-in, folded into the
  existing single read. No user row is changed.
- session.create.before: catch election failures, log
  auth.first_superadmin_election.failed and continue without promotion, so a
  D1 error never blocks login.
- Migration renumbered 0242 -> 0243 (open PR #2721 already uses 0242). It now
  only inserts the marker for installs that already have a non-system
  superadmin and never updates or deletes users; the oldest-superadmin
  demotion is removed.
- Tests: real-SQL election/migration tests on drizzle-built tables (attack
  cases paired with owner controls), the auth.test fixture regression, and
  workers tests that drive BetterAuth's createSession against real D1 (happy
  path, existing-account refusal, D1 outage, owner-email skip, and the
  BOOTSTRAP_OWNER_EMAIL recovery path).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: first-superadmin election, duplicate superadmins and admin recovery

Describe the one-time ordinary election (only-real-account guard, durable
setup.firstSuperadminEstablished marker, login never blocked), how to review
and resolve more than one superadmin, and the recovery paths when no account
can administer the instance: the BOOTSTRAP_OWNER_EMAIL Worker secret
(bootstrapSessionAllowed) or a direct D1 update.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(api): keep first-superadmin migration at 0242 and locate it by name

Coordinator decision: main ends at 0241 and the builder branch also uses 0242;
whichever merges second renumbers, so do not renumber speculatively. Tests now
find the migration by its `_first_superadmin_election.sql` suffix, and the code
comments and docs name it without a number, so a renumber is a file rename only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: correct first-superadmin recovery details after review

- wrangler secret put needs --name (no checked-in env sections)
- owner-email recovery does not apply to an installer-bound instance whose owner
  was already established; use the D1 update there
- the duplicate-superadmin warning is logged only without BOOTSTRAP_OWNER_EMAIL
- admin-settings and .env.example no longer claim nobody is ever promoted again
- rule 40 notes where the promotion lives now

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: parameterize duplicated first-superadmin attack and self-heal cases

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(api): number the first-superadmin migration 0243

0242 is taken by the Cloudflare build executor migration (PR #2721), which is
already applied on staging. Migration-ordering CI rejects duplicate prefixes;
the migration is replay-safe and tests locate it by name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(api): renumber the first-superadmin migration to 0246 after main's 0245

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Raphaël Titsworth-Morin <raphael@raphaeltm.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@simple-agent-manager simple-agent-manager Bot removed the needs-human-review Agent could not complete all review gates — human must approve before merge label Nov 16, 2026
@simple-agent-manager
simple-agent-manager Bot marked this pull request as ready for review November 16, 2026 07:27
@raphaeltm

Copy link
Copy Markdown
Owner

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Action not completed

Incremental review skipped.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@simple-agent-manager
simple-agent-manager Bot merged commit a96b6e8 into main Nov 16, 2026
118 of 122 checks passed
@simple-agent-manager

Copy link
Copy Markdown
Contributor Author

For the owner of this PR (task 01M7C1SRMAWR3PYFWKF03XJ273), from task 01M7HK7TY9GA8DTV3BGS4QYNM8: two staging changes merged today.

Since this PR merged, main has v23 and primary staging is consistent again; nothing needs repairing.

For future migration branches: verify on staging2. If the branch has not merged when you're done, tear staging2 down (Teardown → staging2 → DELETE, after deleting test workspaces and nodes) and redeploy main before releasing. Details: .agent-instructions/reference/rules/13-staging-verification-full.md, "Branches that add a Durable Object migration".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

coderabbit-review Trigger CodeRabbit review for opt-in PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant