# Example: the personal site starter, file by file

The worked example for the `gomnee-ready-site` skill is Gomnee's starter repository, version 2.0.1 (67d0c19):
https://github.com/GOMNEE/starter-personal-site. Prefer "Use this template" on GitHub; this file is for
an agent that builds without it. It builds and passes `pnpm test`, `pnpm build` and `pnpm check` as shown, with
Next.js 16.3, React 19.2, Node 24, pnpm 11 and Postgres. "Your Name" and example.com are placeholders: replace them
with the owner's real facts.

Articles arrive from Gomnee through the site's publishing API and are stored in Postgres. They follow Gomnee's
Article document: https://gomnee.com/schemas/gomnee-article-v2.json

Settings: copy `.env.example` to `.env.local` on your computer. On Gomnee nothing is copied: Gomnee reads
`.env.example` when the repository is connected and, before it deploys, asks the owner for each value marked
`# required:core` (an unmarked line counts as required). The values stay protected and reach the site when it
builds and runs.

## Files

```text
starter-personal-site/
├── AGENTS.md                 rules for coding agents (CLAUDE.md points here)
├── README.md
├── package.json              Node 24, pnpm 11, Next.js 16, Drizzle, pg, zod
├── pnpm-lock.yaml            created by pnpm install; commit it
├── .env.example              DATABASE_URL, GOMNEE_PUBLISHING_TOKEN, GOMNEE_PREVIEW_STAGING_ORIGINS
├── app/
│   ├── page.tsx              home
│   ├── about/page.tsx
│   ├── blog/page.tsx         every Article
│   ├── blog/[slug]/page.tsx  one Article
│   ├── article-preview/[token]/page.tsx   private previews for Gomnee
│   ├── api/integrations/gomnee/publishing/v1/
│   │   ├── route.ts                       GET capabilities
│   │   ├── articles/[articleKey]/route.ts PUT publish, GET read-back
│   │   └── previews/route.ts              POST a private preview
│   ├── privacy/page.tsx
│   ├── not-found.tsx
│   ├── opengraph-image.tsx   the share image
│   ├── llms.txt/route.ts
│   ├── sitemap.ts
│   └── robots.ts
├── components/
│   ├── article-page.tsx      the Article layout
│   ├── article-body.tsx      every part of a Gomnee Article
│   ├── preview-navigation.tsx
│   ├── json-ld.tsx
│   └── date.tsx
├── db/                       Postgres tables (Drizzle)
├── drizzle/                  migrations; pnpm build applies them
├── lib/
│   ├── publishing/           Gomnee's Custom Website protocol
│   ├── articles.ts           the only reader of Articles
│   ├── article-view.ts       sources, anchors and contents
│   ├── metadata.ts           every page's metadata
│   └── site.ts               the site's identity, in one place
├── tests/                    against a real Postgres (_test database)
└── scripts/                  migrate.mjs, check.mjs
```

## package.json

```json
{
  "name": "starter-personal-site",
  "version": "2.0.1",
  "private": true,
  "license": "MIT",
  "packageManager": "pnpm@11.17.0",
  "engines": {
    "node": "24.x"
  },
  "scripts": {
    "dev": "next dev",
    "build": "node scripts/migrate.mjs && next build",
    "start": "next start",
    "test": "vitest run",
    "check": "node scripts/check.mjs",
    "db:generate": "drizzle-kit generate --name publishing",
    "db:migrate": "node scripts/migrate.mjs"
  },
  "dependencies": {
    "drizzle-orm": "0.45.4",
    "next": "16.3.5",
    "pg": "8.23.1",
    "react": "19.2.8",
    "react-dom": "19.2.8",
    "react-markdown": "10.1.0",
    "rehype-sanitize": "6.0.0",
    "remark-gfm": "4.0.1",
    "zod": "4.6.7"
  },
  "devDependencies": {
    "@types/node": "24.13.3",
    "@types/pg": "8.23.1",
    "@types/react": "19.2.17",
    "@types/react-dom": "19.2.7",
    "drizzle-kit": "0.31.11",
    "typescript": "6.0.3",
    "vitest": "5.1.1"
  }
}
```

## pnpm-workspace.yaml

```yaml
# pnpm 11 runs no dependency install scripts unless they are listed here.
# esbuild (used by drizzle-kit and vitest) works from its platform package.
allowBuilds:
  esbuild: false
```

## next.config.ts

```ts
import type { NextConfig } from "next";

/**
 * Only Gomnee may frame a private Article preview: app.gomnee.com, plus any
 * HTTPS origins listed in GOMNEE_PREVIEW_STAGING_ORIGINS (Gomnee's own test
 * environments; leave it empty unless Gomnee asks).
 */
export function previewFrameAncestors(configured = process.env.GOMNEE_PREVIEW_STAGING_ORIGINS ?? "") {
  const origins = new Set(["https://app.gomnee.com"]);
  for (const value of configured.split(/[\s,]+/).filter(Boolean)) {
    const url = new URL(value);
    if (
      url.protocol !== "https:" ||
      url.hostname.includes("*") ||
      url.username ||
      url.password ||
      url.pathname !== "/" ||
      url.search ||
      url.hash
    )
      throw new Error("GOMNEE_PREVIEW_STAGING_ORIGINS must contain HTTPS origins only.");
    origins.add(url.origin);
  }
  return `frame-ancestors ${[...origins].join(" ")};`;
}

const nextConfig: NextConfig = {
  poweredByHeader: false,
  // Every client, crawlers and agents included, gets the title, canonical and
  // meta tags in the initial <head>, never streamed into the body.
  htmlLimitedBots: /.*/,
  async headers() {
    const privateHeaders = [
      { key: "Cache-Control", value: "private, no-store" },
      { key: "Referrer-Policy", value: "no-referrer" },
      { key: "X-Robots-Tag", value: "noindex, nofollow, noarchive" },
    ];
    return [
      {
        // Every page except the private preview refuses to be framed.
        source: "/((?!article-preview(?:/|$)).*)",
        headers: [{ key: "X-Frame-Options", value: "DENY" }],
      },
      {
        source: "/article-preview/:path*",
        headers: [...privateHeaders, { key: "Content-Security-Policy", value: previewFrameAncestors() }],
      },
      {
        source: "/api/:path*",
        headers: [{ key: "X-Robots-Tag", value: "noindex, nofollow" }],
      },
    ];
  },
};

export default nextConfig;
```

## tsconfig.json

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "strict": true,
    "noEmit": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": [
        "./*"
      ]
    },
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    ".next/types/**/*.ts",
    ".next/dev/types/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}
```

## .gitignore

```gitignore
node_modules
.next
.env*
!.env.example
next-env.d.ts
*.tsbuildinfo
```

## .env.example

```sh
# Every setting the site reads. Copy this file to .env.local for your own
# computer (Next.js loads it; Git ignores it), and never commit real values.
#
# Gomnee reads this file when you connect the repository. Each line marked
# "# required:core" is a protected value Gomnee asks you for before it
# deploys the site; "# optional:core" lines are never asked for. A line
# without a mark counts as required. The values are stored protected and
# given to the site when it builds and runs, never written to Git.

# Postgres where the Articles Gomnee publishes are stored. Neon works, and on
# Vercel you can add it from the Marketplace.
DATABASE_URL= # required:core

# The key this site issues to Gomnee: at least 32 random characters
# (openssl rand -hex 32). Paste the same value under Integrations, CMS.
GOMNEE_PUBLISHING_TOKEN= # required:core

# Extra HTTPS origins allowed to frame private Article previews, besides
# https://app.gomnee.com. Leave empty unless Gomnee asks.
GOMNEE_PREVIEW_STAGING_ORIGINS= # optional:core
```

## drizzle.config.ts

```ts
import { defineConfig } from "drizzle-kit";

// pnpm db:generate writes a new migration after a change to db/schema.ts.
export default defineConfig({
  dialect: "postgresql",
  schema: "./db/schema.ts",
  out: "./drizzle",
});
```

## vitest.config.ts

```ts
import { fileURLToPath } from "node:url";
import { defineConfig } from "vitest/config";

// Tests use a real Postgres: TEST_DATABASE_URL, whose database name must end in
// _test (tests/setup-database.ts creates and migrates it).
export default defineConfig({
  resolve: { alias: { "@": fileURLToPath(new URL("./", import.meta.url)) } },
  test: {
    environment: "node",
    globalSetup: ["./tests/setup-database.ts"],
    setupFiles: ["./tests/environment.ts"],
    fileParallelism: false,
  },
});
```

## lib/site.ts

```ts
/**
 * The site's identity, in one place. Every page, the sitemap, the share image
 * and the structured data read it. Replace each value with your own before you
 * publish: `pnpm check` warns while any placeholder is left.
 */
export const SITE = {
  /** The one public address: https, and the host you chose (with or without www). */
  url: "https://example.com",
  /** You, as Articles name their author. A person or an organization, never a model. */
  name: "Your Name",
  /** One sentence about the site, under 160 characters. */
  description:
    "Your Name writes about the work they know best: what worked, what didn't, and why.",
  /** The language of the site, as a BCP 47 code. */
  language: "en",
  email: "you@example.com",
} as const;

/** An absolute URL on the site's one public address. */
export const absoluteUrl = (path: string) => new URL(path, SITE.url).toString();
```

## lib/metadata.ts

```ts
import type { Metadata } from "next";
import { SITE } from "./site";

/** The share image app/opengraph-image.tsx draws, named on every page. */
const SHARE_IMAGE = {
  url: "/opengraph-image",
  width: 1200,
  height: 630,
  alt: SITE.description,
};

/**
 * A page's metadata, complete: title, description, its one canonical address,
 * and Open Graph with the same address, the site's name and the share image.
 * A page's own Open Graph replaces the layout's, so the image is named here.
 */
export function pageMetadata({
  path,
  title,
  description,
  absoluteTitle = false,
  openGraph = {},
}: {
  path: string;
  title: string;
  description: string;
  /** True when the title already names the site, so the template doesn't repeat it. */
  absoluteTitle?: boolean;
  openGraph?: Record<string, unknown>;
}): Metadata {
  return {
    title: absoluteTitle ? { absolute: title } : title,
    description,
    alternates: { canonical: path },
    openGraph: {
      type: "website",
      url: path,
      title,
      description,
      siteName: SITE.name,
      locale: SITE.language,
      images: [SHARE_IMAGE],
      ...openGraph,
    },
    twitter: { card: "summary_large_image" },
  };
}
```

## lib/http.ts

```ts
import { z } from "zod";

export class HttpError extends Error {
  constructor(
    public status: number,
    message: string,
  ) {
    super(message);
  }
}

/** Reads a JSON body, refusing anything that isn't JSON or is larger than `maximum` bytes. */
export async function readJson(request: Request, maximum = 32_000): Promise<unknown> {
  if (!request.headers.get("content-type")?.startsWith("application/json"))
    throw new HttpError(415, "Send JSON.");
  if (Number(request.headers.get("content-length")) > maximum) throw new HttpError(413, "The body is too large.");
  const reader = request.body?.getReader();
  if (!reader) throw new HttpError(400, "The request is empty.");
  const chunks: Uint8Array[] = [];
  let total = 0;
  while (true) {
    const next = await reader.read();
    if (next.done) break;
    total += next.value.byteLength;
    if (total > maximum) {
      await reader.cancel();
      throw new HttpError(413, "The body is too large.");
    }
    chunks.push(next.value);
  }
  const buffer = new Uint8Array(total);
  let offset = 0;
  for (const chunk of chunks) {
    buffer.set(chunk, offset);
    offset += chunk.byteLength;
  }
  try {
    return JSON.parse(new TextDecoder().decode(buffer));
  } catch {
    throw new HttpError(400, "The JSON is not valid.");
  }
}

/** A JSON error for the caller; unexpected errors are logged by name only. */
export function apiError(error: unknown) {
  if (error instanceof HttpError) return Response.json({ error: error.message }, { status: error.status });
  if (error instanceof z.ZodError)
    return Response.json(
      {
        error: "The request does not match the contract.",
        issues: error.issues.map(({ path, message }) => ({ path: path.join("."), message })),
      },
      { status: 400 },
    );
  console.error("Request failed", error instanceof Error ? error.name : "UnknownError");
  return Response.json({ error: "The request could not be completed. Try again shortly." }, { status: 503 });
}
```

## lib/articles.ts

```ts
import { and, desc, eq } from "drizzle-orm";
import { databaseConfigured, getDb } from "@/db";
import { articles, type ArticleRow } from "@/db/schema";
import { articleCategories } from "@/lib/article-view";
import type { ArticlePayload } from "@/lib/publishing/contract";

/**
 * Articles are the ones Gomnee published to this site, stored as Gomnee sent
 * them (lib/publishing). This is the only module public pages read them
 * through. Without DATABASE_URL the site has no Articles yet, and every page
 * still answers.
 */
export type PublishedArticle = Readonly<{
  slug: string;
  payload: ArticlePayload;
  /** ISO date-times, set by this site when Gomnee first published and last updated it. */
  publishedAt: string;
  updatedAt: string;
}>;

/** What lists show: the index, the home page, related Articles, the sitemap. */
export type ArticleSummary = Readonly<{
  slug: string;
  title: string;
  summary: string;
  publishedAt: string;
  updatedAt: string;
  categories: readonly string[];
  /** Listing-card artwork only, never a body image or share image. */
  cover: Readonly<{ url: string; alt: string; width: number; height: number }> | null;
}>;

function published(row: ArticleRow): PublishedArticle {
  return {
    slug: row.slug,
    payload: row.payload,
    publishedAt: row.publishedAt.toISOString(),
    updatedAt: row.updatedAt.toISOString(),
  };
}

export function summaryOf(article: PublishedArticle): ArticleSummary {
  const { payload } = article;
  const cover = payload.contentFormat === "gomnee_article_v2" ? payload.cover : undefined;
  return {
    slug: article.slug,
    title: payload.title,
    summary: payload.summary,
    publishedAt: article.publishedAt,
    updatedAt: article.updatedAt,
    categories: articleCategories(payload),
    cover: cover ? { url: cover.url, alt: cover.alt, width: cover.width, height: cover.height } : null,
  };
}

/** Every published Article, newest first. */
export async function listArticles(): Promise<ArticleSummary[]> {
  if (!databaseConfigured()) return [];
  const rows = await getDb()
    .select()
    .from(articles)
    .where(eq(articles.status, "published"))
    .orderBy(desc(articles.publishedAt));
  return rows.map((row) => summaryOf(published(row)));
}

export async function getArticle(slug: string): Promise<PublishedArticle | null> {
  if (!databaseConfigured()) return null;
  const [row] = await getDb()
    .select()
    .from(articles)
    .where(and(eq(articles.slug, slug), eq(articles.status, "published")));
  return row ? published(row) : null;
}

/** Up to three other Articles: the same category first, then the newest. */
export async function relatedArticles(
  article: Pick<PublishedArticle, "slug" | "payload">,
  limit = 3,
): Promise<ArticleSummary[]> {
  const own = new Set(articleCategories(article.payload).map((category) => category.toLowerCase()));
  const others = (await listArticles()).filter((other) => other.slug !== article.slug);
  const shares = (other: ArticleSummary) => other.categories.some((category) => own.has(category.toLowerCase()));
  return [...others.filter(shares), ...others.filter((other) => !shares(other))].slice(0, limit);
}
```

## lib/article-view.ts

```ts
import type { ArticlePayload, RichArticlePayload } from "@/lib/publishing/contract";
import { SITE } from "@/lib/site";

type Citation = RichArticlePayload["presentation"]["citations"][number];

/** One public source: every citation of the same URL shares its number. */
export type SourceEntry = {
  number: number;
  /** The list entry's anchor, from the first citation with this URL. */
  anchor: string;
  label: string;
  url: string;
  locators: string[];
};
export type SourceIndex = {
  entries: SourceEntry[];
  byKey: ReadonlyMap<string, SourceEntry>;
  /** Sources each section cites, in ascending number order. */
  bySection: ReadonlyMap<string, SourceEntry[]>;
};

/** Numbers sources once per URL, in payload order, and merges their locators. */
export function buildSourceIndex(citations: readonly Citation[]): SourceIndex {
  const entries: SourceEntry[] = [];
  const byUrl = new Map<string, SourceEntry>();
  const byKey = new Map<string, SourceEntry>();
  const bySection = new Map<string, SourceEntry[]>();
  for (const citation of citations) {
    let entry = byUrl.get(citation.url);
    if (!entry) {
      entry = {
        number: entries.length + 1,
        anchor: `source-${citation.key}`,
        label: citation.label,
        url: citation.url,
        locators: [],
      };
      entries.push(entry);
      byUrl.set(citation.url, entry);
    }
    if (citation.locator && !entry.locators.includes(citation.locator)) entry.locators.push(citation.locator);
    byKey.set(citation.key, entry);
    const section = bySection.get(citation.sectionKey) ?? [];
    if (!section.includes(entry)) section.push(entry);
    bySection.set(citation.sectionKey, section);
  }
  for (const section of bySection.values()) section.sort((a, b) => a.number - b.number);
  return { entries, byKey, bySection };
}

/** A module's citation keys as unique sources, in ascending number order. */
export function sourceRefs(index: SourceIndex, keys: readonly string[]) {
  return [
    ...new Set(
      keys.flatMap((key) => {
        const entry = index.byKey.get(key);
        return entry ? [entry] : [];
      }),
    ),
  ].sort((a, b) => a.number - b.number);
}

/** Sources any cell of a comparison row cites, listed once for the row. */
export function rowSourceRefs(index: SourceIndex, cells: readonly { citationKeys: string[] }[]) {
  return sourceRefs(
    index,
    cells.flatMap((cell) => cell.citationKeys),
  );
}

export type ArticleLink =
  | { kind: "internal"; href: string }
  | { kind: "external"; href: string }
  | { kind: "plain"; href: string | undefined };
/**
 * Classifies a link in Article content. An absolute URL on this site becomes a
 * root-relative path, so it stays on whichever address serves the page.
 */
