Skip to content

feat: deploy --preview + smart-prompt + optimistic concurrency (v2) - #11

Merged
Codehagen merged 10 commits into
mainfrom
feat/deploy-preview-v2
Apr 18, 2026
Merged

Codehagen merged 10 commits into
mainfrom
feat/deploy-preview-v2

Conversation

@Codehagen

@Codehagen Codehagen commented Apr 18, 2026 •

Copy link
Copy Markdown
Owner

Summary

v2 of helpbase deploy — see what will change before shipping, destructive operations are gated on a confirmation prompt, concurrent deploys no longer overwrite each other silently.

New surface:

  • helpbase deploy --preview — fetches deployed state, diffs locally, prints a color-coded preview table (added/updated/removed × articles AND categories), exits without deploying. Works on the first-ever deploy (fresh reservation) by diffing against an empty remote without creating the tenant row.
  • Smart-prompt (D1A) — helpbase deploy is silent-by-default on routine add/update flows (one-line summary), full preview + y/n confirm when removes are detected. --yes skips the prompt. Non-interactive (HELPBASE_TOKEN) mode preserves current CI behavior: no state fetch, no prompt.
  • Auto-retry on stale (D3A) — if another client ships between your preview fetch and your confirm, the CLI automatically refetches state, re-renders the diff, and reprompts inline. One-retry cap. Noop ("remote now matches") exits 0 correctly.
  • GET /api/v1/tenants/:id/state — metadata-only snapshot (with per-article content_hash) + deploy_version. Marked force-dynamic to prevent Vercel ISR from serving stale snapshots.

Schema + RPC changes (applied live to Supabase via MCP):

  • tenant_articles.content_hash text NOT NULL DEFAULT '' — SHA-256 over title + description + sorted-key frontmatter + content, exact bytes, no whitespace normalization. Same algorithm on client (@workspace/shared/article-hash) and server (stored by the deploy RPC).
  • tenants.deploy_version bigint NOT NULL DEFAULT 0 — monotonic counter for optimistic concurrency.
  • deploy_tenant RPC now locks the tenant row FOR UPDATE, accepts optional p_expected_deploy_version, raises stale_deploy_version (SQLSTATE P0001) on mismatch, stores content_hash from article payload, returns {deploy_id, new_deploy_version}. Old 5-arg overload dropped.

Test Coverage

42 new tests all passing. 13 existing deploy-chunker/deploy-delete-validation tests still green.

CODE PATH COVERAGE (v2)
===========================
[+] packages/shared/src/article-hash.ts
    └── hashArticle() + stableStringify()
        ├── [★★★ TESTED] Deterministic, SHA-256 format, snapshot locked
        ├── [★★★ TESTED] Frontmatter key-order independence (top + nested)
        ├── [★★★ TESTED] Whitespace NOT normalized (trailing newline, tab vs space)
        ├── [★★★ TESTED] Title/description/content change detection
        └── [★★★ TESTED] Null/undefined/empty frontmatter handling
[+] packages/cli/src/lib/article-diff.ts
    └── computeDiff(), diffHasChanges(), diffHasRemoves(), renderSummaryLine(), renderPreviewTable()
        ├── [★★★ TESTED] Fresh reservation (empty remote) → all added
        ├── [★★★ TESTED] Same/different content_hash → unchanged/updated
        ├── [★★★ TESTED] Category move = remove+add; slug rename = remove+add
        ├── [★★★ TESTED] file_path alone is metadata, not identity
        ├── [★★★ TESTED] Empty remote content_hash (pre-v2 row) shows as updated
        ├── [★★★ TESTED] Mixed add+update+remove+unchanged combinatorics
        ├── [★★★ TESTED] Category title/icon/order/description change = updated
        ├── [★★★ TESTED] Category removed = destructive (diffHasRemoves true)
        └── [★★★ TESTED] Summary line format, long-title truncation, section grouping
[+] packages/cli/src/commands/deploy.ts (tri-state DeployOutcome)
    └── Live CLI dogfood:
        ├── [TESTED] empty dir → "No content/" (not "Not signed in")
        ├── [TESTED] bad frontmatter + no auth → Zod errors first
        └── [TESTED] help-text cross-refs between `deploy` and `preview`

