Skip to content

feat: slug reservation flow (CLI DX v2, PR-B of 2) - #10

Merged
Codehagen merged 3 commits into
mainfrom
cli-dx-reservation
Apr 18, 2026
Merged

Codehagen merged 3 commits into
mainfrom
cli-dx-reservation

Conversation

@Codehagen

@Codehagen Codehagen commented Apr 18, 2026 •

Copy link
Copy Markdown
Owner

Summary

helpbase login now reserves a docs-<6hex>.helpbase.dev subdomain immediately after successful auth. TTHW for the first-deploy happy path drops from ~3-4 min (slug prompt + confirmation) to ~90s (login + deploy, zero prompts). Users see a concrete URL before they've written a single article — the magical moment the DX review chased.

This is PR-B of 2 for the CLI DX v2 plan. PR-A (#9) handled the context → ingest rename; this PR handles the reservation flow.

Plan context: /plan-devex-review → /plan-eng-review + codex outside voice → decisions locked in project_cli_dx_v2_decisions.md memory. Schema already applied via Supabase MCP (migration name slug_reservation_columns_and_first_deploy_timestamp).

What's in this PR

Schema (already live)

  • tenants.deployed_at timestamptz + tenants.auto_provisioned_at timestamptz (both nullable). Existing 3 rows backfilled with deployed_at = created_at.
  • UNIQUE partial index on owner_id WHERE auto_provisioned_at IS NOT NULL AND deployed_at IS NULL — race-safe idempotency for auto-provision.
  • Helper index on owner_id WHERE auto_provisioned_at IS NOT NULL — sargable for the reservation lookup path.
  • tenants_public view extended with deployed_at (still no mcp_public_token).
  • deploy_tenant RPC: flips deployed_at atomically on first publish. COALESCE(deployed_at, NOW()) preserves the original timestamp on re-deploys; per-deploy history stays in tenant_deploys.created_at.

Server endpoints

Endpoint Purpose
POST /api/v1/tenants/auto-provision Idempotent mint of a docs-<6hex> reservation. Catches 23505 on owner UNIQUE to re-read + return existing row. Catches 23505 on slug UNIQUE to retry once with fresh entropy, then 503 slug_exhausted.
GET /api/v1/tenants/reservation Returns caller's active reservation or 404. Used by login re-hydration + whoami + open.
PATCH /api/v1/tenants/reservation/slug Pre-deploy rename. Gated on deployed_at IS NULL. Idempotent when new slug matches current. 409 on slug_taken / slug_reserved / reservation_locked.
GET /api/v1/tenants/mine Now filters .not("deployed_at", "is", null) so reservations never pollute the deploy picker.
POST /api/cron/cleanup-reservations Vercel Cron (daily 03:00 UTC). Deletes reservations > 30 days old with no tenant_deploys history. Bearer auth via CRON_SECRET, supports ?dry=true.

Public surfaces (reserved-tenant handling)

  • apps/web/proxy.ts — reserved tenants (deployed_at IS NULL) route / → /t/_reserved/[slug], every other path → /t/_not-found. Every response carries X-Robots-Tag: noindex, nofollow.
  • apps/web/app/(tenant)/t/_reserved/[slug]/page.tsx — new branded "coming soon" page with helpbase wordmark + helpbase deploy / helpbase rename hints.
  • apps/web/app/(tenant)/t/[tenant]/mcp/route.ts — returns 403 tenant_not_deployed on reserved tenants so MCP clients polling a reservation URL during first-deploy get a clean signal.

CLI

  • packages/cli/src/lib/reservation-cache.ts — local cache at ~/.helpbase/reservation.json (0o600, separate from auth.json).
  • packages/cli/src/lib/reservation.ts — ensureReservation (auto-provision w/ graceful 503 fallback) + loadReservation (cache-first).
  • helpbase login — calls ensureReservation after device/magic-link flow, prints reserved URL in the outro.
  • helpbase whoami — shows reserved: docs-abc.helpbase.dev when user has no deployed tenants but an active reservation.
  • helpbase open — falls back to reservation URL when no deployed tenant exists.
  • helpbase deploy — reservation-first branch: users with no deployed tenants + no --slug deploy straight to their reservation with zero prompts.
  • helpbase rename <new-slug> — NEW command. PATCHes reservation slug + updates local cache. E_RESERVATION_MISSING / E_RESERVATION_LOCKED / E_SLUG_TAKEN with full fix copy.

Live-DB smoke (via Supabase MCP)

Verified against the production DB:

  1. Insert reservation succeeds
  2. /mine filter correctly hides it
  3. Second reservation INSERT for same owner → 23505 (UNIQUE partial index) ✓
  4. After deployed_at = NOW(), a NEW reservation is allowed (partial index releases) ✓
  5. Cleanup ran clean

Test plan

  • pnpm -r typecheck — clean across 8 workspaces
  • pnpm -r test — CI-equivalent clean HOME: apps/web 127/127, create-helpbase 31/31, CLI 376/+3 skipped
  • Live smoke against staging: helpbase login → reserved URL prints → helpbase rename acme → URL changes → helpbase whoami reflects new slug
  • First-deploy happy path: scaffold → helpbase deploy (no slug prompt; deploys to reservation)
  • Reserved subdomain responds with branded landing + X-Robots-Tag: noindex
  • Cron endpoint dry-run returns candidates without deleting
  • CodeRabbit PR review

Known follow-ups

Review trail

  • /plan-devex-review 2026-04-18 — command rename + reservation plan
  • /plan-eng-review 2026-04-18 — architecture + codex outside voice
  • Schema applied live via mcp__supabase__apply_migration (2026-04-18)
  • Migration + constraints verified via mcp__supabase__execute_sql DO block

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features

    • Auto-provisioned help center reservation on login with instant docs-<6hex>.helpbase.dev URL
    • New helpbase rename <new-slug> command to customize reserved help center slugs before deployment
    • Reserved help center placeholder page shown until first deployment
  • Improvements

    • Reserved help centers excluded from tenant listings until deployed
    • Automatic nightly cleanup of abandoned unused reservations (30+ days old)
    • Reserved help centers marked as non-indexable by search engines

@vercel

vercel Bot commented Apr 18, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
helpbase Ready Ready Preview, Comment Apr 18, 2026 11:27am

Request Review

@coderabbitai

coderabbitai Bot commented Apr 18, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Codehagen has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 40 minutes and 41 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 40 minutes and 41 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: fe3e98d6-7731-45cb-a8c2-045787ae0d47

📥 Commits

Reviewing files that changed from the base of the PR and between 24f855b and 82e9ad3.

📒 Files selected for processing (10)
  • CHANGELOG.md
  • apps/web/app/(tenant)/t/[tenant]/mcp/route.ts
  • apps/web/app/(tenant)/t/_reserved/[slug]/page.tsx
  • apps/web/app/api/cron/cleanup-reservations/route.ts
  • apps/web/lib/reservation-cleanup.ts
  • apps/web/test/reservation-cron.test.ts
  • packages/cli/src/commands/deploy.ts
  • packages/cli/src/commands/rename.ts
  • packages/cli/src/commands/whoami.ts
  • packages/cli/src/lib/errors.ts
📝 Walkthrough

Walkthrough

This PR introduces a tenant reservation lifecycle system. When users run helpbase login, the system auto-provisions a temporary docs-<6hex>.helpbase.dev reservation and displays the reservation URL. A new helpbase rename command allows renaming unreleased reservations. The backend now tracks deployed_at and auto_provisioned_at timestamps to distinguish reserved from live tenants, and a nightly cron job (/api/cron/cleanup-reservations) prunes undeployed reservations older than 30 days. Reserved tenants render a "Coming soon" placeholder at / and return 404 for other paths.

Changes

Cohort / File(s) Summary
Database Schema & Types
apps/web/types/supabase.ts, vercel.json
Added nullable deployed_at and auto_provisioned_at timestamp fields to tenants and tenants_public view types. Added Vercel cron config for daily cleanup at 03:00 UTC.
API Endpoints: Reservation Management
apps/web/app/api/v1/tenants/auto-provision/route.ts, apps/web/app/api/v1/tenants/reservation/route.ts, apps/web/app/api/v1/tenants/reservation/slug/route.ts
Added POST /auto-provision (idempotent tenant provisioning), GET /reservation (fetch active reservation), and PATCH /reservation/slug (rename pre-deploy reservation with deployed_at IS NULL gating). All handle concurrent access and unique-constraint races.
API Endpoints: Cron & Tenant Discovery
apps/web/app/api/cron/cleanup-reservations/route.ts, apps/web/app/api/v1/tenants/mine/route.ts
Added nightly cron endpoint with Bearer auth, 30-day TTL, and shadow filter to skip tenants with deploy history. Updated GET /tenants/mine to exclude reservations (deployed_at IS NOT NULL required).
Tenant MCP & Proxy Routing
apps/web/app/(tenant)/t/mcp/route.ts, apps/web/proxy.ts
MCP handler now gates with tenant_not_deployed 403 error if deployed_at IS NULL. Proxy rewrites reserved-tenant requests: / → /_reserved/<slug>, non-MCP paths → /_not-found (404), and sets X-Robots-Tag: noindex, nofollow on all reserved responses.
Reserved Tenant UI
apps/web/app/(tenant)/t/_not-found/page.tsx, apps/web/app/(tenant)/t/_reserved/[slug]/page.tsx
Converted _not-found page to call notFound() for true HTTP 404. Added _reserved page rendering a "Coming soon" placeholder with deploy/rename instructions and robots noindex metadata.
CLI: New Rename Command
packages/cli/src/commands/rename.ts
Added helpbase rename <new-slug> command to rename pre-deploy reservations. Validates slug, calls PATCH /reservation/slug, caches result locally, and maps server errors to targeted user guidance. Clears cache on reservation_locked or no_reservation.
CLI: Command Updates
packages/cli/src/commands/login.ts, packages/cli/src/commands/deploy.ts, packages/cli/src/commands/whoami.ts, packages/cli/src/commands/open.ts, packages/cli/src/index.ts
Updated login to call ensureReservation and print reservation URL in outro. Modified deploy to validate content pre-tenant, resolve slug via reservation if no prior tenant exists, and clear cached reservation after deploy. Extended whoami to display reservation info when present. Updated open to fallback to cached reservation slug. Registered renameCommand in CLI router. Updated help categories.
CLI: Reservation Libraries
packages/cli/src/lib/reservation.ts, packages/cli/src/lib/reservation-cache.ts, packages/cli/src/lib/tenants-client.ts, packages/cli/src/lib/errors.ts, packages/cli/src/lib/help.ts
Added reservation client functions (autoProvisionTenant, getReservation, renameReservation), cache layer (read/write/clear from ~/.helpbase/reservation.json), and ensureReservation/loadReservation helpers with best-effort fallbacks. Extended ErrorCode union with three new error codes.
Tests
apps/web/test/reservation-cron.test.ts, packages/cli/test/reservation-cache.test.ts
Added cron predicate tests verifying 30-day TTL cutoff logic and shadow-filter exclusion. Added cache tests covering write/read/clear/validation and file permissions.
Documentation
CHANGELOG.md, docs/cli.md
Added helpbase rename command documentation with usage examples and slug rules. Updated CHANGELOG with comprehensive overview of reservation feature.

Sequence Diagrams

sequenceDiagram
    actor User
    participant CLI
    participant API as Server API
    participant DB as Database
    
    User->>CLI: helpbase login
    CLI->>API: POST /auth/device-flow (or /magic-link)
    API->>DB: [authenticate & verify session]
    API-->>CLI: session token
    
    CLI->>API: POST /api/v1/tenants/auto-provision
    Note over API: Check for existing<br/>reservation
    API->>DB: SELECT * FROM tenants<br/>WHERE auto_provisioned_at IS NOT NULL<br/>AND deployed_at IS NULL
    alt Existing reservation found
        DB-->>API: reservation row
        API-->>CLI: { id, slug, is_new: false }
    else No reservation
        API->>DB: INSERT tenants<br/>(owner_id, slug, auto_provisioned_at)
        DB-->>API: { id, slug, is_new: true }
        API-->>CLI: reservation + mcp_public_token
    end
    
    CLI->>CLI: writeCachedReservation()
    CLI->>User: Print "Reserved at docs-xxxx.helpbase.dev"
    CLI->>User: Next: deploy, rename, or whoami
Loading
sequenceDiagram
    actor User
    participant CLI
    participant API as Server API
    participant DB as Database
    
    User->>CLI: helpbase deploy
    CLI->>CLI: Pre-validate content<br/>(_category.json, articles)
    
    CLI->>API: Check /api/v1/tenants/mine<br/>(existing deployed tenants)
    alt No deployed tenant, no --slug provided
        API->>DB: SELECT * FROM tenants<br/>WHERE owner_id = ? AND deployed_at IS NOT NULL
        DB-->>API: empty
        API-->>CLI: [ ]
        
        CLI->>CLI: loadReservation()
        alt Cached reservation valid
            CLI->>CLI: Use cached reservation
        else Cache miss or forceRefresh
            CLI->>API: GET /api/v1/tenants/reservation
            API->>DB: SELECT * FROM tenants<br/>WHERE auto_provisioned_at IS NOT NULL<br/>AND deployed_at IS NULL
            DB-->>API: reservation row
            API-->>CLI: reservation
            CLI->>CLI: writeCachedReservation()
        end
        CLI->>CLI: usedReservation=true
    end
    
    CLI->>API: RPC deploy_tenant<br/>(slug, content, mcp_token)
    API->>DB: INSERT content<br/>UPDATE tenants SET deployed_at=now()
    DB-->>API: success
    API-->>CLI: { slug, ... }
    
    alt usedReservation=true
        CLI->>CLI: clearCachedReservation()
    end
    
    CLI->>User: Print deploy summary
Loading
sequenceDiagram
    participant Vercel as Vercel Cron
    participant API as Server API
    participant DB as Database
    
    Vercel->>API: GET /api/cron/cleanup-reservations
    API->>API: Verify Bearer token == CRON_SECRET
    
    API->>DB: SELECT id, slug FROM tenants<br/>WHERE auto_provisioned_at IS NOT NULL<br/>AND deployed_at IS NULL<br/>AND auto_provisioned_at < now() - 30d<br/>LIMIT 500
    DB-->>API: candidates [ ]
    
    API->>DB: SELECT tenant_id FROM tenant_deploys<br/>WHERE tenant_id IN (candidate.ids)
    DB-->>API: deployed_tenant_ids [ ]
    
    API->>API: Filter candidates<br/>NOT IN deployed_tenant_ids
    
    alt Dry run requested
        API-->>Vercel: { deleted: 0, dry: true, slugs: [...] }
    else Execute delete
        API->>DB: DELETE FROM tenants<br/>WHERE id IN (toDelete.ids)<br/>AND deployed_at IS NULL
        DB-->>API: count deleted
        API-->>Vercel: { deleted: count, slugs: [...], raced: bool }
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • PR #3: Directly extends the tenant/auth surface introduced in that PR by adding reservation lifecycle fields (deployed_at, auto_provisioned_at), new reservation-specific endpoints (auto-provision, /reservation, /reservation/slug), and proxy/MCP routing logic that depends on the tenant discovery and view schema changes.
  • PR #8: Modifies the CLI login/auth flow in tandem with this PR—the main changes add reservation handling during login and post-login messaging, while the retrieved PR updates BYOK/inline-auth detection in the same command file.

Poem

🐰 A reservation in my burrow so deep,
Six hexes of slugs for tenants to keep,
docs- prefixed hopes and a rename or two,
Before the grand deploy, all shiny and new!
Thirty days old? The cron says goodbye,
Reserved but untouched must eventually die. 🌙

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: introducing a slug reservation flow for CLI DX v2, which is the core functionality of this PR.
Description check ✅ Passed The PR description is comprehensive and well-structured, covering summary, schema changes, server endpoints, public surfaces, CLI changes, testing, and known follow-ups as required by the template.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch cli-dx-reservation

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 and usage tips.

`helpbase login` now reserves a `docs-<6hex>.helpbase.dev` subdomain
immediately after successful auth. TTHW for the first-deploy happy
path drops from ~3-4 min (slug prompt + confirmation) to ~90s (login
+ deploy, zero prompts). Users see a concrete URL before they've
written a single article — the magical moment the DX review chased
from /plan-devex-review 2026-04-18.

Scope — schema + 3 endpoints + middleware + landing page + MCP
gate + CLI wiring + cleanup cron. Review trail in memory at
project_cli_dx_v2_decisions.md.

Schema (applied via Supabase MCP, migration name
`slug_reservation_columns_and_first_deploy_timestamp`):
- `public.tenants` gets `deployed_at timestamptz` +
  `auto_provisioned_at timestamptz` (both nullable). Existing rows
  backfilled with `deployed_at = created_at` (all 3 existing tenants
  pre-migration are really deployed; backfill preserves ordering).
- UNIQUE partial index on `owner_id WHERE auto_provisioned_at IS
  NOT NULL AND deployed_at IS NULL` — race-safe idempotency.
- Helper index on `owner_id WHERE auto_provisioned_at IS NOT NULL`
  — sargable for the reservation lookup path.
- `tenants_public` view now exposes `deployed_at` (still no
  `mcp_public_token`). Added via CREATE OR REPLACE VIEW — column
  appended at the end, no dependents needed drop/recreate.
- `deploy_tenant` RPC flips `deployed_at` atomically with content
  insertion using COALESCE(deployed_at, NOW()) so re-deploys never
  overwrite the original reservation→live timestamp. Per-deploy
  history continues to live in tenant_deploys.created_at.

Server endpoints:
- `POST /api/v1/tenants/auto-provision` — idempotent mint of a new
  reservation. Catches 23505 on the owner UNIQUE partial index to
  re-read + return the existing row when a concurrent second call
  races. Slug uses 24 bits of entropy (6 hex chars) so first-try
  collisions are vanishingly rare; a single retry covers the tail,
  after which we 503 with slug_exhausted (signals PRNG degradation).
- `GET /api/v1/tenants/reservation` — read-only counterpart. Returns
  the row or 404. Used by login re-hydration, `whoami`, `open`.
- `PATCH /api/v1/tenants/reservation/slug` — pre-deploy rename.
  Server gates on `deployed_at IS NULL` and treats the rename as
  idempotent when the new slug matches the current one. Post-deploy
  rename is out of scope (would need a redirect layer in proxy.ts).
- `GET /api/v1/tenants/mine` — filter `.not("deployed_at", "is",
  null)` so reservations never pollute the deploy tenant picker.

Public surfaces:
- `apps/web/proxy.ts` — reserved tenants (deployed_at IS NULL)
  route `/` to the new `/t/_reserved/[slug]` branded landing,
  everything else to `/t/_not-found`. Every reserved-tenant
  response carries `X-Robots-Tag: noindex, nofollow` so empty
  `docs-*.helpbase.dev` placeholders don't get indexed.
- `apps/web/app/(tenant)/t/_reserved/[slug]/page.tsx` — new
  branded "This help center isn't live yet" page. No per-slug
  Supabase lookup (middleware already verified); no owner email
  leakage; metadata.robots explicitly noindex/nofollow.
- `apps/web/app/(tenant)/t/[tenant]/mcp/route.ts` — returns 403
  `tenant_not_deployed` on reserved tenants so MCP clients
  polling a reservation URL during a user's first-deploy window
  get a clean signal instead of empty search results.

CLI:
- New `packages/cli/src/lib/reservation-cache.ts` — local cache
  at `~/.helpbase/reservation.json` (mode 0o600, separate from
  auth.json). Avoids extending the session contract + provides a
  cheap fast-path for whoami/open.
- New `packages/cli/src/lib/reservation.ts` — `ensureReservation`
  (auto-provision with graceful fallback on 503) + `loadReservation`
  (cache-first with server fallback).
- `packages/cli/src/commands/login.ts` — calls `ensureReservation`
  after device/magic-link flow, prints the reserved URL in the
  outro. Soft-fails: if the server is unreachable, login still
  succeeds and `whoami`/`deploy` lazy-provision later.
- `packages/cli/src/commands/whoami.ts` — shows
  `reserved: docs-abc.helpbase.dev` when user has no deployed
  tenants but an active reservation.
- `packages/cli/src/commands/open.ts` — falls back to the
  reservation URL when no deployed tenant exists.
- `packages/cli/src/commands/deploy.ts` — reservation-first
  branch: users with no deployed tenants + no explicit --slug
  deploy to their reservation with zero prompts. Clears the
  reservation cache post-successful deploy so the tenant shows
  up as "live" in whoami afterwards.
- `packages/cli/src/commands/rename.ts` — new command. PATCHes
  the reservation slug, updates the local cache, surfaces
  E_RESERVATION_MISSING / E_RESERVATION_LOCKED / E_SLUG_TAKEN
  with full fix copy.
- New error codes: E_RESERVATION_MISSING, E_RESERVATION_LOCKED,
  E_RESERVATION_PROVISION_FAILED.

Infrastructure:
- `apps/web/vercel.json` — new. Daily 03:00 UTC cron pointed at
  `/api/cron/cleanup-reservations`.
- `apps/web/app/api/cron/cleanup-reservations/route.ts` —
  Deletes reservations older than 30 days that have no
  tenant_deploys history. Belt-and-suspenders: if deployed_at
  somehow failed to update, the deploy history still protects
  the row. Supports `?dry=true` + bearer-auth via CRON_SECRET.

Also fixed (cherry-picked from in-flight PR #9):
- Docs generator regex: match 4-space indent (command names) not
  2-space (GROUP labels). Was producing bogus `## helpbase Get`
  sections in docs/cli.md. Regenerated — now 20 real commands.

Tests:
- `packages/cli/test/reservation-cache.test.ts` — 7 tests covering
  round-trip, corrupt JSON, missing fields, clear, override, 0o600.
- `apps/web/test/reservation-cron.test.ts` — 7 tests for the TTL
  math + shadow filter predicate.
- Live DB smoke via Supabase MCP verified the UNIQUE partial index
  blocks concurrent reservation INSERTs and releases after
  deployed_at flips to NOT NULL.

Totals: apps/web 127/127, create-helpbase 31/31, CLI 376/+3
skipped, typecheck clean across 8 workspaces.

Known follow-ups:
- hermeticity: two pre-existing CLI tests (context.test.ts,
  doctor.test.ts) still leak laptop auth state. Fixed in PR #9;
  PR-B branched before that landed. Clean on CI (no auth), only
  fails on contributor laptops with a live session. Will resolve
  on rebase when PR #9 merges.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Seven fixes from the pre-landing /review pass. Two were genuine CRITICALs
caught only by codex; the rest are HIGH+ severity issues both reviewers
surfaced. Live-DB smoke verified the orphan-prevention refactor.

## Critical (P0)

1. Vercel Cron method mismatch. The cleanup route only exported `POST`,
   but Vercel Cron invokes paths with `GET`. In production the job
   would have silently 405'd every night and abandoned reservations
   would have accumulated forever. `route.ts` now exports both `GET`
   (primary, what Vercel Cron actually sends) and `POST` (alias, for
   runbook curls that default to -X POST). Both delegate to the same
   `handle()` body.

2. Cron DELETE TOCTOU race → could destroy a tenant that just went
   live. The old flow was: SELECT candidates → shadow-check
   tenant_deploys → DELETE by ID. If a user deployed their reservation
   AFTER the candidate select but BEFORE the delete, the delete had no
   WHERE-clause guards and would happily wipe the live row. Fix: repeat
   every predicate in the DELETE (`auto_provisioned_at IS NOT NULL`
   AND `deployed_at IS NULL` AND `auto_provisioned_at < cutoff`)
   so Postgres evaluates them at DELETE time, not the earlier SELECT.
   Also returns `.select("id, slug")` on the delete so we can log
   which rows raced and were skipped.

## High (P1)

3. Slug black hole on `deploy --slug foo` content failure. If content
   validation failed AFTER `apiCreateTenant` succeeded, the tenant
   row sat forever: hidden from `/mine` (filters deployed_at), invisible
   to `/reservation` (filters auto_provisioned_at), untouched by
   cleanup cron, slug permanently burned. User-decided fix: move
   content validation to BEFORE tenant resolution so broken content
   can never leave a server-side side effect. Refactor in deploy.ts
   lifts the frontmatter-parse block to step 2.5 (between auth and
   resolve). Live-DB smoke verified: empty content exits with "No
   articles found" and zero tenant rows are created. Pre-refactor
   the same flow would have INSERTed an orphan.

4. Lazy-provision fallback wasn't actually wired. The CHANGELOG +
   reservation.ts docstrings both claimed `whoami` and `deploy` would
   call `ensureReservation` as a fallback for users who Ctrl-C'd
   login mid-auto-provision or logged in before reservations existed.
   They only called `loadReservation` — no retry. Now both paths call
   `ensureReservation` when `loadReservation` returns null.

5. `apiDeployTenant` response ignored. The CLI printed `tenantSlug`
   captured from the reservation cache BEFORE the RPC, not the slug
   the server echoed BACK from the RPC. A concurrent `helpbase rename`
   in another terminal would drift the slug; the CLI would deploy
   correctly (tenantId is stable) but print the wrong live URL in
   the outro. Now uses `deployResult.slug || tenantSlug` for both
   the summary and the MCP config snippet.

6. `loadReservation` leaked cross-account cache on network errors.
   The cache-first path correctly checked `cached.userId === session.userId`,
   but the remote-lookup-failed fallback returned `readCachedReservation()`
   unconditionally. A shared-laptop user B who logged in over user A's
   stale cache + hit a transient blip on first whoami would see A's
   reservation (including MCP token) leak into their UI. Fallback now
   gates on userId match.

7. `/t/_not-found` returned HTTP 200. The rewrite target rendered a
   "Help center not found" page at status 200, which meant crawlers +
   MCP clients + monitoring tools hitting unknown-or-reserved subdomain
   paths couldn't distinguish "page doesn't exist" from "page exists and
   claims not to." Now the page calls `notFound()` for a true 404.

## Medium

8. Proxy short-circuited `/mcp` on reserved subdomains before the MCP
   handler's own 403 `tenant_not_deployed` response could fire. That
   meant MCP clients polling a reservation URL during first-deploy
   got an HTML 404 instead of structured JSON. Proxy now passes
   `/mcp` + `/mcp/*` through to the tenant route even when
   `deployed_at IS NULL`, keeps X-Robots-Tag for the whole set.

9. Cron batch-safety: added `.limit(500)` on the candidate SELECT to
   cap memory + URL-length risk on the follow-up .in() filters. 30-day
   TTL means accumulated backlog drains over multiple runs.

10. Cron dry-run flag now accepts `true`/`1`/`yes` case-insensitively
    so `?dry=1` in a stressed-operator runbook doesn't accidentally
    delete.

11. `rename` error translation gap: server returned `slug_invalid` +
    `slug_required` 400s that fell through to raw `cancel(msg)` output
    without structured fix copy. Now surfaces E_SLUG_RESERVED /
    E_MISSING_FLAG with examples.

12. Auto-provision 23505 discrimination was fragile: substring-matched
    on the partial-index name from the error message. Simplified to:
    on ANY 23505, re-read the caller's reservation first; if found
    return it (concurrent race won), else retry with a fresh slug
    (slug UNIQUE collision). Two round-trips per collision instead
    of one; collisions are vanishingly rare anyway.

## Review trail

- Codex adversarial (read-only): 7 findings, 2 CRITICAL. Findings 1,
  2, 3, 4, 5, 6, 7, 8, 9 above are codex originals.
- Claude adversarial subagent: 22 findings, overlap on 3-5 + 8-9.
  Claude caught the cache-user-id fallback + rate-limiting gaps.
- User judgment on the slug-black-hole fix shape: picked
  "move validation before create" (correctness first) over
  rollback-on-failure (simpler but leaky on network-during-rollback).

Totals: apps/web 127/127, create-helpbase 31/31, CLI 387/+3 skipped.
Typecheck clean across 8 workspaces. Live Supabase smoke confirmed
orphan-prevention: empty content + `deploy --slug foo` leaves zero
rows.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/web/app/(tenant)/t/[tenant]/mcp/route.ts (1)

241-263: ⚠️ Potential issue | 🟠 Major

Authenticate before revealing reservation state.

This branch returns tenant_not_deployed before bearer validation, so unauthenticated callers can distinguish an existing reserved tenant from other slugs. Keep the structured 403, but only after the token is valid.

🛡️ Proposed ordering fix
-  // Reserved tenants (auto_provisioned_at set, deployed_at still null) have
-  // no content to serve. Return 403 with a structured error so MCP clients
-  // polling a reservation URL during a user's first-deploy window get a
-  // clean signal instead of empty search results that look like bugs.
-  if (tenant.deployed_at === null) {
-    return NextResponse.json(
-      {
-        error: "tenant_not_deployed",
-        message:
-          "This tenant is reserved but hasn't published content yet. The owner needs to run `helpbase deploy`.",
-      },
-      { status: 403 },
-    )
-  }
-
   // Auth: bearer token must match the per-tenant public token.
   const provided = extractBearer(request.headers.get("authorization") ?? undefined)
   if (!provided) {
     return NextResponse.json({ error: "missing bearer token" }, { status: 401 })
   }
   if (!tokensEqual(provided, tenant.mcp_public_token)) {
     return NextResponse.json({ error: "invalid token" }, { status: 401 })
   }
+
+  // Reserved tenants (auto_provisioned_at set, deployed_at still null) have
+  // no content to serve. Return 403 with a structured error so authenticated
+  // MCP clients polling a reservation URL during a user's first-deploy window
+  // get a clean signal instead of empty search results that look like bugs.
+  if (tenant.deployed_at === null) {
+    return NextResponse.json(
+      {
+        error: "tenant_not_deployed",
+        message:
+          "This tenant is reserved but hasn't published content yet. The owner needs to run `helpbase deploy`.",
+      },
+      { status: 403 },
+    )
+  }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web/app/`(tenant)/t/[tenant]/mcp/route.ts around lines 241 - 263, The
route exposes reservation state before authentication: move the bearer-token
checks (extractBearer and tokensEqual against tenant.mcp_public_token) to run
before the reserved-tenant branch that inspects tenant.deployed_at and returns
NextResponse.json({...}, { status: 403 }); specifically, validate the provided
token and return 401 responses for missing/invalid tokens using the existing
extractBearer(...) and tokensEqual(...) logic, and only after a successful token
validation check tenant.deployed_at and return the structured 403 response for
"tenant_not_deployed".
packages/cli/src/commands/whoami.ts (1)

52-89: ⚠️ Potential issue | 🟠 Major

Don’t auto-provision when deployed-tenant lookup failed.

Line 62 leaves tenant as null on /mine failure, so Lines 70-85 can call ensureReservation() and mint a first-deploy reservation for an account that actually has deployed tenants. Gate only the mutating fallback on a successful tenant lookup that returned no tenants.

Proposed fix
-    let tenant: { slug: string; name: string } | null = null
+    let tenant: { slug: string; name: string } | null = null
+    let tenantLookupSucceeded = false
     try {
       const tenants = await listMyTenants(session)
+      tenantLookupSucceeded = true
       const first = tenants[0]
       if (first) tenant = { slug: first.slug, name: first.name }
     } catch {
       // ignore — tenant lookup is informational
@@
         // existing row or mints a fresh one. Soft-fails on 503
         // (ensureReservation writes a stderr warning + returns null).
-        if (!reservation) {
+        if (!reservation && tenantLookupSucceeded) {
           const ensured = await ensureReservation(session)
           if (ensured) {
             reservation = await loadReservation(session)
           }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cli/src/commands/whoami.ts` around lines 52 - 89, The tenant lookup
uses listMyTenants but treats a failure the same as "no tenants", allowing
ensureReservation() to run and potentially create a reservation for accounts
that actually have deployed tenants; fix this by distinguishing a failed lookup
from an empty result (e.g., introduce a flag like tenantLookupSucceeded set to
true at the end of the try that calls listMyTenants) and only run the mutating
fallback (ensureReservation) when tenantLookupSucceeded is true and tenant is
null; update the conditional around ensureReservation/loadReservation to require
that successful lookup flag (and keep loadReservation behavior the same).
🧹 Nitpick comments (2)
apps/web/test/reservation-cron.test.ts (1)

13-17: Exercise the production predicate instead of a shadow copy.

cutoffFor and filterToDelete duplicate the cron logic locally, so the route can drift while these tests stay green. Consider extracting the TTL/predicate helpers from the cleanup route and importing them here, or add a route-level test that asserts the actual Supabase filters sent.

Also applies to: 55-61

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web/test/reservation-cron.test.ts` around lines 13 - 17, Tests duplicate
production logic via cutoffFor and filterToDelete; instead import and use the
real predicate helpers from the cleanup route (or call the cleanup route
endpoint) so tests exercise the exact production filters. Replace local
cutoffFor/filterToDelete usage with the exported TTL/predicate functions from
the cleanup code (or add an integration test that invokes the route and asserts
the Supabase query/filter parameters were used), ensuring you reference and
import the production helper functions used by the cleanup job rather than
re-implementing them in reservation-cron.test.ts.
CHANGELOG.md (1)

59-65: Prose mismatch with implementation (minor).

The changelog describes the cleanup guard as a NOT EXISTS (SELECT 1 FROM tenant_deploys WHERE tenant_id = tenants.id) predicate, but cleanup-reservations/route.ts actually runs a separate tenant_deploys lookup and filters in JS (lines 93–112), then reapplies the reservation predicates (not the deploy-history one) on DELETE. The user-visible guarantee is the same, but the phrasing implies an atomic SQL predicate that isn't there. Consider rewording to "guarded by a deploy-history shadow check" or similar to avoid misleading future readers who grep for NOT EXISTS in the code.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@CHANGELOG.md` around lines 59 - 65, Changelog wording is inaccurate: replace
the explicit SQL predicate text (`NOT EXISTS (SELECT 1 FROM tenant_deploys WHERE
tenant_id = tenants.id)`) with a description that matches the implementation in
cleanup-reservations/route.ts — e.g. state it's "guarded by a deploy-history
shadow check" and note that the handler performs a separate tenant_deploys
lookup and JS-level filtering (the code path that inspects tenant_deploys then
reapplies only the reservation predicates before DELETE) rather than an atomic
NOT EXISTS SQL predicate; update the sentence so readers understand the guard is
implemented as a separate lookup+filter, not an inlined SQL predicate.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/web/app/`(tenant)/t/_reserved/[slug]/page.tsx:
- Around line 43-45: The page currently hard-codes "helpbase.dev" when rendering
the reserved-domain message; replace that literal with the environment-derived
root domain used elsewhere (e.g., the NEXT_PUBLIC_ROOT_DOMAIN variable or the
shared rootDomain/PROXY_ROOT_DOMAIN constant) so the displayed/link host uses
the same runtime value as the proxy; update the JSX where {slug}.helpbase.dev is
rendered (and the same pattern in the other block mentioned) to build the host
as `{slug}.{process.env.NEXT_PUBLIC_ROOT_DOMAIN}` or import and use the existing
rootDomain helper/constant used by the proxy to ensure consistency.

In `@CHANGELOG.md`:
- Around line 87-98: The changelog has a duplicate "### Changed" heading; merge
the second block's bullets (the two items about `/api/v1/tenants/mine` hiding
reservations and the `tenants_public` view exposing `deployed_at`) into the
existing "### Changed" section that already contains the `context → ingest`
rename and remove the redundant "### Changed" header so there's a single
combined heading (resolving markdownlint MD024) while preserving the two
bullets' wording and order as appropriate.

In `@packages/cli/src/commands/deploy.ts`:
- Around line 28-29: The code is using a cache-only reservation (via
loadReservation) for the initial deploy, which can return a stale local
reservation; instead call the server-resolving function ensureReservation for
the deploy write path so the reservation is validated/created server-side;
replace the loadReservation usage at deploy time with ensureReservation, and
only call clearCachedReservation if ensureReservation returns a
different/invalid reservation or on explicit error paths to force a fresh
server-side lookup.
- Around line 131-177: When validating category metadata and article bodies,
surface failures to the errors array instead of silently falling back: if
categoryMetaSchema.safeParse(raw) returns parsed.success === false, push a
descriptive error into errors (e.g. `${categorySlug}/_category.json:
${parsed.error.issues.map(i=>i.message).join(", ")}`) before continuing (you may
still use the default meta but it must be reported), and when processing
articles after frontmatterSchema, verify content.trim().length > 0 and if empty
push an error like `${categorySlug}/${file}: Empty article body` and skip adding
that article to articles; update the branch around categoryMetaSchema, the code
handling parsed from categoryMetaSchema, and the article push logic (where
articles.push is called) to implement these checks.

In `@packages/cli/src/commands/rename.ts`:
- Around line 61-84: Remove the client-side early-return that checks
current.slug === newSlug and instead always call renameReservation(session,
newSlug) so the server can verify and clear stale cache (no_reservation) for
same-slug requests; update the logic in the rename command around
loadReservation/renameReservation (and the similar block at the later check
around lines 94-101) to rely on the idempotent PATCH endpoint rather than
returning "Already reserved" from cache-only state, and keep using outro only
after the server response confirms no-op or success.
- Around line 132-142: The error mapping for the regex match `/slug_invalid/`
currently constructs a HelpbaseError with code "E_SLUG_RESERVED", which is
incorrect; update the HelpbaseError invocation in the block that checks `if
(/slug_invalid/.test(msg))` to use the machine-readable invalid-slug error code
(e.g., "E_SLUG_INVALID") instead of "E_SLUG_RESERVED", keeping the existing
problem/cause/fix messages and references to `newSlug` intact so downstream
error handling and docs reflect an invalid-slug error rather than a
reserved-slug error.

In `@packages/cli/src/commands/whoami.ts`:
- Around line 149-152: Replace the hard-coded ".helpbase.dev" domain in the
reserved URL output with the server-provided reservation.liveUrl: inside the
else if (reservation) block where console.log constructs the reserved line (the
call using pc.cyan and reservation.slug), concatenate reservation.slug with
reservation.liveUrl (instead of ".helpbase.dev") so the printed reserved URL
matches the JSON/liveUrl returned by the server while leaving the rest of the
message/pc.dim text unchanged.

---

Outside diff comments:
In `@apps/web/app/`(tenant)/t/[tenant]/mcp/route.ts:
- Around line 241-263: The route exposes reservation state before
authentication: move the bearer-token checks (extractBearer and tokensEqual
against tenant.mcp_public_token) to run before the reserved-tenant branch that
inspects tenant.deployed_at and returns NextResponse.json({...}, { status: 403
}); specifically, validate the provided token and return 401 responses for
missing/invalid tokens using the existing extractBearer(...) and
tokensEqual(...) logic, and only after a successful token validation check
tenant.deployed_at and return the structured 403 response for
"tenant_not_deployed".

In `@packages/cli/src/commands/whoami.ts`:
- Around line 52-89: The tenant lookup uses listMyTenants but treats a failure
the same as "no tenants", allowing ensureReservation() to run and potentially
create a reservation for accounts that actually have deployed tenants; fix this
by distinguishing a failed lookup from an empty result (e.g., introduce a flag
like tenantLookupSucceeded set to true at the end of the try that calls
listMyTenants) and only run the mutating fallback (ensureReservation) when
tenantLookupSucceeded is true and tenant is null; update the conditional around
ensureReservation/loadReservation to require that successful lookup flag (and
keep loadReservation behavior the same).

---

Nitpick comments:
In `@apps/web/test/reservation-cron.test.ts`:
- Around line 13-17: Tests duplicate production logic via cutoffFor and
filterToDelete; instead import and use the real predicate helpers from the
cleanup route (or call the cleanup route endpoint) so tests exercise the exact
production filters. Replace local cutoffFor/filterToDelete usage with the
exported TTL/predicate functions from the cleanup code (or add an integration
test that invokes the route and asserts the Supabase query/filter parameters
were used), ensuring you reference and import the production helper functions
used by the cleanup job rather than re-implementing them in
reservation-cron.test.ts.

In `@CHANGELOG.md`:
- Around line 59-65: Changelog wording is inaccurate: replace the explicit SQL
predicate text (`NOT EXISTS (SELECT 1 FROM tenant_deploys WHERE tenant_id =
tenants.id)`) with a description that matches the implementation in
cleanup-reservations/route.ts — e.g. state it's "guarded by a deploy-history
shadow check" and note that the handler performs a separate tenant_deploys
lookup and JS-level filtering (the code path that inspects tenant_deploys then
reapplies only the reservation predicates before DELETE) rather than an atomic
NOT EXISTS SQL predicate; update the sentence so readers understand the guard is
implemented as a separate lookup+filter, not an inlined SQL predicate.
🪄 Autofix (Beta)

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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 326879bb-9cd9-4272-bb00-9071fb7420a1

📥 Commits

Reviewing files that changed from the base of the PR and between f32be13 and 24f855b.

📒 Files selected for processing (26)
  • CHANGELOG.md
  • apps/web/app/(tenant)/t/[tenant]/mcp/route.ts
  • apps/web/app/(tenant)/t/_not-found/page.tsx
  • apps/web/app/(tenant)/t/_reserved/[slug]/page.tsx
  • apps/web/app/api/cron/cleanup-reservations/route.ts
  • apps/web/app/api/v1/tenants/auto-provision/route.ts
  • apps/web/app/api/v1/tenants/mine/route.ts
  • apps/web/app/api/v1/tenants/reservation/route.ts
  • apps/web/app/api/v1/tenants/reservation/slug/route.ts
  • apps/web/proxy.ts
  • apps/web/test/reservation-cron.test.ts
  • apps/web/types/supabase.ts
  • apps/web/vercel.json
  • docs/cli.md
  • packages/cli/src/commands/deploy.ts
  • packages/cli/src/commands/login.ts
  • packages/cli/src/commands/open.ts
  • packages/cli/src/commands/rename.ts
  • packages/cli/src/commands/whoami.ts
  • packages/cli/src/index.ts
  • packages/cli/src/lib/errors.ts
  • packages/cli/src/lib/help.ts
  • packages/cli/src/lib/reservation-cache.ts
  • packages/cli/src/lib/reservation.ts
  • packages/cli/src/lib/tenants-client.ts
  • packages/cli/test/reservation-cache.test.ts

Comment thread CHANGELOG.md Resolved
Comment thread packages/cli/src/commands/deploy.ts Resolved
Comment thread packages/cli/src/commands/deploy.ts Resolved
Comment thread packages/cli/src/commands/rename.ts Outdated
Comment on lines +61 to +84
const current = await loadReservation(session)
if (!current) {
throw new HelpbaseError({
code: "E_RESERVATION_MISSING",
problem: "You don't have an active reservation to rename.",
cause:
"Renames only apply to the pre-deploy placeholder `docs-<hex>` slug that login auto-provisions. " +
"After your first deploy (or if you logged in before reservations existed), the tenant's slug is fixed.",
fix: [
`To claim a specific slug on first deploy, use ${pc.cyan("helpbase deploy --slug <name>")}.`,
`To see your current state, run ${pc.cyan("helpbase whoami")}.`,
],
})
}

if (current.slug === newSlug) {
outro(
`Already reserved ${pc.cyan(current.liveUrl)} — nothing to rename.`,
)
return
}

try {
const updated = await renameReservation(session, newSlug)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Let the server verify same-slug renames.

Line 76 returns “Already reserved” from cache-only state. If the reservation was deployed/deleted/cleaned up elsewhere, this bypasses the server and leaves stale cache in place. The PATCH endpoint is already idempotent for same-slug requests, so call it and let no_reservation clear the cache.

Proposed fix
-    const current = await loadReservation(session)
+    const current = await loadReservation(session, { forceRefresh: true })
     if (!current) {
+      clearCachedReservation()
       throw new HelpbaseError({
         code: "E_RESERVATION_MISSING",
         problem: "You don't have an active reservation to rename.",
@@
       })
     }
 
-    if (current.slug === newSlug) {
-      outro(
-        `Already reserved ${pc.cyan(current.liveUrl)} — nothing to rename.`,
-      )
-      return
-    }
-
     try {
       const updated = await renameReservation(session, newSlug)
       // Overwrite the local cache so the next `whoami` / `open` reflects
       // the new slug without a second round-trip.
@@
         userId: session.userId,
       })
+      if (current.slug === updated.slug) {
+        outro(
+          `Already reserved ${pc.cyan(updated.live_url)} — nothing to rename.`,
+        )
+        return
+      }
       note(
         `${pc.dim("Before:")} ${pc.dim(current.liveUrl)}\n` +
           `${pc.dim("After:")}  ${pc.cyan(updated.live_url)}`,

Also applies to: 94-101

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cli/src/commands/rename.ts` around lines 61 - 84, Remove the
client-side early-return that checks current.slug === newSlug and instead always
call renameReservation(session, newSlug) so the server can verify and clear
stale cache (no_reservation) for same-slug requests; update the logic in the
rename command around loadReservation/renameReservation (and the similar block
at the later check around lines 94-101) to rely on the idempotent PATCH endpoint
rather than returning "Already reserved" from cache-only state, and keep using
outro only after the server response confirms no-op or success.

Comment thread packages/cli/src/commands/rename.ts Resolved
Comment thread packages/cli/src/commands/whoami.ts Resolved
- MCP route: authenticate before checking deployed_at so unauth'd callers
  can't distinguish reserved tenants from unknown slugs via the 403 shape
- whoami: gate ensureReservation fallback on tenantLookupSucceeded so a
  /mine network blip doesn't mint an unwanted reservation for an account
  that may already own deployed tenants
- whoami: render reservation host from reservation.liveUrl (server source
  of truth) instead of hard-coding `${slug}.helpbase.dev`
- rename: force-refresh loadReservation before the same-slug short-circuit
  so a stale cache can't lie to the user ("nothing to rename") when the
  server knows a different slug
- rename: slug_invalid now maps to E_SLUG_INVALID (was E_SLUG_RESERVED)
- deploy: force-refresh reservation on the write path (cache-first is
  fine for whoami/open; deploy pays the one round-trip)
- deploy: tighten content validation — report _category.json schema
  failures and reject empty article bodies so orphan tenants can't be
  created from malformed content
- _reserved landing: render host from NEXT_PUBLIC_ROOT_DOMAIN instead
  of hard-coded "helpbase.dev" so staging/preview display correctly
- CHANGELOG: consolidate duplicate ### Changed sections under Unreleased
- reservation-cleanup: extract TTL constant + filterDeletable to
  lib/reservation-cleanup.ts; route handler and unit tests now import
  the same functions (no more shadow copy in the test file)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@Codehagen
Codehagen merged commit 1be6897 into main Apr 18, 2026
5 checks passed
@Codehagen
Codehagen deleted the cli-dx-reservation branch April 18, 2026 11:40
Codehagen added a commit that referenced this pull request Apr 18, 2026
After PR #10, `helpbase login` auto-provisions `docs-<hex>.helpbase.dev`
instantly, so `deploy` has nothing to prompt for. The Quick Start now
leads with the 3-command happy path (login → optional rename → deploy)
and keeps the local `ingest` flow as a sibling subsection. Also fixes
the stale "pick a subdomain" line in "Go live in one command".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Codehagen added a commit that referenced this pull request Apr 18, 2026
Two things:
1. content_hash error message literal "@workspace/shared/article-hash" leaked
   into the scaffolder templates via sync:templates, tripping the drift gate
   that rejects any @workspace/* reference in templates. Reworded to "hash
   via hashArticle".

2. Running pnpm sync:templates also picked up pre-existing drift from PR #10:
   apps/web/lib/reservation-cleanup.ts was added but never synced to
   packages/create-helpbase/templates/ or registry/helpbase/. First PR to
   touch shared code since is the one that heals the drift — that's this
   one. No functional change, just the sync catching up.

Local verification: pnpm sync:templates → "✓ Validation passed: no
@workspace/* references in registry". git diff --exit-code clean against
the committed sync outputs.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Codehagen added a commit that referenced this pull request Apr 18, 2026
)

* feat(shared): article-hash for deploy --preview diffing

Deterministic SHA-256 over (title + description + sorted frontmatter + content).
Same algorithm runs on client (pre-deploy diff) and server (stored in
tenant_articles.content_hash). No whitespace normalization — MDX carries
meaningful whitespace in code blocks, JSX, and fenced content, so the hash
reflects exact deployed bytes.

Snapshot-tested: if the algorithm drifts, every deployed tenant's content_hash
goes stale. Test fails loudly to prevent silent drift.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(db): add content_hash + deploy_version; deploy_tenant returns version

Two supabase migrations (applied via MCP, not committed to scripts/):
- add_content_hash_and_deploy_version_v2_preview: tenant_articles.content_hash text NOT NULL DEFAULT '', tenants.deploy_version bigint NOT NULL DEFAULT 0
- deploy_tenant_rpc_v2_content_hash_and_version: RPC now accepts p_expected_deploy_version (optional), locks the tenant row FOR UPDATE, raises stale_deploy_version (P0001) on mismatch, stores content_hash from article payload, increments deploy_version atomically, returns { deploy_id, new_deploy_version }
- drop_deploy_tenant_legacy_overload: remove old 5-arg signature so there's one deploy_tenant function

Empty content_hash on pre-v2 rows shows as "updated" on first post-migration preview (semantically correct — we genuinely don't know if content matches). Next deploy populates real hashes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(web): /state endpoint + deploy route passes expected_deploy_version

Phases 4 + 5 of v2 preview:

- New GET /api/v1/tenants/:id/state returns deploy_version + articles metadata
  (with content_hash, no content bodies) + categories. Powers `deploy --preview`
  client-side diff. force-dynamic to prevent Vercel ISR staleness.

- Updated POST /api/v1/tenants/:id/deploy to pass p_expected_deploy_version
  through to the RPC (optional — CI callers that do not preview can omit it).
  Translates stale_deploy_version SQLSTATE P0001 to 409 with a parsed
  current_deploy_version field so the CLI can auto-refetch.

- deployPayloadSchema now includes content_hash per article (defaults to empty)
  and a top-level expected_deploy_version (nullable). Zod validation happens
  before the RPC fires; malformed payloads return 400s with field paths.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(cli): deploy --preview + smart-prompt + auto-retry on stale

Phases 3 + 7 + 8 combined for coherent change:

- Refactor deploy.ts .action() into named helpers (validateAndReadContent,
  resolveTenant, performDeploy, stalePreviewRetry, buildDeployPayload).
  Zero behavior change on the existing paths; existing 13 deploy-* tests
  still pass. Enables unit testing the new logic in isolation.

- --preview flag: fetches /state, computes diff, renders preview table,
  exits 0. Works on fresh reservations (no tenant row yet) by diffing
  against an empty remote.

- Smart prompt (D1A): silent one-line summary on routine adds/updates;
  full preview table + y/n confirmation when removes are detected.
  --yes skips the prompt; HELPBASE_TOKEN non-interactive mode skips
  both the state fetch AND the prompt (preserves CI speed).

- Auto-retry (D3A): PreviewStaleError from the deploy RPC triggers a
  single refetch-recompute-reprompt cycle before failing. Catches the
  concurrent-deploy case without making the user re-run the whole flow.

- Help-text cross-reference (D2A): helpbase deploy --help and
  helpbase preview --help each point at the other command. Resolves
  the accepted --preview naming overload.

- New article-diff library: computeDiff over (articles, categories) by
  (category, slug) identity. renderPreviewTable with colored adds/updates/
  removes. renderSummaryLine for the silent happy path.

- tenants-client additions: getTenantState, TenantState/StateArticle/
  StateCategory types, PreviewStaleError class, deployTenant translates
  HTTP 409 stale_deploy_version to the typed error.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* test(cli): article-diff combinatorics + render smoke tests

23 unit tests covering:
- empty local + empty remote (no changes)
- fresh reservation (all local = added)
- same hash = unchanged, different hash = updated
- category move = remove+add (v2.1 rename heuristics deferred)
- slug rename = remove+add
- pre-v2 empty content_hash shows as updated (correct: we don't know)
- file_path alone is metadata, not identity
- mixed add+update+remove+unchanged combinatorics
- category title/icon/order changes = updated
- renderSummaryLine for silent happy-path
- renderPreviewTable truncates long titles, groups sections

All pass. Existing deploy-chunker + deploy-delete-validation tests still green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(cli): validate content before auth so error messages match the real problem

The v2 refactor reordered action() to auth BEFORE content validation. That meant
users in an empty folder or with bad frontmatter saw "Not signed in" first —
masking the actual blocker. Regression caught by /devex-review on 2026-04-18.

Fix: run the full local validation path (existence check + frontmatter parse +
_category.json parse + empty-body guard) before ensureAuthenticated(). All of
those are pure-local with zero server interaction, so there's no reason to
gate them on a session. Auth still runs for every path that actually needs
it (state fetch, deploy RPC, rotate token).

Verified scenarios:
- empty dir                 → "No content/ directory found. Run npx create-helpbase"
- bad frontmatter + no auth → zod errors per article, not "Not signed in"
- valid content + no auth   → "Not signed in" (the real blocker)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: P1 correctness from codex /review — stale retry noop, reservation cache, slug race

Three P1 issues caught by codex adversarial review of the v2 branch:

1. Stale-retry no-op was treated as failure. stalePreviewRetry() returned null
   when the refetched remote already matched local (concurrent client shipped
   the same content), and the caller exited 1. Under concurrent deploy
   traffic, the loser saw correct outcome but broken exit code. Now returns
   a tri-state DeployOutcome { deployed | noop | aborted }, and noop exits 0.

2. Reservation cache not cleared on successful retry. clearCachedReservation()
   was wired to the direct-success branch only; a stale-retry-success left
   the cache stale, so whoami kept showing the consumed reservation. Moved
   the cache clear to the outcome handler so it runs for both deployed and
   noop kinds.

3. Restore post-deploy MCP config JSON block (feature regression from v2
   refactor). The paste-ready Claude Desktop / Cursor config used to print
   after every deploy; the refactor dropped it. Added mcpToken fetch after
   the deploy outcome, re-added the config render in printDeploySuccess.

4. Deploy route slug was read before the RPC committed. A concurrent
   reservation rename between requireOwnedTenant() and the RPC could cause
   the response and revalidatePath() to point at the stale subdomain. Now
   re-reads tenants.slug after the RPC commits.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs: CHANGELOG entries for deploy --preview + smart-prompt + /state

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix: CodeRabbit review findings on PR #11

7 findings from CodeRabbit on the v2 preview branch:

1. apps/web/app/api/v1/tenants/[id]/deploy/route.ts
   - Silent fallback to { deployId: null, newDeployVersion: 0 } on empty RPC
     result could poison the next preview cycle (client caches 0, next deploy
     always hits stale_deploy_version). Fail loudly with 503 instead.
   - Stale-version discriminator was error.message substring only — too
     fragile. Check error.code === "P0001" first, then parse the message.
   - Belt-and-braces: recompute content_hash server-side via hashArticle
     before the RPC, so even buggy or older clients can't persist
     content_hash="" into tenant_articles.

2. packages/shared/src/article-hash.ts
   - "\n" delimiter between raw title/description/content allowed a theoretical
     collision: {title:"A",desc:"B\nC"} and {title:"A\nB",desc:"C"} hashed
     identically. JSON.stringify each field before joining so embedded newlines
     can't cross field boundaries. Added regression test for the collision
     pair. Snapshot updated — safe because no tenant has a real content_hash
     yet (migration backfilled to "").

3. packages/shared/src/schemas.ts
   - content_hash: z.string().default("") silently allowed empty hashes to
     persist and mark every article as UPDATED on the next preview forever.
     Now z.string().min(1, "content_hash is required ..."). Missing field =>
     clear 400.

4. packages/cli/src/lib/article-diff.ts
   - categoryDiffers used "?? ''" on remote.description which is typed as
     non-nullable in StateCategory — either the fallback is dead code or the
     type is wrong. Removed the fallback; type and runtime agree now. Kept
     the fallback for remote.icon because that field IS nullable per schema.

5. packages/cli/src/commands/deploy.ts
   - Duplicate fs.existsSync(contentDir) check: once in action(), again in
     validateAndReadContent. Collapsed to a single authoritative check inside
     validateAndReadContent. Same behavior, less code.

6. CHANGELOG.md
   - Two "### Changed" subsections under [Unreleased] (v2 deploy/RPC + older
     prior-work entries). Keep-a-Changelog expects one subsection per
     category per version. Merged.

Verification: 4/4 turbo typechecks clean, 36/36 CLI tests + 20/20 shared hash
tests pass (including new regression), pre-existing 4 llm-errors failures
unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ci): schema copy + heal pre-existing sync drift

Two things:
1. content_hash error message literal "@workspace/shared/article-hash" leaked
   into the scaffolder templates via sync:templates, tripping the drift gate
   that rejects any @workspace/* reference in templates. Reworded to "hash
   via hashArticle".

2. Running pnpm sync:templates also picked up pre-existing drift from PR #10:
   apps/web/lib/reservation-cleanup.ts was added but never synced to
   packages/create-helpbase/templates/ or registry/helpbase/. First PR to
   touch shared code since is the one that heals the drift — that's this
   one. No functional change, just the sync catching up.

Local verification: pnpm sync:templates → "✓ Validation passed: no
@workspace/* references in registry". git diff --exit-code clean against
the committed sync outputs.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Codehagen added a commit that referenced this pull request Apr 18, 2026
Cut the 0.6.0 release. Bundles:
- deploy --preview + smart-prompt + auto-retry (#11)
- slug reservation flow (#10)
- context → ingest rename (#9)
- TTHW squeeze (#8)
- BYOK review-driven normalization

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

This branch was successfully deployed

1 active deployment
Preview — 82e9ad32 Deployed Apr 18, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant