Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 76 additions & 22 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,82 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]

### Added
- **`helpbase deploy --preview` shows what would change before shipping.** The CLI
reads your local `content/`, fetches a metadata-only snapshot of the deployed
tenant, and renders a color-coded preview table (added in green, updated in
yellow, removed in red — articles AND categories). Flag exits 0 without
touching the server. Works on the first-ever deploy too: fresh reservation
shows "all N new locally" without creating the tenant row until you confirm.
Pair with `--yes` for CI previews.
- **Smart-prompt on destructive deploys.** `helpbase deploy` now prints a
one-line summary ("Publishing 3 updated, 1 new") and deploys silently on
routine add/update flows. When the diff contains destructive changes
(article removals, category deletions), the CLI pauses and shows the full
preview table before asking y/n. Matches the helm/kubectl/vercel convention
of silent-on-routine, prompt-on-destructive. Non-interactive mode
(`HELPBASE_TOKEN` set) preserves the current CI behavior — no state fetch,
no prompt.
- **Auto-retry on concurrent deploys.** If another client ships between your
preview fetch and your confirm, the CLI automatically refetches `/state`,
re-renders the diff, and reprompts inline. Capped at one retry to prevent
runaway contention loops. If the concurrent deploy already shipped the
content you were about to ship, the CLI reports "Remote now matches your
local content" and exits 0 (correct no-op, not a failure).
- **`GET /api/v1/tenants/:id/state` endpoint.** Returns the full deployed
snapshot (articles with content hashes, categories, deploy_version) so
clients can diff locally without pulling full article bodies. Marked
`force-dynamic` to prevent Vercel ISR from serving stale snapshots that
would make previews lie.

### Changed
- **`deploy_tenant` RPC now returns `{deploy_id, new_deploy_version}`.** Row
is locked `FOR UPDATE` for the duration of the transaction. Accepts an
optional `p_expected_deploy_version` for optimistic concurrency; mismatch
raises `stale_deploy_version` (SQLSTATE P0001) and the web route translates
that to HTTP 409 with the current version in the body. The CLI surfaces
this as a typed `PreviewStaleError` so the retry path can catch it
specifically.
- **Deploy route re-reads tenant slug post-RPC** so a concurrent
reservation rename between `requireOwnedTenant()` and the deploy RPC
doesn't cause the response and `revalidatePath()` to point at a stale
subdomain.
- **`tenant_articles` gained a `content_hash` column** (SHA-256 of
title + description + sorted-key frontmatter JSON + content, exact bytes,
no whitespace normalization). Same algorithm runs client-side in
`@workspace/shared/article-hash` and server-side when the deploy RPC
writes the row. Pre-v2 rows default to empty string and re-hash on the
next deploy.
- **`tenants` gained a `deploy_version` column** (monotonic counter,
bigint, NOT NULL DEFAULT 0) to back the optimistic concurrency path.
- **`helpbase context` renamed to `helpbase ingest`.** `context` described
a domain concept, not an action — `ingest` names what the command does
(walk your code + markdown, synthesize cited how-tos, wire MCP). The
old name continues to work as a deprecation shim: same flags, same
behavior, one-line stderr warning, suppressed under `--json`/`--quiet`.
Help text + README Quick Start + scaffolder next-steps output now lead
with `ingest`. CI scripts pinned to `helpbase context` keep working
until v0.7, which is when the shim is removed. Flag surface is shared
via `applyIngestOptions()` so the two commands can't drift. First PR
of the CLI DX v2 plan.
- **`/api/v1/tenants/mine` hides reservations.** Reservations are
pre-first-deploy placeholders and shouldn't pollute the tenant
picker for multi-tenant users. The new filter is
`.not("deployed_at", "is", null)`. Callers that specifically want
the reservation (login, whoami, open) hit
`GET /api/v1/tenants/reservation` instead.
- **`tenants_public` view now exposes `deployed_at`.** The subdomain
middleware needs this to distinguish reserved tenants from live
ones without granting anon read access to the full tenants table.
`mcp_public_token` still never appears in the view.

