diff --git a/.agent-instructions/reference/rules/13-staging-verification-full.md b/.agent-instructions/reference/rules/13-staging-verification-full.md index 4fab450970..3c32f8854f 100644 --- a/.agent-instructions/reference/rules/13-staging-verification-full.md +++ b/.agent-instructions/reference/rules/13-staging-verification-full.md @@ -77,6 +77,18 @@ name (`sam2-staging2`): `GET /accounts/$CF_ACCOUNT_ID/d1/database?name=sam2-stag the `staging2` Pulumi stack and the `sammy2.party` zone's workspace and node records. Delete test workspaces and nodes first; teardown does not delete VMs. The next deploy rebuilds staging2 from nothing. +**Branches that add a Durable Object migration.** Durable Object migrations only move forward. +Once a branch deploys a tag that `origin/main` lacks (a new `[[migrations]]` entry in +`apps/api/wrangler.toml`), every main-based branch fails the migration preflight on that +installation until the branch merges. So `deploy-staging.yml` refuses such deploys on primary +`staging` before reserving a place (`scripts/deploy/staging-migration-guard.mjs`, which fails closed +when it cannot compare the two files; it runs from your branch's workflow copy, so branches must +include it, and the deploy-time migration preflight stays the backstop). Use `staging2`. Clean-up duty: if your branch has not merged +when you are done on `staging2`, tear it down (Actions → Teardown → `staging2` → `DELETE`, after +deleting test workspaces and nodes) and redeploy `main` to it (`gh workflow run deploy-staging.yml +--ref main -f environment=staging2 -f sam_task_id=`) before you release. staging2 rebuilds +from nothing, so main-based branches can use it again. Nothing does this automatically. + Adding a third: one entry in `scripts/deploy/staging-installations.mjs` plus a zone in the staging Cloudflare account that the staging deploy token can edit. diff --git a/.agents/skills/do/SKILL.md b/.agents/skills/do/SKILL.md index ff3441225a..6d90eddcc7 100644 --- a/.agents/skills/do/SKILL.md +++ b/.agents/skills/do/SKILL.md @@ -16,7 +16,7 @@ Read the full workflow from `.claude/commands/do.md` and execute it. Use `.claud 4. **Implement** — follow checklist, push frequently, run quality checks. After the first push open the PR as a draft (`gh pr create --draft`); draft PRs run only quick CI checks. **For UI changes**: run mandatory Playwright visual audit with mock data on mobile + desktop viewports (see `.claude/rules/17-ui-visual-testing.md`) 5. **Validate** — full quality suite: lint, typecheck, test, build. As soon as the candidate is complete, mark the PR ready (`gh pr ready `), which starts the full CI suite, and request CodeRabbit at the same moment; reviews and staging then run in parallel with CI and CodeRabbit 6. **Review** — invoke local specialist skills / local subagents ($go-specialist, $cloudflare-specialist, etc.) -7. **Staging** — there are two installations, `staging` (`sammy.party`) and `staging2` (`sammy2.party`); read both queues with `node scripts/deploy/staging-lease.mjs status ` (one `gh api` call) and use the free or shorter one with `-f environment=` (staging2 sign-in: workload identity). Reserve first: `gh workflow run deploy-staging.yml --ref -f environment= -f lease_action=reserve -f sam_task_id=`; schedule a SAM wake at your turn start (shown in the run summary and `status`) instead of polling or chatting, and never dispatch a deploy while another branch holds the lease or has its turn. On your turn deploy with the same command minus `lease_action` (only the head of the queue may take a freed slot, for a 10-minute grace period by default). After live checks release with `-f lease_action=release`, confirm success, and if you released early message the next task in the queue. Configurable hold defaults/cap and commands: `.agent-instructions/reference/rules/13-staging-verification-full.md`. **Use `$CF_TOKEN` to query D1/KV/DNS directly** (see `.claude/rules/32-cf-api-debugging.md`) to verify migrations, data state, and feature flags — this is faster and more precise than UI-based checks. Then verify changed behavior end-to-end via Playwright. **For infrastructure changes** (cloud-init, VM agent, DNS, TLS, scripts/deploy): MUST provision a real VM and verify heartbeat arrives. +7. **Staging** — there are two installations, `staging` (`sammy.party`) and `staging2` (`sammy2.party`); read both queues with `node scripts/deploy/staging-lease.mjs status ` (one `gh api` call) and use the free or shorter one with `-f environment=` (staging2 sign-in: workload identity). A branch adding a Durable Object migration tag that main lacks must use staging2 and, if unmerged when done, tear staging2 down and redeploy main before releasing. Reserve first: `gh workflow run deploy-staging.yml --ref -f environment= -f lease_action=reserve -f sam_task_id=`; schedule a SAM wake at your turn start (shown in the run summary and `status`) instead of polling or chatting, and never dispatch a deploy while another branch holds the lease or has its turn. On your turn deploy with the same command minus `lease_action` (only the head of the queue may take a freed slot, for a 10-minute grace period by default). After live checks release with `-f lease_action=release`, confirm success, and if you released early message the next task in the queue. Configurable hold defaults/cap and commands: `.agent-instructions/reference/rules/13-staging-verification-full.md`. **Use `$CF_TOKEN` to query D1/KV/DNS directly** (see `.claude/rules/32-cf-api-debugging.md`) to verify migrations, data state, and feature flags — this is faster and more precise than UI-based checks. Then verify changed behavior end-to-end via Playwright. **For infrastructure changes** (cloud-init, VM agent, DNS, TLS, scripts/deploy): MUST provision a real VM and verify heartbeat arrives. 8. **PR** — the PR is already ready from step 5 (create it now if not, not as a draft). Wait for the full CI run on the ready PR (the required `Durable Object Workers` check reports only after every job finished). CodeRabbit is requested when the PR is marked ready, through the trusted GitHub Actions path: apply the `coderabbit-review` label with `gh pr edit --add-label coderabbit-review`; if the label run did not fire (it never fires on a draft PR), run `gh workflow run coderabbit-bot-review.yml --ref main -f pr_number=`. Do not post `@coderabbitai review` directly with an agent token. Then wait about 15 minutes from the request, ending at once on a `Review skipped`, rate-limit or quota reply. A CodeRabbit review is not required, but one that arrives blocks merge: implement or resolve every finding with a reason, and give incremental reviews after pushed fixes the same wait. If no review arrives (silence, `Review skipped`, rate limit), record that in the PR's CodeRabbit Review Evidence and continue. Do not re-trigger in a loop, and never add `needs-human-review` or wait for a waiver because CodeRabbit is silent (see `.claude/rules/25-review-merge-gate.md`). If the user requested draft PR / do-not-merge, do not mark it ready; get the full suite with `gh workflow run ci.yml --ref `, stop at the draft PR and do not merge. 9. **Cleanup** — remove worktree, pull main diff --git a/.claude/commands/do.md b/.claude/commands/do.md index 2ebc71bac7..0e8e5a8a41 100644 --- a/.claude/commands/do.md +++ b/.claude/commands/do.md @@ -225,6 +225,10 @@ If this PR includes **any code changes** (not just docs/tasks), deploy to stagin one that is free or has the shorter queue and use that name in every command below. They share the `staging` credentials but nothing else. staging2 sign-in is workload identity only; see "Two Staging Installations" in the full reference. + A branch that adds a Durable Object migration tag `origin/main` lacks is refused + on primary `staging`: use `staging2`, and if the branch has not merged when you + are done, tear `staging2` down and redeploy `main` before releasing (full + reference, "Branches that add a Durable Object migration"). 2. **Reserve first, then deploy only on your turn.** Reserving takes seconds and deploys nothing: diff --git a/.claude/rules/13-staging-verification.md b/.claude/rules/13-staging-verification.md index d3947f69fd..d4b4ca2d3c 100644 --- a/.claude/rules/13-staging-verification.md +++ b/.claude/rules/13-staging-verification.md @@ -3,7 +3,7 @@ Keep this root rule compact. The full procedure is preserved at `.agent-instructions/reference/rules/13-staging-verification-full.md`. - Code PRs require staging deployment and live verification unless the change is documentation-only, config-only, or task-file-only. -- There are two staging installations, `staging` (`sammy.party`) and `staging2` (`sammy2.party`), each with its own lease and data. Take whichever is free and pass it as `-f environment=`; staging2 sign-in is workload identity only (full reference, "Two Staging Installations"). +- There are two staging installations, `staging` (`sammy.party`) and `staging2` (`sammy2.party`), each with its own lease and data. Take whichever is free and pass it as `-f environment=`; staging2 sign-in is workload identity only (full reference, "Two Staging Installations"). Branches adding a Durable Object migration must use staging2. - Read both queues with `node scripts/deploy/staging-lease.mjs status `. Reserve first (`deploy-staging.yml -f lease_action=reserve`); no later dispatch can cancel your place. - A freed slot goes to the queue head for `STAGING_LEASE_GRACE_MINUTES` (default 10; after an early release, until the holder's announced expiry plus grace), then the next. Wake at your turn start; never dispatch a deploy while another branch holds the lease or has its turn. - On your turn deploy or `acquire`; release only after every live check, and message the next task when releasing early. Branches older than the queue must update from main. Details: full reference, section 1. diff --git a/.github/workflows/deploy-staging.yml b/.github/workflows/deploy-staging.yml index 40c0d900d5..0a23227dff 100644 --- a/.github/workflows/deploy-staging.yml +++ b/.github/workflows/deploy-staging.yml @@ -125,6 +125,15 @@ jobs: INSTALLATION: ${{ inputs.environment || 'staging' }} PRIMARY_BASE_DOMAIN: ${{ vars.BASE_DOMAIN }} run: node scripts/deploy/staging-installations.mjs workflow-target + # A branch that adds a Durable Object migration tag main lacks would leave primary staging + # ahead of main (migrations only move forward), so every main-based deploy there fails the + # migration preflight until it merges. Refused before a place is reserved; use staging2. + - name: Keep new Durable Object migrations off primary staging + if: ${{ (inputs.environment || 'staging') == 'staging' && (inputs.lease_action == 'deploy' || inputs.lease_action == '') && !inputs.github_trigger_audit_send_only && !inputs.activation_only && !inputs.performance_audit_only }} + env: + LEASE_ENVIRONMENT: ${{ inputs.environment || 'staging' }} + LEASE_ACTION: ${{ inputs.lease_action || 'deploy' }} + run: node scripts/deploy/staging-migration-guard.mjs - name: Reserve a place or confirm this branch's turn id: queue env: diff --git a/scripts/deploy/staging-migration-guard.mjs b/scripts/deploy/staging-migration-guard.mjs new file mode 100644 index 0000000000..266f7852b5 --- /dev/null +++ b/scripts/deploy/staging-migration-guard.mjs @@ -0,0 +1,71 @@ +// Keeps branches that add a Durable Object migration off the primary staging installation. +// Durable Object migrations only move forward: once a branch deploys tag vN+1 to an +// installation, every main-based branch (history ending at vN) fails the migration preflight +// there (scripts/deploy/durable-object-migrations.ts) until that branch merges. Such branches +// verify on staging2, whose holder rebuilds it from main before releasing (staging reference, +// "Branches that add a Durable Object migration"). +// +// node scripts/deploy/staging-migration-guard.mjs # deploy-staging.yml job `queue` +import { execFileSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import { pathToFileURL } from 'node:url'; + +export const WRANGLER_TOML = 'apps/api/wrangler.toml'; +export const PRIMARY_INSTALLATION = 'staging'; +// An absolute path on the runner, so PATH cannot substitute another binary. +const GIT = process.env.GITHUB_ACTIONS === 'true' ? '/usr/bin/git' : 'git'; + +// Tags in [[migrations]] order. Fails closed on anything it cannot read unambiguously. +export function migrationTags(toml, source) { + if (typeof toml !== 'string' || toml.length === 0) + throw new Error(`${source}: empty wrangler.toml`); + const blocks = toml.match(/^\[\[migrations\]\][ \t]*$/gm)?.length ?? 0; + const tags = [ + ...toml.matchAll(/^\[\[migrations\]\][ \t]*\r?\n[ \t]*tag[ \t]*=[ \t]*"([^"\n]+)"/gm), + ].map((match) => match[1]); + if (blocks === 0 || tags.length !== blocks) + throw new Error( + `${source}: cannot read every [[migrations]] tag (${tags.length} of ${blocks})` + ); + return tags; +} + +export function newMigrationTags(branchToml, mainToml) { + const main = new Set(migrationTags(mainToml, 'origin/main')); + return migrationTags(branchToml, 'branch').filter((tag) => !main.has(tag)); +} + +// Returns null when the deploy may proceed, or the refusal message. +export function checkInstallation({ installation, action, branchToml, mainToml }) { + if (installation !== PRIMARY_INSTALLATION || action !== 'deploy') return null; + const added = newMigrationTags(branchToml, mainToml); + if (added.length === 0) return null; + return `This branch adds Durable Object migration tag(s) ${added.join(', ')} that origin/main does not have. Deploying it to primary staging would block every main-based branch there until it merges (migrations only move forward). Use -f environment=staging2; if the branch has not merged when you are done, tear staging2 down and redeploy main before releasing.`; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + try { + const installation = process.env.LEASE_ENVIRONMENT || PRIMARY_INSTALLATION; + const action = process.env.LEASE_ACTION || 'deploy'; + let refusal = null; + if (installation === PRIMARY_INSTALLATION && action === 'deploy') { + execFileSync(GIT, ['fetch', '--quiet', '--depth=1', 'origin', 'main'], { + stdio: 'inherit', + }); + refusal = checkInstallation({ + installation, + action, + branchToml: readFileSync(WRANGLER_TOML, 'utf8'), + mainToml: execFileSync(GIT, ['show', `FETCH_HEAD:${WRANGLER_TOML}`], { + encoding: 'utf8', + }), + }); + } + if (refusal) throw new Error(refusal); + console.log('Durable Object migration guard: no new migration tags for primary staging.'); + } catch (error) { + console.error(`Staging deploy refused: ${error.message}`); + if (process.env.GITHUB_ACTIONS === 'true') console.log(`::error::${error.message}`); + process.exitCode = 1; + } +} diff --git a/scripts/deploy/staging-migration-guard.test.mjs b/scripts/deploy/staging-migration-guard.test.mjs new file mode 100644 index 0000000000..fcf49ba58c --- /dev/null +++ b/scripts/deploy/staging-migration-guard.test.mjs @@ -0,0 +1,113 @@ +// Run in CI through scripts/quality/deploy-staging-permissions.test.ts. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { + appendFileSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { checkInstallation, migrationTags, newMigrationTags } from './staging-migration-guard.mjs'; + +const main = readFileSync(new URL('../../apps/api/wrangler.toml', import.meta.url), 'utf8'); +const tags = migrationTags(main, 'main'); +const next = `v${Number(tags.at(-1).slice(1)) + 1}`; +const withNext = `${main}\n[[migrations]]\ntag = "${next}"\nnew_sqlite_classes = ["NewThing"]\n`; +const check = (installation, action, branchToml, mainToml = main) => + checkInstallation({ installation, action, branchToml, mainToml }); + +test('reads every migration tag of the real wrangler.toml, in order', () => { + assert.ok(tags.length > 10); + assert.equal(new Set(tags).size, tags.length); + assert.equal(tags[0], 'v1'); +}); + +test('a branch adding a migration tag is refused on primary staging deploys only', () => { + assert.deepEqual(newMigrationTags(withNext, main), [next]); + assert.match(check('staging', 'deploy', withNext), new RegExp(`${next}[\\s\\S]*staging2`)); + for (const [installation, action] of [ + ['staging2', 'deploy'], + ['staging', 'acquire'], + ['staging', 'reserve'], + ['staging', 'release'], + ]) + assert.equal(check(installation, action, withNext), null, `${installation} ${action}`); +}); + +test('main-based branches, and branches behind main, may deploy to primary staging', () => { + assert.equal(check('staging', 'deploy', main), null); + assert.equal(check('staging', 'deploy', main, withNext), null); +}); + +test('anything that cannot be compared unambiguously fails closed', () => { + const tagNotFirst = main.replace( + /^\[\[migrations\]\][ \t]*\r?\n([ \t]*tag[ \t]*=[^\n]*)/m, + '[[migrations]]\nnew_classes = ["X"]\n$1' + ); + for (const [branch, base] of [ + ['', main], + [withNext, ''], + [tagNotFirst, main], + ['name = "worker"\n', main], + ]) + assert.throws(() => check('staging', 'deploy', branch, base), /wrangler\.toml|tag/); +}); + +test('the workflow entry point fetches main and fails closed', () => { + const script = fileURLToPath(new URL('./staging-migration-guard.mjs', import.meta.url)); + const root = mkdtempSync(join(tmpdir(), 'migration-guard-')); + const git = (cwd, ...args) => execFileSync('git', args, { cwd, stdio: 'pipe' }); + try { + const origin = join(root, 'origin'); + mkdirSync(join(origin, 'apps/api'), { recursive: true }); + writeFileSync(join(origin, 'apps/api/wrangler.toml'), main); + git(origin, 'init', '-q', '-b', 'main'); + git( + origin, + '-c', + 'user.email=t@t', + '-c', + 'user.name=t', + 'commit', + '-q', + '--allow-empty', + '-m', + 'empty' + ); + git(origin, 'add', '.'); + git(origin, '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-q', '-m', 'main'); + const branch = join(root, 'branch'); + git(root, 'clone', '-q', '--depth=1', `file://${origin}`, branch); + const run = (installation = 'staging') => + spawnSync(process.execPath, [script], { + cwd: branch, + encoding: 'utf8', + env: { + ...process.env, + GITHUB_ACTIONS: '', + LEASE_ENVIRONMENT: installation, + LEASE_ACTION: 'deploy', + }, + }); + assert.equal(run().status, 0, run().stderr); + appendFileSync( + join(branch, 'apps/api/wrangler.toml'), + `\n[[migrations]]\ntag = "${next}"\nnew_sqlite_classes = ["X"]\n` + ); + const refused = run(); + assert.equal(refused.status, 1); + assert.match(refused.stderr, new RegExp(`refused: .*${next}.*staging2`)); + assert.equal(run('staging2').status, 0); + git(branch, 'remote', 'remove', 'origin'); // comparison impossible: fail closed + assert.equal(run().status, 1); + } finally { + rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/scripts/quality/deploy-staging-permissions.test.ts b/scripts/quality/deploy-staging-permissions.test.ts index 8cc295434c..75b4f875ce 100644 --- a/scripts/quality/deploy-staging-permissions.test.ts +++ b/scripts/quality/deploy-staging-permissions.test.ts @@ -375,6 +375,7 @@ it('executes the lease lifecycle and failure-path tests in CI', () => { '--test', fileURLToPath(new URL('../deploy/staging-lease.test.mjs', import.meta.url)), fileURLToPath(new URL('../deploy/staging-lease-queue.test.mjs', import.meta.url)), + fileURLToPath(new URL('../deploy/staging-migration-guard.test.mjs', import.meta.url)), ], { stdio: 'pipe' } ) @@ -402,6 +403,36 @@ describe('job-level broad permission overrides', () => { }); }); +describe('Durable Object migration guard', () => { + it('runs before a place is reserved, for primary-staging deploys only', () => { + const workflow = parse(stagingWorkflow); + const steps = workflow.jobs.queue.steps as { + run?: string; + if?: string; + env?: Record; + }[]; + const guard = steps.findIndex( + (step) => step.run === 'node scripts/deploy/staging-migration-guard.mjs' + ); + const queue = steps.findIndex( + (step) => step.run === 'node scripts/deploy/staging-lease.mjs queue' + ); + expect(guard).toBeGreaterThan(-1); + expect(guard).toBeLessThan(queue); + expect(steps[guard].if).toContain("(inputs.environment || 'staging') == 'staging'"); + expect(steps[guard].if).toContain("inputs.lease_action == 'deploy'"); + // Same deploy conditions as the deploy job, so the guard cannot drift from what deploys. + const deployCondition = String(workflow.jobs.deploy.if).replace(/^\$\{\{\s*|\s*\}\}$/g, ''); + expect(steps[guard].if).toContain(deployCondition); + expect(steps[guard].env).toEqual({ + LEASE_ENVIRONMENT: "${{ inputs.environment || 'staging' }}", + LEASE_ACTION: "${{ inputs.lease_action || 'deploy' }}", + }); + // Production paths are untouched: the guard lives only in the staging workflow. + expect(reusableWorkflow).not.toContain('staging-migration-guard'); + }); +}); + describe('installation targeting', () => { it('runs the lease jobs in the staging Environment with no secrets, validating the target first', () => { const workflow = parse(stagingWorkflow); diff --git a/tasks/active/2026-11-16-staging-lease-fair-queue.md b/tasks/archive/2026-11-16-staging-lease-fair-queue.md similarity index 86% rename from tasks/active/2026-11-16-staging-lease-fair-queue.md rename to tasks/archive/2026-11-16-staging-lease-fair-queue.md index 297ff73e28..9e9f5fbfa9 100644 --- a/tasks/active/2026-11-16-staging-lease-fair-queue.md +++ b/tasks/archive/2026-11-16-staging-lease-fair-queue.md @@ -76,16 +76,16 @@ First night of use (idea notes, 2026-11-16): - [x] Docs: `.claude/commands/do.md`, `.agents/skills/do/SKILL.md`, `.claude/rules/13-staging-verification.md`, `.agent-instructions/reference/rules/13-staging-verification-full.md` - [x] Live proof with two branches (reserve/acquire/release, no full deploys) — on primary `staging`, staging2 was held -- [ ] One real deploy through queue → lease → deploy on staging2 (output wiring) -- [ ] Note on idea, channel `feature.ship-faster` +- [x] Deploy path through queue → lease → deploy proven: dry_run deploy 43901912468 on primary staging (both installations were continuously held by pre-queue branches; staging2 never freed) +- [x] Channel `feature.ship-faster` updated at each take/release and at merge; idea note after part 2 merges ## Checklist — Part 2 (PR 2, after PR 1 merges) -- [ ] Refuse `staging` deploys of a branch whose `apps/api/wrangler.toml` has a DO migration tag +- [x] Refuse `staging` deploys of a branch whose `apps/api/wrangler.toml` has a DO migration tag `origin/main` lacks; fail closed if the comparison can't be made; message says use `staging2` -- [ ] Tests in the existing deploy-script test suite -- [ ] Docs: clean-up duty (teardown + redeploy main on staging2 before release) -- [ ] Tell #2721 owner (task 01M7C1SRMAWR3PYFWKF03XJ273) +- [x] Tests in the existing deploy-script test suite (`staging-migration-guard.test.mjs`, run by `deploy-staging-permissions.test.ts`) +- [x] Docs: clean-up duty (teardown + redeploy main on staging2 before release) +- [ ] Tell #2721 owner (task 01M7C1SRMAWR3PYFWKF03XJ273) — on merge of part 2 (#2721 itself merged 2026-11-16 08:11Z, so primary's v23 state already cleared) ## Acceptance criteria @@ -95,3 +95,9 @@ First night of use (idea notes, 2026-11-16): - No dispatch can cancel another agent's pending run or lose a reserved place. - Old-workflow branches cannot jump the queue. - Migration-carrying branches are refused on primary staging (part 2). + +## Outcome + +- Part 1: PR #2783, merged 2026-11-16 16:15Z (64a264da0). +- Part 2: Durable Object migration guard (`scripts/deploy/staging-migration-guard.mjs`) in the + `queue` job of `deploy-staging.yml`. No production workflow touched.