export function articleLink(href: string | undefined, siteOrigins: readonly string[] = [new URL(SITE.url).origin]): ArticleLink {
  if (!href) return { kind: "plain", href };
  if (href.startsWith("/") && !href.startsWith("//")) return { kind: "internal", href };
  if (!/^https?:\/\//i.test(href)) return { kind: "plain", href };
  let url: URL;
  try {
    url = new URL(href);
  } catch {
    return { kind: "plain", href };
  }
  return siteOrigins.includes(url.origin)
    ? { kind: "internal", href: `${url.pathname}${url.search}${url.hash}` }
    : { kind: "external", href };
}

// Fixed anchors the page and typed modules use; section keys never take them.
export const ANCHORS = {
  procedure: "procedure",
  comparison: "comparison",
  questions: "questions",
  sources: "sources",
  verification: "how-this-was-checked",
} as const;
const RESERVED_PREFIXES = ["step-", "question-", "image-", "source-", "excerpt-"];

/** Section key → an element id that cannot collide with a module's anchor. */
export function sectionAnchors(keys: readonly string[]) {
  const reserved = new Set<string>(Object.values(ANCHORS));
  const anchors = new Map<string, string>();
  const used = new Set(keys);
  for (const key of keys) {
    if (!reserved.has(key) && !RESERVED_PREFIXES.some((prefix) => key.startsWith(prefix))) {
      anchors.set(key, key);
      continue;
    }
    let anchor = `section-${key}`;
    for (let n = 2; used.has(anchor); n++) anchor = `section-${key}-${n}`;
    used.add(anchor);
    anchors.set(key, anchor);
  }
  return anchors;
}

export type ContentsEntry = { id: string; label: string };
/** Anchors, numbered sources and the contents, shared by the page and its body. */
export function articleOutline(payload: ArticlePayload) {
  if (payload.contentFormat === "markdown")
    return { anchors: new Map<string, string>(), sources: buildSourceIndex([]), contents: [] as ContentsEntry[] };
  const typed = payload.contentFormat === "gomnee_article_v2" ? payload : null;
  const anchors = sectionAnchors(payload.sections.map((section) => section.key));
  const sources = buildSourceIndex(payload.presentation.citations);
  const contents: ContentsEntry[] = [
    ...payload.sections.map((section) => ({ id: anchors.get(section.key)!, label: section.heading })),
    ...(typed?.faq.some((item) => item.sectionKey === null) ? [{ id: ANCHORS.questions, label: "Questions" }] : []),
    ...(sources.entries.length ? [{ id: ANCHORS.sources, label: "Sources" }] : []),
    ...(typed?.verification ? [{ id: ANCHORS.verification, label: "How this was checked" }] : []),
  ];
  return { anchors, sources, contents };
}
export type ArticleOutline = ReturnType<typeof articleOutline>;

const WORDS_PER_MINUTE = 220;
/** Estimated reading time of the visible text, rounded up. */
export function readingMinutes(payload: ArticlePayload) {
  const parts: string[] = [];
  if (payload.contentFormat === "markdown") parts.push(payload.content);
  else {
    parts.push(payload.presentation.opening ?? "");
    for (const section of payload.sections) parts.push(section.heading, section.markdown);
  }
  if (payload.contentFormat === "gomnee_article_v2") {
    for (const item of payload.faq) parts.push(item.question, item.answerMarkdown);
    const procedure = payload.procedure;
    if (procedure)
      parts.push(
        procedure.prerequisitesMarkdown ?? "",
        ...procedure.steps.flatMap((step) => [step.name, step.instructionsMarkdown, step.expectedResultMarkdown ?? ""]),
        procedure.verificationMarkdown ?? "",
        procedure.troubleshootingMarkdown ?? "",
      );
    const comparison = payload.comparison;
    if (comparison)
      parts.push(
        comparison.methodMarkdown,
        ...comparison.rows.flatMap((row) => [row.label, ...row.cells.map((cell) => cell.markdown)]),
        comparison.limitationsMarkdown ?? "",
      );
  }
  const words = parts
    // A cheap estimate: drop link targets and Markdown symbols, then count words.
    .flatMap((part) =>
      part
        .replace(/\]\([^)]*\)/g, " ")
        .replace(/[#>*_`|[\]~-]/g, " ")
        .split(/\s+/),
    )
    .filter(Boolean).length;
  return Math.max(1, Math.ceil(words / WORDS_PER_MINUTE));
}

export function articleCategories(payload: ArticlePayload): readonly string[] {
  return payload.contentFormat === "gomnee_article_v2" ? payload.taxonomy.categories : [];
}

export function articleTags(payload: ArticlePayload): readonly string[] {
  return payload.contentFormat === "gomnee_article_v2" ? payload.taxonomy.tags : [];
}

/** The hero image, when the Article has a real (non-decorative) one. */
export function heroImage(payload: ArticlePayload) {
  if (payload.contentFormat === "markdown") return null;
  return payload.presentation.media.find((item) => item.role === "hero" && !item.decorative) ?? null;
}

/** The title and description search engines see: the Article's own overrides first. */
export function searchFields(payload: ArticlePayload) {
  const search = payload.contentFormat === "markdown" ? null : payload.presentation.search;
  return { title: search?.title ?? payload.title, description: search?.description ?? payload.summary };
}
```

## lib/publishing/contract.ts

```ts
import { z } from "zod";

/**
 * Gomnee's public Article wire format and live publication requests, as the
 * Custom Website protocol defines them: Markdown (v1 requests), the rich
 * gomnee_article_v1 document (v2 requests) and the typed gomnee_article_v2
 * document, delivered plain or mapped (v3 requests). The schemas are strict:
 * an unknown field is refused, never stored.
 *
 * Ported from TrovaSEO's destination, which was qualified against Gomnee's own
 * validators. Change it only with Gomnee's contract.
 */
export const slugSchema = z
  .string()
  .min(1)
  .max(180)
  .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/);