### Fixed
- **Local validation runs before auth so empty-folder errors match the real
problem.** Running `helpbase deploy` in a directory without `content/`
previously showed "Not signed in" (because auth ran before the existence
check). Now shows "No content/ directory found. Run npx create-helpbase"
first. Same ordering for bad frontmatter — Zod errors surface before
auth, so the user sees the actual blocker.

- **`helpbase login` reserves a subdomain instantly.** After successful
authentication, the CLI calls `POST /api/v1/tenants/auto-provision`
which mints a product-neutral `docs-<6hex>.helpbase.dev` reservation
Expand Down Expand Up @@ -72,28 +148,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
magic-link path always remains available as a fallback. Cold-path
TTHW drops from ~60s (email round-trip) to ~20s (one-click OAuth).

### Changed
- **`helpbase context` renamed to `helpbase ingest`.** `context` described
a domain concept, not an action — `ingest` names what the command does
(walk your code + markdown, synthesize cited how-tos, wire MCP). The
old name continues to work as a deprecation shim: same flags, same
behavior, one-line stderr warning, suppressed under `--json`/`--quiet`.
Help text + README Quick Start + scaffolder next-steps output now lead
with `ingest`. CI scripts pinned to `helpbase context` keep working
until v0.7, which is when the shim is removed. Flag surface is shared
via `applyIngestOptions()` so the two commands can't drift. First PR
of the CLI DX v2 plan.
- **`/api/v1/tenants/mine` hides reservations.** Reservations are
pre-first-deploy placeholders and shouldn't pollute the tenant
picker for multi-tenant users. The new filter is
`.not("deployed_at", "is", null)`. Callers that specifically want
the reservation (login, whoami, open) hit
`GET /api/v1/tenants/reservation` instead.
- **`tenants_public` view now exposes `deployed_at`.** The subdomain
middleware needs this to distinguish reserved tenants from live
ones without granting anon read access to the full tenants table.
`mcp_public_token` still never appears in the view.

### Schema
- New columns on `public.tenants`: `deployed_at timestamptz` +
`auto_provisioned_at timestamptz` (both nullable). Backfilled
Expand Down
114 changes: 105 additions & 9 deletions apps/web/app/api/v1/tenants/[id]/deploy/route.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { NextResponse, type NextRequest } from "next/server"
import { revalidatePath } from "next/cache"
import { deployPayloadSchema } from "@workspace/shared/schemas"
import { hashArticle } from "@workspace/shared/article-hash"
import { jsonError, requireOwnedTenant } from "../../_shared"

/**
* POST /api/v1/tenants/:id/deploy
* auth: Bearer <Better Auth session token>
* body: { categories: [...], articles: [...], chunks: [...], validation_report?: {...} }
* returns: { deploy_id, article_count, chunk_count, slug }
* body: { categories, articles, chunks, validation_report?, expected_deploy_version? }
* returns: { deploy_id, new_deploy_version, article_count, chunk_count, slug }
* 409 with { error: "stale_deploy_version", current_deploy_version }
* when expected_deploy_version was provided and no longer matches.
*
* Server-side port of what the CLI's `deploy` command used to do by
* calling the `deploy_tenant` RPC directly over a JWT-auth Supabase
Expand All @@ -17,6 +20,9 @@ import { jsonError, requireOwnedTenant } from "../../_shared"
* Also flushes the tenant's ISR cache so `{slug}.helpbase.dev` serves
* fresh content. Replaces /api/revalidate as the post-deploy hook from
* the CLI's perspective — one round-trip instead of two.
*
* As of v2 preview (2026-04-18) the RPC returns a row (deploy_id,
* new_deploy_version) instead of a scalar. Destructure accordingly.
*/

