Repository navigation
feat: deploy --preview + smart-prompt + optimistic concurrency (v2) - #11
Conversation
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>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Rate limit exceeded
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 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 configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (11)
📝 WalkthroughWalkthroughAdded Changes
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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 | 🟡 MinorDuplicate
### Changedsubsection within[Unreleased].There are two
### Changedheaders under[Unreleased]— one at line 38 (v2 deploy/RPC changes) and another at line 131 (older prior-work changes likecontext→ingest, tenants/mine filtering,tenants_publicview). 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### Changedblocks 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_hashdefaulting 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 persistcontent_hash: ""intenant_articles. The diff engine treats empty remote hash asUPDATED(covered byarticle-diff.test.ts"empty remote content_hash ... shows as UPDATED"), so those articles would be markedUPDATEDon 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
hashArticlein 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'sRAISE EXCEPTIONmessage (e.g., i18n, adding a prefix, or renamingstale_deploy_version:todeploy_version_stale:) will silently downgrade a legitimate conflict to a 503deploy_failed, and the CLI'sPreviewStaleErrorauto-retry never fires.Supabase's error object exposes a
codeproperty (SQLSTATE). Since the RPC usesRAISE ... USING ERRCODE P0001(as documented in the schema comments), check the code first and use the message only to parsecurrent_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"intenants/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.descriptionis declaredstring(non-nullable) intenants-client.tsline 64, so the fallback can never fire. Either align the type tostring | nullif the server can actually return null, or drop the??to avoid implying otherwise.remote.icon ?? ""on the next line is correct becauseiconis 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.previewin thiselse ifis always true.The
--previewbranch 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: thecontent/existence check is duplicated.Lines 145-151 check
fs.existsSync(contentDir)and show a friendly message, butvalidateAndReadContentrepeats 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
📒 Files selected for processing (13)
CHANGELOG.mdapps/web/app/api/v1/tenants/[id]/deploy/route.tsapps/web/app/api/v1/tenants/[id]/state/route.tsapps/web/types/supabase.tspackages/cli/src/commands/deploy.tspackages/cli/src/commands/preview.tspackages/cli/src/lib/article-diff.tspackages/cli/src/lib/tenants-client.tspackages/cli/test/article-diff.test.tspackages/shared/package.jsonpackages/shared/src/article-hash.tspackages/shared/src/schemas.tspackages/shared/test/article-hash.test.ts
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>
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.helpbase deployis silent-by-default on routine add/update flows (one-line summary), full preview + y/n confirm when removes are detected.--yesskips the prompt. Non-interactive (HELPBASE_TOKEN) mode preserves current CI behavior: no state fetch, no prompt.GET /api/v1/tenants/:id/state— metadata-only snapshot (with per-articlecontent_hash) +deploy_version. Markedforce-dynamicto 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 overtitle + 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_tenantRPC now locks the tenant rowFOR UPDATE, accepts optionalp_expected_deploy_version, raisesstale_deploy_version(SQLSTATE P0001) on mismatch, storescontent_hashfrom 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-validationtests still green.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):
stalePreviewRetry()returnednullfor both success-noop and abort; caller exited 1. Converted to tri-stateDeployOutcome { deployed \| noop \| aborted }; noop now exits 0 correctly (CI loops no longer spuriously fail on concurrent deploys).clearCachedReservation()was wired to the direct-success branch only. Moved to the outcome handler so it runs for bothdeployedandnoop.requireOwnedTenant()and RPC could stale the response slug. Now re-readstenants.slugafter the RPC commits.DX regression fixed (from /devex-review):
helpbase deployin an empty folder showed "Not signed in". Auth was running before content validation. Restored pre-v2 ordering: local fs + Zod validation runs BEFOREensureAuthenticated()so the error the user sees matches the real blocker.Feature regression caught + restored:
Plan Completion
Design doc:
~/.gstack/projects/help-center/christer-main-design-20260418-151601.md(Approach A locked).article-hash.tsin shared + package exportsdeploy.tsaction refactored into helpers (5B)GET /api/v1/tenants/[id]/stateroute withforce-dynamicexpected_deploy_versionPreviewStaleErrordeploy --previewflag + smart-prompt (D1A) + auto-retry (D3A)All locked design decisions shipped: T1A (first-deploy no-orphan), T2B (deploy_version required), T3A (hash exact bytes + stored column), T4A (single
/stateendpoint 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 passbun test packages/cli/test/article-diff.test.ts— 23 passbun 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 cleanturbo lint— 0 errors on new fileshelpbase deploy --helpshows D2A cross-refnpx create-helpbasedeploy --previewcoldscripts/release.shworkflow)🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes
New Features
--previewflag to deploy command, displaying a color-coded diff table of article and category changes before deployment.Bug Fixes