const text = (max: number) => z.string().trim().min(1).max(max);
const key = z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/);
export const publicUrlSchema = z
  .url()
  .max(2048)
  .refine((value) => {
    const url = new URL(value);
    return (
      url.protocol === "https:" &&
      !url.username &&
      !url.password &&
      !/^(localhost|.*\.localhost$|127\.|0\.|10\.|192\.168\.|169\.254\.|172\.(1[6-9]|2\d|3[01])\.|\[|.*\.local$)/i.test(
        url.hostname,
      )
    );
  }, "Use a public HTTPS address.");

// Public wire format checked against Gomnee's article-public-projection and presentation contracts.
const authorSchema = z.strictObject({
  key,
  kind: z.enum(["person", "organization"]),
  name: text(160),
  profileUrl: publicUrlSchema.nullable(),
  description: text(1000).nullable(),
});
const mediaSchema = z.strictObject({
  key,
  role: z.enum(["hero", "inline"]),
  sectionKey: key.nullable(),
  url: publicUrlSchema,
  alt: z.string().max(1000),
  decorative: z.boolean(),
  caption: text(1200).nullable(),
  credit: text(500).nullable(),
  width: z.number().int().min(1).max(30000),
  height: z.number().int().min(1).max(30000),
});
const citationSchema = z.strictObject({
  key,
  sectionKey: key,
  label: text(300),
  url: publicUrlSchema,
  locator: text(500).nullable(),
});
const richArticleFields = {
  slug: slugSchema,
  title: text(160),
  summary: text(1200),
  sections: z
    .array(
      z.strictObject({
        key,
        heading: text(240),
        markdown: z.string().min(1).max(128000),
      }),
    )
    .min(1)
    .max(30),
  presentation: z.strictObject({
    opening: z.string().min(1).max(12000).nullable(),
    authors: z.array(authorSchema).min(1).max(5),
    reviewer: authorSchema.nullable(),
    media: z.array(mediaSchema).max(16),
    citations: z.array(citationSchema).max(96),
    search: z.strictObject({
      title: text(240).nullable(),
      description: text(500).nullable(),
    }),
  }),
};
function validateArticleReferences(
  article: z.infer<z.ZodObject<typeof richArticleFields>>,
  context: z.RefinementCtx,
) {
  const keys = article.sections.map((section) => section.key);
  const media = article.presentation.media;
  if (
    new Set(keys).size !== keys.length ||
    media.filter((item) => item.role === "hero").length > 1 ||
    new Set(media.map((item) => item.key)).size !== media.length ||
    media.some((item) =>
      item.role === "inline"
        ? !keys.includes(item.sectionKey ?? "")
        : item.sectionKey !== null,
    ) ||
    media.some((item) =>
      item.decorative ? item.alt !== "" : !item.alt.trim(),
    ) ||
    article.presentation.citations.some(
      (item) => !keys.includes(item.sectionKey),
    )
  )
    context.addIssue({
      code: "custom",
      message:
        "Public references must match the sections, and images need consistent alternative text.",
    });
}
export const richArticlePayloadSchema = z
  .strictObject({
    ...richArticleFields,
    contentFormat: z.literal("gomnee_article_v1"),
  })
  .superRefine(validateArticleReferences);

// Typed modules checked against Gomnee's article-public-modules (gomnee_article_v2).
const citationKeys = z.array(key).max(32);
const isoDate = z.iso.date().max(10);
const verificationExcerptSchema = z.union([
  z.strictObject({
    key,
    sectionKey: key,
    kind: z.enum(["terminal_output", "measurement"]),
    command: text(4000).nullable(),
    content: z
      .string()
      .min(1)
      .max(6000)
      .refine((value) => Boolean(value.trim())),
    capturedAt: isoDate,
  }),
  z.strictObject({
    key,
    sectionKey: key,
    kind: z.literal("screenshot"),
    mediaKey: key,
    capturedAt: isoDate,
  }),
]);
export const typedArticlePayloadSchema = z
  .strictObject({
    ...richArticleFields,
    contentFormat: z.literal("gomnee_article_v2"),
    // Listing-card artwork only; it is never a body hero or share image.
    cover: z
      .strictObject({
        key,
        url: publicUrlSchema,
        alt: text(1000),
        caption: text(1200).nullable(),
        credit: text(500).nullable(),
        width: z.number().int().min(1).max(30000),
        height: z.number().int().min(1).max(30000),
      })
      .optional(),
    faq: z
      .array(
        z.strictObject({
          key,
          question: text(500),
          answerMarkdown: text(6000),
          sectionKey: key.nullable(),
          citationKeys,
        }),
      )
      .max(8),
    procedure: z
      .strictObject({
        sectionKey: key,
        prerequisitesMarkdown: text(12000).nullable(),
        steps: z
          .array(
            z.strictObject({
              key,
              name: text(240),
              instructionsMarkdown: text(12000),
              expectedResultMarkdown: text(6000).nullable(),
              citationKeys,
            }),
          )
          .min(1)
          .max(50),
        verificationMarkdown: text(12000).nullable(),
        troubleshootingMarkdown: text(12000).nullable(),
      })
      .nullable(),
    comparison: z
      .strictObject({
        sectionKey: key,
        methodMarkdown: text(12000),
        columns: z
          .array(z.strictObject({ key, label: text(240) }))
          .min(2)
          .max(12),
        rows: z
          .array(
            z.strictObject({
              key,
              label: text(240),
              cells: z
                .array(
                  z.strictObject({
                    columnKey: key,
                    markdown: text(6000),
                    citationKeys,
                  }),
                )
                .min(2)
                .max(12),
            }),
          )
          .min(1)
          .max(50),
        limitationsMarkdown: text(12000).nullable(),
      })
      .nullable(),
    verification: z
      .strictObject({
        mode: z.enum(["first_hand", "docs_only", "not_applicable"]),
        disclosure: text(2000).nullable(),
        lastVerifiedAt: isoDate.nullable(),
        versions: z
          .array(z.strictObject({ name: text(160), version: text(160) }))
          .max(16),
        // Absence is part of the digest; never insert a default.
        excerpts: z.array(verificationExcerptSchema).max(16).optional(),
      })
      .nullable(),
    taxonomy: z.strictObject({
      categories: z.array(text(160)).max(16),
      tags: z.array(text(160)).max(32),
    }),
  })
  .superRefine((article, context) => {
    validateArticleReferences(article, context);
    const sections = new Set(article.sections.map((section) => section.key));
    const citations = new Set(
      article.presentation.citations.map((citation) => citation.key),
    );
    const unique = (values: string[]) => new Set(values).size === values.length;
    const resolved = (keys: string[]) => keys.every((k) => citations.has(k));
    const columns = article.comparison?.columns.map((column) => column.key);
    const excerpts = article.verification?.excerpts ?? [];
    if (
      citations.size !== article.presentation.citations.length ||
      !unique(article.faq.map((item) => item.key)) ||
      !unique(article.faq.map((item) => item.question.toLocaleLowerCase())) ||
      article.faq.some(
        (item) =>
          (item.sectionKey !== null && !sections.has(item.sectionKey)) ||
          !resolved(item.citationKeys),
      ) ||
      (article.procedure &&
        (!sections.has(article.procedure.sectionKey) ||
          !unique(article.procedure.steps.map((step) => step.key)) ||
          article.procedure.steps.some(
            (step) => !resolved(step.citationKeys),
          ))) ||
      (article.comparison &&
        columns &&
        (!sections.has(article.comparison.sectionKey) ||
          !unique(columns) ||
          !unique(article.comparison.rows.map((row) => row.key)) ||
          article.comparison.rows.some(
            (row) =>
              row.cells.length !== columns.length ||
              !unique(row.cells.map((cell) => cell.columnKey)) ||
              row.cells.some(
                (cell) =>
                  !columns.includes(cell.columnKey) ||
                  !resolved(cell.citationKeys),
              ),
          ))) ||
      (excerpts.length > 0 && article.verification?.mode !== "first_hand") ||
      !unique(excerpts.map((excerpt) => excerpt.key)) ||
      excerpts.some(
        (excerpt) =>
          !sections.has(excerpt.sectionKey) ||
          (excerpt.kind === "screenshot" &&
            !article.presentation.media.some(
              (item) =>
                item.key === excerpt.mediaKey &&
                item.role === "inline" &&
                item.sectionKey === excerpt.sectionKey &&
                !item.decorative,
            )),
      )
    )
      context.addIssue({
        code: "custom",
        message:
          "Questions, procedures, comparisons and verification need unique keys and must refer to existing sections, sources and images.",
      });
  });
export const markdownArticlePayloadSchema = z.strictObject({
  slug: slugSchema,
  title: text(160),
  summary: text(1200),
  contentFormat: z.literal("markdown"),
  content: z.string().min(1).max(128000),
});
export const articlePayloadSchema = z.union([
  markdownArticlePayloadSchema,
  richArticlePayloadSchema,
  typedArticlePayloadSchema,
]);
export type ArticlePayload = z.infer<typeof articlePayloadSchema>;
export type RichArticlePayload = Exclude<
  ArticlePayload,
  { contentFormat: "markdown" }
>;
export type TypedArticlePayload = z.infer<typeof typedArticlePayloadSchema>;

const digestSchema = z.string().regex(/^sha256:[a-f0-9]{64}$/);
// The site declares one complete-Article field; Gomnee pins the reviewed mapping.
export const mappedContentSchema = z.strictObject({
  mapping: z.strictObject({
    profileId: z.uuid(),
    version: z.number().int().positive(),
    digest: digestSchema,
    destinationShapeDigest: digestSchema,
  }),
  fields: z.tuple([
    z.strictObject({
      key: z.literal("content"),
      type: z.literal("article"),
      value: typedArticlePayloadSchema,
    }),
  ]),
});
export type MappedContent = z.infer<typeof mappedContentSchema>;

const requestFields = {
  commandId: z.uuid(),
  articleRevisionId: z.uuid(),
  expectedRemoteVersion: z.number().int().positive().nullable(),
  contentDigest: digestSchema,
};
export const publishRequestSchema = z.union([
  z.strictObject({
    schemaVersion: z.literal("gomnee_live_article_publish_v1"),
    ...requestFields,
    article: markdownArticlePayloadSchema,
  }),
  z.strictObject({
    schemaVersion: z.literal("gomnee_live_article_publish_v2"),
    ...requestFields,
    article: richArticlePayloadSchema,
  }),
  z.strictObject({
    schemaVersion: z.literal("gomnee_live_article_publish_v3"),
    ...requestFields,
    article: typedArticlePayloadSchema,
    mappedContent: mappedContentSchema,
  }),
]);
export type PublishRequest = z.infer<typeof publishRequestSchema>;
```

## lib/publishing/publish.ts

```ts
import { createHash } from "node:crypto";
import { eq, sql } from "drizzle-orm";
import { getDb } from "@/db";
import { articles, publicationCommands, type ArticleRow } from "@/db/schema";
import { HttpError } from "@/lib/http";
import { SITE, absoluteUrl } from "@/lib/site";
import {
  publishRequestSchema,
  type ArticlePayload,
  type MappedContent,
  type PublishRequest,
  type TypedArticlePayload,
} from "./contract";

/**
 * The site's side of Gomnee's Custom Website protocol: what it declares it can
 * do, and the one write it accepts. Gomnee checks the declaration, sends one
 * exact approved revision, and reads the result back.
 */
export const ADAPTER_KEY = "gomnee.custom_website_articles";
/** The article page's identity. Bump the version when the page changes what it shows. */
export const TEMPLATE = { id: "personal-site-blog", version: "1" };
// One complete-Article field: the page renders typed modules itself, so no
// separate CMS fields or author/term catalogues are declared.
export const DESTINATION_SHAPE = {
  schemaVersion: "gomnee_publication_destination_v1",
  version: "1",
  fields: [
    {
      key: "content",
      label: "Complete Article",
      type: "article",
      required: true,
      sourceHint: "article",
    },
  ],
};

export function articlePath(slug: string) {
  return `/blog/${slug}`;
}

export function publishingCapabilities() {
  return {
    schemaVersion: "gomnee_publishing_capabilities_v2",
    adapterKey: ADAPTER_KEY,
    adapterVersion: "1",
    siteOrigin: new URL(SITE.url).origin,
    status: "ready",
    capabilities: ["publish_live", "update_live", "read_publication"],
    limitations: [
      "no_remote_drafts",
      "no_remote_delete",
      "no_private_list",
      "slug_immutable_after_publish",
    ],
    contentFormats: ["markdown", "gomnee_article_v1", "gomnee_article_v2"],
    template: TEMPLATE,
    destinationShape: DESTINATION_SHAPE,
    coverPlacement: "listing_card",
  };
}

// Sorted keys and HTML-sensitive escaping, exactly as Gomnee hashes its wire documents.
export function canonicalJson(value: unknown): string {
  if (value === null) return "null";
  if (typeof value === "string")
    return JSON.stringify(value)
      .replaceAll("<", "\\u003c")
      .replaceAll(">", "\\u003e")
      .replaceAll("&", "\\u0026");
  if ((typeof value === "number" && Number.isFinite(value)) || typeof value === "boolean")
    return JSON.stringify(value);
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
  if (typeof value === "object" && value)
    return `{${Object.keys(value)
      .sort()
      .map((key) => `${canonicalJson(key)}:${canonicalJson((value as Record<string, unknown>)[key])}`)
      .join(",")}}`;
  throw new HttpError(400, "Unsupported JSON value.");
}

export function contentDigest(value: unknown) {
  return `sha256:${createHash("sha256").update(canonicalJson(value), "utf8").digest("hex")}`;
}

// A mapped publication's digest covers the canonical Article and its mapped copy.
function publicationDigest(article: ArticlePayload, mappedContent: MappedContent | null | undefined) {
  return contentDigest(mappedContent ? { article, mappedContent } : article);
}

function publicationFields(article: ArticleRow) {
  return {
    adapterKey: ADAPTER_KEY,
    adapterVersion: "1",
    articleKey: article.gomneeArticleKey,
    remoteContentId: article.id,
    remoteVersion: article.version,
    status: "published",
    slug: article.slug,
    publicUrl: absoluteUrl(articlePath(article.slug)),
    contentDigest: publicationDigest(article.payload, article.mappedContent),
    providerTimestamp: article.updatedAt.toISOString(),
    publishedAt: article.publishedAt.toISOString(),
    updatedAt: article.updatedAt.toISOString(),
    template: TEMPLATE,
  };
}

/** What Gomnee reads back: the stored Article exactly as it was sent. */
export function publicationObservation(article: ArticleRow) {
  return {
    schemaVersion: article.mappedContent
      ? "gomnee_live_article_observation_v2"
      : "gomnee_live_article_observation_v1",
    ...publicationFields(article),
    title: article.payload.title,
    summary: article.payload.summary,
    lastArticleRevisionId: article.lastArticleRevisionId,
    lastCommandId: article.lastCommandId,
    article: article.payload,
    ...(article.mappedContent && { mappedContent: article.mappedContent }),
  };
}

/**
 * Creates or updates one live Article. A repeated command returns its original
 * receipt; a stale version, a changed slug or a reused command with other
 * content is refused with 409 and changes nothing.
 */
export async function publishArticle(articleKey: string, input: unknown) {
  const request = publishRequestSchema.parse(input);
  const mappedContent = "mappedContent" in request ? request.mappedContent : null;
  if (mappedContent && canonicalJson(mappedContent.fields[0].value) !== canonicalJson(request.article))
    throw new HttpError(400, "The mapped Article must equal the canonical Article.");
  if (request.contentDigest !== publicationDigest(request.article, mappedContent))
    throw new HttpError(400, "The content digest does not match the article.");
  const requestDigest = contentDigest({ articleKey, ...request });
  return getDb().transaction(async (tx) => {
    await tx.execute(
      sql`select pg_advisory_xact_lock(hashtextextended(${"publication-command:" + request.commandId}, 0))`,
    );
    const [previous] = await tx
      .select()
      .from(publicationCommands)
      .where(eq(publicationCommands.commandId, request.commandId));
    if (previous) {
      if (previous.requestDigest !== requestDigest)
        throw new HttpError(409, "This command ID has already been used with different content.");
      return { ...previous.receipt, operation: "reconciled" };
    }
    // Checked after exact replay, so a later declaration change cannot invalidate an accepted command.
    if (mappedContent && mappedContent.mapping.destinationShapeDigest !== contentDigest(DESTINATION_SHAPE))
      throw new HttpError(409, "The destination fields changed. Refresh the publication mapping.");
    await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${"publication-article:" + articleKey}, 0))`);
    const [existing] = await tx
      .select()
      .from(articles)
      .where(eq(articles.gomneeArticleKey, articleKey))
      .for("update");
    if (
      existing &&
      (existing.status !== "published" ||
        existing.version !== request.expectedRemoteVersion ||
        existing.slug !== request.article.slug)
    )
      throw new HttpError(409, "The article version, slug or publication status has changed.");
    if (!existing && request.expectedRemoteVersion !== null)
      throw new HttpError(409, "The article has not been published yet.");
    if (!existing)
      await tx.execute(
        sql`select pg_advisory_xact_lock(hashtextextended(${"publication-slug:" + request.article.slug}, 0))`,
      );
    const now = new Date();
    let saved: ArticleRow;
    if (existing)
      [saved] = await tx
        .update(articles)
        .set({
          payload: request.article,
          mappedContent,
          version: existing.version + 1,
          updatedAt: now,
          lastArticleRevisionId: request.articleRevisionId,
          lastCommandId: request.commandId,
        })
        .where(eq(articles.id, existing.id))
        .returning();
    else {
      const [slugOwner] = await tx
        .select({ id: articles.id })
        .from(articles)
        .where(eq(articles.slug, request.article.slug));
      if (slugOwner) throw new HttpError(409, "The slug belongs to another article.");
      [saved] = await tx
        .insert(articles)
        .values({
          gomneeArticleKey: articleKey,
          slug: request.article.slug,
          payload: request.article,
          mappedContent,
          status: "published",
          publishedAt: now,
          updatedAt: now,
          lastArticleRevisionId: request.articleRevisionId,
          lastCommandId: request.commandId,
        })
        .returning();
    }
    const receipt = {
      schemaVersion: mappedContent ? "gomnee_live_article_receipt_v2" : "gomnee_live_article_receipt_v1",
      ...publicationFields(saved),
      operation: existing ? "updated" : "created",
      commandId: request.commandId,
      articleRevisionId: request.articleRevisionId,
      requestDigest,
      providerCorrelationId: request.commandId,
      ...(mappedContent && { mapping: mappedContent.mapping }),
    };
    await tx.insert(publicationCommands).values({
      commandId: request.commandId,
      articleId: saved.id,
      requestDigest,
      receipt,
    });
    return receipt;
  });
}

type Ids = {
  commandId: string;
  articleRevisionId: string;
  expectedRemoteVersion: number | null;
};
/** Builds a request the way Gomnee does. Tests and `pnpm check` use it. */
export function makePublishRequest(article: ArticlePayload, ids: Ids): PublishRequest;
export function makePublishRequest(
  article: TypedArticlePayload,
  ids: Ids,
  mapping: Omit<MappedContent["mapping"], "destinationShapeDigest">,
): Extract<PublishRequest, { schemaVersion: "gomnee_live_article_publish_v3" }>;
export function makePublishRequest(
  article: ArticlePayload,
  ids: Ids,
  mapping?: Omit<MappedContent["mapping"], "destinationShapeDigest">,
): PublishRequest {
  const mappedContent =
    mapping && article.contentFormat === "gomnee_article_v2"
      ? {
          mapping: { ...mapping, destinationShapeDigest: contentDigest(DESTINATION_SHAPE) },
          fields: [{ key: "content", type: "article", value: article }],
        }
      : undefined;
  return publishRequestSchema.parse({
    ...ids,
    schemaVersion: mappedContent
      ? "gomnee_live_article_publish_v3"
      : article.contentFormat === "markdown"
        ? "gomnee_live_article_publish_v1"
        : "gomnee_live_article_publish_v2",
    article,
    ...(mappedContent && { mappedContent }),
    contentDigest: publicationDigest(article, mappedContent as MappedContent | undefined),
  });
}
```

## lib/publishing/auth.ts

```ts
import { createHash, timingSafeEqual } from "node:crypto";
import { databaseConfigured } from "@/db";
import { HttpError } from "@/lib/http";

/**
 * Gomnee authenticates with the key this site issues: GOMNEE_PUBLISHING_TOKEN,
 * at least 32 random characters (openssl rand -hex 32). The owner pastes it
 * into Gomnee once; it never appears in Git or in the browser.
 */
export const MINIMUM_TOKEN_LENGTH = 32;

function matches(received: string, expected: string) {
  if (received.length > 1024) return false;
  return timingSafeEqual(
    createHash("sha256").update(received).digest(),
    createHash("sha256").update(expected).digest(),
  );
}

export function requirePublisher(request: Request) {
  const expected = process.env.GOMNEE_PUBLISHING_TOKEN;
  if (!expected || expected.length < MINIMUM_TOKEN_LENGTH || !databaseConfigured())
    throw new HttpError(503, "Publishing is not configured: set GOMNEE_PUBLISHING_TOKEN and DATABASE_URL.");
  const authorization = request.headers.get("authorization");
  if (!authorization?.startsWith("Bearer ") || !matches(authorization.slice(7), expected))
    throw new HttpError(401, "Publishing authorization required.");
}
```

## lib/publishing/preview-contract.ts

```ts
import { z } from "zod";
import { articlePayloadSchema } from "./contract";

export const articlePreviewTemplateSchema = z.strictObject({
  id: z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/),
  version: z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/),
});

/** A private rendering request. It grants no approval and publishes nothing. */
export const articlePreviewRequestSchema = z.strictObject({
  schemaVersion: z.literal("gomnee_article_preview_request_v1"),
  articleKey: z.uuid(),
  sourceRevisionId: z.uuid(),
  snapshotKind: z.enum(["saved", "unsaved"]),
  contentDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/),
  template: articlePreviewTemplateSchema,
  article: articlePayloadSchema,
});

export type ArticlePreviewRequest = z.infer<typeof articlePreviewRequestSchema>;
export type ArticlePreviewTemplate = z.infer<typeof articlePreviewTemplateSchema>;

export type ArticlePreviewReceipt = Omit<ArticlePreviewRequest, "schemaVersion" | "article"> & {
  schemaVersion: "gomnee_article_preview_receipt_v1";
  previewUrl: string;
  expiresAt: string;
};
```

## lib/publishing/preview.ts

```ts
import { createHash, randomBytes } from "node:crypto";
import { and, count, eq, gt, lte, sql } from "drizzle-orm";
import { getDb } from "@/db";
import { articlePreviews, articles } from "@/db/schema";
import { HttpError } from "@/lib/http";
import { absoluteUrl } from "@/lib/site";
import { articlePreviewRequestSchema, type ArticlePreviewReceipt } from "./preview-contract";
import { contentDigest, TEMPLATE } from "./publish";

/** Where a preview renders. Only Gomnee may frame it (see next.config.ts). */
export const PREVIEW_PATH = "/article-preview";
// Leaves transport headroom within the contract's 15-minute maximum.
export const ARTICLE_PREVIEW_LIFETIME_MS = 14 * 60 * 1000;
export const MAX_ACTIVE_ARTICLE_PREVIEWS = 100;
const tokenPattern = /^[a-zA-Z0-9_-]{43}$/;

function tokenHash(token: string) {
  return createHash("sha256").update(token, "utf8").digest("hex");
}

/**
 * Keeps one immutable snapshot to render, never an Article or a publication.
 * The link is a 32-byte random token; only its hash is stored, and it expires
 * after 14 minutes.
 */
export async function createArticlePreview(input: unknown): Promise<ArticlePreviewReceipt> {
  const request = articlePreviewRequestSchema.parse(input);
  if (request.template.id !== TEMPLATE.id || request.template.version !== TEMPLATE.version)
    throw new HttpError(409, "The website template changed. Refresh the destination before previewing.");
  if (contentDigest(request.article) !== request.contentDigest)
    throw new HttpError(400, "The preview digest does not match the article.");

  const token = randomBytes(32).toString("base64url");
  const now = new Date();
  const expiresAt = new Date(now.getTime() + ARTICLE_PREVIEW_LIFETIME_MS);
  await getDb().transaction(async (tx) => {
    // Serializes cleanup and capacity admission across every server instance.
    await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended('article-preview-capacity', 0))`);
    await tx.delete(articlePreviews).where(lte(articlePreviews.expiresAt, now));
    const [active] = await tx.select({ count: count() }).from(articlePreviews);
    if (active.count >= MAX_ACTIVE_ARTICLE_PREVIEWS)
      throw new HttpError(429, "Too many private previews. Wait for an earlier preview to expire.");
    const [publication] = await tx
      .select({ publishedAt: articles.publishedAt, updatedAt: articles.updatedAt })
      .from(articles)
      .where(and(eq(articles.gomneeArticleKey, request.articleKey), eq(articles.status, "published")));
    await tx.insert(articlePreviews).values({
      tokenHash: tokenHash(token),
      articleKey: request.articleKey,
      sourceRevisionId: request.sourceRevisionId,
      snapshotKind: request.snapshotKind,
      contentDigest: request.contentDigest,
      template: request.template,
      article: request.article,
      publishedAt: publication?.publishedAt ?? null,
      publicationUpdatedAt: publication?.updatedAt ?? null,
      createdAt: now,
      expiresAt,
    });
  });
  return {
    schemaVersion: "gomnee_article_preview_receipt_v1",
    articleKey: request.articleKey,
    sourceRevisionId: request.sourceRevisionId,
    snapshotKind: request.snapshotKind,
    contentDigest: request.contentDigest,
    template: request.template,
    previewUrl: absoluteUrl(`${PREVIEW_PATH}/${token}`),
    expiresAt: expiresAt.toISOString(),
  };
}

/** Tokens are capability URLs: an unknown, expired or outdated one reads as not found. */
export async function getArticlePreview(token: string) {
  if (!tokenPattern.test(token)) return null;
  const [preview] = await getDb()
    .select()
    .from(articlePreviews)
    .where(and(eq(articlePreviews.tokenHash, tokenHash(token)), gt(articlePreviews.expiresAt, new Date())));
  if (!preview || preview.template.id !== TEMPLATE.id || preview.template.version !== TEMPLATE.version)
    return null;
  return preview;
}
```

## db/schema.ts

```ts
import { sql } from "drizzle-orm";
import {
  check,
  index,
  integer,
  jsonb,
  pgEnum,
  pgTable,
  text,
  timestamp,
  uuid,
} from "drizzle-orm/pg-core";
import type { ArticlePayload, MappedContent } from "@/lib/publishing/contract";
import type { ArticlePreviewTemplate } from "@/lib/publishing/preview-contract";

/**
 * Every Article on the site is one Gomnee published here. "archived" takes one
 * off the site without deleting it; Gomnee never deletes or unpublishes.
 */
export const articleStatus = pgEnum("article_status", ["published", "archived"]);

export const articles = pgTable(
  "articles",
  {
    id: uuid("id").primaryKey().defaultRandom(),
    gomneeArticleKey: uuid("gomnee_article_key").notNull().unique(),
    slug: text("slug").notNull().unique(),
    payload: jsonb("payload").$type<ArticlePayload>().notNull(),
    // Present only for gomnee_live_article_publish_v3; its digest covers both documents.
    mappedContent: jsonb("mapped_content").$type<MappedContent>(),
    status: articleStatus("status").notNull().default("published"),
    version: integer("version").notNull().default(1),
    lastArticleRevisionId: uuid("last_article_revision_id"),
    lastCommandId: uuid("last_command_id"),
    publishedAt: timestamp("published_at", { withTimezone: true }).notNull(),
    updatedAt: timestamp("updated_at", { withTimezone: true }).notNull(),
  },
  (table) => [
    index("articles_published_idx").on(table.status, table.publishedAt),
    check("articles_slug_matches_payload", sql`${table.slug} = ${table.payload}->>'slug'`),
    check("articles_positive_version", sql`${table.version} > 0`),
    check(
      "articles_mapped_content_format",
      sql`${table.mappedContent} IS NULL OR ${table.payload}->>'contentFormat' = 'gomnee_article_v2'`,
    ),
  ],
);
export type ArticleRow = typeof articles.$inferSelect;

/** One durable receipt per command, so an exact retry returns the same answer. */
export const publicationCommands = pgTable("publication_commands", {
  commandId: uuid("command_id").primaryKey(),
  articleId: uuid("article_id")
    .notNull()
    .references(() => articles.id),
  requestDigest: text("request_digest").notNull(),
  receipt: jsonb("receipt").$type<Record<string, unknown>>().notNull(),
  createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});

/** Expiring private render snapshots. Public pages never read them. */
export const articlePreviews = pgTable(
  "article_previews",
  {
    tokenHash: text("token_hash").primaryKey(),
    articleKey: uuid("article_key").notNull(),
    sourceRevisionId: uuid("source_revision_id").notNull(),
    snapshotKind: text("snapshot_kind").$type<"saved" | "unsaved">().notNull(),
    contentDigest: text("content_digest").notNull(),
    template: jsonb("template").$type<ArticlePreviewTemplate>().notNull(),
    article: jsonb("article").$type<ArticlePayload>().notNull(),
    publishedAt: timestamp("published_at", { withTimezone: true }),
    publicationUpdatedAt: timestamp("publication_updated_at", { withTimezone: true }),
    createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
    expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
  },
  (table) => [
    index("article_previews_expiry_idx").on(table.expiresAt),
    check("article_previews_token_hash", sql`${table.tokenHash} ~ '^[a-f0-9]{64}$'`),
    check("article_previews_digest", sql`${table.contentDigest} ~ '^sha256:[a-f0-9]{64}$'`),
    check("article_previews_kind", sql`${table.snapshotKind} in ('saved', 'unsaved')`),
    check(
      "article_previews_lifetime",
      sql`${table.expiresAt} > ${table.createdAt} and ${table.expiresAt} <= ${table.createdAt} + interval '15 minutes'`,
    ),
  ],
);
export type ArticlePreviewRow = typeof articlePreviews.$inferSelect;
```

## db/index.ts

```ts
import { drizzle } from "drizzle-orm/node-postgres";
import { Pool } from "pg";
import * as schema from "./schema";