─────────────────────────────────
COVERAGE: 42 new tests, 100 expect() calls
Tests: ~260 → ~302 (+42 new)
─────────────────────────────────

Pre-Landing Review

Ran /plan-eng-review (plan stage, 14 issues surfaced), /plan-devex-review (plan stage, D1A/D2A/D3A decisions), and /review (diff stage, 3 P1s). All P1s fixed in this branch.

P1 fixes (from codex /review):

  • Stale-retry noop was treated as failure. stalePreviewRetry() returned null for both success-noop and abort; caller exited 1. Converted to tri-state DeployOutcome { deployed \| noop \| aborted }; noop now exits 0 correctly (CI loops no longer spuriously fail on concurrent deploys).
  • Reservation cache not cleared on successful retry. clearCachedReservation() was wired to the direct-success branch only. Moved to the outcome handler so it runs for both deployed and noop.
  • Deploy route slug read before RPC committed. Concurrent reservation rename between requireOwnedTenant() and RPC could stale the response slug. Now re-reads tenants.slug after the RPC commits.

DX regression fixed (from /devex-review):

  • helpbase deploy in an empty folder showed "Not signed in". Auth was running before content validation. Restored pre-v2 ordering: local fs + Zod validation runs BEFORE ensureAuthenticated() so the error the user sees matches the real blocker.

Feature regression caught + restored:

  • Post-deploy MCP config JSON snippet (paste-ready for Claude Desktop / Cursor / Claude Code) had been dropped during the refactor. Re-added.

Plan Completion

Design doc: ~/.gstack/projects/help-center/christer-main-design-20260418-151601.md (Approach A locked).

  • ✅ Phase 1 — article-hash.ts in shared + package exports
  • ✅ Phase 2 — DB migrations (content_hash + deploy_version) applied via Supabase MCP
  • ✅ Phase 3 — deploy.ts action refactored into helpers (5B)
  • ✅ Phase 4 — GET /api/v1/tenants/[id]/state route with force-dynamic
  • ✅ Phase 5 — Deploy RPC + web route pass expected_deploy_version
  • ✅ Phase 6 — CLI tenants-client + article-diff + PreviewStaleError
  • ✅ Phase 7 — deploy --preview flag + smart-prompt (D1A) + auto-retry (D3A)
  • ✅ Phase 8 — Help-text cross-refs (D2A)
  • ✅ Phase 9 — Tests (hash + diff combinatorics + edge cases)
  • ✅ Phase 10 — Typecheck + lint clean

All locked design decisions shipped: T1A (first-deploy no-orphan), T2B (deploy_version required), T3A (hash exact bytes + stored column), T4A (single /state endpoint with articles + categories + version), T5A (founder-overridden to --preview), T6A→D1A (smart-prompt on destructive only).

Test plan

  • bun test packages/shared/test/article-hash.test.ts — 19 pass
  • bun test packages/cli/test/article-diff.test.ts — 23 pass
  • bun test packages/cli/test/deploy-chunker.test.ts packages/cli/test/deploy-delete-validation.test.ts — 13 pass (no regressions)
  • turbo typecheck — 4/4 packages clean
  • turbo lint — 0 errors on new files
  • Live CLI: helpbase deploy --help shows D2A cross-ref
  • Live CLI: empty dir error points at npx create-helpbase
  • Live CLI: bad frontmatter surfaces Zod errors before auth
  • Send Vegard the updated walkthrough and watch him run deploy --preview cold
  • Cut npm release (separate scripts/release.sh workflow)

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features

    • Added --preview flag to deploy command, displaying a color-coded diff table of article and category changes before deployment.
    • Auto-retry mechanism when concurrent deployments are detected.
  • Bug Fixes

    • Local content validation now runs before authentication checks, surfacing relevant errors to users first.

Codehagen and others added 8 commits April 18, 2026 16:10
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>
…rsion

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>
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>
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>
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>
…al 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>
…n 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>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@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 3:04pm

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 38 minutes and 40 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 38 minutes and 40 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: 99b03e91-b0ba-4802-a27b-30642be58343

📥 Commits