export const runtime = "nodejs"
Expand Down Expand Up @@ -58,18 +64,106 @@ export async function POST(
// types don't satisfy because Frontmatter is `Record<string, unknown>`.
// The `as never` is a type-system escape valve — the actual runtime
// safety comes from the deployPayloadSchema parse above.
const { data: deployId, error } = await admin.rpc("deploy_tenant", {
// Belt-and-braces: recompute content_hash server-side from the article
// payload. The CLI computes it locally (that's the value the preview
// diffed against), and the schema requires it — but if a buggy or older
// client sends an empty string or stale hash, the server-side recompute
// stores the correct value anyway. Prevents content_hash="" from
// polluting tenant_articles and making every subsequent preview mark
// the article as UPDATED. Caught by CodeRabbit on PR #11.
const articlesWithHash = body.articles.map((a) => ({
...a,
content_hash: hashArticle({
title: a.title,
description: a.description,
frontmatter: a.frontmatter,
content: a.content,
}),
}))

const rpcArgs: {
p_tenant_id: string
p_categories: never
p_articles: never
p_chunks: never
p_validation_report: never
p_expected_deploy_version?: number
} = {
p_tenant_id: tenant.id,
p_categories: body.categories as never,
p_articles: body.articles as never,
p_articles: articlesWithHash as never,
p_chunks: body.chunks as never,
p_validation_report: (body.validation_report ?? {}) as never,
})
}
// Only send the version check arg when the client explicitly asked
// for it. The RPC treats NULL as "skip the check", but leaving the
// param undefined is slightly cleaner in the wire format and matches
// the pre-v2 behavior for CI callers exactly.
if (
body.expected_deploy_version !== null &&
body.expected_deploy_version !== undefined
) {
rpcArgs.p_expected_deploy_version = body.expected_deploy_version
}
const { data, error } = await admin.rpc("deploy_tenant", rpcArgs)
if (error) {
// stale_deploy_version raises with SQLSTATE P0001. Check the code
// first (precise), then parse error.message for the "current N"
// value. Matching on a message substring alone is too fragile —
// any other P0001 raise inside the RPC would accidentally get
// translated to a 409. Caught by CodeRabbit on PR #11.
const isStaleVersion =
error.code === "P0001" &&
typeof error.message === "string" &&
error.message.includes("stale_deploy_version")
if (isStaleVersion) {
const m = /current\s+(\d+)/.exec(error.message)
const currentDeployVersion = m ? Number(m[1]) : null
return NextResponse.json(
{
error: "stale_deploy_version",
current_deploy_version: currentDeployVersion,
message:
"Deploy version has advanced since the preview was fetched. Re-run `helpbase deploy` to see the current state.",
},
{ status: 409 },
)
}
console.error("[tenants.deploy] supabase rpc error", { tenantId: tenant.id, error })
return jsonError(503, "deploy_failed", "Deploy RPC failed.")
}

// RPC returns RETURNS TABLE(deploy_id, new_deploy_version). Contract
// guarantees exactly one row on success. An empty result violates the
// contract (driver bug, function/view redefinition, grants change);
// fail loudly rather than returning {deploy_id: null, version: 0}
// which would claim success while silently corrupting the next
// preview cycle's deploy_version baseline. Caught by CodeRabbit on
// PR #11.
const row = Array.isArray(data) ? data[0] : null
if (!row || typeof row.new_deploy_version !== "number") {
console.error("[tenants.deploy] deploy_tenant returned unexpected shape", {
tenantId: tenant.id,
data,
})
return jsonError(503, "deploy_failed", "Deploy RPC returned no row.")
}
const deployId = row.deploy_id
const newDeployVersion = row.new_deploy_version

// Re-read the slug AFTER the RPC commits. `tenant.slug` captured by
// requireOwnedTenant was read before the RPC ran; a concurrent
// reservation rename between requireOwnedTenant and the RPC could have
// changed the slug. Pull the authoritative post-deploy value so the
// response and the revalidatePath both point at the right subdomain.
// Caught by codex /review on 2026-04-18.
const { data: freshTenant } = await admin
.from("tenants")
.select("slug")
.eq("id", tenant.id)
.single()
const finalSlug = freshTenant?.slug ?? tenant.slug

// Count rows post-deploy so the CLI can print a helpful summary.
const [{ count: articleCount }, { count: chunkCount }] = await Promise.all([
admin
Expand All @@ -82,18 +176,20 @@ export async function POST(
.eq("tenant_id", tenant.id),
])

// Fire ISR revalidation for the tenant's subdomain pages. Safe-to-ignore
// errors — cache will self-heal on the next 1h TTL.
// Fire ISR revalidation for the tenant's subdomain pages using the
// post-RPC slug so we don't accidentally revalidate a stale subdomain.
// Safe-to-ignore errors — cache will self-heal on the next 1h TTL.
try {
revalidatePath(`/t/${tenant.slug}`, "layout")
revalidatePath(`/t/${finalSlug}`, "layout")
} catch {
// best-effort
}

return NextResponse.json({
deploy_id: deployId,
new_deploy_version: newDeployVersion,
article_count: articleCount ?? 0,
chunk_count: chunkCount ?? 0,
slug: tenant.slug,
slug: finalSlug,
})
}
75 changes: 75 additions & 0 deletions apps/web/app/api/v1/tenants/[id]/state/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { NextResponse, type NextRequest } from "next/server"
import { jsonError, requireOwnedTenant } from "../../_shared"

/**
* GET /api/v1/tenants/:id/state
* auth: Bearer <Better Auth session token>
* returns: {
* deploy_version: number, // monotonic counter; client passes this
* // back on the next deploy for optimistic
* // concurrency
* articles: [{ // metadata ONLY; no content bodies
* slug, category, title, description, file_path,
* content_hash, // SHA-256 from @workspace/shared/article-hash;
* // empty string for pre-v2 rows
* updated_at,
* order, tags, featured, hero_image, video_embed,
* }],
* categories: [{ slug, title, description, icon, order }],
* }
*
* Powers `helpbase deploy --preview`: CLI hashes its local `content/`, fetches
* this endpoint, diffs by (category, slug) identity. Metadata-only payload so
* the preview round-trip stays small (~kb for hundreds of articles) even
* though tenant_articles.content is large.
*
* Fresh reservation (never deployed) returns empty arrays and deploy_version
* 0 — the CLI renders "all N new locally" without bouncing on the remote.
* The endpoint itself does not require the tenant to have deployed; ownership
* is all that's gated.
*
* IMPORTANT: force-dynamic. Without it, Vercel ISR will cache the previous
* snapshot and clients computing diffs against a stale snapshot will preview
* the wrong changeset. Flagged as a critical gap by the eng review.
*/

export const runtime = "nodejs"
export const dynamic = "force-dynamic"

export async function GET(
req: NextRequest,
ctx: { params: Promise<{ id: string }> },
): Promise<NextResponse> {
const { id } = await ctx.params
const owned = await requireOwnedTenant(req, id)
if (owned instanceof NextResponse) return owned
const { tenant, admin } = owned

const [{ data: articles, error: articlesErr }, { data: categories, error: catsErr }] =
await Promise.all([
admin
.from("tenant_articles")
.select(
"slug, category, title, description, file_path, content_hash, updated_at, order, tags, featured, hero_image, video_embed",
)
.eq("tenant_id", tenant.id),
admin
.from("tenant_categories")
.select("slug, title, description, icon, order")
.eq("tenant_id", tenant.id),
])
if (articlesErr || catsErr) {
console.error("[tenants.state] supabase read error", {
tenantId: tenant.id,
articlesErr,
catsErr,
})
return jsonError(503, "state_fetch_failed", "Could not load tenant state.")
}

return NextResponse.json({
deploy_version: tenant.deploy_version ?? 0,
articles: articles ?? [],
categories: categories ?? [],
})
}
Loading
Loading