/**
 * The site's one database: Postgres at DATABASE_URL (Neon works, and on
 * Vercel you can add it from the Marketplace). Without it the site still
 * serves its pages; the blog is empty and publishing answers 503.
 */
export function databaseConfigured() {
  return Boolean(process.env.DATABASE_URL);
}

const shared = globalThis as unknown as { sitePool?: Pool };
export function getDb() {
  if (!process.env.DATABASE_URL) throw new Error("DATABASE_URL is not configured.");
  shared.sitePool ??= new Pool({
    connectionString: process.env.DATABASE_URL,
    max: 5,
    connectionTimeoutMillis: 5000,
    idleTimeoutMillis: 10000,
  });
  return drizzle(shared.sitePool, { schema });
}

export async function closeDb() {
  await shared.sitePool?.end();
  shared.sitePool = undefined;
}
```

## drizzle/0000_publishing.sql

```sql
CREATE TYPE "public"."article_status" AS ENUM('published', 'archived');--> statement-breakpoint
CREATE TABLE "article_previews" (
	"token_hash" text PRIMARY KEY NOT NULL,
	"article_key" uuid NOT NULL,
	"source_revision_id" uuid NOT NULL,
	"snapshot_kind" text NOT NULL,
	"content_digest" text NOT NULL,
	"template" jsonb NOT NULL,
	"article" jsonb NOT NULL,
	"published_at" timestamp with time zone,
	"publication_updated_at" timestamp with time zone,
	"created_at" timestamp with time zone NOT NULL,
	"expires_at" timestamp with time zone NOT NULL,
	CONSTRAINT "article_previews_token_hash" CHECK ("article_previews"."token_hash" ~ '^[a-f0-9]{64}$'),
	CONSTRAINT "article_previews_digest" CHECK ("article_previews"."content_digest" ~ '^sha256:[a-f0-9]{64}$'),
	CONSTRAINT "article_previews_kind" CHECK ("article_previews"."snapshot_kind" in ('saved', 'unsaved')),
	CONSTRAINT "article_previews_lifetime" CHECK ("article_previews"."expires_at" > "article_previews"."created_at" and "article_previews"."expires_at" <= "article_previews"."created_at" + interval '15 minutes')
);
--> statement-breakpoint
CREATE TABLE "articles" (
	"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
	"gomnee_article_key" uuid NOT NULL,
	"slug" text NOT NULL,
	"payload" jsonb NOT NULL,
	"mapped_content" jsonb,
	"status" "article_status" DEFAULT 'published' NOT NULL,
	"version" integer DEFAULT 1 NOT NULL,
	"last_article_revision_id" uuid,
	"last_command_id" uuid,
	"published_at" timestamp with time zone NOT NULL,
	"updated_at" timestamp with time zone NOT NULL,
	CONSTRAINT "articles_gomnee_article_key_unique" UNIQUE("gomnee_article_key"),
	CONSTRAINT "articles_slug_unique" UNIQUE("slug"),
	CONSTRAINT "articles_slug_matches_payload" CHECK ("articles"."slug" = "articles"."payload"->>'slug'),
	CONSTRAINT "articles_positive_version" CHECK ("articles"."version" > 0),
	CONSTRAINT "articles_mapped_content_format" CHECK ("articles"."mapped_content" IS NULL OR "articles"."payload"->>'contentFormat' = 'gomnee_article_v2')
);
--> statement-breakpoint
CREATE TABLE "publication_commands" (
	"command_id" uuid PRIMARY KEY NOT NULL,
	"article_id" uuid NOT NULL,
	"request_digest" text NOT NULL,
	"receipt" jsonb NOT NULL,
	"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
ALTER TABLE "publication_commands" ADD CONSTRAINT "publication_commands_article_id_articles_id_fk" FOREIGN KEY ("article_id") REFERENCES "public"."articles"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
CREATE INDEX "article_previews_expiry_idx" ON "article_previews" USING btree ("expires_at");--> statement-breakpoint
CREATE INDEX "articles_published_idx" ON "articles" USING btree ("status","published_at");
```

## drizzle/meta/_journal.json

```json
{
  "version": "7",
  "dialect": "postgresql",
  "entries": [
    {
      "idx": 0,
      "version": "7",
      "when": 1795567122951,
      "tag": "0000_publishing",
      "breakpoints": true
    }
  ]
}
```

## drizzle/meta/0000_snapshot.json

```json
{
  "id": "6de03753-bec4-4c24-a59a-ecdf8e42e8f2",
  "prevId": "00000000-0000-0000-0000-000000000000",
  "version": "7",
  "dialect": "postgresql",
  "tables": {
    "public.article_previews": {
      "name": "article_previews",
      "schema": "",
      "columns": {
        "token_hash": {
          "name": "token_hash",
          "type": "text",
          "primaryKey": true,
          "notNull": true
        },
        "article_key": {
          "name": "article_key",
          "type": "uuid",
          "primaryKey": false,
          "notNull": true
        },
        "source_revision_id": {
          "name": "source_revision_id",
          "type": "uuid",
          "primaryKey": false,
          "notNull": true
        },
        "snapshot_kind": {
          "name": "snapshot_kind",
          "type": "text",
          "primaryKey": false,
          "notNull": true
        },
        "content_digest": {
          "name": "content_digest",
          "type": "text",
          "primaryKey": false,
          "notNull": true
        },
        "template": {
          "name": "template",
          "type": "jsonb",
          "primaryKey": false,
          "notNull": true
        },
        "article": {
          "name": "article",
          "type": "jsonb",
          "primaryKey": false,
          "notNull": true
        },
        "published_at": {
          "name": "published_at",
          "type": "timestamp with time zone",
          "primaryKey": false,
          "notNull": false
        },
        "publication_updated_at": {
          "name": "publication_updated_at",
          "type": "timestamp with time zone",
          "primaryKey": false,
          "notNull": false
        },
        "created_at": {
          "name": "created_at",
          "type": "timestamp with time zone",
          "primaryKey": false,
          "notNull": true
        },
        "expires_at": {
          "name": "expires_at",
          "type": "timestamp with time zone",
          "primaryKey": false,
          "notNull": true
        }
      },
      "indexes": {
        "article_previews_expiry_idx": {
          "name": "article_previews_expiry_idx",
          "columns": [
            {
              "expression": "expires_at",
              "isExpression": false,
              "asc": true,
              "nulls": "last"
            }
          ],
          "isUnique": false,
          "concurrently": false,
          "method": "btree",
          "with": {}
        }
      },
      "foreignKeys": {},
      "compositePrimaryKeys": {},
      "uniqueConstraints": {},
      "policies": {},
      "checkConstraints": {
        "article_previews_token_hash": {
          "name": "article_previews_token_hash",
          "value": "\"article_previews\".\"token_hash\" ~ '^[a-f0-9]{64}$'"
        },
        "article_previews_digest": {
          "name": "article_previews_digest",
          "value": "\"article_previews\".\"content_digest\" ~ '^sha256:[a-f0-9]{64}$'"
        },
        "article_previews_kind": {
          "name": "article_previews_kind",
          "value": "\"article_previews\".\"snapshot_kind\" in ('saved', 'unsaved')"
        },
        "article_previews_lifetime": {
          "name": "article_previews_lifetime",
          "value": "\"article_previews\".\"expires_at\" > \"article_previews\".\"created_at\" and \"article_previews\".\"expires_at\" <= \"article_previews\".\"created_at\" + interval '15 minutes'"
        }
      },
      "isRLSEnabled": false
    },
    "public.articles": {
      "name": "articles",
      "schema": "",
      "columns": {
        "id": {
          "name": "id",
          "type": "uuid",
          "primaryKey": true,
          "notNull": true,
          "default": "gen_random_uuid()"
        },
        "gomnee_article_key": {
          "name": "gomnee_article_key",
          "type": "uuid",
          "primaryKey": false,
          "notNull": true
        },
        "slug": {
          "name": "slug",
          "type": "text",
          "primaryKey": false,
          "notNull": true
        },
        "payload": {
          "name": "payload",
          "type": "jsonb",
          "primaryKey": false,
          "notNull": true
        },
        "mapped_content": {
          "name": "mapped_content",
          "type": "jsonb",
          "primaryKey": false,
          "notNull": false
        },
        "status": {
          "name": "status",
          "type": "article_status",
          "typeSchema": "public",
          "primaryKey": false,
          "notNull": true,
          "default": "'published'"
        },
        "version": {
          "name": "version",
          "type": "integer",
          "primaryKey": false,
          "notNull": true,
          "default": 1
        },
        "last_article_revision_id": {
          "name": "last_article_revision_id",
          "type": "uuid",
          "primaryKey": false,
          "notNull": false
        },
        "last_command_id": {
          "name": "last_command_id",
          "type": "uuid",
          "primaryKey": false,
          "notNull": false
        },
        "published_at": {
          "name": "published_at",
          "type": "timestamp with time zone",
          "primaryKey": false,
          "notNull": true
        },
        "updated_at": {
          "name": "updated_at",
          "type": "timestamp with time zone",
          "primaryKey": false,
          "notNull": true
        }
      },
      "indexes": {
        "articles_published_idx": {
          "name": "articles_published_idx",
          "columns": [
            {
              "expression": "status",
              "isExpression": false,
              "asc": true,
              "nulls": "last"
            },
            {
              "expression": "published_at",
              "isExpression": false,
              "asc": true,
              "nulls": "last"
            }
          ],
          "isUnique": false,
          "concurrently": false,
          "method": "btree",
          "with": {}
        }
      },
      "foreignKeys": {},
      "compositePrimaryKeys": {},
      "uniqueConstraints": {
        "articles_gomnee_article_key_unique": {
          "name": "articles_gomnee_article_key_unique",
          "nullsNotDistinct": false,
          "columns": [
            "gomnee_article_key"
          ]
        },
        "articles_slug_unique": {
          "name": "articles_slug_unique",
          "nullsNotDistinct": false,
          "columns": [
            "slug"
          ]
        }
      },
      "policies": {},
      "checkConstraints": {
        "articles_slug_matches_payload": {
          "name": "articles_slug_matches_payload",
          "value": "\"articles\".\"slug\" = \"articles\".\"payload\"->>'slug'"
        },
        "articles_positive_version": {
          "name": "articles_positive_version",
          "value": "\"articles\".\"version\" > 0"
        },
        "articles_mapped_content_format": {
          "name": "articles_mapped_content_format",
          "value": "\"articles\".\"mapped_content\" IS NULL OR \"articles\".\"payload\"->>'contentFormat' = 'gomnee_article_v2'"
        }
      },
      "isRLSEnabled": false
    },
    "public.publication_commands": {
      "name": "publication_commands",
      "schema": "",
      "columns": {
        "command_id": {
          "name": "command_id",
          "type": "uuid",
          "primaryKey": true,
          "notNull": true
        },
        "article_id": {
          "name": "article_id",
          "type": "uuid",
          "primaryKey": false,
          "notNull": true
        },
        "request_digest": {
          "name": "request_digest",
          "type": "text",
          "primaryKey": false,
          "notNull": true
        },
        "receipt": {
          "name": "receipt",
          "type": "jsonb",
          "primaryKey": false,
          "notNull": true
        },
        "created_at": {
          "name": "created_at",
          "type": "timestamp with time zone",
          "primaryKey": false,
          "notNull": true,
          "default": "now()"
        }
      },
      "indexes": {},
      "foreignKeys": {
        "publication_commands_article_id_articles_id_fk": {
          "name": "publication_commands_article_id_articles_id_fk",
          "tableFrom": "publication_commands",
          "tableTo": "articles",
          "columnsFrom": [
            "article_id"
          ],
          "columnsTo": [
            "id"
          ],
          "onDelete": "no action",
          "onUpdate": "no action"
        }
      },
      "compositePrimaryKeys": {},
      "uniqueConstraints": {},
      "policies": {},
      "checkConstraints": {},
      "isRLSEnabled": false
    }
  },
  "enums": {
    "public.article_status": {
      "name": "article_status",
      "schema": "public",
      "values": [
        "published",
        "archived"
      ]
    }
  },
  "schemas": {},
  "sequences": {},
  "roles": {},
  "policies": {},
  "views": {},
  "_meta": {
    "columns": {},
    "schemas": {},
    "tables": {}
  }
}
```

## components/json-ld.tsx

```tsx
import { SITE, absoluteUrl } from "@/lib/site";

/** One JSON-LD block. "<" is escaped so content can never close the script. */
export function JsonLd({ data }: { data: Record<string, unknown> }) {
  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{
        __html: JSON.stringify(data).replace(/</g, "\\u003c"),
      }}
    />
  );
}

/** The person behind the site, described once and referred to by @id. */
export const PERSON_ID = absoluteUrl("/#person");
export const WEBSITE_ID = absoluteUrl("/#website");

/** A page that belongs to the site: WebPage, AboutPage or CollectionPage. */
export function PageJsonLd({
  type,
  path,
  name,
  description,
}: {
  type: "WebPage" | "AboutPage" | "CollectionPage";
  path: string;
  name: string;
  description: string;
}) {
  return (
    <JsonLd
      data={{
        "@context": "https://schema.org",
        "@type": type,
        "@id": absoluteUrl(path),
        url: absoluteUrl(path),
        name,
        description,
        inLanguage: SITE.language,
        isPartOf: { "@id": WEBSITE_ID },
        ...(type === "AboutPage" ? { about: { "@id": PERSON_ID } } : {}),
      }}
    />
  );
}
```

## components/date.tsx

```tsx
/**
 * A visible date that matches the structured data: `iso` is a date
 * (YYYY-MM-DD) or a date-time, shown as its UTC calendar date.
 */
export function DateText({ iso }: { iso: string }) {
  const date = iso.length === 10 ? new Date(`${iso}T00:00:00Z`) : new Date(iso);
  const text = date.toLocaleDateString("en", {
    day: "numeric",
    month: "long",
    year: "numeric",
    timeZone: "UTC",
  });
  return <time dateTime={iso}>{text}</time>;
}

/** The calendar day (UTC) of an ISO date or date-time. */
export const dayOf = (iso: string) => iso.slice(0, 10);
```

## components/article-body.tsx

```tsx
import type { ReactNode } from "react";
import Link from "next/link";
import ReactMarkdown from "react-markdown";
import rehypeSanitize from "rehype-sanitize";
import remarkGfm from "remark-gfm";
import { DateText } from "@/components/date";
import {
  ANCHORS,
  articleLink,
  articleOutline,
  rowSourceRefs,
  sourceRefs,
  type ArticleOutline,
  type SourceEntry,
  type SourceIndex,
} from "@/lib/article-view";
import type { ArticlePayload, RichArticlePayload, TypedArticlePayload } from "@/lib/publishing/contract";

/** Links on this site stay in the app; other sites are ordinary links. */
function ContentLink({ href, children }: { href?: string; children?: ReactNode }) {
  const link = articleLink(href);
  if (link.kind === "internal") return <Link href={link.href}>{children}</Link>;
  return <a href={link.href}>{children}</a>;
}

/** Markdown only: raw HTML in content is skipped and the result sanitized. */
export function Markdown({ text }: { text: string }) {
  return (
    <ReactMarkdown
      remarkPlugins={[remarkGfm]}
      rehypePlugins={[rehypeSanitize]}
      skipHtml
      components={{ a: ({ href, children }) => <ContentLink href={href}>{children}</ContentLink> }}
    >
      {text}
    </ReactMarkdown>
  );
}

/** Numbered links to the Article's one source list. */
function SourceRefs({ entries, label = "Sources" }: { entries: SourceEntry[]; label?: string }) {
  if (!entries.length) return null;
  return (
    <p className="article-refs">
      {label}:{" "}
      {entries.map((entry) => (
        <a key={entry.anchor} href={`#${entry.anchor}`} aria-label={`Source ${entry.number}: ${entry.label}`}>
          [{entry.number}]
        </a>
      ))}
    </p>
  );
}

function Note({ label, tone = "neutral", children }: { label: string; tone?: "neutral" | "success" | "warning"; children: ReactNode }) {
  return (
    <div className={`article-note article-note-${tone}`}>
      <p className="article-note-label">{label}</p>
      {children}
    </div>
  );
}

export const VERIFICATION_MODES = {
  first_hand: "Tested first-hand",
  docs_only: "Based on documentation",
  not_applicable: "Not applicable",
} as const;

type Procedure = NonNullable<TypedArticlePayload["procedure"]>;
function ProcedureBlock({ procedure, sources }: { procedure: Procedure; sources: SourceIndex }) {
  return (
    <div id={ANCHORS.procedure}>
      {procedure.prerequisitesMarkdown && (
        <Note label="Before you start">
          <Markdown text={procedure.prerequisitesMarkdown} />
        </Note>
      )}
      <ol className="article-steps">
        {procedure.steps.map((step) => (
          <li key={step.key} id={`step-${step.key}`}>
            <h3>{step.name}</h3>
            <Markdown text={step.instructionsMarkdown} />
            {step.expectedResultMarkdown && (
              <Note label="Expected result" tone="success">
                <Markdown text={step.expectedResultMarkdown} />
              </Note>
            )}
            <SourceRefs entries={sourceRefs(sources, step.citationKeys)} />
          </li>
        ))}
      </ol>
      {procedure.verificationMarkdown && (
        <>
          <h3>How to check the result</h3>
          <Markdown text={procedure.verificationMarkdown} />
        </>
      )}
      {procedure.troubleshootingMarkdown && (
        <Note label="If something doesn't work" tone="warning">
          <Markdown text={procedure.troubleshootingMarkdown} />
        </Note>
      )}
    </div>
  );
}