Reviewing files that changed from the base of the PR and between d11b9bf and 1b585cb.

📒 Files selected for processing (11)
  • CHANGELOG.md
  • apps/web/app/api/v1/tenants/[id]/deploy/route.ts
  • packages/cli/src/commands/deploy.ts
  • packages/cli/src/lib/article-diff.ts
  • packages/create-helpbase/templates/lib/reservation-cleanup.ts
  • packages/create-helpbase/templates/lib/schemas.ts
  • packages/shared/src/article-hash.ts
  • packages/shared/src/schemas.ts
  • packages/shared/test/article-hash.test.ts
  • registry/helpbase/lib/reservation-cleanup.ts
  • registry/helpbase/lib/schemas.ts
📝 Walkthrough

Walkthrough

Added --preview functionality to CLI deploy command that fetches deployed state, computes local vs remote diff, renders color-coded preview table, and implements optimistic concurrency control via deploy_version. New /api/v1/tenants/:id/state endpoint returns full deployed snapshot. Schema additions include tenant_articles.content_hash and tenants.deploy_version for concurrency tracking.

Changes

Cohort / File(s) Summary
Deploy preview and diff logic
packages/cli/src/lib/article-diff.ts, packages/cli/test/article-diff.test.ts
New diff engine comparing local content against remote snapshot; includes computeDiff, renderPreviewTable, renderSummaryLine, and identity helpers; comprehensive test coverage for article/category added/updated/unchanged/removed states.
Deploy command enhancement
packages/cli/src/commands/deploy.ts
Major refactor adding --preview option, destructive-change detection, interactive/CI confirmation logic, optimistic concurrency via expected_deploy_version, single-retry on stale preview, and helper functions for validation, tenant resolution, and output formatting.
Deploy API route
apps/web/app/api/v1/tenants/[id]/deploy/route.ts
Modified POST handler to accept optional expected_deploy_version, extract new RPC return shape {deploy_id, new_deploy_version}, emit HTTP 409 on stale_deploy_version, and re-read fresh tenant slug post-RPC for accurate ISR revalidation and response payload.
Tenant state endpoint
apps/web/app/api/v1/tenants/[id]/state/route.ts
New GET handler returning full deployed snapshot (articles with content hashes, categories, deploy_version); marked force-dynamic to prevent stale ISR caching; includes concurrent Supabase queries with error handling.
Type definitions and client
apps/web/types/supabase.ts, packages/cli/src/lib/tenants-client.ts
Added content_hash to tenant_articles; added deploy_version to tenants; updated deploy_tenant RPC typing for new return shape and optional concurrency parameter; new client types StateArticle, StateCategory, TenantState; new error class PreviewStaleError and getTenantState function.
Article hashing utility
packages/shared/src/article-hash.ts, packages/shared/test/article-hash.test.ts
Deterministic SHA-256 hashing for articles combining title, description, stable-serialized frontmatter, and content; includes stableStringify for JSON-like serialization with sorted object keys; comprehensive test coverage including snapshot validation and field/order sensitivity.
Shared schema updates
packages/shared/src/schemas.ts, packages/shared/package.json
Extended deployPayloadSchema with per-article content_hash field and optional expected_deploy_version for optimistic concurrency; exposed article-hash module via package exports.
Documentation and help text
packages/cli/src/commands/preview.ts, CHANGELOG.md
Updated helpbase preview command description to reference helpbase deploy --preview; added comprehensive changelog entry documenting preview flow, destructive-change handling, concurrency, retry logic, and validation ordering fixes.

Sequence Diagram

