diff --git a/CHANGELOG.md b/CHANGELOG.md index 3d517cf..37a4602 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 @@ -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 diff --git a/apps/web/app/api/v1/tenants/[id]/deploy/route.ts b/apps/web/app/api/v1/tenants/[id]/deploy/route.ts index c870f0b..fcb8eb2 100644 --- a/apps/web/app/api/v1/tenants/[id]/deploy/route.ts +++ b/apps/web/app/api/v1/tenants/[id]/deploy/route.ts @@ -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 - * 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 @@ -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" @@ -58,18 +64,106 @@ export async function POST( // types don't satisfy because Frontmatter is `Record`. // 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 @@ -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, }) } diff --git a/apps/web/app/api/v1/tenants/[id]/state/route.ts b/apps/web/app/api/v1/tenants/[id]/state/route.ts new file mode 100644 index 0000000..e92c0a9 --- /dev/null +++ b/apps/web/app/api/v1/tenants/[id]/state/route.ts @@ -0,0 +1,75 @@ +import { NextResponse, type NextRequest } from "next/server" +import { jsonError, requireOwnedTenant } from "../../_shared" + +/** + * GET /api/v1/tenants/:id/state + * auth: Bearer + * 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 { + 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 ?? [], + }) +} diff --git a/apps/web/types/supabase.ts b/apps/web/types/supabase.ts index 50dc4ea..51b591f 100644 --- a/apps/web/types/supabase.ts +++ b/apps/web/types/supabase.ts @@ -239,6 +239,7 @@ export type Database = { Row: { category: string content: string + content_hash: string created_at: string description: string featured: boolean @@ -257,6 +258,7 @@ export type Database = { Insert: { category: string content: string + content_hash?: string created_at?: string description?: string featured?: boolean @@ -275,6 +277,7 @@ export type Database = { Update: { category?: string content?: string + content_hash?: string created_at?: string description?: string featured?: boolean @@ -520,6 +523,7 @@ export type Database = { active: boolean auto_provisioned_at: string | null created_at: string + deploy_version: number deployed_at: string | null id: string mcp_calls_today: number @@ -534,6 +538,7 @@ export type Database = { active?: boolean auto_provisioned_at?: string | null created_at?: string + deploy_version?: number deployed_at?: string | null id?: string mcp_calls_today?: number @@ -548,6 +553,7 @@ export type Database = { active?: boolean auto_provisioned_at?: string | null created_at?: string + deploy_version?: number deployed_at?: string | null id?: string mcp_calls_today?: number @@ -682,10 +688,14 @@ export type Database = { p_articles: Json p_categories: Json p_chunks: Json + p_expected_deploy_version?: number p_tenant_id: string p_validation_report?: Json } - Returns: string + Returns: { + deploy_id: string + new_deploy_version: number + }[] } get_global_tokens_today: { Args: never; Returns: number } get_user_tokens_today: { Args: { p_user_id: string }; Returns: number } diff --git a/packages/cli/src/commands/deploy.ts b/packages/cli/src/commands/deploy.ts index 790f1f8..6a6ca9d 100644 --- a/packages/cli/src/commands/deploy.ts +++ b/packages/cli/src/commands/deploy.ts @@ -6,14 +6,18 @@ import fs from "node:fs" import path from "node:path" import matter from "gray-matter" import { frontmatterSchema, categoryMetaSchema, type TenantChunk, type DeployReport } from "@workspace/shared/schemas" +import { hashArticle } from "@workspace/shared/article-hash" import { checkSlugAvailability, createTenant as apiCreateTenant, deleteTenant as apiDeleteTenant, deployTenant as apiDeployTenant, getTenant as apiGetTenant, + getTenantState as apiGetTenantState, listMyTenants, + PreviewStaleError, rotateMcpToken as apiRotateMcpToken, + type TenantState, } from "../lib/tenants-client.js" import { getCurrentSession, @@ -27,6 +31,15 @@ import { } from "../lib/project-config.js" import { ensureReservation, loadReservation } from "../lib/reservation.js" import { clearCachedReservation } from "../lib/reservation-cache.js" +import { + computeDiff, + diffHasChanges, + diffHasRemoves, + renderPreviewTable, + renderSummaryLine, + type LocalArticle, + type LocalCategory, +} from "../lib/article-diff.js" const SLUG_REGEX = /^[a-z0-9][a-z0-9-]*[a-z0-9]$/ // Kept in sync with RESERVED_SLUGS in link.ts and the subdomain-middleware allowlist. @@ -37,9 +50,49 @@ const RESERVED_SLUGS = new Set([ "cdn", "static", "assets", "files", "media", "images", "img", ]) +/** + * Internal shape after validateAndReadContent(). Articles carry a + * pre-computed content_hash so both the preview diff and the deploy + * payload can use the same value without hashing twice. + */ +interface ReadContent { + categories: Array<{ + slug: string + title: string + description: string + icon: string + order: number + }> + articles: Array<{ + slug: string + category: string + title: string + description: string + content: string + frontmatter: Record + content_hash: string + order: number + tags: string[] + heroImage: string | null + videoEmbed: string | null + featured: boolean + filePath: string + }> +} + export const deployCommand = new Command("deploy") - .description("Deploy your help center to helpbase cloud") + .description( + "Deploy your help center to helpbase cloud. Shows a preview on removes; " + + "silent on routine adds/updates. For local MDX preview (browser dev " + + "server), see `helpbase preview` — separate command.", + ) .option("--slug ", "Subdomain slug (e.g., my-product)") + .option( + "--preview", + "Show what would change against the deployed tenant, without deploying. " + + "Exits 0. For local browser preview of MDX, use `helpbase preview`.", + ) + .option("--yes", "Skip the confirmation prompt when removes are detected.") .option( "--rotate-mcp-token", "Rotate the tenant's MCP bearer token (invalidates all currently-active clients). Does not publish content.", @@ -48,541 +101,925 @@ export const deployCommand = new Command("deploy") "--delete ", "Hard-delete a tenant and release its slug. Requires owner match. Cascades to articles, categories, chunks, deploys, and queries.", ) - .option("--yes", "Skip the confirmation prompt for --delete (required for non-interactive).") .addHelpText( "after", ` Examples: - $ helpbase deploy - $ helpbase deploy --slug acme-docs - $ HELPBASE_TOKEN=xxx helpbase deploy --slug acme-docs # CI / non-interactive + $ helpbase deploy # smart: silent on adds/updates, prompts on removes + $ helpbase deploy --preview # show what would change, don't deploy + $ helpbase deploy --slug acme-docs # first deploy with explicit slug + $ helpbase deploy --yes # skip the removes-confirmation prompt (CI-friendly) + $ HELPBASE_TOKEN=xxx helpbase deploy --slug acme-docs # CI / non-interactive (preview skipped) $ helpbase deploy --rotate-mcp-token # rotate MCP token only $ helpbase deploy --delete acme-docs --yes # delete tenant + release slug `, ) - .action(async (opts: { slug?: string; rotateMcpToken?: boolean; delete?: string; yes?: boolean }) => { - intro(pc.bgCyan(pc.black(" helpbase deploy "))) - - // 0. --delete short-circuit: auth + delete + exit. Skips content checks - // and tenant-by-link resolution because the target tenant is supplied - // explicitly as --delete . - if (opts.delete) { - await handleDelete(opts.delete, { yes: opts.yes ?? false }) - return - } - - // 1. Check we're in a helpbase project (skipped for --rotate-mcp-token since - // rotation only touches the tenant row; no content upload needed). - const contentDir = path.resolve("content") - if (!opts.rotateMcpToken && !fs.existsSync(contentDir)) { - cancel( - "No content/ directory found. Run this from a helpbase project root, or create one:\n" + - pc.cyan(" npx create-helpbase") - ) - process.exit(1) - } - - // 2. Authenticate - const session = await ensureAuthenticated() - - // 2.5. Read + validate content BEFORE resolving / creating a tenant. - // Content failures must never leave an orphan tenant row — if - // `deploy --slug foo` hit apiCreateTenant first and then failed - // on frontmatter validation, the row would sit forever with - // auto_provisioned_at=NULL + deployed_at=NULL, hidden from - // /mine, invisible to /reservation, untouched by cleanup cron, - // slug permanently burned. Validating first means content - // problems fail with zero server-side state change. Skipped - // for --rotate-mcp-token (it doesn't touch content). - // Caught by /review codex on 2026-04-18. - const categories: Array<{ - slug: string - title: string - description: string - icon: string - order: number - }> = [] - const articles: Array<{ - slug: string - category: string - title: string - description: string - content: string - frontmatter: Record - order: number - tags: string[] - heroImage: string | null - videoEmbed: string | null - featured: boolean - filePath: string - }> = [] - if (!opts.rotateMcpToken) { - const s = spinner() - s.start("Reading content...") - const errors: string[] = [] - const categoryDirs = fs - .readdirSync(contentDir, { withFileTypes: true }) - .filter((d) => d.isDirectory()) - - for (const dir of categoryDirs) { - const categorySlug = dir.name - const categoryPath = path.join(contentDir, categorySlug) - - const metaPath = path.join(categoryPath, "_category.json") - let meta = { title: categorySlug, description: "", icon: "file-text", order: 999 } - if (fs.existsSync(metaPath)) { - try { - const raw = JSON.parse(fs.readFileSync(metaPath, "utf-8")) - const parsed = categoryMetaSchema.safeParse(raw) - if (parsed.success) { - meta = parsed.data - } else { - // Previously we silently fell back to defaults when the - // schema didn't match, which let malformed _category.json - // ship as "categorySlug / no description / file-text icon" - // without any signal to the user. Surface the issue so it - // gets fixed before the deploy atomic write. CodeRabbit - // caught this on PR #10. - errors.push( - `${categorySlug}/_category.json: ${parsed.error.issues.map((i) => i.message).join(", ")}`, - ) - } - } catch { - errors.push(`${categorySlug}/_category.json: Invalid JSON`) - } - } + .action( + async (opts: { + slug?: string + preview?: boolean + rotateMcpToken?: boolean + delete?: string + yes?: boolean + }) => { + intro(pc.bgCyan(pc.black(" helpbase deploy "))) - categories.push({ slug: categorySlug, ...meta }) - - const files = fs - .readdirSync(categoryPath) - .filter((f) => f.endsWith(".mdx") || f.endsWith(".md")) - - for (const file of files) { - const filePath = path.join(categoryPath, file) - const raw = fs.readFileSync(filePath, "utf-8") - const { data, content } = matter(raw) - - const parsed = frontmatterSchema.safeParse(data) - if (!parsed.success) { - errors.push( - `${categorySlug}/${file}: ${parsed.error.issues.map((i) => i.message).join(", ")}`, - ) - continue - } - - const articleSlug = file.replace(/\.mdx?$/, "") - - // Reject articles whose body is empty (or only whitespace). A - // frontmatter-only MDX file deploys as a ghost article with a - // title but no content — visible in search, clickable, then - // renders a blank page. Catch it at deploy time instead. - // CodeRabbit caught this on PR #10. - if (content.trim().length === 0) { - errors.push( - `${categorySlug}/${file}: article body is empty (add content below the frontmatter)`, - ) - continue - } - - articles.push({ - slug: articleSlug, - category: categorySlug, - title: parsed.data.title, - description: parsed.data.description, - content, - frontmatter: data as Record, - order: parsed.data.order, - tags: parsed.data.tags, - heroImage: parsed.data.heroImage ?? null, - videoEmbed: parsed.data.videoEmbed ?? null, - featured: parsed.data.featured ?? false, - filePath: `content/${categorySlug}/${file}`, - }) - } + // 0. --delete short-circuit: auth + delete + exit. Skips content checks + // and tenant-by-link resolution because the target tenant is supplied + // explicitly as --delete . + if (opts.delete) { + await handleDelete(opts.delete, { yes: opts.yes ?? false }) + return } - s.stop(`Found ${categories.length} categories, ${articles.length} articles`) + // 1. Local validation BEFORE auth. Content existence + frontmatter + // validity are deterministic local checks with zero server + // interaction; surfacing them first keeps the error the user + // sees aligned with the problem they actually have. A dev in + // an empty folder should not be told "Not signed in" — that's + // the DX audit from 2026-04-18 speaking. Skipped for + // --rotate-mcp-token since it doesn't touch content. + // validateAndReadContent owns the existence check + error + // messaging (with the `npx create-helpbase` hint). + const contentDir = path.resolve("content") + const content: ReadContent | null = opts.rotateMcpToken + ? null + : validateAndReadContent(contentDir) - if (errors.length > 0) { - cancel( - `${errors.length} article(s) have invalid frontmatter:\n` + - errors.map((e) => ` ${pc.red("•")} ${e}`).join("\n") + - "\n\nFix these and run helpbase deploy again.", - ) - process.exit(1) - } + // 2. Auth. validateAndReadContent above exits on errors, so by the + // time we hit this we've confirmed the local project shape is + // deployable. Any auth-path error that surfaces now is the real + // blocker, not a noise-on-top-of-something-else error. + const session = await ensureAuthenticated() - if (articles.length === 0) { - cancel( - "No articles found in content/.\n" + - `Generate some: ${pc.cyan("helpbase generate --url ")}`, - ) - process.exit(1) + // --rotate-mcp-token short-circuit: resolve tenant, rotate, exit. + // Matches prior behavior — no content read, no state fetch, no + // preview. + if (opts.rotateMcpToken) { + const { tenantId, tenantSlug } = await resolveTenantForRotate(session, opts) + await rotateAndReport(session, tenantId, tenantSlug) + return } - } - // 3. Get or create tenant - // Priority: .helpbase/project.json → owner lookup → create new. - // All tenant CRUD now goes through /api/v1/tenants/* — the CLI - // talks to the hosted API instead of Supabase directly. Better - // Auth session tokens are not Supabase JWTs, and the RLS *_own - // policies were dropped in the 2026-04-17 migration; ownership - // is enforced server-side. - const linked = readProjectConfig() - let existingTenant: { id: string; slug: string } | null = null - // Flag so the post-deploy cleanup knows to invalidate the reservation - // cache — once deploy_tenant flips deployed_at, the cached reservation - // is stale and next whoami would still read the old row as "reserved". - let usedReservation = false - - if (linked) { - // apiGetTenant now throws on 403 (caller isn't the owner). Treat - // that as "fix your link" the same as a missing/inactive row. - const tenant = await apiGetTenant(session, linked.tenantId).catch( - () => null, - ) - if (tenant && tenant.active) { - existingTenant = { id: tenant.id, slug: tenant.slug } - } else { - cancel( - `Linked tenant "${linked.slug}" not found, inactive, or not owned by you.\n` + - ` Run ${pc.cyan("helpbase link --remove")} then ${pc.cyan("helpbase link")} to fix.`, - ) + // content is non-null here because the only path that leaves it null + // above is --rotate-mcp-token, which returned early. + if (!content) { + cancel("Internal error: content missing after validation.") process.exit(1) } - } else { - const tenants = await listMyTenants(session) - // Reservation-first path: if the user has no deployed tenants and - // didn't pass an explicit --slug, use the auto-provisioned reservation - // (minted at login). Skips the interactive slug prompt entirely for - // the common first-deploy happy path — matches the DX review's - // "TTHW drops from 3-4 min to 90s" target. --slug override still - // creates a new tenant (user intentionally chose a custom slug). - // - // Lazy-provision: if no cached/remote reservation exists, call - // ensureReservation (idempotent POST /auto-provision). Covers users - // who Ctrl-C'd login mid-auto-provision, or who logged in before - // reservations existed. Soft-fails on 503 → falls through to the - // interactive slug prompt. - if (tenants.length === 0 && !opts.slug) { - // Write path: force-refresh from the server so a stale cache - // (e.g. reservation was renamed in another shell, or deleted by - // the cleanup cron) doesn't send us to a tenantId that no longer - // exists. The read-only whoami/open stay cache-first for speed; - // deploy pays the one round-trip. CodeRabbit flagged this on PR #10. - let reservation = await loadReservation(session, { forceRefresh: true }).catch( - () => null, - ) - if (!reservation) { - const ensured = await ensureReservation(session) - if (ensured) { - reservation = await loadReservation(session, { forceRefresh: true }).catch( - () => null, - ) - } - } - if (reservation) { - existingTenant = { id: reservation.tenantId, slug: reservation.slug } - usedReservation = true + + // 2. Resolve the target tenant. May auto-provision via reservation + // on first deploy; may prompt for a slug if none is linked and + // the reservation path doesn't apply. Does NOT create a tenant + // unless the user provided --slug or went through the slug + // picker — preview on a fresh reservation stays within the + // existing row. + const resolved = await resolveTenant(session, opts, { + hasLinkedProject: !!readProjectConfig(), + }) + + // 3. Fetch deployed state for diffing. Skipped in non-interactive + // mode (CI) for backwards compat — CI users opted out of + // optimistic concurrency explicitly in T2B. If the tenant is + // brand new (reservation row with no deploys yet) or /state + // returns null, diff against an empty remote. + const skipStateFetch = isNonInteractive() + let remoteState: TenantState | null = null + let stateFetchFailed = false + if (!skipStateFetch) { + try { + remoteState = await apiGetTenantState(session, resolved.tenantId) + } catch (err) { + // Any non-404 failure — 5xx, network timeout, unexpected 403 + // after a slug rename — falls through to the "deploy without + // preview?" fallback below. Never block a deploy on a flaky + // read endpoint. Error logged for debugging, not surfaced as a + // stack to the user. + stateFetchFailed = true + const msg = err instanceof Error ? err.message : String(err) + process.stderr.write( + `${pc.yellow("⚠")} Preview fetch failed: ${pc.dim(msg)}\n`, + ) } } - if (existingTenant) { - // Already resolved via reservation — skip the picker/disambiguator - // logic below. - } else if (tenants.length === 0) { - existingTenant = null - } else if (tenants.length === 1) { - const only = tenants[0]! - existingTenant = { id: only.id, slug: only.slug } - } else if (opts.slug) { - // Multi-tenant + explicit --slug: honor the choice if it matches - // one the user owns; otherwise treat it as "create a new tenant - // with this slug" downstream (which will 409 if taken). - const match = tenants.find((t) => t.slug === opts.slug) - existingTenant = match ? { id: match.id, slug: match.slug } : null - } else if (isNonInteractive()) { - cancel( - `You own ${tenants.length} tenants. Pass ${pc.cyan("--slug ")} ` + - `to pick one in non-interactive mode.`, - ) - process.exit(1) - } else { - // Interactive disambiguation — tenants[0] was non-deterministic. - const pickedValue = await select({ - message: "You own multiple tenants. Which one should this project deploy to?", - options: [ - ...tenants.map((t) => ({ - value: t.id, - label: `${t.slug}.helpbase.dev`, - hint: t.name ?? undefined, - })), - { value: "__new__", label: pc.cyan("+ Create a new tenant") }, - ], + + const diff = remoteState + ? computeDiff(toDiffInput(content), remoteState) + : computeDiff(toDiffInput(content), { articles: [], categories: [] }) + + // 4. --preview mode: render the table and exit 0 without deploying. + // This works even on a fresh reservation (all local articles + // appear as "added"; no remote fetch needed because remoteState + // is null and we used an empty remote above). + if (opts.preview) { + renderPreviewOutput(resolved.tenantSlug, diff, content, remoteState, { + stateFetchFailed, + skippedForCi: skipStateFetch, }) - if (isCancel(pickedValue)) { + outro(`${pc.dim("Preview complete. Run without --preview to deploy.")}`) + return + } + + // 5. Fallback path when /state failed — ask permission to deploy + // blind (no concurrency protection, no change summary). + if (stateFetchFailed && !opts.yes) { + const proceed = await confirm({ + message: "Preview unavailable. Deploy without seeing what will change?", + initialValue: false, + }) + if (isCancel(proceed) || !proceed) { cancel("Cancelled.") process.exit(0) } - if (pickedValue === "__new__") { - existingTenant = null - } else { - const picked = tenants.find((t) => t.id === pickedValue)! - existingTenant = { id: picked.id, slug: picked.slug } - } - } - } - - let tenantId: string - let tenantSlug: string - - if (existingTenant) { - tenantId = existingTenant.id - tenantSlug = existingTenant.slug - const tag = linked - ? "(linked)" - : usedReservation - ? "(reserved at login)" - : "" - note( - tag - ? `Deploying to ${pc.cyan(`${tenantSlug}.helpbase.dev`)} ${pc.dim(tag)}` - : `Deploying to ${pc.cyan(`${tenantSlug}.helpbase.dev`)}`, - "Tenant", - ) - // Backfill the project config for owner-lookup users so their next - // deploy is deterministic and commitable. - if (!linked) { - writeProjectConfig({ tenantId, slug: tenantSlug }) } - } else { - // First deploy: create tenant - let slug = opts.slug - if (!slug) { - if (isNonInteractive()) { - cancel( - "Non-interactive mode (HELPBASE_TOKEN set) requires --slug on first deploy.", - ) - process.exit(1) - } - const input = await text({ - message: "Choose a subdomain for your help center:", - placeholder: "my-product", - validate: (v) => { - if (!v) return "Subdomain is required" - if (!SLUG_REGEX.test(v)) return "Use lowercase letters, numbers, and hyphens" - if (v.length < 3) return "Must be at least 3 characters" - if (v.length > 40) return "Must be 40 characters or less" - if (RESERVED_SLUGS.has(v)) return `"${v}" is reserved. Choose another.` - return undefined - }, + // 6. Smart-prompt (D1A): silent on no-removes (routine add/update), + // full preview + prompt when destructive changes are in the diff. + // --yes skips the prompt. Non-interactive always skips. + const mustPrompt = + !opts.yes && !isNonInteractive() && remoteState !== null && diffHasRemoves(diff) + if (mustPrompt) { + process.stdout.write(`\n${renderPreviewTable(diff)}\n\n`) + const proceed = await confirm({ + message: "Proceed with deploy? This will remove articles or categories from your tenant.", + initialValue: false, }) - - if (isCancel(input)) { - cancel("Cancelled.") + if (isCancel(proceed) || !proceed) { + cancel("Cancelled — nothing deployed.") process.exit(0) } + } else if (remoteState !== null && !opts.preview) { + // Silent happy path — show a one-line summary so users know what + // shipped without the full table clutter. Skipped when we're about + // to render the table via the prompt above. + if (diffHasChanges(diff)) { + note(renderSummaryLine(diff), "Deploying") + } else { + // Nothing to ship. Exit early — deploying "no changes" still + // bumps deploy_version and revalidates the ISR cache, which is + // wasteful when there's nothing to do. + outro(`${pc.green("✓")} No changes. Your tenant is already up to date.`) + return + } + } - slug = input as string + // 7. Perform the deploy. Passes expected_deploy_version when we + // fetched remoteState successfully, so concurrent deploys get + // rejected with PreviewStaleError. D3A auto-retry handles that + // once; a second stale is surfaced to the user. + const outcome = await performDeploy(session, resolved, content, { + expectedVersion: remoteState?.deploy_version ?? null, + previouslyDiffed: remoteState, + diff, + }) + + // Reservation cache clearing runs for BOTH the direct-success and + // the stale-retry-success paths — previously it only ran on direct + // success, so a first-deploy that landed via the retry path left a + // stale "reserved" entry in whoami. Caught by codex /review on + // 2026-04-18. + if (resolved.usedReservation && outcome.kind !== "aborted") { + clearCachedReservation() } - // Check availability - const availability = await checkSlugAvailability(slug) - if (!availability.available) { - cancel(`Subdomain "${slug}" is already taken. Try another with --slug `) + if (outcome.kind === "noop") { + // Concurrent client shipped the same content while we were + // reviewing. The tenant is in the state we intended, so exit 0. + // Previously this path exited 1, which broke CI loops. Caught by + // codex /review on 2026-04-18. + return + } + if (outcome.kind === "aborted") { + // User cancelled at the retry prompt, or a non-PreviewStale error + // inside the retry. cancel() already printed the reason; exit 1 + // so shells/CI see a failure. process.exit(1) } - let newTenant: Awaited> + // Fetch mcp_public_token post-deploy so we can print the paste-ready + // MCP client config block. Best-effort — the deploy already succeeded + // so a token-read failure should degrade to "no config snippet" not + // a visible error. + const tenantAfter = await apiGetTenant(session, outcome.finalTenantId).catch( + () => null, + ) + const mcpToken = tenantAfter?.mcp_public_token ?? "" + + printDeploySuccess(resolved.tenantSlug, content, outcome, mcpToken) + }, + ) + +// ─────────────────────────────────────────────────────────────────────── +// Helpers extracted from the prior monolithic .action() body (5B refactor). +// Each does one thing; the action above orchestrates them. +// ─────────────────────────────────────────────────────────────────────── + +/** + * Read + validate everything under `content/`. Fails cleanly on + * malformed frontmatter, empty article bodies, and invalid + * `_category.json` files. Computes content_hash for each article so + * both the preview diff and the deploy payload reuse the same value. + * + * Exits the process on any validation error — the same contract as + * the pre-v2 2.5-step body. Preserves the "no tenant write before + * content is known-good" invariant. + */ +function validateAndReadContent(contentDir: string): ReadContent { + if (!fs.existsSync(contentDir)) { + cancel( + "No content/ directory found. Run this from a helpbase project root, or create one:\n" + + pc.cyan(" npx create-helpbase"), + ) + process.exit(1) + } + const s = spinner() + s.start("Reading content...") + const errors: string[] = [] + const categories: ReadContent["categories"] = [] + const articles: ReadContent["articles"] = [] + + const categoryDirs = fs + .readdirSync(contentDir, { withFileTypes: true }) + .filter((d) => d.isDirectory()) + + for (const dir of categoryDirs) { + const categorySlug = dir.name + const categoryPath = path.join(contentDir, categorySlug) + + const metaPath = path.join(categoryPath, "_category.json") + let meta = { title: categorySlug, description: "", icon: "file-text", order: 999 } + if (fs.existsSync(metaPath)) { try { - newTenant = await apiCreateTenant(session, slug) - } catch (err) { - const msg = err instanceof Error ? err.message : String(err) - if (/slug_taken|slug_reserved/.test(msg)) { - cancel(`Subdomain "${slug}" is unavailable. Try another with --slug `) + const raw = JSON.parse(fs.readFileSync(metaPath, "utf-8")) + const parsed = categoryMetaSchema.safeParse(raw) + if (parsed.success) { + meta = parsed.data } else { - cancel(`Failed to create tenant: ${msg}`) + errors.push( + `${categorySlug}/_category.json: ${parsed.error.issues.map((i) => i.message).join(", ")}`, + ) } - process.exit(1) + } catch { + errors.push(`${categorySlug}/_category.json: Invalid JSON`) } + } - tenantId = newTenant.id - tenantSlug = newTenant.slug - writeProjectConfig({ tenantId, slug: tenantSlug }) - note( - `Created ${pc.cyan(`${tenantSlug}.helpbase.dev`)}\n` + - `Wrote ${pc.dim(".helpbase/project.json")} — commit it so teammates deploy to the same tenant.`, - "New help center", - ) + categories.push({ slug: categorySlug, ...meta }) + + const files = fs + .readdirSync(categoryPath) + .filter((f) => f.endsWith(".mdx") || f.endsWith(".md")) + + for (const file of files) { + const filePath = path.join(categoryPath, file) + const raw = fs.readFileSync(filePath, "utf-8") + const { data, content: body } = matter(raw) + + const parsed = frontmatterSchema.safeParse(data) + if (!parsed.success) { + errors.push( + `${categorySlug}/${file}: ${parsed.error.issues.map((i) => i.message).join(", ")}`, + ) + continue + } + + const articleSlug = file.replace(/\.mdx?$/, "") + + // Empty body = ghost article: title appears in search, clickable, + // renders a blank page. Catch at deploy time. CodeRabbit, PR #10. + if (body.trim().length === 0) { + errors.push( + `${categorySlug}/${file}: article body is empty (add content below the frontmatter)`, + ) + continue + } + + const content_hash = hashArticle({ + title: parsed.data.title, + description: parsed.data.description, + frontmatter: data as Record, + content: body, + }) + + articles.push({ + slug: articleSlug, + category: categorySlug, + title: parsed.data.title, + description: parsed.data.description, + content: body, + frontmatter: data as Record, + content_hash, + order: parsed.data.order, + tags: parsed.data.tags, + heroImage: parsed.data.heroImage ?? null, + videoEmbed: parsed.data.videoEmbed ?? null, + featured: parsed.data.featured ?? false, + filePath: `content/${categorySlug}/${file}`, + }) } + } - // 3.5. Handle --rotate-mcp-token early-exit: skip content read/upload, - // mint a new public token, print it, and exit. - if (opts.rotateMcpToken) { - const rotateSpinner = spinner() - rotateSpinner.start("Rotating MCP token...") - let newToken: string - try { - newToken = await apiRotateMcpToken(session, tenantId) - } catch (err) { - rotateSpinner.stop("Rotation failed") - cancel(`Failed to rotate token: ${err instanceof Error ? err.message : String(err)}`) - process.exit(1) + s.stop(`Found ${categories.length} categories, ${articles.length} articles`) + + if (errors.length > 0) { + cancel( + `${errors.length} article(s) have invalid frontmatter:\n` + + errors.map((e) => ` ${pc.red("•")} ${e}`).join("\n") + + "\n\nFix these and run helpbase deploy again.", + ) + process.exit(1) + } + + if (articles.length === 0) { + cancel( + "No articles found in content/.\n" + + `Generate some: ${pc.cyan("helpbase generate --url ")}`, + ) + process.exit(1) + } + + return { categories, articles } +} + +interface ResolvedTenant { + tenantId: string + tenantSlug: string + usedReservation: boolean + linkedProjectConfig: boolean +} + +/** + * Priority: .helpbase/project.json → reservation → owner lookup (single + * tenant) → interactive picker (multi) → explicit --slug or create-new + * prompt. Mirrors the pre-v2 control flow; pulled out so the main action + * reads as orchestration. + */ +async function resolveTenant( + session: AuthSession, + opts: { slug?: string }, + context: { hasLinkedProject: boolean }, +): Promise { + const linked = readProjectConfig() + if (linked) { + const tenant = await apiGetTenant(session, linked.tenantId).catch(() => null) + if (tenant && tenant.active) { + return { + tenantId: tenant.id, + tenantSlug: tenant.slug, + usedReservation: false, + linkedProjectConfig: true, } - rotateSpinner.stop(`Rotated MCP token for ${tenantSlug}`) - const mcpUrl = `https://${tenantSlug}.helpbase.dev/mcp` - const mcpConfig = JSON.stringify( - { - mcpServers: { - [tenantSlug]: { - url: mcpUrl, - headers: { Authorization: `Bearer ${newToken}` }, - }, - }, - }, - null, - 2, - ) - outro(`${pc.green("✓")} Token rotated.`) + } + cancel( + `Linked tenant "${linked.slug}" not found, inactive, or not owned by you.\n` + + ` Run ${pc.cyan("helpbase link --remove")} then ${pc.cyan("helpbase link")} to fix.`, + ) + process.exit(1) + } + + const tenants = await listMyTenants(session) + let usedReservation = false + + // Reservation-first on first deploy: if the user has no deployed + // tenants and didn't pass --slug, prefer the auto-provisioned + // reservation over the slug picker. Matches the DX review's + // TTHW target. + if (tenants.length === 0 && !opts.slug) { + let reservation = await loadReservation(session, { forceRefresh: true }).catch( + () => null, + ) + if (!reservation) { + const ensured = await ensureReservation(session) + if (ensured) { + reservation = await loadReservation(session, { forceRefresh: true }).catch( + () => null, + ) + } + } + if (reservation) { + writeProjectConfig({ tenantId: reservation.tenantId, slug: reservation.slug }) note( - `${pc.yellow("⚠")} All currently-active MCP clients have been invalidated.\n` + - ` Paste the new config into every client that queries this tenant:\n\n${pc.dim(mcpConfig)}`, - "New MCP config", + `Deploying to ${pc.cyan(`${reservation.slug}.helpbase.dev`)} ${pc.dim("(reserved at login)")}`, + "Tenant", ) - return + return { + tenantId: reservation.tenantId, + tenantSlug: reservation.slug, + usedReservation: true, + linkedProjectConfig: false, + } + } + } + + if (tenants.length === 1) { + const only = tenants[0]! + writeProjectConfig({ tenantId: only.id, slug: only.slug }) + note(`Deploying to ${pc.cyan(`${only.slug}.helpbase.dev`)}`, "Tenant") + return { + tenantId: only.id, + tenantSlug: only.slug, + usedReservation, + linkedProjectConfig: false, } + } - // 5. Compute chunks (CLI-side chunking for MCP search_docs). Content - // was already read + validated at step 2.5 (pre-tenant-resolution) - // so by the time we reach this point `articles` + `categories` are - // populated and known-valid. - const s = spinner() - s.start("Chunking content for search...") - const chunks: TenantChunk[] = [] - for (const a of articles) { - for (const chunk of chunkArticleContent(a.content)) { - chunks.push({ - article_slug: a.slug, - article_category: a.category, - chunk_index: chunk.index, - content: chunk.content, - file_path: a.filePath, - line_start: chunk.lineStart, - line_end: chunk.lineEnd, - token_count: chunk.tokenCount, - }) + if (tenants.length > 1 && opts.slug) { + const match = tenants.find((t) => t.slug === opts.slug) + if (match) { + writeProjectConfig({ tenantId: match.id, slug: match.slug }) + note(`Deploying to ${pc.cyan(`${match.slug}.helpbase.dev`)}`, "Tenant") + return { + tenantId: match.id, + tenantSlug: match.slug, + usedReservation, + linkedProjectConfig: false, } } - s.stop(`Chunked into ${chunks.length} search chunks`) - - // 6. Atomic deploy via Supabase RPC — single transaction, no empty-page window. - s.start("Publishing (atomic)...") - const validationReport: DeployReport = { - kept_count: articles.length, - dropped_count: 0, - dropped: [], - ran_at: new Date().toISOString(), + // --slug didn't match any owned tenant — fall through to create-new. + } + + if (tenants.length > 1 && !opts.slug) { + if (isNonInteractive()) { + cancel( + `You own ${tenants.length} tenants. Pass ${pc.cyan("--slug ")} ` + + `to pick one in non-interactive mode.`, + ) + process.exit(1) } - let deployResult: Awaited> - try { - deployResult = await apiDeployTenant(session, tenantId, { - categories: categories.map((c) => ({ - slug: c.slug, - title: c.title, - description: c.description, - icon: c.icon, - order: c.order, - })), - articles: articles.map((a) => ({ - slug: a.slug, - category: a.category, - title: a.title, - description: a.description, - content: a.content, - frontmatter: a.frontmatter, - order: a.order, - tags: a.tags, - hero_image: a.heroImage, - video_embed: a.videoEmbed, - featured: a.featured, - file_path: a.filePath, + const pickedValue = await select({ + message: "You own multiple tenants. Which one should this project deploy to?", + options: [ + ...tenants.map((t) => ({ + value: t.id, + label: `${t.slug}.helpbase.dev`, + hint: t.name ?? undefined, })), - chunks, - validation_report: validationReport as unknown as Record, - }) - } catch (err) { - s.stop("Deploy failed") - cancel(`Deploy error: ${err instanceof Error ? err.message : String(err)}`) + { value: "__new__", label: pc.cyan("+ Create a new tenant") }, + ], + }) + if (isCancel(pickedValue)) { + cancel("Cancelled.") + process.exit(0) + } + if (pickedValue !== "__new__") { + const picked = tenants.find((t) => t.id === pickedValue)! + writeProjectConfig({ tenantId: picked.id, slug: picked.slug }) + note(`Deploying to ${pc.cyan(`${picked.slug}.helpbase.dev`)}`, "Tenant") + return { + tenantId: picked.id, + tenantSlug: picked.slug, + usedReservation, + linkedProjectConfig: false, + } + } + } + + // Create new tenant path — explicit --slug or user asked for __new__ + const created = await createNewTenant(session, opts.slug) + return { + tenantId: created.id, + tenantSlug: created.slug, + usedReservation: false, + linkedProjectConfig: false, + } +} + +async function createNewTenant( + session: AuthSession, + explicitSlug?: string, +): Promise<{ id: string; slug: string }> { + let slug = explicitSlug + if (!slug) { + if (isNonInteractive()) { + cancel( + "Non-interactive mode (HELPBASE_TOKEN set) requires --slug on first deploy.", + ) process.exit(1) } - s.stop( - `Published ${deployResult.article_count} articles, ${deployResult.chunk_count} chunks ` + - `(deploy ${deployResult.deploy_id.slice(0, 8)})`, + const input = await text({ + message: "Choose a subdomain for your help center:", + placeholder: "my-product", + validate: (v) => { + if (!v) return "Subdomain is required" + if (!SLUG_REGEX.test(v)) return "Use lowercase letters, numbers, and hyphens" + if (v.length < 3) return "Must be at least 3 characters" + if (v.length > 40) return "Must be 40 characters or less" + if (RESERVED_SLUGS.has(v)) return `"${v}" is reserved. Choose another.` + return undefined + }, + }) + if (isCancel(input)) { + cancel("Cancelled.") + process.exit(0) + } + slug = input as string + } + + const availability = await checkSlugAvailability(slug) + if (!availability.available) { + cancel(`Subdomain "${slug}" is already taken. Try another with --slug `) + process.exit(1) + } + + let newTenant: Awaited> + try { + newTenant = await apiCreateTenant(session, slug) + } catch (err) { + const msg = err instanceof Error ? err.message : String(err) + if (/slug_taken|slug_reserved/.test(msg)) { + cancel(`Subdomain "${slug}" is unavailable. Try another with --slug `) + } else { + cancel(`Failed to create tenant: ${msg}`) + } + process.exit(1) + } + writeProjectConfig({ tenantId: newTenant.id, slug: newTenant.slug }) + note( + `Created ${pc.cyan(`${newTenant.slug}.helpbase.dev`)}\n` + + `Wrote ${pc.dim(".helpbase/project.json")} — commit it so teammates deploy to the same tenant.`, + "New help center", + ) + return { id: newTenant.id, slug: newTenant.slug } +} + +async function resolveTenantForRotate( + session: AuthSession, + opts: { slug?: string }, +): Promise { + // Rotation needs a tenant but never a content read. Reuse resolveTenant's + // linked/single/picker logic; don't force reservation auto-provision + // (you can't rotate a token on a tenant that's never had one). + return resolveTenant(session, opts, { hasLinkedProject: !!readProjectConfig() }) +} + +async function rotateAndReport( + session: AuthSession, + tenantId: string, + tenantSlug: string, +): Promise { + const s = spinner() + s.start("Rotating MCP token...") + let newToken: string + try { + newToken = await apiRotateMcpToken(session, tenantId) + } catch (err) { + s.stop("Rotation failed") + cancel(`Failed to rotate token: ${err instanceof Error ? err.message : String(err)}`) + process.exit(1) + } + s.stop(`Rotated MCP token for ${tenantSlug}`) + const mcpUrl = `https://${tenantSlug}.helpbase.dev/mcp` + const mcpConfig = JSON.stringify( + { + mcpServers: { + [tenantSlug]: { + url: mcpUrl, + headers: { Authorization: `Bearer ${newToken}` }, + }, + }, + }, + null, + 2, + ) + outro(`${pc.green("✓")} Token rotated.`) + note( + `${pc.yellow("⚠")} All currently-active MCP clients have been invalidated.\n` + + ` Paste the new config into every client that queries this tenant:\n\n${pc.dim(mcpConfig)}`, + "New MCP config", + ) +} + +/** + * Turn the validated content into the shape computeDiff() expects. + * Pure mapping; no I/O. + */ +function toDiffInput(content: ReadContent): { + articles: LocalArticle[] + categories: LocalCategory[] +} { + return { + articles: content.articles.map((a) => ({ + slug: a.slug, + category: a.category, + title: a.title, + description: a.description, + file_path: a.filePath, + content_hash: a.content_hash, + order: a.order, + tags: a.tags, + featured: a.featured, + hero_image: a.heroImage, + video_embed: a.videoEmbed, + })), + categories: content.categories.map((c) => ({ + slug: c.slug, + title: c.title, + description: c.description, + icon: c.icon, + order: c.order, + })), + } +} + +function renderPreviewOutput( + tenantSlug: string, + diff: ReturnType, + content: ReadContent, + remoteState: TenantState | null, + ctx: { stateFetchFailed: boolean; skippedForCi: boolean }, +): void { + if (ctx.stateFetchFailed) { + note( + `${pc.yellow("⚠")} Could not fetch deployed state. Showing local content only.`, + "Preview", + ) + } else if (ctx.skippedForCi) { + note( + `${pc.dim("Non-interactive mode skips state fetch. Preview shown against empty remote.")}`, + "Preview", + ) + } else if (remoteState === null) { + note( + `First deploy for ${pc.cyan(`${tenantSlug}.helpbase.dev`)}. All articles shown as added.`, + "Preview", ) + } else { + note(`Comparing ${pc.cyan(`${tenantSlug}.helpbase.dev`)} against local ${pc.cyan("content/")}`, "Preview") + } + process.stdout.write(`\n${renderPreviewTable(diff)}\n\n`) + summaryTable([ + ["Local articles", String(content.articles.length)], + ["Local categories", String(content.categories.length)], + ["Remote deploy_version", String(remoteState?.deploy_version ?? 0)], + ]) +} + +interface PerformDeployInput { + expectedVersion: number | null + previouslyDiffed: TenantState | null + diff: ReturnType +} + +/** + * Tri-state outcome so the caller can distinguish "we shipped" (deployed) + * from "someone else shipped the same content while we were reviewing" + * (noop, still a success — the tenant is in the state we wanted) from + * "the user cancelled or we hit a hard retry failure" (aborted). + */ +type DeployOutcome = + | { + kind: "deployed" + deployId: string + newDeployVersion: number + articleCount: number + chunkCount: number + finalSlug: string + finalTenantId: string + } + | { kind: "noop" } + | { kind: "aborted" } + +async function performDeploy( + session: AuthSession, + resolved: ResolvedTenant, + content: ReadContent, + ctx: PerformDeployInput, +): Promise { + const { tenantId } = resolved + + const chunks = computeChunks(content) + const validationReport: DeployReport = { + kept_count: content.articles.length, + dropped_count: 0, + dropped: [], + ran_at: new Date().toISOString(), + } + const payload = buildDeployPayload(content, chunks, validationReport, ctx.expectedVersion) + + const s = spinner() + s.start("Publishing (atomic)...") + let result: Awaited> + try { + result = await apiDeployTenant(session, tenantId, payload) + } catch (err) { + if (err instanceof PreviewStaleError) { + s.stop(pc.yellow("Remote changed during review.")) + // D3A auto-retry: refetch /state, recompute diff, re-prompt (if + // removes) or proceed silently (if not). Capped at one retry to + // avoid infinite loops under contention. + return stalePreviewRetry(session, resolved, content, validationReport, chunks) + } + s.stop("Deploy failed") + cancel(`Deploy error: ${err instanceof Error ? err.message : String(err)}`) + process.exit(1) + } + s.stop( + `Published ${result.article_count} articles, ${result.chunk_count} chunks ` + + `(deploy ${result.deploy_id.slice(0, 8)}, version ${result.new_deploy_version})`, + ) + + return { + kind: "deployed", + deployId: result.deploy_id, + newDeployVersion: result.new_deploy_version, + articleCount: result.article_count, + chunkCount: result.chunk_count, + finalSlug: result.slug, + finalTenantId: tenantId, + } +} + +async function stalePreviewRetry( + session: AuthSession, + resolved: ResolvedTenant, + content: ReadContent, + validationReport: DeployReport, + chunks: TenantChunk[], +): Promise { + const s = spinner() + s.start("Fetching updated state...") + let freshState: TenantState | null + try { + freshState = await apiGetTenantState(session, resolved.tenantId) + } catch (err) { + s.stop("Could not refetch state") + cancel( + `${pc.red("✖")} Deploy aborted: remote state changed and refresh failed (${err instanceof Error ? err.message : String(err)}).\n` + + ` Run ${pc.cyan("helpbase deploy --preview")} to see the current state.`, + ) + return { kind: "aborted" } + } + s.stop("Fetched updated state") + + const freshDiff = computeDiff(toDiffInput(content), freshState ?? { articles: [], categories: [] }) + + // "Remote now matches" = concurrent client shipped the same content we + // were about to ship. Our intent is satisfied; treat as a success exit + // so CI loops don't spuriously fail. Previously returned null and the + // caller exit 1. Caught by codex /review on 2026-04-18. + if (!diffHasChanges(freshDiff)) { + outro(`${pc.green("✓")} Remote now matches your local content. No changes to publish.`) + return { kind: "noop" } + } + + process.stdout.write( + `\n${pc.yellow("⚠")} Remote changed while you were reviewing. Current diff:\n\n${renderPreviewTable(freshDiff)}\n\n`, + ) - // Fetch the tenant's MCP token for the copy-paste config snippet. - // Server-side revalidation runs inside /api/v1/tenants/:id/deploy, so - // no second round-trip for cache invalidation is needed. - const tenantAfter = await apiGetTenant(session, tenantId).catch(() => null) - const mcpToken = tenantAfter?.mcp_public_token ?? "" - - // 9. Done. If we consumed a reservation to get here, the server just - // flipped deployed_at in deploy_tenant — invalidate the cache so - // `helpbase whoami` stops showing the tenant as "reserved". - if (usedReservation) { - clearCachedReservation() + // Re-prompt: the user's first confirmation was based on stale info, + // so they re-confirm against the current state. --yes from the first + // attempt doesn't carry across a stale-retry, per D3A. + const proceed = await confirm({ + message: "Still deploy with the current state?", + initialValue: false, + }) + if (isCancel(proceed) || !proceed) { + cancel("Cancelled — nothing deployed.") + return { kind: "aborted" } + } + + // Re-run the deploy with the fresh deploy_version. A SECOND stale + // exception surfaces as a hard error — no infinite retry. + const payload = buildDeployPayload(content, chunks, validationReport, freshState?.deploy_version ?? null) + const s2 = spinner() + s2.start("Publishing (atomic, retry)...") + try { + const result = await apiDeployTenant(session, resolved.tenantId, payload) + s2.stop( + `Published ${result.article_count} articles, ${result.chunk_count} chunks ` + + `(deploy ${result.deploy_id.slice(0, 8)}, version ${result.new_deploy_version})`, + ) + return { + kind: "deployed", + deployId: result.deploy_id, + newDeployVersion: result.new_deploy_version, + articleCount: result.article_count, + chunkCount: result.chunk_count, + finalSlug: result.slug, + finalTenantId: resolved.tenantId, + } + } catch (err) { + s2.stop("Deploy failed") + if (err instanceof PreviewStaleError) { + cancel( + `${pc.red("✖")} Remote changed AGAIN during retry. Giving up to avoid an infinite loop.\n` + + ` Re-run ${pc.cyan("helpbase deploy")} to start fresh.`, + ) + return { kind: "aborted" } + } + cancel(`Deploy error: ${err instanceof Error ? err.message : String(err)}`) + return { kind: "aborted" } + } +} + +function buildDeployPayload( + content: ReadContent, + chunks: TenantChunk[], + validationReport: DeployReport, + expectedVersion: number | null, +) { + return { + categories: content.categories.map((c) => ({ + slug: c.slug, + title: c.title, + description: c.description, + icon: c.icon, + order: c.order, + })), + articles: content.articles.map((a) => ({ + slug: a.slug, + category: a.category, + title: a.title, + description: a.description, + content: a.content, + content_hash: a.content_hash, + frontmatter: a.frontmatter, + order: a.order, + tags: a.tags, + hero_image: a.heroImage, + video_embed: a.videoEmbed, + featured: a.featured, + file_path: a.filePath, + })), + chunks, + validation_report: validationReport as unknown as Record, + expected_deploy_version: expectedVersion, + } +} + +function computeChunks(content: ReadContent): TenantChunk[] { + const chunks: TenantChunk[] = [] + for (const a of content.articles) { + for (const chunk of chunkArticleContent(a.content)) { + chunks.push({ + article_slug: a.slug, + article_category: a.category, + chunk_index: chunk.index, + content: chunk.content, + file_path: a.filePath, + line_start: chunk.lineStart, + line_end: chunk.lineEnd, + token_count: chunk.tokenCount, + }) } - // Use the slug the SERVER echoes from deploy_tenant, not the local - // `tenantSlug` captured before the RPC. The local value can be stale: - // a concurrent `helpbase rename` in another terminal (or an admin - // rename in the dashboard) might have changed the slug between our - // loadReservation cache hit and this print. The deploy RPC resolves - // by tenantId and returns the canonical slug; trust that for the - // URL summary. Caught by /review codex on 2026-04-18. - const finalSlug = deployResult.slug || tenantSlug - const liveUrl = `https://${finalSlug}.helpbase.dev` - const mcpUrl = `https://${finalSlug}.helpbase.dev/mcp` - outro(`${pc.green("✓")} Deployed! Your help center is live.`) - summaryTable([ - ["Tenant", `${finalSlug}.helpbase.dev`], - ["Articles", String(articles.length)], - ["Chunks", String(chunks.length)], - ["Categories", String(categories.length)], - ["Live URL", liveUrl], - ["MCP URL", mcpUrl], - ]) - - // MCP client config — paste into Claude Code, Cursor, or Claude Desktop. - if (mcpToken) { - const mcpConfig = JSON.stringify( - { - mcpServers: { - [finalSlug]: { - url: mcpUrl, - headers: { Authorization: `Bearer ${mcpToken}` }, - }, + } + return chunks +} + +function printDeploySuccess( + tenantSlug: string, + content: ReadContent, + result: Extract, + mcpToken: string, +): void { + // Use the slug the SERVER echoed — local tenantSlug could be stale after + // a concurrent rename. Caught by /review codex on 2026-04-18. + const finalSlug = result.finalSlug || tenantSlug + const liveUrl = `https://${finalSlug}.helpbase.dev` + const mcpUrl = `https://${finalSlug}.helpbase.dev/mcp` + outro(`${pc.green("✓")} Deployed! Your help center is live.`) + summaryTable([ + ["Tenant", `${finalSlug}.helpbase.dev`], + ["Articles", String(content.articles.length)], + ["Chunks", String(result.chunkCount)], + ["Categories", String(content.categories.length)], + ["Deploy version", String(result.newDeployVersion)], + ["Live URL", liveUrl], + ["MCP URL", mcpUrl], + ]) + + // MCP client config block — paste into Claude Desktop, Claude Code, + // Cursor, or any MCP-compatible agent. Dropped from printDeploySuccess + // during the v2 refactor and restored via /review 2026-04-18. + if (mcpToken) { + const mcpConfig = JSON.stringify( + { + mcpServers: { + [finalSlug]: { + url: mcpUrl, + headers: { Authorization: `Bearer ${mcpToken}` }, }, }, - null, - 2, - ) - note( - `Paste this into your Claude Desktop / Claude Code / Cursor MCP config:\n\n${pc.dim(mcpConfig)}\n\n` + + }, + null, + 2, + ) + note( + `Paste this into your Claude Desktop / Claude Code / Cursor MCP config:\n\n${pc.dim(mcpConfig)}\n\n` + `${pc.yellow("⚠")} Anyone with this token has full MCP access to this tenant.\n` + ` Rotate with ${pc.cyan("helpbase deploy --rotate-mcp-token")} (invalidates all active clients).`, - "MCP config", - ) - } + "MCP config", + ) + } - nextSteps({ - commands: ["helpbase open", "helpbase deploy"], - urls: [ - { label: "docs:", url: liveUrl }, - { label: "mcp:", url: mcpUrl }, - ], - }) + nextSteps({ + commands: ["helpbase open", "helpbase deploy --preview"], + urls: [ + { label: "docs:", url: liveUrl }, + { label: "mcp:", url: mcpUrl }, + ], }) +} /** * Split article MDX into search chunks. Target: ~1600 chars per chunk @@ -672,10 +1109,6 @@ async function ensureAuthenticated(): Promise { process.exit(1) } - // Browser device-flow is the only supported interactive login path. - // Don't inline it here — `helpbase login` owns the full UX (progressive - // spinner hints, URL-paste fallback, retries). Telling the user to run - // that command keeps deploy focused on deploying. cancel( `Not signed in. Run ${pc.cyan("helpbase login")} first, then re-run ${pc.cyan("helpbase deploy")}.`, ) @@ -701,7 +1134,6 @@ async function handleDelete( slug: string, { yes }: { yes: boolean }, ): Promise { - // Validate slug shape so we don't ship a typo'd curl to Supabase. if (!SLUG_REGEX.test(slug)) { cancel(`Invalid slug: "${slug}". Slugs are lowercase letters, numbers, and hyphens.`) process.exit(1) @@ -709,14 +1141,9 @@ async function handleDelete( const session = await ensureAuthenticated() - // Resolve the tenant row among the user's own tenants. Ownership - // filter is implicit: listMyTenants only returns rows the caller owns. const tenants = await listMyTenants(session) const tenant = tenants.find((t) => t.slug === slug) ?? null if (!tenant) { - // Either the slug doesn't exist, or it exists but the caller doesn't - // own it. Either way we refuse — the server-side DELETE endpoint - // would 403 anyway, but failing here gives a cleaner CLI message. const availability = await checkSlugAvailability(slug).catch(() => null) if (availability && !availability.available) { cancel( @@ -729,8 +1156,6 @@ async function handleDelete( process.exit(1) } - // Confirm — unless --yes or non-interactive (in which case --yes is required - // as a failsafe against accidental CI deletions). if (!yes) { if (isNonInteractive()) { cancel( @@ -760,7 +1185,6 @@ async function handleDelete( process.exit(1) } - // Clean up local project.json if it pointed at this tenant. const linked = readProjectConfig() if (linked && linked.tenantId === tenant.id) { removeProjectConfig() diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.ts index 7101906..f41cee4 100644 --- a/packages/cli/src/commands/preview.ts +++ b/packages/cli/src/commands/preview.ts @@ -44,7 +44,8 @@ interface PreviewOpts { export const previewCommand = new Command("preview") .description( - "Open a browser-viewable help center from the docs `helpbase ingest` generated.", + "Open a browser-viewable help center from the docs `helpbase ingest` generated. " + + "For a remote deploy diff (what would change on your tenant), use `helpbase deploy --preview`.", ) .option("-p, --port ", "Port to serve on", "3000") .option("--reset", "Wipe the cached preview renderer and re-scaffold") @@ -62,6 +63,7 @@ First run takes ~45-60s (scaffold + install). Every run after is ~3s. Pair with: $ helpbase ingest . # generate the docs first + $ helpbase deploy --preview # show remote deploy diff (different flow) `, ) .action(async (opts: PreviewOpts) => { diff --git a/packages/cli/src/lib/article-diff.ts b/packages/cli/src/lib/article-diff.ts new file mode 100644 index 0000000..fe6b006 --- /dev/null +++ b/packages/cli/src/lib/article-diff.ts @@ -0,0 +1,228 @@ +import pc from "picocolors" +import type { StateArticle, StateCategory } from "./tenants-client.js" + +/** + * Client-side diff engine for `helpbase deploy --preview` and the + * smart-prompt default flow. Compares what the user has in `content/` + * (freshly validated by deploy's step-2.5 reader) against the deployed + * state snapshot returned by GET /state. + * + * Identity model (T3A/T4A): + * articles: (category, slug) is canonical; file_path is metadata. + * A rename keeping the same (category, slug) = UPDATE if the + * content_hash differs, unchanged otherwise. Category move + * or slug change = REMOVE + ADD. Smart rename heuristics + * are deferred to v2.1. + * categories: slug is canonical. Anything else (title/icon/order/ + * description) change = UPDATE. + * + * Hashes are equal-compared directly. Empty remote hash (pre-v2 rows) + * always reads as "different" from any local hash — the first post-v2 + * preview will correctly show those articles as UPDATED until the next + * deploy populates real hashes. + */ + +export interface LocalArticle { + slug: string + category: string + title: string + description: string + file_path: string + content_hash: string + order: number + tags: string[] + featured: boolean + hero_image: string | null + video_embed: string | null +} + +export interface LocalCategory { + slug: string + title: string + description: string + icon: string + order: number +} + +export interface ArticleDiff { + added: LocalArticle[] + updated: Array<{ local: LocalArticle; remote: StateArticle }> + removed: StateArticle[] + unchanged: Array<{ local: LocalArticle; remote: StateArticle }> +} + +export interface CategoryDiff { + added: LocalCategory[] + updated: Array<{ local: LocalCategory; remote: StateCategory }> + removed: StateCategory[] +} + +export interface DeployDiff { + articles: ArticleDiff + categories: CategoryDiff +} + +function articleKey(a: { category: string; slug: string }): string { + return `${a.category}/${a.slug}` +} + +function categoryDiffers(local: LocalCategory, remote: StateCategory): boolean { + if (local.title !== remote.title) return true + if (local.description !== remote.description) return true + // icon IS nullable in StateCategory per the /state response — normalize + // null to "" so a locally-declared "file-text" default doesn't register + // as different from a remote null. + if (local.icon !== (remote.icon ?? "")) return true + if (local.order !== remote.order) return true + return false +} + +export function computeDiff( + local: { articles: LocalArticle[]; categories: LocalCategory[] }, + remote: { articles: StateArticle[]; categories: StateCategory[] }, +): DeployDiff { + const localByKey = new Map(local.articles.map((a) => [articleKey(a), a])) + const remoteByKey = new Map(remote.articles.map((a) => [articleKey(a), a])) + + const added: LocalArticle[] = [] + const updated: Array<{ local: LocalArticle; remote: StateArticle }> = [] + const unchanged: Array<{ local: LocalArticle; remote: StateArticle }> = [] + for (const [key, localArticle] of localByKey) { + const remoteArticle = remoteByKey.get(key) + if (!remoteArticle) { + added.push(localArticle) + } else if (remoteArticle.content_hash !== localArticle.content_hash) { + updated.push({ local: localArticle, remote: remoteArticle }) + } else { + unchanged.push({ local: localArticle, remote: remoteArticle }) + } + } + + const removed: StateArticle[] = [] + for (const [key, remoteArticle] of remoteByKey) { + if (!localByKey.has(key)) removed.push(remoteArticle) + } + + const localCatBySlug = new Map(local.categories.map((c) => [c.slug, c])) + const remoteCatBySlug = new Map(remote.categories.map((c) => [c.slug, c])) + + const catAdded: LocalCategory[] = [] + const catUpdated: Array<{ local: LocalCategory; remote: StateCategory }> = [] + for (const [slug, localCat] of localCatBySlug) { + const remoteCat = remoteCatBySlug.get(slug) + if (!remoteCat) { + catAdded.push(localCat) + } else if (categoryDiffers(localCat, remoteCat)) { + catUpdated.push({ local: localCat, remote: remoteCat }) + } + } + const catRemoved: StateCategory[] = [] + for (const [slug, remoteCat] of remoteCatBySlug) { + if (!localCatBySlug.has(slug)) catRemoved.push(remoteCat) + } + + return { + articles: { added, updated, removed, unchanged }, + categories: { added: catAdded, updated: catUpdated, removed: catRemoved }, + } +} + +export function diffHasChanges(diff: DeployDiff): boolean { + return ( + diff.articles.added.length > 0 || + diff.articles.updated.length > 0 || + diff.articles.removed.length > 0 || + diff.categories.added.length > 0 || + diff.categories.updated.length > 0 || + diff.categories.removed.length > 0 + ) +} + +/** + * Destructive-op detection for D1A smart-prompt: removing articles or + * categories is the scary case that warrants a confirmation prompt. + * Adds + updates are "routine" and deploy silently on the happy path. + */ +export function diffHasRemoves(diff: DeployDiff): boolean { + return diff.articles.removed.length > 0 || diff.categories.removed.length > 0 +} + +/** + * Short one-liner for the silent-deploy happy path. + * "Publishing 3 updated, 1 new." + * "Publishing 2 new, 1 category updated." + * "No changes to publish." + */ +export function renderSummaryLine(diff: DeployDiff): string { + const parts: string[] = [] + if (diff.articles.added.length > 0) parts.push(`${diff.articles.added.length} new`) + if (diff.articles.updated.length > 0) parts.push(`${diff.articles.updated.length} updated`) + if (diff.articles.removed.length > 0) parts.push(`${diff.articles.removed.length} removed`) + const catChanges = + diff.categories.added.length + diff.categories.updated.length + diff.categories.removed.length + if (catChanges > 0) { + parts.push(`${catChanges} categor${catChanges === 1 ? "y" : "ies"} changed`) + } + if (parts.length === 0) return "No changes to publish." + return `Publishing ${parts.join(", ")}.` +} + +/** + * Full preview table for --preview mode and the removes-detected prompt + * path. Groups by change type, colors destructive rows red, preserves + * file_path so users can find the source file. + * + * Long titles are truncated to fit in a single terminal line; the full + * title is still in the MDX file. Truncation is cosmetic. + */ +export function renderPreviewTable(diff: DeployDiff): string { + const lines: string[] = [] + const { articles, categories } = diff + + if (articles.added.length > 0) { + lines.push(pc.bold(pc.green(` Added (${articles.added.length}):`))) + for (const a of articles.added) { + lines.push(` ${pc.green("+")} ${pc.cyan(articleKey(a))} ${pc.dim(truncate(a.title, 60))}`) + } + } + if (articles.updated.length > 0) { + lines.push(pc.bold(pc.yellow(` Updated (${articles.updated.length}):`))) + for (const { local } of articles.updated) { + lines.push( + ` ${pc.yellow("~")} ${pc.cyan(articleKey(local))} ${pc.dim(truncate(local.title, 60))}`, + ) + } + } + if (articles.removed.length > 0) { + lines.push(pc.bold(pc.red(` Removed (${articles.removed.length}):`))) + for (const a of articles.removed) { + lines.push(` ${pc.red("-")} ${pc.cyan(articleKey(a))} ${pc.dim(truncate(a.title, 60))}`) + } + } + + const catChanges = + categories.added.length + categories.updated.length + categories.removed.length + if (catChanges > 0) { + lines.push(pc.bold(pc.dim(` Categories:`))) + for (const c of categories.added) { + lines.push(` ${pc.green("+")} ${pc.cyan(c.slug)} ${pc.dim(truncate(c.title, 60))}`) + } + for (const { local } of categories.updated) { + lines.push(` ${pc.yellow("~")} ${pc.cyan(local.slug)} ${pc.dim(truncate(local.title, 60))}`) + } + for (const c of categories.removed) { + lines.push(` ${pc.red("-")} ${pc.cyan(c.slug)} ${pc.dim(truncate(c.title, 60))}`) + } + } + + if (lines.length === 0) return " No changes." + return lines.join("\n") +} + +function truncate(s: string, maxLen: number): string { + if (s.length <= maxLen) return s + return s.slice(0, maxLen - 1) + "…" +} + +// Re-export for tests + deploy.ts +export { articleKey } diff --git a/packages/cli/src/lib/tenants-client.ts b/packages/cli/src/lib/tenants-client.ts index 40e2849..a3e5f66 100644 --- a/packages/cli/src/lib/tenants-client.ts +++ b/packages/cli/src/lib/tenants-client.ts @@ -32,11 +32,64 @@ export interface TenantCreated extends TenantSummary { export interface DeployResult { deploy_id: string + new_deploy_version: number article_count: number chunk_count: number slug: string } +/** + * One article in the /state response. Metadata only — no content bytes — + * so the payload stays small for tenants with many articles. Mirrors the + * server-side GET /api/v1/tenants/:id/state route. + */ +export interface StateArticle { + slug: string + category: string + title: string + description: string + file_path: string + content_hash: string + updated_at: string + order: number + tags: string[] | null + featured: boolean + hero_image: string | null + video_embed: string | null +} + +export interface StateCategory { + slug: string + title: string + description: string + icon: string | null + order: number +} + +export interface TenantState { + deploy_version: number + articles: StateArticle[] + categories: StateCategory[] +} + +/** + * Thrown when the server rejects a deploy because another client bumped + * tenant.deploy_version between our preview fetch and our deploy RPC. + * `helpbase deploy` catches this, auto-refetches /state, re-renders the + * preview, and re-prompts — one retry only (D3A). + */ +export class PreviewStaleError extends Error { + readonly currentDeployVersion: number | null + constructor(currentDeployVersion: number | null, message?: string) { + super( + message ?? + "Deploy version has advanced since the preview was fetched. Re-run `helpbase deploy` to see the current state.", + ) + this.name = "PreviewStaleError" + this.currentDeployVersion = currentDeployVersion + } +} + export interface SlugAvailability { available: boolean id?: string @@ -138,6 +191,14 @@ export interface DeployPayload { articles: unknown[] chunks: unknown[] validation_report?: Record + /** + * Optimistic concurrency: the deploy_version the client observed on + * its most recent /state fetch. When present, the server compares it + * against the current row; a mismatch raises PreviewStaleError. Omit + * (or pass null) for CI callers that skip --preview and accept last- + * writer-wins semantics. + */ + expected_deploy_version?: number | null } export async function deployTenant( @@ -158,10 +219,42 @@ export async function deployTenant( DEPLOY_TIMEOUT_MS, ) const body = await parseBody(res) + // 409 = optimistic concurrency failure. Translate to a typed error so + // deploy.ts can catch it specifically and trigger the D3A auto-refetch. + if (res.status === 409) { + const obj = body as { error?: string; current_deploy_version?: number | null } | null + if (obj?.error === "stale_deploy_version") { + throw new PreviewStaleError(obj.current_deploy_version ?? null) + } + } if (!res.ok) throwHttp("deploy tenant", res, body) return body as DeployResult } +/** + * Fetch the current deployed state of a tenant — metadata + content_hash + * per article, categories, and the authoritative deploy_version used for + * optimistic concurrency on the next `deployTenant` call. + * + * 404 = tenant doesn't exist (caller should treat as "first deploy, no + * remote state yet" and render "all N new locally"). + * 403 = tenant exists but caller isn't the owner. + * 5xx/network = throws; deploy.ts catches and offers the "deploy without + * preview?" fallback. + */ +export async function getTenantState( + session: AuthSession, + tenantId: string, +): Promise { + const res = await v1Fetch(`/${encodeURIComponent(tenantId)}/state`, { + headers: { authorization: `Bearer ${session.accessToken}` }, + }) + if (res.status === 404) return null + const body = await parseBody(res) + if (!res.ok) throwHttp("get tenant state", res, body) + return body as TenantState +} + export async function deleteTenant( session: AuthSession, tenantId: string, diff --git a/packages/cli/test/article-diff.test.ts b/packages/cli/test/article-diff.test.ts new file mode 100644 index 0000000..8dece21 --- /dev/null +++ b/packages/cli/test/article-diff.test.ts @@ -0,0 +1,370 @@ +import { describe, it, expect } from "vitest" +import { + computeDiff, + diffHasChanges, + diffHasRemoves, + renderSummaryLine, + renderPreviewTable, + type LocalArticle, + type LocalCategory, +} from "../src/lib/article-diff.js" +import type { StateArticle, StateCategory } from "../src/lib/tenants-client.js" + +/** + * Unit tests for the deploy --preview diff engine. + * + * Identity model under test: + * - articles: (category, slug) is the canonical identity + * - file_path / title / description are metadata (diff UPDATE, not REMOVE+ADD) + * - category move OR slug rename = REMOVE + ADD (by design, v2.1 adds heuristics) + * - content_hash equality determines UPDATED vs unchanged + */ + +function localArticle(partial: Partial & { slug: string; category: string }): LocalArticle { + return { + title: "T", + description: "D", + file_path: `content/${partial.category}/${partial.slug}.mdx`, + content_hash: "h", + order: 0, + tags: [], + featured: false, + hero_image: null, + video_embed: null, + ...partial, + } +} + +function stateArticle(partial: Partial & { slug: string; category: string }): StateArticle { + return { + title: "T", + description: "D", + file_path: `content/${partial.category}/${partial.slug}.mdx`, + content_hash: "h", + updated_at: "2026-04-18T00:00:00Z", + order: 0, + tags: null, + featured: false, + hero_image: null, + video_embed: null, + ...partial, + } +} + +function localCategory(slug: string, overrides: Partial = {}): LocalCategory { + return { + slug, + title: slug, + description: "", + icon: "file-text", + order: 0, + ...overrides, + } +} + +function stateCategory(slug: string, overrides: Partial = {}): StateCategory { + return { + slug, + title: slug, + description: "", + icon: "file-text", + order: 0, + ...overrides, + } +} + +describe("computeDiff — articles", () => { + it("empty local + empty remote = no changes", () => { + const diff = computeDiff( + { articles: [], categories: [] }, + { articles: [], categories: [] }, + ) + expect(diff.articles.added).toHaveLength(0) + expect(diff.articles.updated).toHaveLength(0) + expect(diff.articles.removed).toHaveLength(0) + expect(diffHasChanges(diff)).toBe(false) + expect(diffHasRemoves(diff)).toBe(false) + }) + + it("fresh reservation (empty remote) = all local are added", () => { + const diff = computeDiff( + { + articles: [ + localArticle({ slug: "one", category: "cat" }), + localArticle({ slug: "two", category: "cat" }), + ], + categories: [localCategory("cat")], + }, + { articles: [], categories: [] }, + ) + expect(diff.articles.added).toHaveLength(2) + expect(diff.articles.updated).toHaveLength(0) + expect(diff.articles.removed).toHaveLength(0) + expect(diff.categories.added).toHaveLength(1) + expect(diffHasChanges(diff)).toBe(true) + expect(diffHasRemoves(diff)).toBe(false) + }) + + it("same hash = unchanged (no ADD, no UPDATE)", () => { + const local = localArticle({ slug: "s", category: "c", content_hash: "abc" }) + const remote = stateArticle({ slug: "s", category: "c", content_hash: "abc" }) + const diff = computeDiff( + { articles: [local], categories: [] }, + { articles: [remote], categories: [] }, + ) + expect(diff.articles.unchanged).toHaveLength(1) + expect(diff.articles.added).toHaveLength(0) + expect(diff.articles.updated).toHaveLength(0) + expect(diff.articles.removed).toHaveLength(0) + expect(diffHasChanges(diff)).toBe(false) + }) + + it("different hash = UPDATED (same category/slug)", () => { + const local = localArticle({ slug: "s", category: "c", content_hash: "NEW" }) + const remote = stateArticle({ slug: "s", category: "c", content_hash: "OLD" }) + const diff = computeDiff( + { articles: [local], categories: [] }, + { articles: [remote], categories: [] }, + ) + expect(diff.articles.updated).toHaveLength(1) + expect(diff.articles.updated[0]!.local).toBe(local) + expect(diff.articles.updated[0]!.remote).toBe(remote) + expect(diffHasRemoves(diff)).toBe(false) + }) + + it("category-move = REMOVE + ADD (per v2 design)", () => { + const local = localArticle({ slug: "s", category: "NEW", content_hash: "same" }) + const remote = stateArticle({ slug: "s", category: "OLD", content_hash: "same" }) + const diff = computeDiff( + { articles: [local], categories: [] }, + { articles: [remote], categories: [] }, + ) + expect(diff.articles.added).toHaveLength(1) + expect(diff.articles.removed).toHaveLength(1) + expect(diff.articles.updated).toHaveLength(0) + expect(diffHasRemoves(diff)).toBe(true) + }) + + it("slug rename with same category = REMOVE + ADD", () => { + const local = localArticle({ slug: "NEW", category: "c" }) + const remote = stateArticle({ slug: "OLD", category: "c" }) + const diff = computeDiff( + { articles: [local], categories: [] }, + { articles: [remote], categories: [] }, + ) + expect(diff.articles.added).toHaveLength(1) + expect(diff.articles.removed).toHaveLength(1) + }) + + it("empty remote content_hash (pre-v2 row) shows as UPDATED", () => { + // The migration defaults content_hash to '' for existing rows. Any + // non-empty local hash differs, so the first post-v2 preview reads + // those articles as UPDATED until the next deploy populates real + // hashes. Semantically correct: we don't know if content matches. + const local = localArticle({ slug: "s", category: "c", content_hash: "real-hash" }) + const remote = stateArticle({ slug: "s", category: "c", content_hash: "" }) + const diff = computeDiff( + { articles: [local], categories: [] }, + { articles: [remote], categories: [] }, + ) + expect(diff.articles.updated).toHaveLength(1) + }) + + it("file_path change alone with same hash = unchanged (identity is category/slug)", () => { + const local = localArticle({ + slug: "s", + category: "c", + file_path: "content/c/new-name.mdx", + content_hash: "same", + }) + const remote = stateArticle({ + slug: "s", + category: "c", + file_path: "content/c/old-name.mdx", + content_hash: "same", + }) + const diff = computeDiff( + { articles: [local], categories: [] }, + { articles: [remote], categories: [] }, + ) + expect(diff.articles.unchanged).toHaveLength(1) + expect(diff.articles.updated).toHaveLength(0) + }) + + it("mixed combinatorics — add + update + remove + unchanged", () => { + const local = [ + localArticle({ slug: "a", category: "c", content_hash: "h" }), // unchanged + localArticle({ slug: "b", category: "c", content_hash: "NEW" }), // updated + localArticle({ slug: "c", category: "c" }), // added + ] + const remote = [ + stateArticle({ slug: "a", category: "c", content_hash: "h" }), + stateArticle({ slug: "b", category: "c", content_hash: "OLD" }), + stateArticle({ slug: "d", category: "c" }), // removed + ] + const diff = computeDiff( + { articles: local, categories: [] }, + { articles: remote, categories: [] }, + ) + expect(diff.articles.added).toHaveLength(1) + expect(diff.articles.updated).toHaveLength(1) + expect(diff.articles.removed).toHaveLength(1) + expect(diff.articles.unchanged).toHaveLength(1) + expect(diffHasChanges(diff)).toBe(true) + expect(diffHasRemoves(diff)).toBe(true) + }) +}) + +describe("computeDiff — categories", () => { + it("category added = ADD", () => { + const diff = computeDiff( + { articles: [], categories: [localCategory("new")] }, + { articles: [], categories: [] }, + ) + expect(diff.categories.added).toHaveLength(1) + expect(diff.categories.updated).toHaveLength(0) + expect(diff.categories.removed).toHaveLength(0) + expect(diffHasChanges(diff)).toBe(true) + }) + + it("category title change = UPDATE", () => { + const diff = computeDiff( + { articles: [], categories: [localCategory("c", { title: "New Title" })] }, + { articles: [], categories: [stateCategory("c", { title: "Old Title" })] }, + ) + expect(diff.categories.updated).toHaveLength(1) + }) + + it("category icon change = UPDATE", () => { + const diff = computeDiff( + { articles: [], categories: [localCategory("c", { icon: "star" })] }, + { articles: [], categories: [stateCategory("c", { icon: "file-text" })] }, + ) + expect(diff.categories.updated).toHaveLength(1) + }) + + it("category order change = UPDATE", () => { + const diff = computeDiff( + { articles: [], categories: [localCategory("c", { order: 5 })] }, + { articles: [], categories: [stateCategory("c", { order: 0 })] }, + ) + expect(diff.categories.updated).toHaveLength(1) + }) + + it("category removed = REMOVE (destructive)", () => { + const diff = computeDiff( + { articles: [], categories: [] }, + { articles: [], categories: [stateCategory("gone")] }, + ) + expect(diff.categories.removed).toHaveLength(1) + expect(diffHasRemoves(diff)).toBe(true) + }) + + it("identical categories produce no diff", () => { + const diff = computeDiff( + { articles: [], categories: [localCategory("c", { title: "T", description: "D", icon: "x", order: 3 })] }, + { articles: [], categories: [stateCategory("c", { title: "T", description: "D", icon: "x", order: 3 })] }, + ) + expect(diff.categories.added).toHaveLength(0) + expect(diff.categories.updated).toHaveLength(0) + expect(diff.categories.removed).toHaveLength(0) + }) +}) + +describe("renderSummaryLine", () => { + it("empty diff = no-changes string", () => { + const diff = computeDiff( + { articles: [], categories: [] }, + { articles: [], categories: [] }, + ) + expect(renderSummaryLine(diff)).toBe("No changes to publish.") + }) + + it("single add", () => { + const diff = computeDiff( + { articles: [localArticle({ slug: "a", category: "c" })], categories: [] }, + { articles: [], categories: [] }, + ) + expect(renderSummaryLine(diff)).toBe("Publishing 1 new.") + }) + + it("multiple changes joined by commas", () => { + const diff = computeDiff( + { + articles: [ + localArticle({ slug: "a", category: "c" }), // added + localArticle({ slug: "b", category: "c", content_hash: "NEW" }), // updated + ], + categories: [], + }, + { + articles: [ + stateArticle({ slug: "b", category: "c", content_hash: "OLD" }), + stateArticle({ slug: "c", category: "c" }), // removed + ], + categories: [], + }, + ) + expect(renderSummaryLine(diff)).toBe("Publishing 1 new, 1 updated, 1 removed.") + }) + + it("pluralizes categories correctly", () => { + const single = computeDiff( + { articles: [], categories: [localCategory("c")] }, + { articles: [], categories: [] }, + ) + expect(renderSummaryLine(single)).toBe("Publishing 1 category changed.") + + const multi = computeDiff( + { articles: [], categories: [localCategory("a"), localCategory("b")] }, + { articles: [], categories: [] }, + ) + expect(renderSummaryLine(multi)).toBe("Publishing 2 categories changed.") + }) +}) + +describe("renderPreviewTable", () => { + it("empty diff returns 'No changes' string", () => { + const diff = computeDiff( + { articles: [], categories: [] }, + { articles: [], categories: [] }, + ) + const out = renderPreviewTable(diff) + expect(out).toContain("No changes") + }) + + it("includes added article keys", () => { + const diff = computeDiff( + { + articles: [localArticle({ slug: "my-doc", category: "getting-started", title: "Hello World" })], + categories: [], + }, + { articles: [], categories: [] }, + ) + const out = renderPreviewTable(diff) + expect(out).toMatch(/getting-started\/my-doc/) + expect(out).toMatch(/Hello World/) + }) + + it("truncates very long titles", () => { + const longTitle = "x".repeat(200) + const diff = computeDiff( + { articles: [localArticle({ slug: "s", category: "c", title: longTitle })], categories: [] }, + { articles: [], categories: [] }, + ) + const out = renderPreviewTable(diff) + // Full 200-char title should not be present verbatim (truncation kicks in) + expect(out).not.toContain(longTitle) + expect(out).toContain("…") + }) + + it("renders removed items in a separate section", () => { + const diff = computeDiff( + { articles: [], categories: [] }, + { articles: [stateArticle({ slug: "bye", category: "c", title: "Old Doc" })], categories: [] }, + ) + const out = renderPreviewTable(diff) + expect(out).toContain("Removed") + expect(out).toContain("c/bye") + }) +}) diff --git a/packages/create-helpbase/templates/lib/reservation-cleanup.ts b/packages/create-helpbase/templates/lib/reservation-cleanup.ts new file mode 100644 index 0000000..446b8b4 --- /dev/null +++ b/packages/create-helpbase/templates/lib/reservation-cleanup.ts @@ -0,0 +1,35 @@ +/** + * Pure helpers for the cleanup-reservations cron. Extracted so unit tests + * exercise the same predicate the route handler runs, not a shadow copy. + * CodeRabbit flagged the duplication on PR #10. + * + * The route still performs the actual SELECT + DELETE against Supabase + * (that part is not unit-testable without a live DB); what we pin here + * is the 30-day TTL math and the shadow-safety filter. + */ + +export const RESERVATION_TTL_DAYS = 30 + +/** ISO timestamp of the cutoff: anything auto_provisioned before this is TTL-expired. */ +export function reservationCutoff(now: Date): string { + return new Date(now.getTime() - RESERVATION_TTL_DAYS * 24 * 60 * 60 * 1000).toISOString() +} + +export interface Candidate { + id: string + slug: string +} + +/** + * Given candidate reservation rows (TTL-expired) and the set of tenant_ids + * that have deploy history, returns only the rows that are safe to delete. + * Belt-and-suspenders: any candidate with a tenant_deploys row is preserved + * even if `deployed_at` is null (data-repair state, failed RPC, etc.). + */ +export function filterDeletable( + candidates: Candidate[], + deployedShadows: Array<{ tenant_id: string }>, +): Candidate[] { + const shadowSet = new Set(deployedShadows.map((r) => r.tenant_id)) + return candidates.filter((c) => !shadowSet.has(c.id)) +} diff --git a/packages/create-helpbase/templates/lib/schemas.ts b/packages/create-helpbase/templates/lib/schemas.ts index 1913b60..acc80bf 100644 --- a/packages/create-helpbase/templates/lib/schemas.ts +++ b/packages/create-helpbase/templates/lib/schemas.ts @@ -279,6 +279,14 @@ export const deployPayloadSchema = z.object({ title: z.string().min(1), description: z.string().default(""), content: z.string(), + // content_hash is required, not defaulted: an empty string persists + // straight through to tenant_articles.content_hash and the diff + // engine treats "" as UPDATED-forever until the next deploy. That's + // a silent DX regression. The server recomputes on the deploy route + // as belt-and-braces, but requiring at the schema level catches + // malformed callers with a clear 400 before the RPC fires. Caught + // by CodeRabbit on PR #11. + content_hash: z.string().min(1, "content_hash is required (hash via hashArticle)"), frontmatter: z.record(z.string(), z.unknown()).default({}), order: z.number().int().default(0), tags: z.array(z.string()).optional().nullable(), @@ -289,6 +297,12 @@ export const deployPayloadSchema = z.object({ })), chunks: z.array(tenantChunkSchema), validation_report: deployReportSchema.optional(), + // Optimistic concurrency: client passes the deploy_version it observed + // when fetching /state. Server raises stale_deploy_version (SQLSTATE P0001) + // if the value has advanced since. Optional — CI and legacy callers + // that don't run `deploy --preview` first pass undefined and skip the + // check. See `deploy_tenant_rpc_v2_content_hash_and_version` migration. + expected_deploy_version: z.number().int().nonnegative().nullable().optional(), }) export type DeployPayload = z.infer diff --git a/packages/shared/package.json b/packages/shared/package.json index 83e1414..00d388a 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -4,6 +4,7 @@ "type": "module", "private": true, "exports": { + "./article-hash": "./src/article-hash.ts", "./schemas": "./src/schemas.ts", "./types": "./src/types.ts", "./slugify": "./src/slugify.ts", diff --git a/packages/shared/src/article-hash.ts b/packages/shared/src/article-hash.ts new file mode 100644 index 0000000..bc3351d --- /dev/null +++ b/packages/shared/src/article-hash.ts @@ -0,0 +1,72 @@ +import { createHash } from "node:crypto" + +/** + * Deterministic content hash for a deployed article. Drives the preview + * diff between local `content/` and the hosted tenant, so the algorithm + * MUST produce byte-identical output on the client (during `helpbase + * deploy --preview`) and the server (stored in `tenant_articles.content_hash` + * when `deploy_tenant` writes a row). + * + * Canonical serialization: + * title + "\n" + description + "\n" + stableStringify(frontmatter) + "\n" + content + * + * No whitespace normalization. MDX carries meaningful whitespace — code + * blocks, JSX text, fenced content, preformatted examples — so normalizing + * would hide real edits and produce "unchanged" false positives on the + * preview. Hash exactly what's stored. + * + * Frontmatter keys are sorted at every object level so + * `{ title: "X", order: 1 }` and `{ order: 1, title: "X" }` hash the + * same. Array order is preserved (it's semantic: tags, citations). + * + * Hash parity is validated by packages/shared/test/article-hash.test.ts + * via snapshot fixtures, which fail loudly if the algorithm drifts. + */ +export interface ArticleHashInput { + title: string + description: string + frontmatter: Record + content: string +} + +const SEPARATOR = "\n" + +export function hashArticle(input: ArticleHashInput): string { + // JSON.stringify every field before joining so newlines inside + // `title` or `description` cannot collide with the SEPARATOR and + // confuse two otherwise-distinct articles into the same hash. + // Without this, { title: "A", description: "B\nC", ... } and + // { title: "A\nB", description: "C", ... } would hash identically. + // Caught by CodeRabbit on PR #11 — fixing in the same migration + // window while no tenant has a real content_hash yet. + const payload = [ + JSON.stringify(input.title), + JSON.stringify(input.description), + stableStringify(input.frontmatter), + JSON.stringify(input.content), + ].join(SEPARATOR) + return createHash("sha256").update(payload, "utf8").digest("hex") +} + +/** + * JSON.stringify with recursively sorted object keys. Ensures that two + * semantically-equal objects produce the same string regardless of how + * their keys were inserted. Arrays keep their order. + * + * Exported so tests (and future server code) can snapshot-verify the + * canonical form without hashing. + */ +export function stableStringify(value: unknown): string { + if (value === null || value === undefined) return JSON.stringify(value ?? null) + if (typeof value !== "object") return JSON.stringify(value) + if (Array.isArray(value)) { + return "[" + value.map(stableStringify).join(",") + "]" + } + const obj = value as Record + const keys = Object.keys(obj).sort() + return ( + "{" + + keys.map((k) => JSON.stringify(k) + ":" + stableStringify(obj[k])).join(",") + + "}" + ) +} diff --git a/packages/shared/src/schemas.ts b/packages/shared/src/schemas.ts index 1913b60..acc80bf 100644 --- a/packages/shared/src/schemas.ts +++ b/packages/shared/src/schemas.ts @@ -279,6 +279,14 @@ export const deployPayloadSchema = z.object({ title: z.string().min(1), description: z.string().default(""), content: z.string(), + // content_hash is required, not defaulted: an empty string persists + // straight through to tenant_articles.content_hash and the diff + // engine treats "" as UPDATED-forever until the next deploy. That's + // a silent DX regression. The server recomputes on the deploy route + // as belt-and-braces, but requiring at the schema level catches + // malformed callers with a clear 400 before the RPC fires. Caught + // by CodeRabbit on PR #11. + content_hash: z.string().min(1, "content_hash is required (hash via hashArticle)"), frontmatter: z.record(z.string(), z.unknown()).default({}), order: z.number().int().default(0), tags: z.array(z.string()).optional().nullable(), @@ -289,6 +297,12 @@ export const deployPayloadSchema = z.object({ })), chunks: z.array(tenantChunkSchema), validation_report: deployReportSchema.optional(), + // Optimistic concurrency: client passes the deploy_version it observed + // when fetching /state. Server raises stale_deploy_version (SQLSTATE P0001) + // if the value has advanced since. Optional — CI and legacy callers + // that don't run `deploy --preview` first pass undefined and skip the + // check. See `deploy_tenant_rpc_v2_content_hash_and_version` migration. + expected_deploy_version: z.number().int().nonnegative().nullable().optional(), }) export type DeployPayload = z.infer diff --git a/packages/shared/test/article-hash.test.ts b/packages/shared/test/article-hash.test.ts new file mode 100644 index 0000000..694a531 --- /dev/null +++ b/packages/shared/test/article-hash.test.ts @@ -0,0 +1,189 @@ +import { describe, it, expect } from "vitest" +import { hashArticle, stableStringify } from "../src/article-hash.js" + +/** + * Snapshot + invariant tests for the article content hash. + * + * These fixtures are the contract: if the hashing algorithm changes, + * every existing deployed tenant's content_hash column becomes stale, + * every `helpbase deploy --preview` starts showing every article as + * UPDATED, and users lose trust. So these tests are intentionally + * brittle — they fail the moment the bytes change. + * + * To intentionally change the algorithm: write the migration + backfill + * first, then update these fixtures + the migration version together. + */ + +const FIXTURE = { + title: "How to reset your password", + description: "Step-by-step: recover access when you forget.", + frontmatter: { + schemaVersion: 1, + title: "How to reset your password", + description: "Step-by-step: recover access when you forget.", + order: 3, + tags: ["auth", "account"], + featured: false, + }, + content: "# Reset password\n\nClick **Forgot password** on the login screen.\n", +} + +describe("hashArticle", () => { + it("produces a 64-char hex SHA-256 digest", () => { + const digest = hashArticle(FIXTURE) + expect(digest).toMatch(/^[0-9a-f]{64}$/) + }) + + it("is deterministic across calls", () => { + expect(hashArticle(FIXTURE)).toBe(hashArticle(FIXTURE)) + }) + + it("snapshot — the canonical fixture digest", () => { + // Locks the current serialization. If this changes, EVERY deployed + // tenant's content_hash goes stale. See file header. + // Snapshot changed after the JSON-encoding fix for hash collisions. + // See article-hash.ts header for rationale. + expect(hashArticle(FIXTURE)).toMatchInlineSnapshot( + `"696ec28189c46f0bf677fca9bc1b4c391b0816bdab441bcc6ffd62abbb2dc5e6"`, + ) + }) + + it("frontmatter key order does not affect the hash", () => { + const reordered = { + ...FIXTURE, + frontmatter: { + featured: false, + tags: ["auth", "account"], + order: 3, + description: "Step-by-step: recover access when you forget.", + title: "How to reset your password", + schemaVersion: 1, + }, + } + expect(hashArticle(reordered)).toBe(hashArticle(FIXTURE)) + }) + + it("nested frontmatter objects also stable across key order", () => { + const withNested = { + ...FIXTURE, + frontmatter: { + ...FIXTURE.frontmatter, + meta: { author: "christer", published: "2026-04-18" }, + }, + } + const reordered = { + ...FIXTURE, + frontmatter: { + ...FIXTURE.frontmatter, + meta: { published: "2026-04-18", author: "christer" }, + }, + } + expect(hashArticle(withNested)).toBe(hashArticle(reordered)) + }) + + it("array order IS semantic — tags order change DOES change the hash", () => { + const flipped = { + ...FIXTURE, + frontmatter: { ...FIXTURE.frontmatter, tags: ["account", "auth"] }, + } + expect(hashArticle(flipped)).not.toBe(hashArticle(FIXTURE)) + }) + + it("title change changes the hash", () => { + const modified = { ...FIXTURE, title: "How to reset your password!" } + expect(hashArticle(modified)).not.toBe(hashArticle(FIXTURE)) + }) + + it("description change changes the hash", () => { + const modified = { ...FIXTURE, description: FIXTURE.description + "." } + expect(hashArticle(modified)).not.toBe(hashArticle(FIXTURE)) + }) + + it("content change changes the hash", () => { + const modified = { ...FIXTURE, content: FIXTURE.content + "\n" } + expect(hashArticle(modified)).not.toBe(hashArticle(FIXTURE)) + }) + + it("does NOT normalize whitespace — trailing newline matters", () => { + // T3A decision: MDX whitespace is meaningful (code blocks, JSX, + // fenced content). Hash reflects exact stored bytes. + const withTrailing = { ...FIXTURE, content: FIXTURE.content } + const withoutTrailing = { + ...FIXTURE, + content: FIXTURE.content.replace(/\n$/, ""), + } + expect(hashArticle(withTrailing)).not.toBe(hashArticle(withoutTrailing)) + }) + + it("does NOT normalize whitespace — indent change matters", () => { + const tabbed = { + ...FIXTURE, + content: "```ts\n\tconst x = 1\n```\n", + } + const spaced = { + ...FIXTURE, + content: "```ts\n const x = 1\n```\n", + } + expect(hashArticle(tabbed)).not.toBe(hashArticle(spaced)) + }) + + it("empty frontmatter hashes consistently", () => { + const empty = { ...FIXTURE, frontmatter: {} } + expect(hashArticle(empty)).toBe(hashArticle(empty)) + expect(hashArticle(empty)).not.toBe(hashArticle(FIXTURE)) + }) + + it("handles null values in frontmatter", () => { + const withNull = { + ...FIXTURE, + frontmatter: { ...FIXTURE.frontmatter, heroImage: null }, + } + expect(hashArticle(withNull)).not.toBe(hashArticle(FIXTURE)) + expect(hashArticle(withNull)).toBe(hashArticle(withNull)) + }) + + it("regression: field-boundary collision does NOT match (CodeRabbit PR #11)", () => { + // Without JSON-encoding the raw delimiters, these two hash the same. + const a = { ...FIXTURE, title: "A", description: "B\nC" } + const b = { ...FIXTURE, title: "A\nB", description: "C" } + expect(hashArticle(a)).not.toBe(hashArticle(b)) + }) + + it("handles undefined values in frontmatter (treated as null)", () => { + const withUndef = { + ...FIXTURE, + frontmatter: { ...FIXTURE.frontmatter, heroImage: undefined }, + } + // undefined serializes as null in our stableStringify, and the key + // is still present in Object.keys so the hash differs from the + // FIXTURE (which omits heroImage entirely). + expect(hashArticle(withUndef)).not.toBe(hashArticle(FIXTURE)) + }) +}) + +describe("stableStringify", () => { + it("sorts keys at top level", () => { + expect(stableStringify({ b: 1, a: 2 })).toBe('{"a":2,"b":1}') + }) + + it("sorts keys at nested levels", () => { + expect(stableStringify({ outer: { b: 1, a: 2 } })).toBe( + '{"outer":{"a":2,"b":1}}', + ) + }) + + it("preserves array order", () => { + expect(stableStringify([3, 1, 2])).toBe("[3,1,2]") + }) + + it("handles primitives", () => { + expect(stableStringify("hello")).toBe('"hello"') + expect(stableStringify(42)).toBe("42") + expect(stableStringify(true)).toBe("true") + expect(stableStringify(null)).toBe("null") + }) + + it("serializes undefined as null", () => { + expect(stableStringify(undefined)).toBe("null") + }) +}) diff --git a/registry/helpbase/lib/reservation-cleanup.ts b/registry/helpbase/lib/reservation-cleanup.ts new file mode 100644 index 0000000..446b8b4 --- /dev/null +++ b/registry/helpbase/lib/reservation-cleanup.ts @@ -0,0 +1,35 @@ +/** + * Pure helpers for the cleanup-reservations cron. Extracted so unit tests + * exercise the same predicate the route handler runs, not a shadow copy. + * CodeRabbit flagged the duplication on PR #10. + * + * The route still performs the actual SELECT + DELETE against Supabase + * (that part is not unit-testable without a live DB); what we pin here + * is the 30-day TTL math and the shadow-safety filter. + */ + +export const RESERVATION_TTL_DAYS = 30 + +/** ISO timestamp of the cutoff: anything auto_provisioned before this is TTL-expired. */ +export function reservationCutoff(now: Date): string { + return new Date(now.getTime() - RESERVATION_TTL_DAYS * 24 * 60 * 60 * 1000).toISOString() +} + +export interface Candidate { + id: string + slug: string +} + +/** + * Given candidate reservation rows (TTL-expired) and the set of tenant_ids + * that have deploy history, returns only the rows that are safe to delete. + * Belt-and-suspenders: any candidate with a tenant_deploys row is preserved + * even if `deployed_at` is null (data-repair state, failed RPC, etc.). + */ +export function filterDeletable( + candidates: Candidate[], + deployedShadows: Array<{ tenant_id: string }>, +): Candidate[] { + const shadowSet = new Set(deployedShadows.map((r) => r.tenant_id)) + return candidates.filter((c) => !shadowSet.has(c.id)) +} diff --git a/registry/helpbase/lib/schemas.ts b/registry/helpbase/lib/schemas.ts index 1913b60..acc80bf 100644 --- a/registry/helpbase/lib/schemas.ts +++ b/registry/helpbase/lib/schemas.ts @@ -279,6 +279,14 @@ export const deployPayloadSchema = z.object({ title: z.string().min(1), description: z.string().default(""), content: z.string(), + // content_hash is required, not defaulted: an empty string persists + // straight through to tenant_articles.content_hash and the diff + // engine treats "" as UPDATED-forever until the next deploy. That's + // a silent DX regression. The server recomputes on the deploy route + // as belt-and-braces, but requiring at the schema level catches + // malformed callers with a clear 400 before the RPC fires. Caught + // by CodeRabbit on PR #11. + content_hash: z.string().min(1, "content_hash is required (hash via hashArticle)"), frontmatter: z.record(z.string(), z.unknown()).default({}), order: z.number().int().default(0), tags: z.array(z.string()).optional().nullable(), @@ -289,6 +297,12 @@ export const deployPayloadSchema = z.object({ })), chunks: z.array(tenantChunkSchema), validation_report: deployReportSchema.optional(), + // Optimistic concurrency: client passes the deploy_version it observed + // when fetching /state. Server raises stale_deploy_version (SQLSTATE P0001) + // if the value has advanced since. Optional — CI and legacy callers + // that don't run `deploy --preview` first pass undefined and skip the + // check. See `deploy_tenant_rpc_v2_content_hash_and_version` migration. + expected_deploy_version: z.number().int().nonnegative().nullable().optional(), }) export type DeployPayload = z.infer