type Comparison = NonNullable<TypedArticlePayload["comparison"]>;
function ComparisonBlock({ comparison, caption, sources }: { comparison: Comparison; caption: string; sources: SourceIndex }) {
  return (
    <div id={ANCHORS.comparison}>
      <Note label="How this comparison works">
        <Markdown text={comparison.methodMarkdown} />
      </Note>
      {/* Focusable so a keyboard can scroll a wide table. */}
      <div className="article-table" role="region" aria-label={caption} tabIndex={0}>
        <table>
          <caption className="visually-hidden">{caption}</caption>
          <thead>
            <tr>
              <th scope="col">Item</th>
              {comparison.columns.map((column) => (
                <th key={column.key} scope="col">
                  {column.label}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {comparison.rows.map((row) => (
              <tr key={row.key}>
                <th scope="row">{row.label}</th>
                {comparison.columns.map((column, index) => {
                  const cell = row.cells.find((item) => item.columnKey === column.key)!;
                  return (
                    <td key={column.key}>
                      <Markdown text={cell.markdown} />
                      {index === comparison.columns.length - 1 && (
                        <SourceRefs entries={rowSourceRefs(sources, row.cells)} label="Sources for this row" />
                      )}
                    </td>
                  );
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      {comparison.limitationsMarkdown && (
        <Note label="Limits of this comparison">
          <Markdown text={comparison.limitationsMarkdown} />
        </Note>
      )}
    </div>
  );
}

function Questions({ faq, sources }: { faq: TypedArticlePayload["faq"]; sources: SourceIndex }) {
  if (!faq.length) return null;
  return (
    <div className="article-faq">
      {faq.map((item) => (
        <div key={item.key}>
          <h3 id={`question-${item.key}`}>{item.question}</h3>
          <Markdown text={item.answerMarkdown} />
          <SourceRefs entries={sourceRefs(sources, item.citationKeys)} />
        </div>
      ))}
    </div>
  );
}

type Excerpt = NonNullable<NonNullable<TypedArticlePayload["verification"]>["excerpts"]>[number];
function ExcerptBlock({ excerpt, media }: { excerpt: Excerpt; media: RichArticlePayload["presentation"]["media"] }) {
  if (excerpt.kind === "screenshot") {
    const image = media.find((item) => item.key === excerpt.mediaKey)!;
    return (
      <p id={`excerpt-${excerpt.key}`} className="article-shot">
        Screenshot taken <DateText iso={excerpt.capturedAt} />:{" "}
        <a href={`#image-${image.key}`}>{image.caption ?? image.alt}</a>.
      </p>
    );
  }
  const measurement = excerpt.kind === "measurement";
  // Captured text is literal: React escapes it, so it is never read as Markdown or HTML.
  return (
    <figure id={`excerpt-${excerpt.key}`} className="article-excerpt">
      <figcaption>
        <strong>{measurement ? "Measurement" : "Output"}</strong> captured <DateText iso={excerpt.capturedAt} />
      </figcaption>
      {excerpt.command &&
        (measurement ? (
          <p className="article-excerpt-method">Method: {excerpt.command}</p>
        ) : (
          <pre aria-label="Command">
            <code>{excerpt.command}</code>
          </pre>
        ))}
      <pre>
        <code>{excerpt.content}</code>
      </pre>
    </figure>
  );
}

type Media = RichArticlePayload["presentation"]["media"];
function Figures({ items }: { items: Media }) {
  return items.map((item) => (
    <figure className="article-figure" key={item.key} id={`image-${item.key}`}>
      {/* Public images load directly from their own address; nothing here fetches them. */}
      {/* eslint-disable-next-line @next/next/no-img-element */}
      <img
        src={item.url}
        alt={item.alt}
        width={item.width}
        height={item.height}
        loading={item.role === "hero" ? "eager" : "lazy"}
      />
      {(item.caption || item.credit) && (
        <figcaption>
          {item.caption}
          {item.caption && item.credit ? " · " : null}
          {item.credit}
        </figcaption>
      )}
    </figure>
  ));
}

/**
 * The Article's body, each part only when the Article has it: the opening, the
 * hero image, the sections with their procedure, comparison, questions,
 * evidence, images and sources, then general questions, the one numbered
 * source list, how it was checked, and its categories and tags.
 */
export function ArticleBody({
  payload,
  outline = articleOutline(payload),
  contents,
}: {
  payload: ArticlePayload;
  outline?: ArticleOutline;
  /** Placed before the first section. */
  contents?: ReactNode;
}) {
  if (payload.contentFormat === "markdown")
    return (
      <div className="body">
        <Markdown text={payload.content} />
      </div>
    );
  const typed = payload.contentFormat === "gomnee_article_v2" ? payload : null;
  const { anchors, sources } = outline;
  const media = payload.presentation.media;
  const generalFaq = typed?.faq.filter((item) => item.sectionKey === null) ?? [];
  const verification = typed?.verification;
  const excerpts = verification?.excerpts ?? [];
  const taxonomy = typed?.taxonomy;
  return (
    <div className="body">
      {payload.presentation.opening && (
        <div className="article-brief">
          <p className="article-note-label">In short</p>
          <Markdown text={payload.presentation.opening} />
        </div>
      )}
      <Figures items={media.filter((item) => item.role === "hero")} />
      {contents}
      {payload.sections.map((section) => (
        <section key={section.key} id={anchors.get(section.key)}>
          <h2>{section.heading}</h2>
          <Markdown text={section.markdown} />
          {typed?.procedure?.sectionKey === section.key && <ProcedureBlock procedure={typed.procedure} sources={sources} />}
          {typed?.comparison?.sectionKey === section.key && (
            <ComparisonBlock comparison={typed.comparison} caption={section.heading} sources={sources} />
          )}
          {typed && <Questions faq={typed.faq.filter((item) => item.sectionKey === section.key)} sources={sources} />}
          {excerpts
            .filter((excerpt) => excerpt.sectionKey === section.key)
            .map((excerpt) => (
              <ExcerptBlock key={excerpt.key} excerpt={excerpt} media={media} />
            ))}
          <Figures items={media.filter((item) => item.sectionKey === section.key)} />
          <SourceRefs entries={sources.bySection.get(section.key) ?? []} label="Sources for this section" />
        </section>
      ))}
      {generalFaq.length ? (
        <section id={ANCHORS.questions}>
          <h2>Questions</h2>
          <Questions faq={generalFaq} sources={sources} />
        </section>
      ) : null}
      {sources.entries.length > 0 && (
        <section id={ANCHORS.sources} aria-labelledby="sources-title">
          <h2 id="sources-title">Sources</h2>
          <ol className="article-sources">
            {sources.entries.map((entry) => (
              <li key={entry.anchor} id={entry.anchor}>
                <ContentLink href={entry.url}>{entry.label}</ContentLink>
                {entry.locators.length > 0 && <span> · {entry.locators.join("; ")}</span>}
              </li>
            ))}
          </ol>
        </section>
      )}
      {verification && (
        <section id={ANCHORS.verification} aria-labelledby="checked-title" className="article-checked">
          <h2 id="checked-title">How this was checked</h2>
          <dl className="article-facts">
            <div>
              <dt>Kind of check</dt>
              <dd>{VERIFICATION_MODES[verification.mode]}</dd>
            </div>
            {verification.lastVerifiedAt && (
              <div>
                <dt>Last checked</dt>
                <dd>
                  <DateText iso={verification.lastVerifiedAt} />
                </dd>
              </div>
            )}
            {verification.versions.length > 0 && (
              <div>
                <dt>Versions checked</dt>
                <dd>{verification.versions.map((item) => `${item.name} ${item.version}`).join(", ")}</dd>
              </div>
            )}
            {excerpts.length > 0 && (
              <div>
                <dt>Evidence in the text</dt>
                <dd>
                  <a href={`#excerpt-${excerpts[0]!.key}`}>
                    {excerpts.length === 1 ? "1 excerpt" : `${excerpts.length} excerpts`}
                  </a>
                </dd>
              </div>
            )}
          </dl>
          {verification.disclosure && <p>{verification.disclosure}</p>}
        </section>
      )}
      {taxonomy && (taxonomy.categories.length > 0 || taxonomy.tags.length > 0) && (
        <dl className="article-taxonomy">
          {taxonomy.categories.length > 0 && (
            <div>
              <dt>{taxonomy.categories.length === 1 ? "Category" : "Categories"}</dt>
              <dd>{taxonomy.categories.join(", ")}</dd>
            </div>
          )}
          {taxonomy.tags.length > 0 && (
            <div>
              <dt>Tags</dt>
              <dd>{taxonomy.tags.join(", ")}</dd>
            </div>
          )}
        </dl>
      )}
    </div>
  );
}
```

## components/article-page.tsx

```tsx
import Link from "next/link";
import type { ReactNode } from "react";
import { ArticleBody, VERIFICATION_MODES } from "@/components/article-body";
import { DateText, dayOf } from "@/components/date";
import { JsonLd, PERSON_ID } from "@/components/json-ld";
import {
  articleCategories,
  articleOutline,
  articleTags,
  heroImage,
  readingMinutes,
  searchFields,
} from "@/lib/article-view";
import type { ArticleSummary } from "@/lib/articles";
import type { ArticlePayload } from "@/lib/publishing/contract";
import { articlePath } from "@/lib/publishing/publish";
import { SITE, absoluteUrl } from "@/lib/site";

type Person = Readonly<{
  kind: "person" | "organization";
  name: string;
  profileUrl: string | null;
  description: string | null;
  /** The site's own person, described once on the home page. */
  isSite?: boolean;
}>;

/** Who wrote it. A Markdown Article carries no authors: it is the site owner's. */
function authorsOf(payload: ArticlePayload): Person[] {
  if (payload.contentFormat === "markdown")
    return [{ kind: "person", name: SITE.name, profileUrl: absoluteUrl("/about"), description: null, isSite: true }];
  return payload.presentation.authors;
}

function Name({ person }: { person: Person }) {
  return person.profileUrl ? <a href={person.profileUrl}>{person.name}</a> : <>{person.name}</>;
}

function joined(people: readonly Person[]): ReactNode {
  return people.map((person, index) => (
    <span key={`${index}:${person.name}`}>
      {index > 0 ? (index === people.length - 1 ? " and " : ", ") : null}
      <Name person={person} />
    </span>
  ));
}

const schemaPerson = (person: Person) =>
  person.isSite
    ? { "@type": "Person", "@id": PERSON_ID, name: person.name }
    : {
        "@type": person.kind === "organization" ? "Organization" : "Person",
        name: person.name,
        ...(person.profileUrl ? { url: person.profileUrl } : {}),
      };

/** Markdown to the plain words a reader sees, for structured data. */
const plain = (markdown: string) =>
  markdown
    .replace(/!\[[^\]]*\]\([^)]*\)/g, "")
    .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
    .replace(/[*_`~#>]/g, "")
    .replace(/\s+/g, " ")
    .trim();

/**
 * One Article, laid out like the pages Gomnee publishes to: the way back, what
 * it is and how long it takes, who wrote and checked it, the contents, the
 * body, and the people behind it. Each part appears only when the Article has
 * it. The private preview renders this same page without structured data.
 */
export function ArticlePage({
  slug,
  payload,
  publication,
  related,
  status,
  structuredData = true,
}: {
  slug: string;
  payload: ArticlePayload;
  /** null for a preview of an Article that isn't published yet. */
  publication: { publishedAt: string; updatedAt: string } | null;
  related: readonly ArticleSummary[];
  /** A line above the title, used by the private preview. */
  status?: ReactNode;
  structuredData?: boolean;
}) {
  const url = absoluteUrl(articlePath(slug));
  const outline = articleOutline(payload);
  const [category] = articleCategories(payload);
  const tags = articleTags(payload);
  const authors = authorsOf(payload);
  const reviewer = payload.contentFormat === "markdown" ? null : payload.presentation.reviewer;
  const verification = payload.contentFormat === "gomnee_article_v2" ? payload.verification : null;
  const faq = payload.contentFormat === "gomnee_article_v2" ? payload.faq : [];
  const hero = heroImage(payload);
  const described = [...authors, ...(reviewer ? [reviewer] : [])].filter((person) => person.description);
  const updated = publication && dayOf(publication.updatedAt) !== dayOf(publication.publishedAt);
  return (
    <>
      {structuredData && publication ? (
        <>
          <JsonLd
            data={{
              "@context": "https://schema.org",
              "@type": "BlogPosting",
              headline: payload.title,
              description: searchFields(payload).description,
              datePublished: publication.publishedAt,
              dateModified: publication.updatedAt,
              author: authors.map(schemaPerson),
              publisher: { "@type": "Person", "@id": PERSON_ID, name: SITE.name },
              mainEntityOfPage: url,
              url,
              inLanguage: SITE.language,
              image: hero ? hero.url : absoluteUrl("/opengraph-image"),
              ...(category ? { articleSection: category } : {}),
              ...(tags.length ? { keywords: tags.join(", ") } : {}),
              ...(outline.sources.entries.length ? { citation: outline.sources.entries.map((entry) => entry.url) } : {}),
            }}
          />
          <JsonLd
            data={{
              "@context": "https://schema.org",
              "@type": "BreadcrumbList",
              itemListElement: [
                { "@type": "ListItem", position: 1, name: "Home", item: absoluteUrl("/") },
                { "@type": "ListItem", position: 2, name: "Blog", item: absoluteUrl("/blog") },
                { "@type": "ListItem", position: 3, name: payload.title, item: url },
              ],
            }}
          />
          {faq.length ? (
            <JsonLd
              data={{
                "@context": "https://schema.org",
                "@type": "FAQPage",
                mainEntity: faq.map((entry) => ({
                  "@type": "Question",
                  name: entry.question,
                  acceptedAnswer: { "@type": "Answer", text: plain(entry.answerMarkdown) },
                })),
              }}
            />
          ) : null}
        </>
      ) : null}

      <nav className="crumbs" aria-label="Breadcrumb">
        <ol>
          <li>
            <Link href="/">Home</Link>
          </li>
          <li>
            <Link href="/blog">Blog</Link>
          </li>
          <li aria-current="page">{payload.title}</li>
        </ol>
      </nav>

      <article className="article">
        <header>
          {status}
          <p className="kicker">
            {category ? <span className="chip">{category}</span> : null}
            <span>{readingMinutes(payload)} min read</span>
          </p>
          <h1>{payload.title}</h1>
          <p className="deck">{payload.summary}</p>
          <div className="byline">
            <p>
              By {joined(authors)}
              {reviewer ? (
                <>
                  {" "}
                  · reviewed by <Name person={reviewer} />
                </>
              ) : null}
            </p>
            {publication ? (
              <p>
                Published <DateText iso={publication.publishedAt} />
                {updated ? (
                  <>
                    {" "}
                    · Updated <DateText iso={publication.updatedAt} />
                  </>
                ) : null}
              </p>
            ) : (
              <p>Preview · not published</p>
            )}
            {verification && verification.mode !== "not_applicable" ? (
              <a className="pill" href="#how-this-was-checked">
                {VERIFICATION_MODES[verification.mode]}
                {verification.lastVerifiedAt ? (
                  <>
                    {" "}
                    · <DateText iso={verification.lastVerifiedAt} />
                  </>
                ) : null}
              </a>
            ) : null}
          </div>
        </header>

        <ArticleBody
          payload={payload}
          outline={outline}
          contents={
            outline.contents.length >= 3 ? (
              <nav className="contents" aria-labelledby="contents-title">
                <p id="contents-title">In this article</p>
                <ol>
                  {outline.contents.map((entry) => (
                    <li key={entry.id}>
                      <a href={`#${entry.id}`}>{entry.label}</a>
                    </li>
                  ))}
                </ol>
              </nav>
            ) : null
          }
        />

        {described.length ? (
          <section className="people" aria-labelledby="about-the-authors">
            <h2 id="about-the-authors">{described.length === 1 ? "About the author" : "About the authors"}</h2>
            {described.map((person, index) => (
              <p key={`${index}:${person.name}`}>
                <b>
                  <Name person={person} />
                </b>{" "}
                {person.description}
              </p>
            ))}
          </section>
        ) : null}
      </article>

      {related.length ? (
        <aside className="related" aria-labelledby="related-title">
          <h2 id="related-title">Read next</h2>
          <ul>
            {related.map((other) => (
              <li key={other.slug}>
                <Link href={articlePath(other.slug)}>{other.title}</Link>
                <p>{other.summary}</p>
              </li>
            ))}
          </ul>
        </aside>
      ) : null}
    </>
  );
}
```

## components/preview-navigation.tsx

```tsx
"use client";

import { useEffect } from "react";

/**
 * Inside Gomnee's preview frame, real site links open in a new tab, while the
 * Article's own contents links (#…) keep the preview in place.
 */
export function PreviewNavigation() {
  useEffect(() => {
    const follow = (event: MouseEvent) => {
      if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.altKey || event.shiftKey)
        return;
      const link = (event.target as Element).closest?.<HTMLAnchorElement>("a[href]");
      if (!link) return;
      const href = link.getAttribute("href");
      if (!href || href.startsWith("#")) return;
      const target = new URL(link.href, location.href);
      if (
        target.origin === location.origin &&
        target.pathname === location.pathname &&
        target.search === location.search &&
        target.hash
      )
        return;
      event.preventDefault();
      window.open(target.href, "_blank", "noopener,noreferrer");
    };
    // Capture runs before Next's Link handler would replace the private page.
    document.addEventListener("click", follow, true);
    return () => document.removeEventListener("click", follow, true);
  }, []);
  return null;
}
```

## app/layout.tsx

```tsx
import type { Metadata } from "next";
import Link from "next/link";
import { SITE } from "@/lib/site";
import "./globals.css";

/**
 * Paths Gomnee's hosted-site measurement never counts: private previews and
 * the API. Each covers that path and everything below it.
 */
const UNMEASURED = ["/article-preview", "/api"].join(",");

export const metadata: Metadata = {
  metadataBase: new URL(SITE.url),
  title: { default: SITE.name, template: `%s · ${SITE.name}` },
  description: SITE.description,
};

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang={SITE.language}>
      <head>
        {/* Stays mounted with the layout, so the tag is present on every page. */}
        <meta name="gomnee-measurement-exclude" content={UNMEASURED} />
      </head>
      <body>
        <header className="site-header">
          <Link href="/">{SITE.name}</Link>
          <nav aria-label="Main">
            <Link href="/blog">Blog</Link>
            <Link href="/about">About</Link>
          </nav>
        </header>
        <main>{children}</main>
        <footer className="site-footer">
          <Link href="/privacy">Privacy</Link>
        </footer>
      </body>
    </html>
  );
}
```

## app/globals.css

```css
:root {
  color-scheme: light dark;
  font-family: system-ui, sans-serif;
  line-height: 1.6;
}
body {
  max-width: 42rem;
  margin: 0 auto;
  padding: 0 1rem 4rem;
}
.site-header,
.site-footer {
  display: flex;
  justify-content: space-between;
  gap: 1rem;
  padding: 1.5rem 0;
}
.site-header nav {
  display: flex;
  gap: 1rem;
}
a {
  color: inherit;
  text-underline-offset: 3px;
}
img {
  max-width: 100%;
  height: auto;
}
pre,
table {
  display: block;
  overflow-x: auto;
}
.byline,
.article-list p {
  color: GrayText;
}