sequenceDiagram
    participant CLI as CLI (deploy --preview)
    participant Auth as Auth/Token
    participant Server as API Server
    participant DB as Database
    
    CLI->>Auth: Validate credentials
    Auth-->>CLI: Session confirmed
    CLI->>CLI: Read local content/ & compute hashes
    
    CLI->>Server: GET /api/v1/tenants/:id/state
    Server->>DB: Query articles, categories, deploy_version
    DB-->>Server: Return deployed snapshot
    Server-->>CLI: TenantState {articles, categories, deploy_version}
    
    CLI->>CLI: computeDiff(local, remote)
    CLI->>CLI: renderPreviewTable(diff)
    CLI->>CLI: Detect destructive changes (removes)
    
    alt Has removals
        CLI->>CLI: Prompt user for confirmation
        CLI->>CLI: User confirms/aborts
    else No removals
        CLI->>CLI: Print summary line only
    end
    
    alt User continues
        CLI->>Server: POST /api/v1/tenants/:id/deploy<br/>{expected_deploy_version, articles, ...}
        Server->>DB: Call deploy_tenant RPC<br/>(optimistic concurrency check)
        
        alt Concurrent deploy detected
            DB-->>Server: stale_deploy_version error
            Server-->>CLI: HTTP 409 {current_deploy_version}
            CLI->>Server: GET /api/v1/tenants/:id/state (retry)
            Server-->>CLI: Updated TenantState
            CLI->>CLI: Recompute diff & re-prompt
            CLI->>Server: POST /api/v1/tenants/:id/deploy (2nd attempt)
            Server->>DB: Call deploy_tenant RPC (should succeed)
            DB-->>Server: {deploy_id, new_deploy_version}
            Server->>DB: Re-read tenant slug
            Server-->>CLI: Deploy success response
        else Version matches
            DB-->>Server: {deploy_id, new_deploy_version}
            Server->>DB: Re-read tenant slug
            Server-->>CLI: Deploy success response
        end
        
        CLI->>CLI: Print deploy success & next steps
    else User aborts
        CLI->>CLI: Exit without deploy
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

  • PR #10: Modifies tenant deployment RPC and schema (adds reservation/deployed_at semantics); directly related to this PR's concurrent deploy_version and RPC return-shape changes.
  • PR #3: Updates tenant deploy API route (/api/v1/tenants/:id/deploy) and CLI tenant client surface; overlaps significantly with this PR's modifications to the same endpoint and client types.

Poem

🐰 A preview before we deploy, oh what joy!
Hash-checked articles and diffs on display,
Stale versions retry with elegant poise,
Color-coded tables light up the way. 🎨✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.30% 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 feature additions (deploy --preview, smart-prompt, optimistic concurrency v2) and reflects the primary scope of this large changeset.
Description check ✅ Passed The description is comprehensive, covering the summary, technical changes, test coverage, review fixes, and plan completion. However, the template requires checking boxes for specific items (pnpm test/typecheck/build, smoke tests if applicable) which are not explicitly marked in the provided description.

✏️ 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 feat/deploy-preview-v2

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.

@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: 2

Caution

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

⚠️ Outside diff range comments (1)
CHANGELOG.md (1)

38-131: ⚠️ Potential issue | 🟡 Minor

Duplicate ### Changed subsection within [Unreleased].

There are two ### Changed headers under [Unreleased] — one at line 38 (v2 deploy/RPC changes) and another at line 131 (older prior-work changes like context → ingest, tenants/mine filtering, tenants_public view). Keep-a-Changelog expects one subsection per category per version, and release-note generators that group by header will either merge them (OK) or drop the second block (not OK). Consolidate the two ### Changed blocks into one under [Unreleased].

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

In `@CHANGELOG.md` around lines 38 - 131, Under the [Unreleased] section there are
two identical "### Changed" headers; remove the second "### Changed" header and
merge its bullet lines (the older prior-work items like the context→ingest note,
tenants/mine filtering, tenants_public view, etc.) into the first "### Changed"
block that begins with the v2 deploy/RPC notes so there is only one consolidated
"### Changed" subsection; ensure you keep all bullets and their order/format and
delete the duplicate header line.
🧹 Nitpick comments (6)
packages/shared/src/schemas.ts (1)

282-282: content_hash defaulting to "" silently weakens the preview-diff contract.

The server stores whatever the client sends, with no recomputation (see apps/web/app/api/v1/tenants/[id]/deploy/route.ts). A legitimate v2 CLI always computes the hash, but any caller that omits the field — or a future SDK bug — would persist content_hash: "" in tenant_articles. The diff engine treats empty remote hash as UPDATED (covered by article-diff.test.ts "empty remote content_hash ... shows as UPDATED"), so those articles would be marked UPDATED on every subsequent preview until the next successful deploy rewrites the row. That's a silent, persistent DX regression.

