# oink: preview and multi-version serving from a docs repository

> A draft PRD for one lean oink Go binary that orchestrates official Hugo on a Git documentation repository for local preview, self-hosted multi-version serving behind Cloudflare CDN, frozen archives, scoped SQLite FTS5 search, and Brotli-packed .oink packages for Crib, with minimal OINK theme coordination.

---

LLMS index: [llms.txt](/llms.txt)

---

> [!WARNING] Draft, 2026-11-28 (v2 redesign)
> This proposal describes a product direction that is not implemented. Do not use it as a
> configuration or command reference. Current behavior is defined by the
> [architecture contract](/docs/design/architecture/), the [CLI contract](/docs/design/decisions/cli/)
> and the [versions guide](/docs/customize/versions/).

## Status and surface {#status}

**Status and date**: draft (v2 redesign after adversarial review and local benchmarking), 2026-11-28; product requirements and architecture direction, not an implementation contract.

**Owner**: OINK maintainer.

**Baseline**: OINK v1.7.0 / v1.8.0-dev (plain CSS, no Sass, no Bootstrap JS); installed Hugo v0.170.1; the local `0.1.0-dev` candidate of `pgsty/oink-cli` (unreleased, no users).

**Affected contracts**: [CLI contract](/docs/design/decisions/cli/) (superseded if this proposal is accepted),
[Architecture · Outputs and runtime](/docs/design/architecture/#outputs-and-runtime),
[Shell · Search, actions, and runtime](/docs/design/shell/#search-actions-and-runtime),
and the [versions guide](/docs/customize/versions/).

**Related proposals**: takes over the unimplemented version-lifecycle stage of the
[CLI roadmap](/docs/design/proposals/oink-cli-roadmap/#version-lifecycle); answers the open question of
[theme roadmap R2](/docs/design/proposals/theme-roadmap/#version-lifecycle), "native version dimension or
independent builds"; delivers the SQLite search backend left open by the
[local search proposal](/docs/design/proposals/local-search-engine/).

**Affected implementation**: a new, clean Go repository for the `oink` binary (`pgsty/oink-server`, retiring `pgsty/oink-cli` as archived history); six small, low-coupling OINK theme additions (`C1–C6`, see [theme coordination](#theme-coordination)).

**Release intent**: staged, delivering local preview (`M0`) and Git multi-version Hugo serving (`M1`) first; see [milestones](#milestones). This proposal commits to no release date.

## Summary {#summary}

Run one lean Go binary (`oink`, ~20 MB) directly against any OINK or Hugo Git documentation repository:

```sh
oink                                 # inside a site directory: same as oink dev
oink dev                             # preview the working tree, live reload on save
oink serve                           # production: publish Git branches, tags and frozen archives
oink freeze v3.5                     # snapshot a version before a breaking theme upgrade
oink build -o dist/                  # export static output (for Cloudflare Pages, etc.)
oink build --versions -o pgdoc.oink  # export a compacted, signed read-only .oink archive
```

`oink` does not fork Hugo and does not import Hugo's unstable internal Go packages. It orchestrates the official Hugo binary as an isolated child process (using `PATH` or an auto-cached, SHA-256-verified official release), stores deduplicated outputs in local SQLite (`CGO_ENABLED=0`) packed with standard RFC 7932 Brotli clusters, and sits behind Cloudflare's free CDN without requiring D1 or Workers.

The core model fits in one sentence: **Git is the authoritative source, a version is a pointer to a Git ref or frozen archive, rendered output is an immutable content-addressed snapshot, and the server never rewrites HTML bytes.**

Four mutually consistent invariants run through the whole design:

1. **Plain Hugo still builds every OINK site unchanged.** Ordinary consumers need only the official Hugo binary; removing `oink` breaks nothing.
2. **Production serves only immutable snapshots with zero cross-request tearing.** Production never reads the working tree; failed, timed-out, or OOM builds never replace live pointers; fingerprinted assets stay resolvable across a `≥ 48h` grace window after snapshot switches.
3. **Zero server-side HTML splicing.** The server performs no byte-offset HTML rewriting and no fragment builds. Version menus and outdated/prerelease banners are progressively enhanced on the client from `/_oink/versions.json` (with a static fallback link to `/versions/` when JavaScript is off), while SEO canonical and indexing rules travel in standard HTTP response headers (`Link` and `X-Robots-Tag`).
4. **Cost follows active unique content, with honest boundaries.** Publishing a new release never rebuilds old versions; historical versions that predate breaking theme retirements are frozen via `oink freeze` rather than re-compiled; full-text search indexes only configured active version lines by default.

## Context and evidence {#context}

### Current state {#current-state}

- OINK treats each documentation version as an independent Hugo build with `params.versions` baked into every page. Adding a version forces updating every maintained branch and rebuilding all of them (see the [versions guide](/docs/customize/versions/)).
- `pgsty/oink-cli` is an unreleased `0.1.0-dev` candidate with no users; the owner confirmed the new design need not be constrained by it.
- Multi-version documentation such as the Chinese PostgreSQL manual (`pgdoc-cn`, 560 versions) explodes into gigabytes when deployed as per-version static trees and exceeds Cloudflare Pages file limits.
- Self-hosted Go + local SQLite behind Cloudflare's free CDN avoids per-row/storage pricing of managed edge databases such as Cloudflare D1 while keeping one binary for local preview, production serving, and offline reading.

### Empirical benchmarks {#benchmarks}

Measured read-only on 2026-11-28 on the actual target repositories (`darwin/arm64`, Hugo `v0.170.1`, SQLite `3.54.0`, `zstd`, `brotli`):

| Measurement | Observed result | Design consequence |
| --- | --- | --- |
| `pgdoc-cn` Git repository | 559 `v*` tags + `master` (560 versions; 1,118 tags total including `REL_*` duplicates), Git pack `78.18 MiB` | Regex matching deduplicates twin tags on the same commit |
| `pgdoc-cn` tree scan & body dedup | 528,798 HTML entries, 527,348 unique Git blobs (`5,856.9 MiB`); stripping `navheader`/`navfooter` leaves **98,141 unique bodies (`1,206.7 MiB`)** | Reading and stripping all 527k blobs takes `48.9 s` in Python (est. `12–25 s` in Go), so full materialization runs asynchronously in the background |
| `pgdoc-cn` base SQLite store (no FTS5) | 1 MiB clusters + `14.60 MiB` SQLite metadata (`entries WITHOUT ROWID`, `objects`, `paths`, `snapshots`) = **`44–62 MiB`** depending on cluster ordering and codec | All 560 versions fit comfortably under `65 MiB` without search |
| `pgdoc-cn` contentless FTS5 (`content=''`, `detail=full`, CJK bigrams) | **Latest 1 line** (1,155 docs): **`10.84 MiB`** (`0.92 s`); **Latest 6 major lines PG 13–18** (4,250 unique docs): **`32.41 MiB`** (`5.07 s`); All 29 major lines (20,177 docs): `98.46 MiB` (`20.81 s`); **All 560 versions (98,141 docs): `> 473 MiB`** (`> 100 s`) | Indexing all 560 minor releases blows past `< 100 MiB` by > 5× and distorts IDF. Separating `search.db` and indexing active major lines keeps `pgdoc-cn` (content + 6 active lines search) at **`~75–85 MiB`** |
| Cluster codec comparison (15 × 1 MiB `pgdoc-cn` clusters, `14.23 MiB` raw, `(path, version)` order) | `zstd -3`: `0.411 MiB` (`34.6×`); `zstd -9`: `0.372 MiB` (`38.3×`); `zstd -15`: `0.361 MiB` (`39.4×`); **`brotli -q 6 (lgwin=22)`**: **`0.337 MiB` (`42.2×`)**, `dec p50=0.29 ms / p99=0.76 ms`; **`brotli -q 9`**: **`0.326 MiB` (`43.6×`)**, `dec p50=0.26 ms / p99=0.34 ms`; **`brotli -q 11`**: **`0.306 MiB` (`46.6×`)**, `dec p50=0.27 ms / p99=0.42 ms` | **Brotli beats zstd on ratio, matches zstd decode speed (`< 1 ms` p99), runs pure-Go (`CGO_ENABLED=0`), and is natively decoded by Apple's `Compression` framework (`COMPRESSION_BROTLI`) with zero third-party dependencies in Crib** |
| `pigsty.io` (bilingual OINK docs) | 1,547 files, Git pack `154.92 MiB`; `data/` holds `contributors.yaml`, `footer/`, `landing/`, `pgext/`, `upstreams.yaml`, `star_history.json` | Confirms `data/` and `static/` carry version-specific content and must travel with the version commit |
| `pgext.cloud` & `pg.center` | `pgext.cloud/public` is `1.2 GB` for 1,493 HTML files (`71 MB` `index.xml`); both `pgext serve` and `pg.center` already run as dedicated Go + PostgreSQL (`pgx`) apps | Database-backed catalogs and knowledge graphs stay dedicated Go+PG apps sharing OINK's `chrome` CSS bundle, rather than being forced into static sidebar trees |
| Local binary & theme sizes | `hugo v0.170.1` binary = `87 MB`; OINK runtime assets (`layouts`, `assets`, `i18n`, `data`, `static`) = `25.77 MiB`; theme `tests/` = `79 MB` | Decoupling official Hugo keeps `oink` around `~20 MB` and allows independent Hugo upgrades |
{.wide .expand}

### Owner inputs {#owner-inputs}

Confirmed premises from the 2026-11-27 and 2026-11-28 discussions:

1. One Go binary named `oink` running directly on a Git documentation repository: local live preview while editing (`oink dev`) and production serving (`oink serve`).
2. Production is Git-aware: pin one branch or serve configured branches and tags as multi-version documentation without exploding storage across 500+ PostgreSQL versions.
3. Self-hosted Go server + local SQLite (avoiding expensive managed edge databases like Cloudflare D1), sitting behind Cloudflare CDN; large media can remain on nginx or local media mounts.
4. Full-text search and optional page views on SQLite; single-file `.oink` packages readable directly by `oink serve` and the macOS reader app Crib (which has zero third-party dependencies).
5. **ACL / access control is deferred out of v1**; the unreleased `oink-cli` need not constrain the design.

## Goals and non-goals {#goals}

**Goals:**

- **G1 Lean single binary.** Running `oink` in any OINK repo previews it locally (auto-resolving official Hugo if absent); the same binary runs production serving and static/package exports.
- **G2 Git-aware multi-version serving.** Branches, tags, aliases (`current`, `latest`), and frozen archives resolve deterministically; all 560 versions of `pgdoc-cn` are reachable; publishing a new version never rebuilds existing versions.
- **G3 Bounded storage without explosion.** Storage follows unique content via Brotli clusters; all 560 `pgdoc-cn` versions plus active-line FTS5 stay under `100 MiB`.
- **G4 Resilient atomic operations.** Production serves only committed/frozen immutable snapshots; bad commits, build OOMs, timeouts, and `kill -9` never degrade live traffic; rollback completes in `< 1 s`; fingerprinted assets never 404 across snapshot switches.
- **G5 Honest theme compatibility.** Plain Hugo stays untouched; active lines share theme styling safely while keeping their own `data/` and `static/`; versions predating breaking OINK retirements freeze cleanly without violating OINK's no-compat-shim rule.
- **G6 Scoped search and offline `.oink`.** Active-line FTS5 handles CJK and technical identifiers accurately; one compacted, signed, Brotli-compressed `.oink` archive opens directly in `oink serve` and Crib with zero Crib third-party dependencies.

**Non-goals for v1:**

- **No ACL, RBAC, OAuth accounts, login sessions, or authenticated preview hosts** (deferred to a separate proposal that must isolate private content at build time rather than via HTTP path filters).
- **No built-in comment or moderation platform** (v1 keeps giscus and adds a version-independent `term` key so discussions stay unified across versions).
- **No server-side HTML slot splicing** (no `<template data-td-slot>` offsets or fragment builds).
- **No Hugo fork and no importing `github.com/gohugoio/hugo/commands`**.
- **No database-driven catalog/graph pages inside `oink`** (`pgext serve` and `pg.center` remain separate Go+PG services sharing OINK's `chrome` CSS).
- **No multi-tenant hosting, multi-instance shared state, or built-in ACME TLS** (run behind Cloudflare, nginx, or Caddy).
- **No Hugo multihost (per-language domain) routing** in v1.

## Users and target sites {#scenarios}

| Target site | Shape | How it uses `oink` |
| --- | --- | --- |
| `oink.pgsty.com` / `pigsty.io` | Bilingual EN/ZH Hugo + OINK docs, tens of versions, rich `data/` | `oink dev` locally; `oink serve` with active build track + `oink freeze` for pre-breaking legacy versions; Cloudflare CDN in front |
| `pgdoc-cn` / `pgdoc-en` (`pgsql.cc`) | 560 versions of DocBook/pgweb HTML | `renderer: html (profile: pgweb)`, lines + releases + `current` alias, active-line FTS5 (`< 100 MiB` total), compacted `.oink` package for Crib |
| Static sites on Cloudflare Pages | Single version or small version set | `oink build [--versions] -o dist/` exports static files + `versions.json` + `_redirects` |
| `pgext.cloud` / `pg.center` | Dedicated Go + PostgreSQL dynamic apps | Keep their Go+PG backends; share OINK look via `css/bundle.html "chrome"`; optionally mount `oink serve` under `/docs/` via reverse proxy or embed a read-only `oink/reader` package later |
{.wide .expand}

## Product shape {#product}

### Commands {#commands}

| Command | Behavior |
| --- | --- |
| `oink` | Runs `oink dev` inside a Hugo/OINK site directory; prints help elsewhere |
| `oink dev [DIR]` | Previews the working tree (drafts/future included) by proxying official `hugo server`; `--versions` mounts already-built Git versions read-only |
| `oink serve [DIR \| GIT-URL \| FILE.oink]` | Production server: publishes Git refs + frozen archives, or serves one `.oink` file read-only |
| `oink freeze <VERSION> [--from DIR \| REF] [-o FILE]` | Captures a complete static build into a frozen archive snapshot so future breaking theme upgrades never break it |
| `oink build [--versions] [-o DIR \| FILE.oink]` | Exports a static directory tree (with `versions.json` and `_redirects`) or a compacted, signed `.oink` archive |
| `oink check [--versions]` | Builds in isolation, validates version config, reports warnings/broken local links, and flags active lines incompatible with an upcoming theme upgrade (`0` pass / `1` findings / `2` error) |
| `oink versions` | Resolves Git refs and `oink.yaml` and prints versions, aliases, default, and archived status without building |
| `oink status \| rebuild \| rollback \| backup` | Operates a running `oink serve` over its `0600` local Unix socket; `backup` runs SQLite `VACUUM INTO` on `state.db` |
| `oink hugo …` | Invokes the resolved official Hugo binary directly with all arguments passed through |
| `oink --version` | Prints versions of `oink`, resolved Hugo, embedded SQLite driver, and cached OINK theme |

### Development mode {#dev}

- Listens on `127.0.0.1` by default and serves the working tree including uncommitted edits and drafts.
- Spawns official `hugo server` on an ephemeral loopback port with `--appendPort=false --liveReloadPort=<proxy_port> --baseURL=http://127.0.0.1:<proxy_port>/` and reverse-proxies it:
  - forwards HTTP/1.1 `Upgrade: websocket` (`/livereload`) transparently so LiveReload works out of the box;
  - serves `/_oink/versions.json`, `/_oink/where`, `/_oink/search`, and `/_oink/hit` locally against dev state;
  - streams Hugo's own diagnostics cleanly to the terminal rather than scraping unstructured stderr text to fabricate source line numbers or injecting scripts that break site CSP/gzip responses.

### Production mode {#serve}

- Reads only committed Git refs and explicitly registered frozen archives; never touches the working tree.
- Serves immediately at cold start from existing snapshots in `cache.db` without blocking on rebuilds.
- Accepts a local checkout (using `.git`), a bare repository push target, a trusted remote Git URL (mirrored into `--data-dir`), or a single `.oink` file (read-only mode, zero background builds).
- Upgrades cleanly: replacing the `oink` binary and restarting never triggers snapshot rebuilds unless the Hugo version, skin commit, or corpus profile version actually changed.

### Static export, freezing and packages {#build}

- `oink build -o public/` produces output byte-identical to running the same official Hugo release directly.
- `oink build --versions -o dist/` writes each version under its prefix alongside a generated `/_oink/versions.json`, a static `/versions/` index page, and `_redirects` (for Cloudflare Pages / Netlify).
- `oink freeze <version>` snapshots a version's built output into a self-contained immutable archive before a breaking OINK/Hugo upgrade.
- `oink build --versions -o site.oink` writes a compacted, single-file, Ed25519-signed `.oink` archive readable by both `oink serve site.oink` and Crib.

## Core model {#model}

```text
Git refs / frozen archives ──resolve──▶ versions ──build/import──▶ immutable snapshots ──atomic flip──▶ serve
       (oink.yaml)                   (line/tag/alias)              (cache.db + search.db)          (HTTP headers +
                                                                                                    versions.json)
```

| Concept | Definition |
| --- | --- |
| **Source** | A Git repository plus optional frozen archive snapshots (`mode: archive`) |
| **Version** | A published label bound to a Git ref (`3.7 → v3.7.2`, `devel → main`) or a frozen snapshot (`2.7 → v2.7.oink`) |
| **Line** | A release series (`17` covers `17.0`–`17.12`; `3.7` covers `3.7.0`–`3.7.x`) |
| **Alias** | A movable pointer to a version (`current → 18`, `latest → highest-numbered line`) |
| **Skin** | The ref supplying shared layout and styling for active Hugo builds (defaults to the **newest stable release tag**, not moving `main`) |
| **Snapshot** | An immutable manifest mapping paths to content-addressed objects, keyed by `H(version_commit, skin_commit, hugo_version, profile_version, url_base)` |
| **Cache / Search / State** | Three physically separate SQLite files: `cache.db` (rebuildable content store), `search.db` (rebuildable FTS5 index), and `state.db` (durable counters and audit log, back up via `oink backup`) |

### Versions from Git refs {#versions}

- Without `oink.yaml`, the default branch HEAD is the sole version, served at `/` (`--ref <branch>` pins another branch).
- `tags` is a regular expression with named capture groups `line` and `patch`. Ordering compares dotted integer components numerically. Non-matching tags (such as `REL_*` aliases or `-rc1`) are ignored; duplicate tags on the same commit collapse to one canonical label.
- `releases: true` additionally exposes every matched patch tag (e.g. `/docs/17.4/`).
- `branches` maps explicit single-segment URL-safe labels (`^[a-z0-9][a-z0-9._-]*$`) to branches (preventing branch names containing `/` from producing ambiguous URL prefixes).
- `line_branch` optionally tracks the head of each line's maintenance branch instead of its newest tag (for translation repos shipping mid-release fixes).
- `default` names the version served without a prefix at `/`. When `default` is omitted (as in `pgdoc-cn` where all versions live under `/docs/{label}/`), `oink.yaml` **must** specify `root_redirect` (e.g. `/docs/current/`, answered with `302`) or a root landing source; an omitted `default` without `root_redirect` is a validation error.

### Dual-track version lifecycle {#lifecycle}

OINK intentionally retires public interfaces in minor releases with zero compatibility shims (for example, v1.6.0 removed Sass hooks and v1.8.0 removed the `social` shortcode, causing older content to fail Hugo builds). Real sites such as `pigsty.io` also store versioned facts in `data/` and `static/`. Therefore `oink` supports two explicit tracks for Hugo versions:

1. **Track A — Active build track (`mode: build`, default).** Used for release lines sharing the current breaking-change generation of OINK:
   - **Content domain comes from the version commit**: all resolved `contentDir` and content mounts declared in effective `hugo.yaml`, plus `data/`, `static/`, and non-style/non-script `assets/` (so versioned screenshots, download manifests, checksums, and `data/docs_nav.json` stay accurate to that version).
   - **Skin domain overlays appearance only**: from the pinned `skin` ref (default: newest release tag, never moving `main`), taking `layouts/`, theme module pin, `assets/css/`, `assets/js/`, `i18n/`, and appearance-only parameters (`params.ui.preset*`, `dark_mode`).
   - Any version that requires its own configuration/layouts can set `skin: self`.
   - **Content adapter guard**: `_content.gotmpl` files found in non-skin refs are rejected by default during materialization unless `allow_content_adapters: true` is explicitly set in `oink.yaml`.
2. **Track B — Frozen archive track (`mode: archive`).** Used whenever a version crosses a breaking theme or Hugo upgrade:
   - Before upgrading the site across a breaking OINK release, the maintainer runs `oink freeze <version>` (or imports an existing built static tree) and lists it under `versions.frozen` in `oink.yaml`.
   - Frozen snapshots are ingested directly into `cache.db` as immutable objects and **never rebuilt from source again**, yet participate seamlessly in `/_oink/versions.json`, archived banners, `/_oink/where`, and HTTP SEO headers.

### External HTML corpus importer {#html-corpus}

For pre-rendered HTML repositories such as `pgdoc-cn` and `pgdoc-en`, `renderer: { type: html, profile: pgweb }` provides a dedicated importer:

- Streams objects directly from Git via `git cat-file --batch` without checking out a worktree.
- Strips DocBook `navheader`/`navfooter` into location-independent body HTML and parses `index.html` into a compact per-version navigation JSON.
- **Preserves single visual authority**: the importer does **not** hand-generate complex OINK component markup in Go. Pages render inside a minimal theme-built shell template (theme item `C6`) with one body insertion point, and a dedicated `.td-corpus-pgweb` CSS layer styles native DocBook classes directly.

### URLs, redirects and SEO {#urls}

- **Layout**: single-host path layout `/{version}/{lang}/...` (default version drops `{version}`). Hugo multihost is unsupported and reported clearly by `oink check` / `oink serve`.
- **Default version redirect**: `/v{default}/x` responds with **`302 Found`** and `Cache-Control: public, max-age=300` (never `301`, so browsers are never pinned to stale redirects when `default` advances).
- **Aliases**: HTML corpus aliases (location-independent bodies) serve in place; Hugo version aliases respond with `302` (`max-age=300`).
- **Orthogonal SEO via HTTP headers** (compliant with Google Search Central; zero HTML rewriting):

| Version kind | HTTP `X-Robots-Tag` | HTTP `Link: rel="canonical"` | HTML `<link rel="canonical">` & `hreflang` | In `sitemap.xml` / RSS |
| --- | --- | --- | --- | --- |
| Default version (or primary alias) | none | none (HTML self-canonical) | self-canonical + full `hreflang` | yes (sole source) |
| Non-default major line (e.g. `/v3.6/`, `/docs/16/`) | none | target same-language path in default version if present, else self | omitted at build time (`C3`) | no |
| Exact patch release & prerelease (`17.4`, `devel`) | **`noindex, follow`** | **none** (never combine `noindex` with cross-version `canonical`) | omitted at build time (`C3`) | no |
{.wide .expand}

- **Error pages**: `404` carries `X-Robots-Tag: noindex`, loads `/_oink/where?path=...` to suggest versions containing that path, and marks `data-td-no-history`. Unbuilt versions return `503 Service Unavailable` with `Retry-After: 10`. Error page language resolves in order: matched URL language prefix → `Accept-Language` header → site default language.

## Architecture {#architecture}

### Pipeline {#pipeline}

```text
Git refs / archives ─▶ resolve ─▶ materialize ─▶ build/import ─▶ ingest ─▶ publish ─▶ HTTP
(fetch/webhook/push)   versions   content+skin   Hugo child or   Brotli    atomic     headers +
                                  (or freeze)    pgweb stream    + FTS5    pointer    cache
                                                                    │         │
                                                                    ▼         ▼
                                                            cache.db +     state.db
                                                            search.db     (back up)
```

1. **Resolve**: read `oink.yaml` from the configured ref, compute version/alias tables, and derive `snapshot_key = H(version_commit, skin_commit, hugo_version, profile_version, url_base)`. Matching keys are skipped immediately.
2. **Materialize**: for Track A Hugo versions, create a temporary `git worktree` at the version commit and overlay only the skin's appearance files; for Track B archives and HTML corpora, read directly without a worktree.
3. **Build / Import**: invoke official Hugo in an isolated child process into a temporary output directory, or stream HTML corpus pages through the `pgweb` profile.
4. **Ingest**: hash every output file, pack only unseen objects into Brotli clusters in `cache.db`, populate `entries` and `recent_assets`, and update `search.db` if the version is inside `search.scope`.
5. **Publish**: flip `versions` and `aliases` pointers in a single SQLite transaction, regenerate `/_oink/versions.json` payload, and enqueue batched Cloudflare prefix purges if configured.

### Decoupled Hugo engine and isolation {#engine}

- **External official Hugo binary**: `oink` never imports `gohugoio/hugo/commands`. It resolves Hugo in order: `--hugo` → `PATH` → auto-managed `~/.cache/oink/hugo/<version>/hugo` (downloaded from official GitHub Releases with pinned SHA-256 verification unless `--offline`). This keeps `oink` around `~20 MB`, avoids Go dependency bloat, and lets sites upgrade Hugo independently of `oink`.
- **Theme provisioning**: `_vendor/` → Go module cache (when `go` is present) → cached OINK theme release injected via `HUGO_MODULE_REPLACEMENTS`, `GOWORK=off`, and `HUGO_MODULE_WORKSPACE=off`. Sites importing additional non-vendored Hugo modules require `go` or `hugo mod vendor`; `oink` does not reimplement Go's MVS resolver.
- **Portable child-process resource isolation**:
  - **Never set `RLIMIT_AS`** on Go child processes (Go's 64-bit virtual arena `mmap` fails immediately with `ENOMEM`).
  - Every build child runs in its own process group (`Setpgid: true`), receives `GOMEMLIMIT` set to 80% of `build_memory_limit` (default `4 GiB`), runs at lowered priority (`setpriority` / `nice`, plus Linux `ionice`), and is watched every 500 ms by a parent RSS monitor (Linux `/proc/<pid>/status`, macOS `proc_pidinfo`) that `SIGKILL`s the entire process group on RSS breach or timeout.
  - On Linux hosts with delegated cgroup v2 write access (such as systemd `Delegate=yes`), `oink` additionally enforces kernel `memory.max`.
- **Build security**: skin refs are explicitly trusted code; `oink serve` still injects a configuration overlay forcing `security.exec.allow: []` unless `--allow-exec` is explicitly passed, and passes only a minimal environment variable allowlist to build children (never CDN tokens or host secrets).

### Storage, Brotli clusters and asset retention {#store}

- **SQLite Go driver (`CGO_ENABLED=0`)**: default to **`github.com/ncruces/go-sqlite3`** (WASM SQLite with full FTS5, compact binary, zero C toolchain for cross-compilation), benchmarked against `mattn/go-sqlite3` during `M0` before freezing.
- **Physical separation into three SQLite databases**:
  - **`cache.db`** (WAL, `PRAGMA synchronous = NORMAL`, rebuildable): `meta`, `clusters(id, codec, raw_size, data)`, `objects(id, hash, cluster, offset, size, media_type)`, `paths(id, path)`, `snapshots(id, key, version, commit_sha, state, created_at)`, `entries(snapshot, path, object) WITHOUT ROWID`, `recent_assets(path, object, expires_at)`, `versions`, `aliases`. On startup, `oink` cleans up any interrupted `state='building'` snapshots and unreferenced orphan clusters left by a prior crash.
  - **`search.db`** (WAL, `PRAGMA synchronous = NORMAL`, rebuildable): decoupled FTS5 index so search maintenance never contends with content reads or bloats content snapshots.
  - **`state.db`** (WAL, **`PRAGMA synchronous = FULL`** for power-loss durability, non-rebuildable): daily page-view totals and build/audit history. Backed up safely online with `oink backup` (SQLite `VACUUM INTO`) or Litestream.
- **Single universal codec — RFC 7932 Brotli (`lgwin=22`)**:
  - Empirically verified on `pgdoc-cn` 1 MiB clusters to achieve **42.2× at `-q 6` (`0.76 ms` p99 decode)** and **43.6–46.6× at `-q 9..11` (`0.34–0.42 ms` p99 decode)**, outperforming `zstd -15` while decoding natively in Apple's `Compression` framework (`COMPRESSION_BROTLI`) with zero third-party dependencies in Crib and pure-Go (`github.com/andybalholm/brotli`) in `oink`.
  - Online `cache.db` appends use fast `-q 6`; compacted `.oink` exports re-sort objects by `(path, version_sort_key)` and pack at `-q 9` (or `-q 11` with `--max-compress`).
  - **Adaptive cluster size**: `1 MiB` raw target for small-page corpora (`median < 64 KiB`); `4 MiB` raw target for large Hugo pages (`median ≥ 64 KiB`, still inside Brotli's `lgwin=22` 4 MiB sliding window!) so tens of versions share one compression window cleanly.
- **Cross-request asset retention (eliminating switch/GC 404s)**:
  - Garbage collection retains snapshots and objects for **`max(3 latest snapshots, 48 hours)`** — strictly longer than CDN edge TTL (`24h`) plus `stale-if-error` (`1h`).
  - Whenever a request for a fingerprinted asset (`/css/*`, `/js/*`, `/webfonts/*`, hashed media) misses the newly switched current snapshot, the server falls back to `recent_assets` and returns `200 OK` from the retained object.
- **Read-only `.oink` distribution archive (`oink.store/v1`)**:
  - Exported with `oink build --versions -o site.oink`: compacted clusters, `journal_mode=DELETE`, `VACUUM`, optional scoped FTS5 tables, and **canonical logical Ed25519 signing** (SHA-256 over sorted `meta` excluding `signature` plus sorted `(snapshot, path, object_hash)` records stored in `meta['manifest_sha256']` and signed in `meta['signature']`, avoiding circular file-byte hashing).

### Scoped FTS5 search {#search}

- **Explicit index scope (`search.scope`)**: defaults to `active-lines` (non-archived major lines), with options `default-only` and `all`. On `pgdoc-cn`, indexing the 6 active major lines (PG 13–18, 4,250 unique docs) adds only **`32.4 MiB`** in `5.1 s`, keeping total `pgdoc-cn` storage (`cache.db` + `search.db`) around **`75–85 MiB` (< `100 MiB`)**.
- **Version and language isolation**: queries filter by `(version_line, lang)` directly inside the index rather than taking global Top-K across all versions and post-filtering (preventing empty recalls on high-frequency terms and cross-language leakage).
- **Tokenization and section granularity**:
  - Hugo sites ingest section-level records directly from OINK's `offline-search-index.<lang>.json` (preserving headings, `data-td-search-entry` anchors, and excerpts); `pgweb` corpora split sections on headings.
  - FTS5 uses `content=''` and `tokenize="unicode61 tokenchars '_-./:'"` so identifiers (`work_mem`, `--baseURL`, `/pg/data`) stay intact; a shared Go pre-processor emits overlapping CJK bigrams and normalizes common SQL/JSON operators (`->>`, `::`, `@>`).
  - Acceptance uses a fixed curated **60-query EN + ZH + identifier/operator benchmark** (targeting Top-5 recall `≥ 90%` and p99 latency `< 25 ms`), rather than claiming byte-level ranking equivalence with the browser's 922-line scanning engine.

### Serving, Cloudflare caching and updates {#serving}

Request dispatch order: `/_oink/*` endpoints → `/versions/` static directory → longest-prefix version/alias match (or default version / `root_redirect`) → pin current snapshot → entry lookup → `recent_assets` fallback (for fingerprinted assets) → language-aware `404` / `503`.

| Response | Browser `Cache-Control` | Cloudflare `Cloudflare-CDN-Cache-Control` | Invalidation |
| --- | --- | --- | --- |
| Fingerprinted assets | `public, max-age=31536000, immutable` | `max-age=31536000` | Content-addressed filename |
| Release / line HTML | `public, max-age=300` + `ETag` | **`max-age=86400, stale-while-revalidate=600, stale-if-error=3600`** | Batched prefix purge on publish |
| Moving branch HTML (`devel`) | `public, max-age=60` + `ETag` | **`max-age=300, stale-while-revalidate=60, stale-if-error=1800`** | Prefix purge on publish |
| `/_oink/versions.json` | `public, max-age=60` | `max-age=60, stale-while-revalidate=300, stale-if-error=3600` | Single-URL purge on version change |
| `/_oink/search`, `/where`, `/hit` | `private, no-store` (`/where`: `public, max-age=60`) | `no-store` | Never cached |
{.wide .expand}

- **Cloudflare Cache Rules contract**: Cloudflare does not cache HTML by default, and `s-maxage` causes Cloudflare to ignore `stale-if-error`. Using `Cloudflare-CDN-Cache-Control` avoids that conflict so edge nodes serve stale pages across origin restarts. Operators configure one Cache Rule matching public paths (excluding `/_oink/*`) with `Eligible for cache` and **`Use cache-control header if present`** (never "Ignore cache-control header"). The purge client batches up to 100 prefixes per API call and rate-limits cleanly under Cloudflare Free's `5 req/min` ceiling.
- **Updates and fair scheduling**: triggered by periodic `git fetch` (default 60 s), HMAC-verified webhooks (`POST /_oink/hooks/<provider>`), or local bare-repo pushes. Builds run at default concurrency `1` with **aging priority** (default version first, waiting versions gain priority over time so frequent `main` commits cannot starve low-traffic lines); newer commits coalesce queued builds for the same version.

### Cookieless page views and hybrid apps {#services}

- **Page views (`/_oink/hit`, opt-in, off by default)**: pages send `navigator.sendBeacon`. The server verifies same-origin `Origin`/`Sec-Fetch-Site`, filters common bot UAs, and deduplicates repeat views in memory using a Plausible-style daily rotating random salt hash `SHA256(daily_salt || host || ip || ua || path)` (no cookie, no IP written to disk, salt discarded every 24 hours). Increments flush every 60 s into daily aggregates in `state.db`.
- **Comments**: v1 uses OINK's existing giscus integration enhanced with a version-independent `term` key (`C4`).
- **Hybrid integration for `pgext` and `pg.center`**: those applications retain their own Go + PostgreSQL runtime for live catalogs and knowledge graphs, share OINK's visual identity via `partial "css/bundle.html" "chrome"`, and either reverse-proxy `/docs/` to `oink serve` or (in a later library phase) embed a read-only `oink/reader` Go package over `.oink` archives.

### Configuration {#configuration}

Two files with clean ownership: `hugo.yaml` owns page rendering and `params.ui.*`; `oink.yaml` (`schema_version: oink.serve/v1`) owns publishing, versions, search scope, media mounts, and CDN purging. Secrets come strictly from environment variables.

```yaml {title="oink.yaml (product docs)"}
schema_version: oink.serve/v1
origin: https://docs.pigsty.io
skin: latest                                     # pin to newest stable tag, not moving main

versions:
  tags: '^v(?P<line>\d+\.\d+)\.(?P<patch>\d+)$'
  branches: { devel: main }
  default: latest
  url: '/v{label}/'
  archived: ['< 3.0']
  frozen:
    '2.7': ./archives/v2.7.oink

search:
  enable: true
  scope: active-lines

page_views:
  enable: false

cdn:
  provider: cloudflare                           # OINK_CF_API_TOKEN, OINK_CF_ZONE_ID

media:
  - url: /media/
    dir: /srv/media
```

```yaml {title="oink.yaml (pgdoc-cn, 560 HTML versions)"}
schema_version: oink.serve/v1
origin: https://pgsql.cc
root_redirect: /docs/current/

versions:
  renderer: { type: html, profile: pgweb }
  tags: '^v(?P<line>\d+(?:\.\d+)??)\.(?P<patch>\d+)$'
  releases: true
  branches: { devel: master }
  aliases: { current: latest }
  url: '/docs/{label}/'
  archived: ['< 15']

search:
  enable: true
  scope: active-lines
```

### Output, accessibility and security boundaries {#boundaries}

- **Output and progressive enhancement**: static HTML stays complete without JavaScript; without JS, the version control degrades to a semantic link to `/versions/` (a theme-rendered static directory of all versions); Print, Markdown, and LLMS remain per-version; RSS and `sitemap.xml` come from the default version only.
- **Accessibility and localization**: every new user-visible string (`503`, `prerelease` banner, `/versions/` page, 404 version hints, version-scoped search) ships natively in all 32 OINK locales and passes the documentation site's axe checks.
- **Management and metrics isolation**: management CLI commands talk solely over `<data-dir>/oink.sock` created with mode `0600`. Prometheus `/metrics` is served **only** on `oink.sock` or an explicit loopback-only listener (`--metrics-listen 127.0.0.1:9091`), never on the public reverse-proxied HTTP port.
- **No accidental secret exposure**: child Hugo processes run with `security.exec.allow: []` by default and stripped environment variables; CSP headers permit OINK's own startup scripts without wildcard inline execution.

## Theme coordination {#theme-coordination}

Dropping server-side HTML slot splicing, accounts, and built-in comments trims theme work down to six small, high-leverage changes (`C1–C6`). All paths below are relative to the OINK theme repository root.

### Theme changes (C1–C6) {#theme-changes}

| Item | Change | Files | Stage |
| --- | --- | --- | --- |
| **C1** | Fix O(N²) linear scan in `pager-state.html` with a cached `path → index` map; update `sidebar-nav.js` to highlight the active row from `window.location.pathname` rather than `link[rel="canonical"]` | `layouts/_partials/pager-state.html`, `assets/js/sidebar-nav.js` | M1 |
| **C2** | Emit `noindex` on `404.html`; add a localized `503` ("building") template across all 32 locales; add `data-td-no-history` to error templates and update `history.js` to skip any page carrying it | `layouts/404.html`, `layouts/_partials/head.html`, `assets/js/history.js`, `i18n/*.yaml` | M1 |
| **C3** | Add a build-level `oink_managed_seo` switch that omits HTML `<link rel="canonical">` and `hreflang` on non-default versions (delegated to HTTP headers); remove `target="_blank"` on same-site archive banner links and add a `prerelease` banner (32 locales); support configuring site-root storage scope for history and shortcuts without breaking subpath isolation | `layouts/_partials/seo-alternates.html`, `layouts/_partials/version-banner.html`, `layouts/_partials/scripts.html`, `layouts/_partials/shell/history-dialog.html` | M1 |
| **C4** | Add an opt-in `js/chunks/oink-versions.js` runtime that hydrates the navbar/drawer/footer version menu, Command Palette `switch_version` options (preserving page path), and archived/prerelease banners from `/_oink/versions.json`, with a no-JS static link to `/versions/`; fetch `/_oink/where` on 404 pages; add a version-independent `term` option to `giscus.html` | `layouts/_partials/navbar.html`, `layouts/_partials/actions/context.html`, `layouts/_partials/giscus.html`, `assets/js/` | M1 |
| **C5** | Refactor `command-palette.js` query execution to support an opt-in async remote search backend (`/_oink/search` with debounce, `AbortController`, and version-scope toggle), preserving zero network requests when unconfigured | `assets/js/command-palette.js`, `layouts/_partials/shell/search-dialog.html` | M2 |
| **C6** | Add a minimal corpus shell layout (one body insertion slot + navigation JSON hook) and a `.td-corpus-pgweb` CSS adapter layer so external HTML corpora inherit OINK styling cleanly | `layouts/`, `assets/css/td/` | M2 |
{.wide .expand}

*(Independent theme housekeeping, non-blocking: add an empty `tests/go.mod` in the OINK theme repository so the `79 MB` test fixtures stop inflating Go module zips for all consumers.)*

### Process coordination {#theme-process}

- **Independent releases**: because `oink` does not embed Hugo or require a lockstep `embed.go` in the theme root, OINK theme releases and `oink` binary releases ship independently.
- **Contract ownership**: `/_oink/versions.json` schema, `/_oink/search` response shape, and the `C6` corpus shell contract live in OINK's bilingual Design contracts with explicit version fields.
- **Checkers**: `oink` Go tests verify plain-Hugo parity, `pgdoc-cn` storage/latency budgets, `kill -9` recovery, asset grace-window retention, HTTP SEO headers, and `exec` isolation; theme checkers (`check-shell.py`, `check-goldens.py`, `check-i18n.py`) and `oink.pgsty.com` Playwright suites verify rendered output.

## Compatibility and migration {#compatibility}

- **Plain Hugo sites are completely unaffected.** The theme repository remains pure templates, CSS, JS, and i18n with no server code or `embed.go` requirement.
- **Existing `params.versions` static sites keep working unchanged.** Adopting `oink serve` switches them to `/_oink/versions.json` without editing historical tags.
- **Retiring `oink-cli`.** If accepted, the [CLI contract](/docs/design/decisions/cli/) is marked superseded and `pgsty/oink-cli` is archived. Essential link/translation checks move to `oink check`; `oink.result/v1` and `oink.policy/v1` are retired cleanly (`oink.yaml` uses explicit `schema_version: oink.serve/v1`).
- **Crib compatibility.** Existing `.crib` files are untouched; Crib adds `.oink` (`oink.store/v1`) reading using Apple's built-in `libsqlite3` and `COMPRESSION_BROTLI` with zero new third-party dependencies.

## Implementation and checker plan {#implementation}

Create a clean Go repository (`pgsty/oink-server`, producing the `oink` binary) split into focused packages: `hugoexec` (official Hugo resolution, SHA-256 caching, isolated child runner + RSS watchdog), `gitsrc` (ref resolution, worktree materialization, `cat-file --batch` streaming), `corpus/pgweb`, `store` (`cache.db` + Brotli clusters + `.oink` compaction & Ed25519 manifest signing), `search` (`search.db` scoped FTS5 + CJK/identifier analyzer), `serve` (routing, HTTP SEO/CDN headers, Cloudflare batched purge, `recent_assets` fallback), `pv` (daily-salt dedup counter + `state.db`), and `admin` (`0600` Unix socket + `VACUUM INTO` backup).

### Milestones {#milestones}

| Milestone | Estimate | Scope | Exit evidence |
| --- | --- | --- | --- |
| **M0: Lean dev & check binary** | 2 weeks | `oink` (`dev`, `build`, `check`, `versions`, `hugo`); official Hugo auto-cache + SHA-256 verification; LiveReload WebSocket proxy; `ncruces` vs `mattn` SQLite benchmark | Clean machine without preinstalled Hugo/Go previews `oink.pgsty.com` and `pigsty.io` with live reload; `oink build` matches plain Hugo byte-for-byte |
| **M1: Multi-version Hugo serving** | 3 weeks | `oink serve`, `oink.yaml (v1)`, `oink freeze`, dual-track lifecycle, `cache.db` (Brotli clusters + 48h `recent_assets` grace window), atomic switch, `status`/`rebuild`/`rollback`/`backup`, HTTP SEO & Cloudflare headers, theme **C1–C4** | Bilingual site with 5+ tags, 1 frozen legacy version, and moving `devel` runs live; publishing a new tag rebuilds zero old versions; bad commits/OOM/`kill -9` keep live site up; old HTML fetching old fingerprinted CSS returns `200`; rollback `< 1 s`; EN/ZH + axe pass |
| **M2: `pgdoc-cn` 560 versions & scoped search** | 2–3 weeks | `pgweb` importer, theme **C5–C6**, `search.db` (active-line FTS5 + CJK bigrams + identifiers/operators), 60-query benchmark | All 560 `pgdoc-cn` versions reachable; `cache.db` + 6 active major lines `search.db` total **`< 100 MiB`**; cold start `< 2 s`; hit p99 `< 5 ms`, cluster miss `< 15 ms`; resident RAM `< 512 MiB`; 60-query Top-5 recall `≥ 90%` |
| **M3: `.oink` packages, Crib & PV** | 2 weeks | Compacted `.oink` export (`brotli -q 9`), Ed25519 manifest signing & verification, `oink serve x.oink`, Crib native reader (`libsqlite3` + `COMPRESSION_BROTLI`), daily-salt `/_oink/hit` PV | Signed `.oink` round-trip serves byte-identical output; Crib opens all 560 `pgdoc-cn` versions with zero third-party libraries; PV deduplicates refreshes with no IP persisted |
{.wide .expand}

### Acceptance criteria {#acceptance}

1. **Zero-rebuild publishing**: pushing a new tag `v3.8.0` on an M1 test site triggers exactly one Hugo build; existing versions remain untouched; `/_oink/versions.json` updates and client version menus show `v3.8.0` with working same-page links.
2. **No cross-request asset tearing**: after 4 consecutive CSS-changing publishes and a GC pass within 48 hours, an older cached HTML page's request for its original fingerprinted CSS still returns `200 OK`.
3. **Resilience & memory containment**: an intentionally low `build_memory_limit` triggers watchdog `SIGKILL` of the Hugo child process group without degrading server availability; `kill -9` mid-ingest leaves live snapshots intact and auto-cleans orphan clusters on restart; `oink rollback` completes in `< 1 s`.
4. **`pgdoc-cn` scale & latency**: all 560 versions resolve; `cache.db` + 6-line `search.db` stay under `100 MiB`; cold start `< 2 s`; p99 `< 5 ms` (LRU hit) / `< 15 ms` (cluster decode); 60-query EN/ZH/identifier search benchmark hits Top-5 `≥ 90%` at `< 25 ms` p99.
5. **SEO & security verification**: default version emits self-canonical + `hreflang`; non-default lines emit HTTP `Link: rel="canonical"` with no conflicting HTML canonical/`hreflang`; patch releases and `devel` emit only `X-Robots-Tag: noindex, follow`; `/v{default}/x` returns `302`; repositories enabling `security.exec` are blocked by default; `oink.sock` is `0600`; `/_oink/metrics` is `404` on the public listener.
6. **Package round-trip**: `oink build --versions -o x.oink` followed by `oink serve x.oink` passes Ed25519 verification and serves byte-identical responses for every URL.

## Risks {#risks}

| Risk | Mitigation |
| --- | --- |
| Readers without JS do not see the interactive version dropdown | Every page carries a static `<a href="/versions/">` link to a theme-rendered full version index; SEO relies on HTTP headers, not JS |
| Maintainer upgrades OINK across a breaking change without freezing old lines first | `oink check --versions` audits active lines against the new theme and lists versions needing `oink freeze` before cutover |
| Cloudflare Cache Rule misconfiguration or Free-tier purge throttling (`5 req/min`) | Ship copy-pasteable Respect-Origin Cache Rule recipes + `oink verify-cdn`; batch up to 100 prefixes per purge with rate backoff |
| Background builds saturate a small single-core VPS | Default concurrency `1`, `nice`/`ionice`, `GOMEMLIMIT`, RSS watchdog, and Cloudflare edge absorption (`stale-if-error=3600`) |
| `pgweb` DocBook HTML variations across 25 years of PostgreSQL releases | Test importer across all 560 real `pgdoc-cn` / `pgdoc-en` tags (v6.0–v20devel) in `M2` CI fixtures |

## Alternatives {#alternatives}

| Alternative | Conclusion |
| --- | --- |
| Per-version static builds on Cloudflare Pages (`mike` / Read the Docs style) | `mike` and RTD already use client-side `versions.json` (no full menu rebuilds), so small sites work well via `oink build --versions`; however 560 `pgdoc-cn` versions (`529k` files, `6.15 GB`) exceed Pages' 20k/100k file limits and blow up storage |
| Cloudflare R2 + Workers + D1 | Avoids a VPS origin, but D1 query/storage pricing for 529k manifests and full-text search is unacceptable to the owner; self-hosted `oink` + local SQLite + free Cloudflare CDN keeps cost flat and works identically offline |
| Embedding `github.com/gohugoio/hugo/commands` in-process/re-exec | Couples to an unstable internal Go API, bloats binary to `~130–145 MB`, and forces releasing `oink` on every Hugo upgrade; orchestrating the official Hugo binary is cleaner and smaller |
| Server-side HTML byte-offset slot splicing (v1 draft Stage 2) | Breaks page-for-page `version_menu_pagelinks` without server-side URL rewriting, ties all old versions' ETags to default-version page deletions, and doubles theme surface (`T1–T12`); client `versions.json` + HTTP SEO headers achieve the same goal far more simply |
| Kiwix/ZIM or `docs.rs` S3 + PostgreSQL | ZIM is a strong read-only archive reference (clusters + index), while SQLite + Brotli avoids writing a custom binary parser for Crib (Apple ships `libsqlite3` + `COMPRESSION_BROTLI`); `docs.rs` targets multi-terabyte Rust crates with container fleets, overkill for single-repo docs |
| Hugo native `[versions]` matrix (v0.153+) | Builds every version together in one Hugo invocation; memory and rebuild cost scale as `versions × pages` (unworkable for 560 versions). Suitable only for small static sites under theme roadmap R2 |

## Resolved design decisions {#decisions}

All architectural decisions previously left open are resolved for this v2 baseline:

1. **Decoupled official Hugo binary** (instead of importing `gohugoio/hugo/commands`): keeps `oink` ~20 MB, decouples Hugo upgrades, and eliminates Go dependency conflicts.
2. **Zero HTML splicing (`/_oink/versions.json` + HTTP `Link`/`X-Robots-Tag` headers)** (instead of Stage-2 `<template data-td-slot>` splicing): removes full rebuilds on release, preserves page-for-page switching, and cuts theme coordination from 12 items to 6.
3. **Dual-track version lifecycle (`mode: build` + `oink freeze`)**: active lines keep their own `data/` and `static/` while sharing a pinned release-tag `skin`; historical versions crossing breaking OINK retirements freeze cleanly without compatibility shims.
4. **Universal RFC 7932 Brotli (`lgwin=22`) for `oink.store/v1`**: empirically outperforms `zstd -15` on `pgdoc-cn` 1 MiB clusters (`42.2–46.6×`, `< 0.8 ms` p99 decode), runs pure-Go in `oink`, and decodes natively in Crib via Apple's `COMPRESSION_BROTLI` with zero third-party dependencies.
5. **Scoped `search.db` (`active-lines` default)**: separates FTS5 from `cache.db` and indexes active major lines by default (`32.4 MiB` for PG 13–18), keeping all 560 `pgdoc-cn` versions + search under `100 MiB`.
6. **Clean new binary repository (`pgsty/oink-server`) and explicit `oink.yaml` schema (`oink.serve/v1`)**: retires `pgsty/oink-cli` cleanly without carrying dead `oink.result/v1` history.
7. **Defer ACL/auth/comments and keep `pgext`/`pg.center` dynamic apps separate**: keeps v1 focused, secure behind Cloudflare CDN, and deliverable in ~9–10 weeks across `M0–M3`.

## Decision log {#decision-log}

| Date | Record |
| --- | --- |
| 2026-11-27 | Owner defines online needs: multi-version docs (including 500+ PG versions), search, page views, comments, `pgext`/`pg.center`, Cloudflare preference |
| 2026-11-28 | Initial v1 draft written (embedded Hugo CLI, Stage-2 HTML slot splicing, zstd SQLite store, full-corpus FTS5, accounts/ACL/comments) |
| 2026-11-28 | Adversarial architecture review and live local benchmarks on `pgdoc-cn`, `pigsty.io`, `pgext.cloud`, and `pg.center` identify key flaws: 560-version FTS5 exceeds `473 MiB`, Stage-2 splicing conflicts with `version_menu_pagelinks` and per-page canonical, `content/`-only skinning breaks `data/`/`static/` and retired shortcodes, `RLIMIT_AS` crashes Go children, `s-maxage` disables Cloudflare `stale-if-error`, and `brotli` beats `zstd` while matching Apple's native `COMPRESSION_BROTLI` |
| 2026-11-28 | Owner confirms self-hosted SQLite behind Cloudflare CDN (no D1), defers ACL out of v1, and delegates remaining architecture decisions; proposal rewritten as v2 redesign |

---

Backlinks:

- [Proposals](/docs/design/proposals/)
- [Spec boards](/docs/design/proposals/spec-boards/)