/* ---------- articles ---------- */
.crumbs ol {
  display: flex;
  flex-wrap: wrap;
  gap: 0.25rem 0.5rem;
  margin: 0.5rem 0 1.5rem;
  padding: 0;
  list-style: none;
  font-size: 0.875rem;
  color: GrayText;
}
.crumbs li + li::before {
  content: "›";
  margin-right: 0.5rem;
}
.article header h1 {
  margin: 0.25rem 0 0.75rem;
  font-size: clamp(2rem, 5vw, 2.6rem);
  line-height: 1.15;
  letter-spacing: -0.02em;
}
.kicker {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 0.75rem;
  margin: 0;
  font-size: 0.875rem;
  color: GrayText;
}
.chip {
  padding: 0.1rem 0.6rem;
  border: 1px solid currentColor;
  border-radius: 999px;
}
.deck {
  margin: 0 0 1rem;
  font-size: 1.2rem;
  line-height: 1.5;
}
.byline {
  display: grid;
  gap: 0.25rem;
  padding: 0.75rem 0 1.25rem;
  border-bottom: 1px solid color-mix(in srgb, currentColor 18%, transparent);
  font-size: 0.925rem;
}
.byline p {
  margin: 0;
}
.pill {
  justify-self: start;
  margin-top: 0.25rem;
  padding: 0.15rem 0.6rem;
  border: 1px solid currentColor;
  border-radius: 999px;
  font-size: 0.85rem;
  text-decoration: none;
}
.article-figure {
  margin: 1.5rem 0;
}
.article-figure figcaption {
  margin-top: 0.5rem;
  font-size: 0.85rem;
  color: GrayText;
}
.contents {
  margin: 1.5rem 0;
  padding: 1rem 1.25rem;
  border: 1px solid color-mix(in srgb, currentColor 18%, transparent);
  border-radius: 6px;
}
.contents p {
  margin: 0 0 0.5rem;
  font-weight: 600;
}
.contents ol {
  margin: 0;
  padding-left: 1.25rem;
}
.body h2,
.people h2 {
  margin-top: 2.5rem;
}
.body [id] {
  scroll-margin-top: 1rem;
}
.article-faq h3,
.article-steps h3 {
  margin-bottom: 0.25rem;
  font-size: 1.05rem;
}
.people p {
  margin: 0.5rem 0;
}
.related {
  margin-top: 3rem;
  padding-top: 1rem;
  border-top: 1px solid color-mix(in srgb, currentColor 18%, transparent);
}
.related ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
.related li {
  margin: 0.75rem 0;
}
.related p {
  margin: 0.25rem 0 0;
  color: GrayText;
}

/* Parts of an Article Gomnee publishes, each shown only when it has them. */
.article-brief,
.article-note {
  margin: 1.25rem 0;
  padding: 0.75rem 1rem;
  border-left: 3px solid color-mix(in srgb, currentColor 35%, transparent);
  background: color-mix(in srgb, currentColor 5%, transparent);
}
.article-note-success {
  border-left-color: color-mix(in srgb, green 60%, currentColor);
}
.article-note-warning {
  border-left-color: color-mix(in srgb, orange 70%, currentColor);
}
.article-note-label {
  margin: 0 0 0.25rem;
  font-size: 0.85rem;
  font-weight: 600;
}
.article-note > :last-child,
.article-brief > :last-child {
  margin-bottom: 0;
}
.article-steps {
  padding-left: 1.25rem;
}
.article-table table {
  display: table;
  width: 100%;
  border-collapse: collapse;
}
.article-table {
  overflow-x: auto;
}
.article-table th,
.article-table td {
  padding: 0.5rem;
  border-bottom: 1px solid color-mix(in srgb, currentColor 18%, transparent);
  text-align: left;
  vertical-align: top;
}
.article-refs {
  font-size: 0.85rem;
  color: GrayText;
}
.article-refs a {
  margin-right: 0.25rem;
}
.article-sources li {
  margin: 0.4rem 0;
}
.article-excerpt {
  margin: 1.25rem 0;
}
.article-excerpt figcaption,
.article-excerpt-method,
.article-shot {
  font-size: 0.85rem;
  color: GrayText;
}
.article-facts div,
.article-taxonomy div {
  display: flex;
  flex-wrap: wrap;
  gap: 0 0.5rem;
}
.article-facts dt,
.article-taxonomy dt {
  font-weight: 600;
}
.article-facts dd,
.article-taxonomy dd {
  margin: 0;
}
.article-taxonomy {
  margin-top: 2rem;
  font-size: 0.9rem;
  color: GrayText;
}
.article-list img {
  display: block;
  margin-bottom: 0.5rem;
  border-radius: 6px;
}
.preview-status {
  margin: 0 0 0.75rem;
  padding: 0.25rem 0.6rem;
  border: 1px dashed currentColor;
  border-radius: 6px;
  font-size: 0.85rem;
}
.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}
```

## app/page.tsx

```tsx
import Link from "next/link";
import { JsonLd, PERSON_ID, WEBSITE_ID } from "@/components/json-ld";
import { listArticles } from "@/lib/articles";
import { articlePath } from "@/lib/publishing/publish";
import { pageMetadata } from "@/lib/metadata";
import { SITE, absoluteUrl } from "@/lib/site";

export const metadata = pageMetadata({
  path: "/",
  title: `${SITE.name}: notes from the work`,
  description: SITE.description,
  absoluteTitle: true,
});
export const dynamic = "force-dynamic";

export default async function HomePage() {
  const latest = (await listArticles()).slice(0, 3);
  return (
    <>
      <JsonLd
        data={{
          "@context": "https://schema.org",
          "@graph": [
            {
              "@type": "WebSite",
              "@id": WEBSITE_ID,
              url: SITE.url,
              name: SITE.name,
              inLanguage: SITE.language,
              publisher: { "@id": PERSON_ID },
            },
            {
              "@type": "Person",
              "@id": PERSON_ID,
              name: SITE.name,
              url: absoluteUrl("/about"),
            },
          ],
        }}
      />
      {/* Replace this heading and paragraph with what the site is about. */}
      <h1>Notes from the work.</h1>
      <p>{SITE.description}</p>
      {latest.length ? (
        <>
          <h2>Latest</h2>
          <ul>
            {latest.map((article) => (
              <li key={article.slug}>
                <Link href={articlePath(article.slug)}>{article.title}</Link>
              </li>
            ))}
          </ul>
        </>
      ) : null}
      <p>
        <a href={`mailto:${SITE.email}`} data-gomnee-cta="contact">
          Email me
        </a>
      </p>
    </>
  );
}
```

## app/about/page.tsx

```tsx
import { PageJsonLd } from "@/components/json-ld";
import { pageMetadata } from "@/lib/metadata";
import { SITE } from "@/lib/site";

const description = `Who ${SITE.name} is, and why this site exists.`;

export const metadata = pageMetadata({ path: "/about", title: "About", description });

export default function AboutPage() {
  return (
    <>
      <PageJsonLd type="AboutPage" path="/about" name="About" description={description} />
      <h1>About</h1>
      {/* Real facts only, from you. No invented clients, numbers or quotes. */}
      <p>I&apos;m {SITE.name}. Write two or three sentences about who you are and what you write about.</p>
    </>
  );
}
```

## app/blog/page.tsx

```tsx
import Link from "next/link";
import { DateText } from "@/components/date";
import { PageJsonLd } from "@/components/json-ld";
import { listArticles } from "@/lib/articles";
import { pageMetadata } from "@/lib/metadata";
import { articlePath } from "@/lib/publishing/publish";

const description = "Every article, newest first.";

export const metadata = pageMetadata({ path: "/blog", title: "Blog", description });
export const dynamic = "force-dynamic";

export default async function BlogIndex() {
  const articles = await listArticles();
  return (
    <>
      <PageJsonLd type="CollectionPage" path="/blog" name="Blog" description={description} />
      <h1>Blog</h1>
      {articles.length ? (
        <ul className="article-list">
          {articles.map((article) => (
            <li key={article.slug}>
              {article.cover ? (
                // A listing card's artwork; it never appears in the article itself.
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={article.cover.url}
                  alt={article.cover.alt}
                  width={article.cover.width}
                  height={article.cover.height}
                  loading="lazy"
                />
              ) : null}
              <Link href={articlePath(article.slug)}>{article.title}</Link>
              <p>{article.summary}</p>
              <DateText iso={article.publishedAt} />
            </li>
          ))}
        </ul>
      ) : (
        <p>No articles yet. They appear here as Gomnee publishes them.</p>
      )}
    </>
  );
}
```

## app/blog/[slug]/page.tsx

```tsx
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { cache } from "react";
import { ArticlePage } from "@/components/article-page";
import { heroImage, articleTags, searchFields } from "@/lib/article-view";
import { getArticle, relatedArticles } from "@/lib/articles";
import { pageMetadata } from "@/lib/metadata";
import { articlePath } from "@/lib/publishing/publish";

type Props = { params: Promise<{ slug: string }> };

// Articles arrive from Gomnee at any time, so each request reads the database.
// An Article's address never changes once published.
export const dynamic = "force-dynamic";

const load = cache(getArticle);

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const article = await load((await params).slug);
  if (!article) return {};
  const { payload } = article;
  const search = searchFields(payload);
  const hero = heroImage(payload);
  const authors =
    payload.contentFormat === "markdown" ? [] : payload.presentation.authors.map((author) => author.name);
  const tags = articleTags(payload);
  return pageMetadata({
    path: articlePath(article.slug),
    title: search.title,
    description: search.description,
    openGraph: {
      type: "article",
      publishedTime: article.publishedAt,
      modifiedTime: article.updatedAt,
      ...(authors.length ? { authors } : {}),
      ...(hero ? { images: [{ url: hero.url, width: hero.width, height: hero.height, alt: hero.alt }] } : {}),
      ...(tags.length ? { tags: [...tags] } : {}),
    },
  });
}

export default async function Page({ params }: Props) {
  const article = await load((await params).slug);
  if (!article) notFound();
  return (
    <ArticlePage
      slug={article.slug}
      payload={article.payload}
      publication={{ publishedAt: article.publishedAt, updatedAt: article.updatedAt }}
      related={await relatedArticles(article)}
    />
  );
}
```

## app/privacy/page.tsx

```tsx
import { PageJsonLd } from "@/components/json-ld";
import { pageMetadata } from "@/lib/metadata";
import { SITE } from "@/lib/site";

const description = `How ${SITE.name}'s site handles your data.`;

export const metadata = pageMetadata({ path: "/privacy", title: "Privacy", description });

export default function PrivacyPage() {
  return (
    <>
      <PageJsonLd type="WebPage" path="/privacy" name="Privacy" description={description} />
      <h1>Privacy</h1>
      <p>This site sets no cookies. Email {SITE.email} with any question.</p>
      {/* When Gomnee measurement is switched on, add its short entry here:
          page views and link clicks, counted without cookies or identifiers. */}
    </>
  );
}
```

## app/not-found.tsx

```tsx
import Link from "next/link";

export default function NotFound() {
  return (
    <>
      <h1>Page not found</h1>
      <p>
        <Link href="/blog">See every article</Link>
      </p>
    </>
  );
}
```

## app/sitemap.ts

```ts
import type { MetadataRoute } from "next";
import { listArticles } from "@/lib/articles";
import { articlePath } from "@/lib/publishing/publish";
import { absoluteUrl } from "@/lib/site";

// Lists each Article as soon as Gomnee publishes it.
export const dynamic = "force-dynamic";

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const articles = await listArticles();
  const latest = articles[0]?.updatedAt;
  return [
    { url: absoluteUrl("/"), lastModified: latest },
    { url: absoluteUrl("/blog"), lastModified: latest },
    { url: absoluteUrl("/about") },
    ...articles.map((article) => ({
      url: absoluteUrl(articlePath(article.slug)),
      lastModified: article.updatedAt,
    })),
  ];
}
```

## app/robots.ts

```ts
import type { MetadataRoute } from "next";
import { absoluteUrl } from "@/lib/site";

export default function robots(): MetadataRoute.Robots {
  return {
    rules: { userAgent: "*", allow: "/" },
    sitemap: absoluteUrl("/sitemap.xml"),
  };
}
```

## app/opengraph-image.tsx

```tsx
import { ImageResponse } from "next/og";
import { SITE } from "@/lib/site";

// The share image every page uses unless it has its own.
export const alt = SITE.description;
export const size = { width: 1200, height: 630 };
export const contentType = "image/png";

export default function OpengraphImage() {
  return new ImageResponse(
    (
      <div
        style={{
          width: "100%",
          height: "100%",
          display: "flex",
          flexDirection: "column",
          justifyContent: "space-between",
          padding: 80,
          background: "#f6f5f1",
          color: "#1a1a18",
        }}
      >
        <div style={{ fontSize: 72, fontWeight: 700, letterSpacing: -2 }}>{SITE.name}</div>
        <div style={{ fontSize: 34, lineHeight: 1.35, maxWidth: 980 }}>{SITE.description}</div>
        <div style={{ fontSize: 26, color: "#5c5c57" }}>{SITE.url.replace("https://", "")}</div>
      </div>
    ),
    size,
  );
}
```

## app/llms.txt/route.ts

```ts
import { listArticles } from "@/lib/articles";
import { articlePath } from "@/lib/publishing/publish";
import { SITE, absoluteUrl } from "@/lib/site";

// /llms.txt (llmstxt.org): what the site is, for AI tools, and where to read.
// Optional: delete this folder if you don't want one.
export const dynamic = "force-dynamic";

export async function GET() {
  const articles = await listArticles();
  const text = [
    `# ${SITE.name}`,
    "",
    `> ${SITE.description}`,
    "",
    "## Pages",
    "",
    `- [About](${absoluteUrl("/about")}): who writes this site`,
    `- [Blog](${absoluteUrl("/blog")}): every article, newest first`,
    ...(articles.length
      ? ["", "## Articles", "", ...articles.map((article) => `- [${article.title}](${absoluteUrl(articlePath(article.slug))}): ${article.summary}`)]
      : []),
    "",
  ].join("\n");
  return new Response(text, { headers: { "content-type": "text/plain; charset=utf-8" } });
}
```

## app/api/integrations/gomnee/publishing/v1/route.ts

```ts
import { sql } from "drizzle-orm";
import { getDb } from "@/db";
import { apiError } from "@/lib/http";
import { requirePublisher } from "@/lib/publishing/auth";
import { publishingCapabilities } from "@/lib/publishing/publish";

// What the site can do, after a database round trip: Gomnee checks this before
// it connects, and again before every delivery.
export const dynamic = "force-dynamic";

export async function GET(request: Request) {
  try {
    requirePublisher(request);
    await getDb().execute(sql`select 1`);
    return Response.json(publishingCapabilities(), { headers: { "Cache-Control": "no-store" } });
  } catch (error) {
    return apiError(error);
  }
}
```

## app/api/integrations/gomnee/publishing/v1/articles/[articleKey]/route.ts

```ts
import { and, eq } from "drizzle-orm";
import { z } from "zod";
import { getDb } from "@/db";
import { articles } from "@/db/schema";
import { apiError, HttpError, readJson } from "@/lib/http";
import { requirePublisher } from "@/lib/publishing/auth";
import { publicationObservation, publishArticle } from "@/lib/publishing/publish";

export const dynamic = "force-dynamic";

type Context = { params: Promise<{ articleKey: string }> };

/** Read one published Article back, exactly as stored. */
export async function GET(request: Request, context: Context) {
  try {
    requirePublisher(request);
    const articleKey = z.uuid().parse((await context.params).articleKey);
    const [article] = await getDb()
      .select()
      .from(articles)
      .where(and(eq(articles.gomneeArticleKey, articleKey), eq(articles.status, "published")));
    if (!article) throw new HttpError(404, "Publication not found.");
    return Response.json(publicationObservation(article), { headers: { "Cache-Control": "no-store" } });
  } catch (error) {
    return apiError(error);
  }
}

/** Create or update one live Article. */
export async function PUT(request: Request, context: Context) {
  try {
    requirePublisher(request);
    const articleKey = z.uuid().parse((await context.params).articleKey);
    // Gomnee caps mapped commands, which carry the Article twice, at 250,000 bytes.
    const receipt = await publishArticle(articleKey, await readJson(request, 260_000));
    return Response.json(receipt, { headers: { "Cache-Control": "no-store" } });
  } catch (error) {
    return apiError(error);
  }
}
```

## app/api/integrations/gomnee/publishing/v1/previews/route.ts

```ts
import { apiError, readJson } from "@/lib/http";
import { requirePublisher } from "@/lib/publishing/auth";
import { createArticlePreview } from "@/lib/publishing/preview";

export const dynamic = "force-dynamic";

/** A private, expiring snapshot Gomnee shows in its review screen. It publishes nothing. */
export async function POST(request: Request) {
  try {
    requirePublisher(request);
    const receipt = await createArticlePreview(await readJson(request, 262_144));
    return Response.json(receipt, { status: 201, headers: { "Cache-Control": "private, no-store" } });
  } catch (error) {
    const response = apiError(error);
    response.headers.set("Cache-Control", "private, no-store");
    return response;
  }
}
```

## app/article-preview/[token]/page.tsx

```tsx
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { ArticlePage } from "@/components/article-page";
import { PreviewNavigation } from "@/components/preview-navigation";
import { relatedArticles } from "@/lib/articles";
import { getArticlePreview } from "@/lib/publishing/preview";