Two cheap options, pick one:

  • Make it required (no default) so a missing hash is a 400 rather than stored pollution. Safe because the current CLI always sends it.
  • Recompute server-side via hashArticle in the deploy route before passing to the RPC — belt-and-braces against buggy/older clients.
🔧 Option A — require the field
-    content_hash: z.string().default(""),
+    content_hash: z.string().min(1),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/shared/src/schemas.ts` at line 282, The schema's content_hash
currently defaults to "" which allows empty hashes to be persisted and causes
the diff engine to mark articles as UPDATED; either make content_hash required
in the Zod schema (remove .default("") from content_hash in
packages/shared/src/schemas.ts so z.string() is required and missing values will
400) or ensure the server recomputes the hash before persisting by calling
hashArticle in the deploy route handler (the deploy/route.ts logic that prepares
rows for tenant_articles should compute and set content_hash via hashArticle
before calling the RPC) — pick one and implement accordingly.
apps/web/app/api/v1/tenants/[id]/deploy/route.ts (1)

91-112: Tighten stale-deploy detection by gating on SQLSTATE in addition to message substring.

The error.message.includes("stale_deploy_version") check at line 97 is fragile and couples the 409 branch to the exact wording the RPC produces. Any future reword of the RPC's RAISE EXCEPTION message (e.g., i18n, adding a prefix, or renaming stale_deploy_version: to deploy_version_stale:) will silently downgrade a legitimate conflict to a 503 deploy_failed, and the CLI's PreviewStaleError auto-retry never fires.

Supabase's error object exposes a code property (SQLSTATE). Since the RPC uses RAISE ... USING ERRCODE P0001 (as documented in the schema comments), check the code first and use the message only to parse current_deploy_version:

🔧 Tighten the discriminator
-    if (typeof error.message === "string" && error.message.includes("stale_deploy_version")) {
+    const isStale =
+      error.code === "P0001" &&
+      typeof error.message === "string" &&
+      error.message.includes("stale_deploy_version")
+    if (isStale) {
       const m = /current\s+(\d+)/.exec(error.message)

This pattern is already used elsewhere in the codebase for other SQLSTATE checks (e.g., error.code === "23505" in tenants/route.ts).

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

In `@apps/web/app/api/v1/tenants/`[id]/deploy/route.ts around lines 91 - 112, The
stale-deploy branch is too fragile because it only checks error.message; change
the discriminator to first verify the SQLSTATE code (error.code === "P0001") and
then, if present, parse error.message for the "current N" value to populate
current_deploy_version; update the conditional around the existing block that
returns NextResponse.json (and leave the parsing logic and return
payload/message intact), otherwise fall through to the existing console.error +
jsonError("deploy_failed") path.
packages/cli/src/lib/article-diff.ts (1)

69-75: Nit: remote.description ?? "" is unreachable.

StateCategory.description is declared string (non-nullable) in tenants-client.ts line 64, so the fallback can never fire. Either align the type to string | null if the server can actually return null, or drop the ?? to avoid implying otherwise. remote.icon ?? "" on the next line is correct because icon is declared nullable.

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

In `@packages/cli/src/lib/article-diff.ts` around lines 69 - 75, The comparison in
categoryDiffers incorrectly uses a nullish coalescing fallback for
remote.description even though StateCategory.description is non-nullable; update
the code so the comparison is straightforward (remove the "?? ''" fallback) OR
change the StateCategory type to string | null if the server can return null;
locate the categoryDiffers function and either remove the nullish fallback from
the description comparison or adjust the StateCategory.description declaration
to allow null and keep the fallback, ensuring consistency between the runtime
behavior and the type declaration.
packages/cli/src/commands/deploy.ts (3)

257-270: Minor: !opts.preview in this else if is always true.

The --preview branch already returned at line 226, so reaching this point implies !opts.preview. Not a bug, just dead code in the condition — either drop the clause or add a comment clarifying it's defensive.

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

In `@packages/cli/src/commands/deploy.ts` around lines 257 - 270, The condition
`else if (remoteState !== null && !opts.preview)` contains a redundant
`!opts.preview` because the `--preview` branch already returns earlier; update
the condition to `else if (remoteState !== null)` (or keep the current code but
add a brief comment explaining it's defensive) so the clause is not misleading.
Locate the block using the symbols `remoteState`, `opts.preview`,
`diffHasChanges`, and `renderSummaryLine` inside the deploy command and either
remove the `!opts.preview` check or add a clarifying comment above it.

212-214: Nit: ternary can collapse with nullish-coalescing on the remote arg.

Proposed simplification
-      const diff = remoteState
-        ? computeDiff(toDiffInput(content), remoteState)
-        : computeDiff(toDiffInput(content), { articles: [], categories: [] })
+      const diff = computeDiff(
+        toDiffInput(content),
+        remoteState ?? { articles: [], categories: [] },
+      )

Behavior is identical; reads a bit cleaner.

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

In `@packages/cli/src/commands/deploy.ts` around lines 212 - 214, The ternary that
sets diff can be simplified by using nullish coalescing on remoteState; replace
the computeDiff call that currently does remoteState ?
computeDiff(toDiffInput(content), remoteState) :
computeDiff(toDiffInput(content), { articles: [], categories: [] }) with a
single computeDiff(toDiffInput(content), remoteState ?? { articles: [],
categories: [] }) so it still passes the default empty state when remoteState is
null/undefined; update the assignment to the diff variable in deploy.ts where
computeDiff, toDiffInput, and remoteState are used.

142-153: Optional: the content/ existence check is duplicated.

Lines 145-151 check fs.existsSync(contentDir) and show a friendly message, but validateAndReadContent repeats the same check at lines 334-340. Either collapse the outer guard and let the helper own the check, or drop the helper's redundant block. Current behavior is correct, just redundant.

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

In `@packages/cli/src/commands/deploy.ts` around lines 142 - 153, The outer
existence check for the content/ directory is redundant with
validateAndReadContent; remove the fs.existsSync guard and its
cancel/process.exit path in the deploy command and simply call
validateAndReadContent(contentDir) when !opts.rotateMcpToken, relying on
validateAndReadContent to perform the existence check and user-facing error
messaging; leave the contentDir const and the content variable as-is so callers
and error handling in validateAndReadContent (the unique symbol) remain
authoritative.
🤖 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/api/v1/tenants/`[id]/deploy/route.ts:
- Around line 114-119: The RPC deploy_tenant contract guarantees a row, so
silently falling back to deployId=null and newDeployVersion=0 is unsafe; change
the handling in route.ts where data -> row/newDeployVersion is derived
(variables row, deployId, newDeployVersion) to detect an empty or unexpected
response and fail loudly: log an error including the raw RPC result and
throw/return a 500 (or otherwise propagate an error) instead of returning
defaults, so callers/CLI see the contract violation and the next preview cycle
is not poisoned.

In `@packages/shared/src/article-hash.ts`:
- Around line 32-42: hashArticle currently joins raw title and description with
SEPARATOR ("\n"), allowing boundary collisions; change hashArticle to
JSON-encode (e.g., JSON.stringify) each field before joining (apply to title,
description, and keep stableStringify(frontmatter) as is or JSON.stringify it
for consistency) or alternatively use an unambiguous separator like a NUL byte,
then re-run and update the inline snapshot in
packages/shared/test/article-hash.test.ts and add a regression test that covers
the collision pair (title "A", description "B\nC" vs title "A\nB", description
"C") to ensure the new encoding fixes the issue.

---

Outside diff comments:
In `@CHANGELOG.md`:
- Around line 38-131: Under the [Unreleased] section there are two identical
"### Changed" headers; remove the second "### Changed" header and merge its
bullet lines (the older prior-work items like the context→ingest note,
tenants/mine filtering, tenants_public view, etc.) into the first "### Changed"
block that begins with the v2 deploy/RPC notes so there is only one consolidated
"### Changed" subsection; ensure you keep all bullets and their order/format and
delete the duplicate header line.

---

Nitpick comments:
In `@apps/web/app/api/v1/tenants/`[id]/deploy/route.ts:
- Around line 91-112: The stale-deploy branch is too fragile because it only
checks error.message; change the discriminator to first verify the SQLSTATE code
(error.code === "P0001") and then, if present, parse error.message for the
"current N" value to populate current_deploy_version; update the conditional
around the existing block that returns NextResponse.json (and leave the parsing
logic and return payload/message intact), otherwise fall through to the existing
console.error + jsonError("deploy_failed") path.