// A private snapshot Gomnee shows while you review an Article. It is never
// listed, indexed or measured, and only Gomnee may frame it (next.config.ts).
export const dynamic = "force-dynamic";
export const metadata: Metadata = {
  title: "Private article preview",
  robots: { index: false, follow: false, noarchive: true },
  referrer: "no-referrer",
  openGraph: null,
  twitter: null,
  alternates: { canonical: null },
};

export default async function ArticlePreviewPage({ params }: { params: Promise<{ token: string }> }) {
  const preview = await getArticlePreview((await params).token);
  if (!preview) notFound();
  const { article } = preview;
  return (
    <>
      <PreviewNavigation />
      <ArticlePage
        slug={article.slug}
        payload={article}
        publication={
          preview.publishedAt && preview.publicationUpdatedAt
            ? { publishedAt: preview.publishedAt.toISOString(), updatedAt: preview.publicationUpdatedAt.toISOString() }
            : null
        }
        related={await relatedArticles({ slug: article.slug, payload: article })}
        structuredData={false}
        status={
          <p className="preview-status" role="status">
            Private preview · {preview.snapshotKind === "unsaved" ? "Unsaved changes" : "Saved draft"} · Not published
          </p>
        }
      />
    </>
  );
}
```

## scripts/migrate.mjs

```js
// Applies the migrations in drizzle/ to the database at DATABASE_URL. `pnpm build`
// runs it first, so a deploy brings its own tables; without DATABASE_URL it
// does nothing and the site builds with an empty blog.
import { drizzle } from "drizzle-orm/node-postgres";
import { migrate } from "drizzle-orm/node-postgres/migrator";
import pg from "pg";

if (!process.env.DATABASE_URL) {
  console.log("DATABASE_URL is not set: no migrations applied.");
  process.exit(0);
}
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 1 });
try {
  await migrate(drizzle(pool), { migrationsFolder: new URL("../drizzle", import.meta.url).pathname });
  console.log("Database migrations applied.");
} finally {
  await pool.end();
}
```

## scripts/check.mjs

```js
// Checks the built site the way Gomnee's onboarding and free audit look at it:
// every page answers, carries complete metadata and one main heading,
// structured data parses and matches, the sitemap lists every article, and
// the publishing destination answers.
//
// Against a test database (a name ending in _test, as in CI) it also publishes
// one Article and opens one private preview through the running site, the way
// Gomnee would. It never publishes to any other database.
//
// Run after a build: pnpm build && pnpm check
import { spawn } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
import { existsSync, readFileSync } from "node:fs";

const site = readFileSync("lib/site.ts", "utf8");
const field = (name) => site.match(new RegExp(`${name}:\\s*"([^"]*)"`))?.[1] ?? "";
const SITE_URL = field("url").replace(/\/$/, "");
const pages = ["/", "/about", "/blog", "/privacy"];

const failures = [];
const warnings = [];
const fail = (path, message) => failures.push(`${path}: ${message}`);

const port = 3900 + Math.floor(Math.random() * 90);
const base = `http://127.0.0.1:${port}`;
const server = spawn("node_modules/.bin/next", ["start", "-H", "127.0.0.1", "-p", String(port)], {
  stdio: "ignore",
});
const stop = () => server.kill();
process.on("exit", stop);

async function ready() {
  for (let attempt = 0; attempt < 60; attempt++) {
    try {
      if ((await fetch(base)).ok) return;
    } catch {}
    await new Promise((resolve) => setTimeout(resolve, 500));
  }
  throw new Error("The site didn't start. Run pnpm build first.");
}

const all = (html, pattern) => [...html.matchAll(pattern)].map((match) => match[1]);
const meta = (html, attribute, name) =>
  html.match(new RegExp(`<meta ${attribute}="${name}" content="([^"]*)"`))?.[1];
const strip = (url) => (url ?? "").replace(/\/$/, "");

// Gomnee's canonical JSON and digest (lib/publishing/publish.ts), for the sample request.
function canonicalJson(value) {
  if (value === null) return "null";
  if (typeof value === "string")
    return JSON.stringify(value).replaceAll("<", "\\u003c").replaceAll(">", "\\u003e").replaceAll("&", "\\u0026");
  if (typeof value !== "object") return JSON.stringify(value);
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
  return `{${Object.keys(value)
    .sort()
    .map((key) => `${canonicalJson(key)}:${canonicalJson(value[key])}`)
    .join(",")}}`;
}
const digest = (value) => `sha256:${createHash("sha256").update(canonicalJson(value), "utf8").digest("hex")}`;

await ready();

// ---------- the publishing destination ----------
const API = `${base}/api/integrations/gomnee/publishing/v1`;
const token = process.env.GOMNEE_PUBLISHING_TOKEN;
const headers = { authorization: `Bearer ${token}`, "content-type": "application/json" };
const capabilities = await fetch(API, { headers });
let published = [];
if (capabilities.status === 503) {
  warnings.push("publishing is not configured: set DATABASE_URL and GOMNEE_PUBLISHING_TOKEN to receive Articles from Gomnee");
} else if (capabilities.status !== 200) {
  fail(API, `answered ${capabilities.status}, not 200`);
} else {
  const declared = await capabilities.json();
  if (declared.siteOrigin !== new URL(SITE_URL).origin)
    fail(API, `declares ${declared.siteOrigin}, not ${new URL(SITE_URL).origin}`);
  const testDatabase = new URL(process.env.DATABASE_URL ?? "postgres://x/").pathname.endsWith("_test");
  if (testDatabase) {
    const article = {
      slug: `check-${Date.now()}`,
      title: "A check from pnpm check",
      summary: "Published through the site's own API, the way Gomnee publishes.",
      contentFormat: "markdown",
      content: "## What this checks\n\nThat an Article Gomnee sends becomes a page.",
    };
    const articleKey = randomUUID();
    const put = await fetch(`${API}/articles/${articleKey}`, {
      method: "PUT",
      headers,
      body: JSON.stringify({
        schemaVersion: "gomnee_live_article_publish_v1",
        commandId: randomUUID(),
        articleRevisionId: randomUUID(),
        expectedRemoteVersion: null,
        contentDigest: digest(article),
        article,
      }),
    });
    if (put.status !== 200) fail(`${API}/articles`, `publishing answered ${put.status}, not 200`);
    else {
      published = [article.slug];
      pages.push(`/blog/${article.slug}`);
      const back = await fetch(`${API}/articles/${articleKey}`, { headers });
      if ((await back.json()).contentDigest !== digest(article)) fail(`${API}/articles`, "read-back digest differs");
    }
    const preview = await fetch(`${API}/previews`, {
      method: "POST",
      headers,
      body: JSON.stringify({
        schemaVersion: "gomnee_article_preview_request_v1",
        articleKey,
        sourceRevisionId: randomUUID(),
        snapshotKind: "saved",
        contentDigest: digest(article),
        template: declared.template,
        article,
      }),
    });
    if (preview.status !== 201) fail(`${API}/previews`, `answered ${preview.status}, not 201`);
    else {
      const { previewUrl } = await preview.json();
      const page = await fetch(base + new URL(previewUrl).pathname);
      if (page.status !== 200) fail("/article-preview", `answered ${page.status}, not 200`);
      if (!page.headers.get("x-robots-tag")?.includes("noindex")) fail("/article-preview", "is not noindex");
      if (!page.headers.get("content-security-policy")?.includes("frame-ancestors https://app.gomnee.com"))
        fail("/article-preview", "Gomnee cannot frame it");
    }
  }
}

// ---------- every page ----------
for (const path of pages) {
  const response = await fetch(base + path);
  if (response.status !== 200) {
    fail(path, `answered ${response.status}, not 200`);
    continue;
  }
  const html = await response.text();
  const head = html.slice(0, html.indexOf("</head>"));
  const canonical = head.match(/<link rel="canonical" href="([^"]*)"/)?.[1];
  if (!/<title>[^<]+<\/title>/.test(head)) fail(path, "no <title> in the head");
  if (!meta(head, "name", "description")) fail(path, "no meta description in the head");
  if (strip(canonical) !== strip(SITE_URL + path)) fail(path, `canonical is ${canonical ?? "missing"}, not ${SITE_URL}${path}`);
  if (!/<html[^>]* lang="[^"]+"/.test(html)) fail(path, "no lang on <html>");
  if (!meta(head, "name", "gomnee-measurement-exclude")) fail(path, "no gomnee-measurement-exclude tag");
  const h1 = (html.match(/<h1[\s>]/g) ?? []).length;
  if (h1 !== 1) fail(path, `${h1} h1 headings, not one`);
  for (const property of ["og:title", "og:type", "og:url", "og:site_name", "og:image"])
    if (!meta(head, "property", property)) fail(path, `no ${property}`);
  if (strip(meta(head, "property", "og:url")) !== strip(canonical)) fail(path, "og:url differs from the canonical");
  const blocks = all(html, /<script type="application\/ld\+json">(.*?)<\/script>/gs);
  const data = [];
  for (const block of blocks) {
    try {
      data.push(JSON.parse(block));
    } catch {
      fail(path, "a JSON-LD block doesn't parse");
    }
  }
  if (!data.length) fail(path, "no structured data");
  const description = meta(head, "name", "description") ?? "";
  if (description.length > 160) warnings.push(`${path}: the meta description runs past 160 characters`);
  if (path.startsWith("/blog/")) {
    const posts = data.filter((item) => item["@type"] === "BlogPosting");
    if (posts.length !== 1) fail(path, `${posts.length} BlogPosting blocks, not one`);
    else if (!posts[0].datePublished) fail(path, "BlogPosting has no datePublished");
    if (data.filter((item) => item["@type"] === "BreadcrumbList").length !== 1)
      fail(path, "no BreadcrumbList for its breadcrumbs");
    const visible = html
      .replace(/<script[\s\S]*?<\/script>/g, " ")
      .replace(/<[^>]+>/g, " ")
      .replace(/&#x27;/g, "'")
      .replace(/&quot;/g, '"')
      .replace(/&amp;/g, "&");
    for (const faq of data.filter((item) => item["@type"] === "FAQPage"))
      for (const question of faq.mainEntity ?? [])
        if (!visible.includes(question.name)) fail(path, `FAQ question not shown on the page: ${question.name}`);
  }
}

const sitemap = await (await fetch(`${base}/sitemap.xml`)).text();
for (const slug of published)
  if (!sitemap.includes(`<loc>${SITE_URL}/blog/${slug}</loc>`)) fail("/sitemap.xml", `doesn't list /blog/${slug}`);
const robots = await (await fetch(`${base}/robots.txt`)).text();
if (!/^Sitemap: \S+/m.test(robots)) fail("/robots.txt", "names no sitemap");
const missing = await fetch(`${base}/no-such-page-${port}`);
if (missing.status !== 404) fail("/no-such-page", `answered ${missing.status}, not 404`);
if (existsSync("app/llms.txt") && (await fetch(`${base}/llms.txt`)).status !== 200) fail("/llms.txt", "doesn't answer 200");

// Gomnee reads .env.example the same way: an unmarked setting counts as required.
for (const line of readFileSync(".env.example", "utf8").split(/\r?\n/)) {
  const name = line.match(/^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)\s*=/)?.[1];
  if (name && name !== "NODE_ENV" && !/#\s*(required|optional):[A-Za-z0-9_-]+/i.test(line))
    warnings.push(`.env.example: mark ${name} "# required:core" or "# optional:core"; Gomnee treats it as required`);
}

if (SITE_URL === "https://example.com") warnings.push("lib/site.ts: replace example.com with your address");
if (field("name") === "Your Name") warnings.push("lib/site.ts: replace Your Name");
if (field("email").endsWith("@example.com")) warnings.push("lib/site.ts: replace the example email");

stop();
for (const warning of warnings) console.log(`warning  ${warning}`);
for (const failure of failures) console.log(`fail     ${failure}`);
console.log(failures.length ? `\n${failures.length} problems in ${pages.length} pages.` : `\nAll ${pages.length} pages pass.`);
process.exit(failures.length ? 1 : 0);
```

## tests/environment.ts

```ts
// Every test process talks to the test database and the test publishing key.
const url = process.env.TEST_DATABASE_URL ?? "postgres://postgres:postgres@127.0.0.1:5432/starter_test";
if (!new URL(url).pathname.endsWith("_test")) throw new Error("Tests need a database whose name ends in _test.");
process.env.DATABASE_URL = url;
process.env.GOMNEE_PUBLISHING_TOKEN = "test-only-publishing-key-0000000000000000";
```

## tests/setup-database.ts

```ts
import { drizzle } from "drizzle-orm/node-postgres";
import { migrate } from "drizzle-orm/node-postgres/migrator";
import { Pool } from "pg";

/** Creates the test database when it is missing, then applies every migration. */
export default async function setup() {
  const url = new URL(process.env.TEST_DATABASE_URL ?? "postgres://postgres:postgres@127.0.0.1:5432/starter_test");
  const name = url.pathname.slice(1);
  if (!/^[a-z0-9_]+_test$/.test(name)) throw new Error("Tests need a database whose name ends in _test.");
  const admin = new URL(url);
  admin.pathname = "/postgres";
  const adminPool = new Pool({ connectionString: admin.toString() });
  try {
    const exists = await adminPool.query("select 1 from pg_database where datname = $1", [name]);
    if (!exists.rowCount) await adminPool.query(`CREATE DATABASE "${name}"`);
  } finally {
    await adminPool.end();
  }
  const pool = new Pool({ connectionString: url.toString() });
  try {
    await migrate(drizzle(pool), { migrationsFolder: new URL("../drizzle", import.meta.url).pathname });
  } finally {
    await pool.end();
  }
}
```

## tests/fixtures.ts

```ts
import { randomUUID } from "node:crypto";
import { sql } from "drizzle-orm";
import { getDb } from "@/db";
import { PUT } from "@/app/api/integrations/gomnee/publishing/v1/articles/[articleKey]/route";
import { articlePayloadSchema, typedArticlePayloadSchema, type ArticlePayload } from "@/lib/publishing/contract";
import { makePublishRequest } from "@/lib/publishing/publish";

export const KEY = process.env.GOMNEE_PUBLISHING_TOKEN!;

/** A Markdown Article: Gomnee's simplest format, with no authors or modules. */
export function markdownArticle(slug = "hello-from-gomnee") {
  return articlePayloadSchema.parse({
    slug,
    title: "Hello from Gomnee",
    summary: "The first Article Gomnee published here.",
    contentFormat: "markdown",
    content: "## What this is\n\nA short Article.\n\n<script>alert('no')</script>",
  });
}

/** A gomnee_article_v2 document with every typed module Gomnee can send. */
export function typedArticle(slug = "compare-two-proposals") {
  return typedArticlePayloadSchema.parse({
    slug,
    title: "Compare two proposals step by step",
    summary: "Questions, steps and a comparison for reading two proposals.",
    contentFormat: "gomnee_article_v2",
    sections: [
      { key: "why", heading: "Why compare", markdown: "Two proposals rarely describe the same work.\n\n<img src=x onerror=alert(1)>" },
      { key: "steps", heading: "How to compare", markdown: "Work through them in order." },
      { key: "sources", heading: "Side by side", markdown: "The main differences, [with a guide](https://docs.example.org/guide)." },
    ],
    presentation: {
      opening: "Read both proposals with the same questions.",
      authors: [
        {
          key: "ada",
          kind: "person",
          name: "Ada Example",
          profileUrl: "https://ada.example.org/",
          description: "Ada writes about buying professional services.",
        },
      ],
      reviewer: null,
      media: [
        {
          key: "hero",
          role: "hero",
          sectionKey: null,
          url: "https://images.example.org/hero.png",
          alt: "Two documents side by side",
          decorative: false,
          caption: "Two proposals",
          credit: null,
          width: 1600,
          height: 900,
        },
      ],
      citations: [
        { key: "guide", sectionKey: "why", label: "A public guide", url: "https://docs.example.org/guide", locator: "Section 2" },
        { key: "guide-again", sectionKey: "sources", label: "A public guide", url: "https://docs.example.org/guide", locator: "Section 3" },
      ],
      search: { title: null, description: null },
    },
    cover: {
      key: "cover",
      url: "https://images.example.org/cover.png",
      alt: "A cover for the guide",
      caption: null,
      credit: null,
      width: 1200,
      height: 630,
    },
    faq: [
      {
        key: "difference",
        question: "What differs most?",
        answerMarkdown: "The **scope** of the work.",
        sectionKey: "why",
        citationKeys: ["guide"],
      },
      { key: "guarantee", question: "Can anyone guarantee results?", answerMarkdown: "No.", sectionKey: null, citationKeys: [] },
    ],
    procedure: {
      sectionKey: "steps",
      prerequisitesMarkdown: "Collect both proposals.",
      steps: [
        {
          key: "list",
          name: "List the work",
          instructionsMarkdown: "Write down each task.",
          expectedResultMarkdown: "A list you can compare.",
          citationKeys: [],
        },
        { key: "ask", name: "Ask for evidence", instructionsMarkdown: "Ask for examples.", expectedResultMarkdown: null, citationKeys: ["guide"] },
      ],
      verificationMarkdown: null,
      troubleshootingMarkdown: "Ask for a written proposal.",
    },
    comparison: {
      sectionKey: "sources",
      methodMarkdown: "We compare what each proposal says it includes.",
      columns: [
        { key: "first", label: "First proposal" },
        { key: "second", label: "Second proposal" },
      ],
      rows: [
        {
          key: "goal",
          label: "Goal",
          cells: [
            { columnKey: "first", markdown: "Search results", citationKeys: [] },
            { columnKey: "second", markdown: "AI answers", citationKeys: ["guide-again"] },
          ],
        },
      ],
      limitationsMarkdown: null,
    },
    verification: {
      mode: "docs_only",
      disclosure: "Based on public documentation.",
      lastVerifiedAt: "2026-11-20",
      versions: [],
    },
    taxonomy: { categories: ["Guides"], tags: ["Proposals"] },
  });
}

export const MAPPING = { profileId: randomUUID(), version: 1, digest: `sha256:${"a".repeat(64)}` };

export function ids(expectedRemoteVersion: number | null = null) {
  return { commandId: randomUUID(), articleRevisionId: randomUUID(), expectedRemoteVersion };
}

/** Calls the live PUT route the way Gomnee does. */
export async function put(articleKey: string, body: unknown, key = KEY) {
  const response = await PUT(
    new Request(`https://example.com/api/integrations/gomnee/publishing/v1/articles/${articleKey}`, {
      method: "PUT",
      headers: { "content-type": "application/json", authorization: `Bearer ${key}` },
      body: JSON.stringify(body),
    }),
    { params: Promise.resolve({ articleKey }) },
  );
  return { status: response.status, body: (await response.json()) as Record<string, unknown> };
}

/** Publishes an Article as Gomnee would, typed ones mapped (v3), and returns its key. */
export async function publish(article: ArticlePayload = markdownArticle()) {
  const articleKey = randomUUID();
  const request =
    article.contentFormat === "gomnee_article_v2"
      ? makePublishRequest(article, ids(), MAPPING)
      : makePublishRequest(article, ids());
  const result = await put(articleKey, request);
  if (result.status !== 200) throw new Error(`publish failed: ${JSON.stringify(result.body)}`);
  return articleKey;
}

export async function emptyDatabase() {
  await getDb().execute(sql`truncate publication_commands, articles, article_previews`);
}
```

## tests/publishing.test.ts

```ts
import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { afterAll, beforeEach, describe, expect, it } from "vitest";
import { closeDb, getDb } from "@/db";
import { articles } from "@/db/schema";
import { GET as capabilities } from "@/app/api/integrations/gomnee/publishing/v1/route";
import { GET as readBack } from "@/app/api/integrations/gomnee/publishing/v1/articles/[articleKey]/route";
import { contentDigest, DESTINATION_SHAPE, makePublishRequest, TEMPLATE } from "@/lib/publishing/publish";
import { SITE } from "@/lib/site";
import { emptyDatabase, ids, KEY, MAPPING, markdownArticle, put, typedArticle } from "./fixtures";

const base = "https://example.com/api/integrations/gomnee/publishing/v1";
const auth = (key = KEY) => ({ authorization: `Bearer ${key}` });

async function read(articleKey: string) {
  const response = await readBack(new Request(`${base}/articles/${articleKey}`, { headers: auth() }), {
    params: Promise.resolve({ articleKey }),
  });
  return { status: response.status, body: (await response.json()) as Record<string, unknown> };
}

beforeEach(emptyDatabase);
afterAll(closeDb);

describe("capabilities", () => {
  it("declares the neutral Custom Website destination for this site's origin", async () => {
    const response = await capabilities(new Request(base, { headers: auth() }));
    expect(response.status).toBe(200);
    const body = await response.json();
    expect(body).toMatchObject({
      schemaVersion: "gomnee_publishing_capabilities_v2",
      adapterKey: "gomnee.custom_website_articles",
      siteOrigin: new URL(SITE.url).origin,
      contentFormats: ["markdown", "gomnee_article_v1", "gomnee_article_v2"],
      template: TEMPLATE,
      destinationShape: DESTINATION_SHAPE,
      coverPlacement: "listing_card",
    });
    expect(response.headers.get("cache-control")).toBe("no-store");
  });

  it("refuses a wrong key, and says when publishing is not configured", async () => {
    expect((await capabilities(new Request(base, { headers: auth("x".repeat(40)) }))).status).toBe(401);
    expect((await capabilities(new Request(base))).status).toBe(401);
    const saved = process.env.GOMNEE_PUBLISHING_TOKEN;
    delete process.env.GOMNEE_PUBLISHING_TOKEN;
    try {
      expect((await capabilities(new Request(base, { headers: auth() }))).status).toBe(503);
    } finally {
      process.env.GOMNEE_PUBLISHING_TOKEN = saved;
    }
  });
});

describe("publishing", () => {
  it("creates, reads back, updates and reconciles an exact retry", async () => {
    const articleKey = randomUUID();
    const article = markdownArticle();
    const create = makePublishRequest(article, ids());
    const created = await put(articleKey, create);
    expect(created.status).toBe(200);
    expect(created.body).toMatchObject({
      schemaVersion: "gomnee_live_article_receipt_v1",
      operation: "created",
      remoteVersion: 1,
      publicUrl: `${new URL(SITE.url).origin}/blog/${article.slug}`,
      contentDigest: contentDigest(article),
    });

    const observed = await read(articleKey);
    expect(observed.status).toBe(200);
    expect(observed.body).toMatchObject({ schemaVersion: "gomnee_live_article_observation_v1", remoteVersion: 1 });
    expect(observed.body.article).toEqual(article);

    const changed = { ...article, summary: "Updated summary." };
    const updated = await put(articleKey, makePublishRequest(changed, ids(1)));
    expect(updated.body).toMatchObject({ operation: "updated", remoteVersion: 2 });

    // The exact first command again: its original receipt, content untouched.
    const replay = await put(articleKey, create);
    expect(replay.body).toMatchObject({ operation: "reconciled", remoteVersion: 1 });
    expect((await read(articleKey)).body).toMatchObject({ remoteVersion: 2, summary: "Updated summary." });
  });

  it("refuses stale versions, changed slugs, reused commands and wrong digests without changing anything", async () => {
    const articleKey = randomUUID();
    const article = markdownArticle();
    const create = makePublishRequest(article, ids());
    await put(articleKey, create);

    expect((await put(articleKey, makePublishRequest(article, ids(7)))).status).toBe(409);
    expect((await put(articleKey, makePublishRequest({ ...article, slug: "another-address" }, ids(1)))).status).toBe(409);
    expect((await put(articleKey, { ...create, article: { ...article, title: "Other" } })).status).toBe(400);
    const reused = makePublishRequest({ ...article, title: "Other" }, { ...ids(1), commandId: create.commandId });
    expect((await put(articleKey, reused)).status).toBe(409);
    expect((await put(randomUUID(), makePublishRequest(article, ids()))).status).toBe(409);
    expect((await put(randomUUID(), makePublishRequest(markdownArticle("never-published"), ids(1)))).status).toBe(409);
    expect((await put(articleKey, { ...create, article: { ...article, unexpected: true } })).status).toBe(400);

    expect((await read(articleKey)).body).toMatchObject({ remoteVersion: 1, title: article.title });
  });

  it("publishes a mapped typed Article and returns the complete pair on read-back", async () => {
    const articleKey = randomUUID();
    const article = typedArticle();
    const request = makePublishRequest(article, ids(), MAPPING);
    const receipt = await put(articleKey, request);
    expect(receipt.status).toBe(200);
    expect(receipt.body).toMatchObject({
      schemaVersion: "gomnee_live_article_receipt_v2",
      mapping: { ...MAPPING, destinationShapeDigest: contentDigest(DESTINATION_SHAPE) },
    });
    const observed = await read(articleKey);
    expect(observed.body.schemaVersion).toBe("gomnee_live_article_observation_v2");
    expect(observed.body.article).toEqual(article);
    expect(observed.body.mappedContent).toEqual(request.mappedContent);

    const stale = makePublishRequest(article, ids(1), MAPPING);
    stale.mappedContent.mapping.destinationShapeDigest = `sha256:${"b".repeat(64)}`;
    stale.contentDigest = contentDigest({ article, mappedContent: stale.mappedContent });
    expect((await put(articleKey, stale)).status).toBe(409);
  });

  it("keeps an archived Article out of read-back and refuses to update it", async () => {
    const articleKey = randomUUID();
    await put(articleKey, makePublishRequest(markdownArticle(), ids()));
    await getDb().update(articles).set({ status: "archived" }).where(eq(articles.gomneeArticleKey, articleKey));
    expect((await read(articleKey)).status).toBe(404);
    expect((await put(articleKey, makePublishRequest(markdownArticle(), ids(1)))).status).toBe(409);
  });
});
```

## tests/preview.test.ts

```ts
import { randomUUID } from "node:crypto";
import { sql } from "drizzle-orm";
import { renderToStaticMarkup } from "react-dom/server";
import { afterAll, beforeEach, describe, expect, it } from "vitest";
import { closeDb, getDb } from "@/db";
import { articlePreviews } from "@/db/schema";
import { POST } from "@/app/api/integrations/gomnee/publishing/v1/previews/route";
import ArticlePreviewPage, { metadata } from "@/app/article-preview/[token]/page";
import nextConfig, { previewFrameAncestors } from "@/next.config";
import { contentDigest, TEMPLATE } from "@/lib/publishing/publish";
import { getArticlePreview, MAX_ACTIVE_ARTICLE_PREVIEWS } from "@/lib/publishing/preview";
import { emptyDatabase, KEY, markdownArticle, typedArticle } from "./fixtures";

function request(article: ReturnType<typeof markdownArticle> | ReturnType<typeof typedArticle> = typedArticle()) {
  return {
    schemaVersion: "gomnee_article_preview_request_v1",
    articleKey: randomUUID(),
    sourceRevisionId: randomUUID(),
    snapshotKind: "saved",
    contentDigest: contentDigest(article),
    template: TEMPLATE,
    article,
  };
}

async function post(body: unknown) {
  const response = await POST(
    new Request("https://example.com/api/integrations/gomnee/publishing/v1/previews", {
      method: "POST",
      headers: { "content-type": "application/json", authorization: `Bearer ${KEY}` },
      body: JSON.stringify(body),
    }),
  );
  return { status: response.status, body: (await response.json()) as Record<string, string>, response };
}

const tokenOf = (previewUrl: string) => new URL(previewUrl).pathname.split("/").at(-1)!;

beforeEach(emptyDatabase);
afterAll(closeDb);

describe("private previews", () => {
  it("returns an expiring private URL that renders the snapshot without publishing it", async () => {
    const { status, body, response } = await post(request());
    expect(status).toBe(201);
    expect(response.headers.get("cache-control")).toBe("private, no-store");
    expect(body.schemaVersion).toBe("gomnee_article_preview_receipt_v1");
    expect(new URL(body.previewUrl).pathname).toMatch(/^\/article-preview\/[A-Za-z0-9_-]{43}$/);
    const lifetime = new Date(body.expiresAt).getTime() - Date.now();
    expect(lifetime).toBeGreaterThan(13 * 60_000);
    expect(lifetime).toBeLessThanOrEqual(15 * 60_000);

    const page = await ArticlePreviewPage({ params: Promise.resolve({ token: tokenOf(body.previewUrl) }) });
    const html = renderToStaticMarkup(page);
    expect(html).toContain("Private preview · Saved draft · Not published");
    expect(html).toContain("Compare two proposals step by step");
    expect(html).not.toContain("application/ld+json");
    expect(metadata.robots).toMatchObject({ index: false, follow: false });
    const [stored] = await getDb().select().from(articlePreviews);
    expect(stored!.tokenHash).not.toContain(tokenOf(body.previewUrl));
  });

  it("refuses a wrong digest or an outdated template", async () => {
    expect((await post({ ...request(), contentDigest: `sha256:${"0".repeat(64)}` })).status).toBe(400);
    expect((await post({ ...request(), template: { id: TEMPLATE.id, version: "0" } })).status).toBe(409);
  });

  it("forgets expired previews and admits at most a hundred at once", async () => {
    const { body } = await post(request(markdownArticle()));
    await getDb().execute(
      sql`update article_previews set created_at = now() - interval '20 minutes', expires_at = now() - interval '6 minutes'`,
    );
    expect(await getArticlePreview(tokenOf(body.previewUrl))).toBeNull();

    for (let index = 0; index < MAX_ACTIVE_ARTICLE_PREVIEWS; index++)
      expect((await post(request(markdownArticle()))).status).toBe(201);
    expect((await post(request(markdownArticle()))).status).toBe(429);
  });
});

describe("framing", () => {
  it("lets only Gomnee frame previews and denies framing everywhere else", async () => {
    const rules = await nextConfig.headers!();
    const preview = rules.find((rule) => rule.source === "/article-preview/:path*")!;
    expect(preview.headers).toContainEqual({ key: "Content-Security-Policy", value: "frame-ancestors https://app.gomnee.com;" });
    expect(preview.headers).toContainEqual({ key: "X-Robots-Tag", value: "noindex, nofollow, noarchive" });
    const pages = rules.find((rule) => rule.headers.some((header) => header.key === "X-Frame-Options"))!;
    expect(new RegExp(`^${pages.source.replace("/((?!", "/(?!").replace(").*)", ").*")}$`).test("/blog/a")).toBe(true);
    expect(previewFrameAncestors("https://staging.gomnee.com")).toBe(
      "frame-ancestors https://app.gomnee.com https://staging.gomnee.com;",
    );
    expect(() => previewFrameAncestors("http://insecure.example.com")).toThrow();
    expect(() => previewFrameAncestors("https://*.example.com")).toThrow();
  });
});
```

## tests/pages.test.tsx

```tsx
import { eq } from "drizzle-orm";
import { renderToStaticMarkup } from "react-dom/server";
import { afterAll, beforeEach, describe, expect, it } from "vitest";
import { closeDb, getDb } from "@/db";
import { articles } from "@/db/schema";
import ArticleRoute, { generateMetadata } from "@/app/blog/[slug]/page";
import BlogIndex from "@/app/blog/page";
import sitemap from "@/app/sitemap";
import { SITE } from "@/lib/site";
import { emptyDatabase, markdownArticle, publish, typedArticle } from "./fixtures";

async function render(slug: string) {
  return renderToStaticMarkup(await ArticleRoute({ params: Promise.resolve({ slug }) }));
}

function jsonLd(html: string) {
  return [...html.matchAll(/<script type="application\/ld\+json">([\s\S]*?)<\/script>/g)].map(
    ([, json]) => JSON.parse(json!) as Record<string, unknown>,
  );
}

beforeEach(emptyDatabase);
afterAll(closeDb);

describe("article pages", () => {
  it("render every module of a typed Article once, with one h1 and matching structured data", async () => {
    await publish(typedArticle());
    const html = await render("compare-two-proposals");
    expect(html.match(/<h1[\s>]/g)).toHaveLength(1);
    for (const part of [
      "In short",
      "Two documents side by side",
      "Before you start",
      "Expected result",
      "If something doesn&#x27;t work",
      "How this comparison works",
      "First proposal",
      "What differs most?",
      "Can anyone guarantee results?",
      "How this was checked",
      "Based on documentation",
      "About the author",
    ])
      expect(html).toContain(part);
    // One numbered list, one entry per URL, with both locators.
    expect(html).toContain("Section 2; Section 3");
    expect(html.match(/<li id="source-/g)).toHaveLength(1);
    // Raw HTML in content is skipped, never injected.
    expect(html).not.toContain("<img src=\"x\"");
    expect(html).not.toContain("onerror");

    const [posting, breadcrumbs, faq] = jsonLd(html);
    expect(posting).toMatchObject({
      "@type": "BlogPosting",
      headline: "Compare two proposals step by step",
      author: [{ "@type": "Person", name: "Ada Example", url: "https://ada.example.org/" }],
      image: "https://images.example.org/hero.png",
      citation: ["https://docs.example.org/guide"],
    });
    expect(String(posting!.datePublished)).toMatch(/^\d{4}-\d{2}-\d{2}T/);
    expect(breadcrumbs!["@type"]).toBe("BreadcrumbList");
    expect(faq!["@type"]).toBe("FAQPage");
  });

  it("credit a Markdown Article to the site's owner", async () => {
    await publish(markdownArticle());
    const html = await render("hello-from-gomnee");
    expect(html).toContain(`By <span><a href="${SITE.url}/about">${SITE.name}</a></span>`);
    expect(html).not.toContain("alert(");
    const [posting] = jsonLd(html);
    expect(posting!.author).toEqual([{ "@type": "Person", "@id": `${SITE.url}/#person`, name: SITE.name }]);
    const metadata = await generateMetadata({ params: Promise.resolve({ slug: "hello-from-gomnee" }) });
    expect(metadata.alternates?.canonical).toBe("/blog/hello-from-gomnee");
  });

  it("list published Articles in the index and the sitemap, and hide archived ones", async () => {
    await publish(typedArticle());
    await publish(markdownArticle());
    let index = renderToStaticMarkup(await BlogIndex());
    expect(index).toContain("Compare two proposals step by step");
    expect(index).toContain("https://images.example.org/cover.png");
    expect((await sitemap()).map((entry) => entry.url)).toContain(`${SITE.url}/blog/hello-from-gomnee`);

    await getDb().update(articles).set({ status: "archived" }).where(eq(articles.slug, "hello-from-gomnee"));
    index = renderToStaticMarkup(await BlogIndex());
    expect(index).not.toContain("Hello from Gomnee");
    expect((await sitemap()).map((entry) => entry.url)).not.toContain(`${SITE.url}/blog/hello-from-gomnee`);
    await expect(render("hello-from-gomnee")).rejects.toThrow();
  });
});
```

## .github/workflows/check.yml

```yaml
name: Check

on:
  push:
  pull_request:

permissions:
  contents: read

jobs:
  check:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:17-alpine
        env:
          POSTGRES_PASSWORD: postgres
          POSTGRES_DB: starter_test
        ports:
          - 5432:5432
        options: >-
          --health-cmd "pg_isready -U postgres"
          --health-interval 5s
          --health-timeout 5s
          --health-retries 10
    env:
      # A throwaway test database and key; the real values live where the site runs.
      TEST_DATABASE_URL: postgres://postgres:postgres@localhost:5432/starter_test
      DATABASE_URL: postgres://postgres:postgres@localhost:5432/starter_test
      GOMNEE_PUBLISHING_TOKEN: ci-only-publishing-key-not-a-secret-000000
    steps:
      - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
      - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
        with:
          node-version: 24
      - run: corepack enable
      - run: pnpm install --frozen-lockfile
      - run: pnpm test
      - run: pnpm build
      - run: pnpm check
```

## Check it

```sh
pnpm install    # the first time: creates pnpm-lock.yaml, which you commit
TEST_DATABASE_URL=postgres://…/site_test pnpm test
pnpm build && pnpm check
```