In `@packages/cli/src/commands/deploy.ts`:
- Around line 257-270: The condition `else if (remoteState !== null &&
!opts.preview)` contains a redundant `!opts.preview` because the `--preview`
branch already returns earlier; update the condition to `else if (remoteState
!== null)` (or keep the current code but add a brief comment explaining it's
defensive) so the clause is not misleading. Locate the block using the symbols
`remoteState`, `opts.preview`, `diffHasChanges`, and `renderSummaryLine` inside
the deploy command and either remove the `!opts.preview` check or add a
clarifying comment above it.
- Around line 212-214: The ternary that sets diff can be simplified by using
nullish coalescing on remoteState; replace the computeDiff call that currently
does remoteState ? computeDiff(toDiffInput(content), remoteState) :
computeDiff(toDiffInput(content), { articles: [], categories: [] }) with a
single computeDiff(toDiffInput(content), remoteState ?? { articles: [],
categories: [] }) so it still passes the default empty state when remoteState is
null/undefined; update the assignment to the diff variable in deploy.ts where
computeDiff, toDiffInput, and remoteState are used.
- Around line 142-153: The outer existence check for the content/ directory is
redundant with validateAndReadContent; remove the fs.existsSync guard and its
cancel/process.exit path in the deploy command and simply call
validateAndReadContent(contentDir) when !opts.rotateMcpToken, relying on
validateAndReadContent to perform the existence check and user-facing error
messaging; leave the contentDir const and the content variable as-is so callers
and error handling in validateAndReadContent (the unique symbol) remain
authoritative.

In `@packages/cli/src/lib/article-diff.ts`:
- Around line 69-75: The comparison in categoryDiffers incorrectly uses a
nullish coalescing fallback for remote.description even though
StateCategory.description is non-nullable; update the code so the comparison is
straightforward (remove the "?? ''" fallback) OR change the StateCategory type
to string | null if the server can return null; locate the categoryDiffers
function and either remove the nullish fallback from the description comparison
or adjust the StateCategory.description declaration to allow null and keep the
fallback, ensuring consistency between the runtime behavior and the type
declaration.

In `@packages/shared/src/schemas.ts`:
- Line 282: The schema's content_hash currently defaults to "" which allows
empty hashes to be persisted and causes the diff engine to mark articles as
UPDATED; either make content_hash required in the Zod schema (remove
.default("") from content_hash in packages/shared/src/schemas.ts so z.string()
is required and missing values will 400) or ensure the server recomputes the
hash before persisting by calling hashArticle in the deploy route handler (the
deploy/route.ts logic that prepares rows for tenant_articles should compute and
set content_hash via hashArticle before calling the RPC) — pick one and
implement accordingly.
🪄 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: 5ccc74c8-d2a5-499c-80a3-b2736a8c47ef

📥 Commits

Reviewing files that changed from the base of the PR and between 976fc4d and d11b9bf.

📒 Files selected for processing (13)
  • CHANGELOG.md
  • apps/web/app/api/v1/tenants/[id]/deploy/route.ts
  • apps/web/app/api/v1/tenants/[id]/state/route.ts
  • apps/web/types/supabase.ts
  • packages/cli/src/commands/deploy.ts
  • packages/cli/src/commands/preview.ts
  • packages/cli/src/lib/article-diff.ts
  • packages/cli/src/lib/tenants-client.ts
  • packages/cli/test/article-diff.test.ts
  • packages/shared/package.json
  • packages/shared/src/article-hash.ts
  • packages/shared/src/schemas.ts
  • packages/shared/test/article-hash.test.ts

Comment thread packages/shared/src/article-hash.ts Resolved
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>
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
Codehagen merged commit fc47cf3 into main Apr 18, 2026
5 checks passed
@Codehagen
Codehagen deleted the feat/deploy-preview-v2 branch April 18, 2026 17:50
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 — 1b585cbf 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